Skip to content

Ising

The two-dimensional Ising system on a torus.

  • Class: IsingSystem
  • Import: from skcomplex.systems.physics.statistical_mechanics import IsingSystem
  • Field: physics/statistical_mechanics
  • Topics: lattice, Monte Carlo, phase transition, spins
  • References:
    • Ising 1925
    • Onsager 1944
    • Jensen 2023

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 IsingSystem

trajectory = IsingSystem().prepare().simulate()

Parameters

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

Parameter Default
size 64
temperature 2.0
J 1.0
h 0.0
initial 'random'
sampler 'metropolis'
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 IsingSystem(systems.BaseSystem):
    """The two-dimensional Ising system on a torus.

    The system orders below the critical temperature `2 / ln(1 + sqrt 2)`.

    One unit of time is one sweep of checkerboard updates. The system has the spins `spins.spin`.

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

        temperature:
            The temperature in units of the coupling, which can change during a run.

        J:
            The coupling between neighbouring spins.

        h:
            The external field.

        initial:
            `'random'` for random spins or `'up'` for all spins up.

        sampler:
            The acceptance rule, `'metropolis'`, `'glauber'`, or `'heat-bath'`.

        random_state:
            The seed or generator 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.

    Examples:
        >>> from skcomplex.systems.physics.statistical_mechanics import IsingSystem
        >>> IsingSystem(8, temperature=1.5).prepare().system_.elements[0].temperature
        1.5
    """

    field = 'physics/statistical_mechanics'
    topics = ('lattice', 'Monte Carlo', 'phase transition', 'spins')
    references = ('Ising 1925', 'Onsager 1944', 'Jensen 2023')
    until = 200
    dt = 1

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

    def __init__(
        self,
        size: int | Sequence[int] = 64,
        *,
        temperature: float = 2.0,
        J: float = 1.0,
        h: float = 0.0,
        initial: str = 'random',
        sampler: str = 'metropolis',
        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.initial = initial
        self.sampler = sampler
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the Ising spins of a torus, all up or random at the start.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        shape = IsingSystem._get_square(self.size)
        spins = (
            np.ones(shape)
            if self.initial == 'up'
            else np.random.default_rng(self.random_state).choice([-1.0, 1.0], size=shape)
        )
        group = IsingSpinElement(
            'spins',
            spin=spins.ravel(),
            J=self.J,
            h=self.h,
            temperature=self.temperature,
            space=LatticeSpace(shape),
        )
        self.system_ = systems.System(
            self.label,
            elements=[group],
            interactions=[IsingSamplingInteraction('sampling', target='spins')],
            solver=MetropolisSolver(moves={'spins.spin': 'flip'}, rule=self.sampler),
        )

Components

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

Elements:

Interactions:

  • IsingSamplingInteraction, from Interaction
class IsingSpinElement(Element):
    """Ising spins, up at 1 or down at -1.

    Every spin has its coupling `J`, its field `h`, and its temperature.

    An `IsingSamplingInteraction` flips the spins by Monte Carlo sweeps at the temperature of the spins.

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

        spin:
            The initial spin, 1 or -1, or one spin per site.

        J:
            The coupling between neighbouring spins.

        h:
            The external field.

        temperature:
            The temperature in units of the coupling.

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

    Examples:
        >>> from skcomplex.systems.physics.common.spins import IsingSpinElement
        >>> IsingSpinElement('spin').temperature
        2.0
    """

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

class IsingSamplingInteraction(SpinSamplingInteraction):
    """Boltzmann weight of Ising spins `s = ±1`, whose local energy is `-J s sum_j s_j - h s`.

    The coupling `J`, the field `h`, and the temperature are values of the spins, and the `MetropolisSolver` of the
    system flips them, `MetropolisSolver(moves={'spins.spin': 'flip'})`.

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

        target:
            The path of the group of spins.

        state:
            The name of the state that holds the spin.

    Examples:
        >>> from types import SimpleNamespace
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.systems.physics.common.spins import IsingSamplingInteraction
        >>> ising = IsingSamplingInteraction('ising', target='spins')
        >>> other = SimpleNamespace(spin=var('t'))
        >>> ising.energy(SimpleNamespace(target=SimpleNamespace(spin=var('s'), J=1, h=var('h'), other=other)))
        -h*s - s*neighbors(t, reduce='sum')
    """

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

    def _get_energy(self, namespace: SimpleNamespace) -> Expression:
        """Return the local energy `-J s sum_j s_j - h s` of a spin."""
        spin, other = getattr(namespace.target, self.state), getattr(namespace.target.other, self.state)
        return -namespace.target.J * spin * neighbors(other) - namespace.target.h * spin