Skip to content

Edwards-Anderson spin glass

The Edwards-Anderson spin glass on a periodic square lattice.

  • Class: EdwardsAndersonSystem
  • Import: from skcomplex.systems.physics.statistical_mechanics import EdwardsAndersonSystem
  • Field: physics/statistical_mechanics
  • Topics: spin glass, disorder, lattice, Monte Carlo, spins
  • References:
    • Edwards and Anderson 1975
    • Bertin 2021
    • Binder and Young 1986

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.physics.statistical_mechanics import EdwardsAndersonSystem

trajectory = EdwardsAndersonSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
size 48
temperature 0.8
J 1.0
h 0.0
disorder 'bimodal'
random_state 0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time discrete
Space lattice
Laws sampling
Randomness stochastic
Domains real
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class EdwardsAndersonSystem(systems.BaseSystem):
    """The Edwards-Anderson spin glass on a periodic square lattice.

    The bonds are quenched and random.

    Every bond takes the coupling `+J` or `-J` with equal probability, or a Gaussian coupling of mean 0 and standard
    deviation `J`, drawn once. The magnetization stays near zero at every temperature, while at low temperature the
    spins freeze in random directions and the energy per spin approaches the ground-state energy, about `-1.40 J` for
    `+J` and `-J` bonds. One unit of time is one sweep of Metropolis updates. The system has the spins `spins.spin`, the
    couplings `spins.J_right` and `spins.J_down` of the bonds to the right and down, and the observable `magnetization`.

    Args:
        size:
            The side of the square lattice, or its two sides.

        temperature:
            The temperature, which can change during a run.

        J:
            The scale of the couplings.

        h:
            The external field.

        disorder:
            `'bimodal'` for couplings `+J` and `-J`, or `'gaussian'` for Gaussian couplings.

        random_state:
            The seed or generator of the couplings and of the random initial spins.

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Raises:
        ValidationError:
            The disorder is neither `'bimodal'` nor `'gaussian'`.

    Examples:
        >>> from skcomplex.systems.physics.statistical_mechanics import EdwardsAndersonSystem
        >>> sorted(set(EdwardsAndersonSystem(8).prepare().system_.elements[0].J_right.tolist()))
        [-1.0, 1.0]
    """

    field = 'physics/statistical_mechanics'
    topics = ('spin glass', 'disorder', 'lattice', 'Monte Carlo', 'spins')
    references = ('Edwards and Anderson 1975', 'Bertin 2021', 'Binder and Young 1986')
    until = 500
    dt = 5
    observables = (Observable('magnetization', group='spins', variable='spin'),)

    @staticmethod
    def _get_square(size: int | Sequence[int]) -> tuple[int, int]:
        """Return the shape of a square lattice of a side, or a given shape of two sides."""
        if isinstance(size, Sequence):
            rows, columns = (int(item) for item in size)
            return rows, columns
        return int(size), int(size)

    @staticmethod
    def _get_bond_states(
        right: npt.NDArray[np.floating],
        down: npt.NDArray[np.floating],
    ) -> dict[str, npt.NDArray[np.floating]]:
        """Return the couplings of every site to its up, left, right, and down neighbours.

        The couplings come from the bonds right and down.
        """
        return {
            'J_up': np.roll(down, 1, axis=0),
            'J_left': np.roll(right, 1, axis=1),
            'J_right': right,
            'J_down': down,
        }

    def __init__(
        self,
        size: int | Sequence[int] = 48,
        *,
        temperature: float = 0.8,
        J: float = 1.0,
        h: float = 0.0,
        disorder: str = 'bimodal',
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.size = size
        self.temperature = temperature
        self.J = J
        self.h = h
        self.disorder = disorder
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the Edwards-Anderson spin glass on a periodic square lattice, with quenched random bonds.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        shape = EdwardsAndersonSystem._get_square(self.size)
        rng = np.random.default_rng(self.random_state)
        if self.disorder == 'bimodal':
            right, down = self.J * rng.choice([-1.0, 1.0], size=(2, *shape))
        elif self.disorder == 'gaussian':
            right, down = self.J * rng.standard_normal((2, *shape))
        else:
            error_msg = f"The disorder is 'bimodal' or 'gaussian', not {self.disorder!r}."
            raise ValidationError(error_msg)
        spins = rng.choice([-1.0, 1.0], size=shape)
        bonds = {name: np.ravel(value) for name, value in EdwardsAndersonSystem._get_bond_states(right, down).items()}
        group = BondSpinElement(
            'spins',
            spin=spins.ravel(),
            h=self.h,
            temperature=self.temperature,
            space=LatticeSpace(shape),
            **bonds,
        )
        self.system_ = systems.System(
            self.label,
            elements=[group],
            interactions=[BondSamplingInteraction('sampling', target='spins')],
            solver=MetropolisSolver(moves={'spins.spin': 'flip'}, neighborhood=NEAREST),
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

Interactions:

  • BondSamplingInteraction, from Interaction
class BondSpinElement(Element):
    """Ising spin on a square lattice with quenched couplings to its four neighbours.

    Its local energy is `-s sum J_k s_k`.

    The couplings are constant states of every site, so a bond between two sites is stored at both of them with the same
    value. A `BondSamplingInteraction` flips the spins by Metropolis Monte Carlo at the temperature `T`, with the energy
    `-sum_<ij> J_ij s_i s_j - h sum_i s_i`.

    Args:
        label:
            The label of the spin or the lattice group.

        spin:
            The initial spin, 1 or -1.

        J_up:
            The coupling to the upper neighbour.

        J_left:
            The coupling to the left neighbour.

        J_right:
            The coupling to the right neighbour.

        J_down:
            The coupling to the lower neighbour.

        h:
            The external field.

        temperature:
            The temperature.

        space:
            The lattice of the spins, or `None` for one spin.

    Examples:
        >>> from skcomplex.systems.physics.statistical_mechanics import BondSpinElement
        >>> BondSpinElement('spin', J_left=-1.0).J_left
        -1.0
    """

    visual = VisualSpec('image', {'states': ('spin',), 'low': -1.0, 'high': 1.0})

    def __init__(
        self,
        label: str,
        *,
        spin: object = 1.0,
        J_up: object = 1.0,
        J_left: object = 1.0,
        J_right: object = 1.0,
        J_down: object = 1.0,
        h: float = 0.0,
        temperature: Annotated[float, RealSet.open(0, oo)] = 1.0,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.spin = spin
        self.J_up = J_up
        self.J_left = J_left
        self.J_right = J_right
        self.J_down = J_down
        self.h = h
        self.temperature = temperature

class BondSamplingInteraction(SpinSamplingInteraction):
    """Metropolis sweeps of Ising spins with quenched couplings to their neighbours.

    The local energy is `-s (sum J_k s_k + h)`.

    The couplings `J_up`, `J_left`, `J_right`, and `J_down` are constant states of every spin, in the order of the
    offsets of the von Neumann neighbourhood, and the field `h` and the temperature are its parameters.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        target:
            The path of the lattice group of spins.

    Examples:
        >>> from skcomplex.systems.physics.statistical_mechanics import BondSamplingInteraction
        >>> BondSamplingInteraction('sampling', target='spins').state
        'spin'
    """

    def __init__(self, label: str, *, target: Role) -> None:
        super().__init__(label, target=target, state='spin', energy=self._get_energy)

    def _get_energy(self, namespace: SimpleNamespace) -> Expression:
        """Return the local energy `-s (sum_k J_k s_k + h)` of a spin."""
        s = namespace.target
        couplings = (s.J_up, s.J_left, s.J_right, s.J_down)
        neighbours = neighbors(s.spin, NEAREST, reduce='each')
        return -s.spin * (sum(coupling * other for coupling, other in zip(couplings, neighbours, strict=True)) + s.h)