"""Dynamic MCState factory for Monte Carlo moves.
MCState is built at runtime by the MWG factory based on the active move
set. Core fields (positions, types, energy, cell, step_size, step_sizes,
n_accepted, n_proposed) are always present. Move-specific fields (e.g.
direction for Galilean) are added only when the corresponding move is
in the MWG descriptor list.
The factory uses dataclasses.make_dataclass() and registers each unique
class as a JAX pytree. Classes are cached by field names to avoid
duplicate registration.
"""
from __future__ import annotations
import dataclasses
import jax.numpy as jnp
from jaxtyping import Array, Bool, Float, Int
from jaxrens.state.walker import register_dataclass_pytree, static_field
# ---------------------------------------------------------------------------
# MCState-specific helper
# ---------------------------------------------------------------------------
def _add_set_method(cls):
"""Add a .set(**kwargs) method for functional updates.
WalkerState/NSState define ``.set`` in their class body; the dynamically
built MCState gets it injected here instead.
"""
def set_method(self, **kwargs):
return dataclasses.replace(self, **kwargs)
cls.set = set_method
# ---------------------------------------------------------------------------
# MCState factory
# ---------------------------------------------------------------------------
_MC_STATE_CACHE: dict[frozenset, type] = {}
[docs]
def make_mc_state_class(extra_fields: dict[str, type] | None = None) -> type:
"""Create an MCState dataclass with core + move-specific fields.
Args:
extra_fields: Dict mapping field names to types for move-specific
fields. E.g. {"direction": jnp.ndarray}. If None or empty,
only core fields are included.
Returns:
A dataclass type registered as a JAX pytree with a .set() method.
Cached by field names — same fields return the same class.
"""
if extra_fields is None:
extra_fields = {}
cache_key = frozenset(extra_fields.keys())
if cache_key in _MC_STATE_CACHE:
return _MC_STATE_CACHE[cache_key]
# Core fields — always present. Shapes carry an optional batch prefix
# ``*B`` because the MWG sampler vmaps/pmaps a single-walker MCState (see
# ``jaxrens.state.walker`` for the same convention).
core = [
("positions", Float[Array, "*B N 3"]),
("types", Int[Array, "*B N"]),
("energy", Float[Array, "*B"]),
("cell", Float[Array, "*B 3 3"]),
("step_size", Float[Array, "*B"]),
("step_sizes", Float[Array, "*B n_moves"]),
("n_accepted", Int[Array, "*B n_moves"]),
("n_proposed", Int[Array, "*B n_moves"]),
# actual max neighbors observed
("max_neighbor_count", Int[Array, "*B"]),
("overflow", Bool[Array, "*B"]), # any overflow detected
(
"ensemble_params",
dict,
), # e.g. {"pressure": scalar, "chemical_potentials": (n_species,)}
]
# Move-specific fields
extra = [(name, typ) for name, typ in sorted(extra_fields.items())]
# Static fields (compile-time constants)
static = [
("max_neighbors", int, static_field(default=0)),
("n_atoms", int, static_field(default=0)),
]
cls = dataclasses.make_dataclass("MCState", core + extra + static)
_add_set_method(cls)
register_dataclass_pytree(cls)
_MC_STATE_CACHE[cache_key] = cls
return cls
# ---------------------------------------------------------------------------
# Which fields belong to the walker and which to the run
# ---------------------------------------------------------------------------
#: Fields describing the *run* a walker slot belongs to, not the
#: configuration in it. When replica exchange moves a configuration to
#: another run these stay with the slot: the run's ensemble params, its
#: adapted step sizes (``step_size`` is re-derived from ``step_sizes`` on every
#: move) and the acceptance counters of the moves made in this run. Every
#: other non-static field -- including all move-specific extra fields such as
#: GMC's ``direction`` -- describes the configuration and travels with it.
#: A move whose extra field is per-run state must be added here.
RUN_BOUND_FIELDS: frozenset[str] = frozenset(
{"ensemble_params", "step_size", "step_sizes", "n_accepted", "n_proposed"}
)
[docs]
def walker_bound_fields(state) -> tuple[str, ...]:
"""Names of the non-static fields of ``state`` that travel with the walker.
Args:
state: An MCState instance (any field set built by
:func:`make_mc_state_class`).
Returns:
Field names in declaration order, excluding static fields and
:data:`RUN_BOUND_FIELDS`.
"""
return tuple(
f.name
for f in dataclasses.fields(state)
if not f.metadata.get("static", False)
and f.name not in RUN_BOUND_FIELDS
)
# ---------------------------------------------------------------------------
# Convenience: default MCState with no extra fields
# ---------------------------------------------------------------------------
MCState = make_mc_state_class()