Skip to content

Lattice Maxwell and gauge link fields

Link variables on the cell complex of a periodic lattice.

  • Class: LatticeGaugeFieldsSystem
  • Import: from skcomplex.systems.physics.waves import LatticeGaugeFieldsSystem
  • Field: physics/waves
  • Topics: gauge, lattice, monte carlo, maxwell, cell complex
  • References:
    • Schwichtenberg 2020
    • Wilson 1974

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.waves import LatticeGaugeFieldsSystem

trajectory = LatticeGaugeFieldsSystem().prepare().simulate()

Parameters

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

Parameter Default
size 32
dimension 2
n None
beta 2.0
dynamics 'monte-carlo'
charges None
angles None
amplitude 0.1
seed 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 cell complex
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 LatticeGaugeFieldsSystem(BaseSystem):
    """Link variables on the cell complex of a periodic lattice.

    The variables are sampled or evolved in real time.

    With Monte Carlo dynamics, link angles sample the Wilson action `-beta sum_p cos(theta_p)` under discrete time, as
    U(1) angles or as the angles `2 pi k / n` of Z_n. With Hamiltonian dynamics, a potential on the links follows the
    lattice Maxwell equations `A_t = -E` and `E_t = codifferential(dA)` under continuous time, from static charges on
    the sites and a transverse wave. In two dimensions the U(1) mean plaquette at large size is `I_1(beta) / I_0(beta)`.

    Args:
        size:
            The number of sites along every axis.

        dimension:
            The number of axes of the lattice.

        n:
            The order of the Z_n group, or `None` for U(1).

        beta:
            The inverse coupling of the Wilson action.

        dynamics:
            `'monte-carlo'` or `'hamiltonian'`.

        charges:
            The static charge of every site, of total 0, or `None` for none, with Hamiltonian dynamics.

        angles:
            The initial link angles, or `None` for random angles, with Monte Carlo dynamics.

        amplitude:
            The amplitude of the initial transverse wave, with Hamiltonian dynamics.

        seed:
            The seed of the initial link angles.

        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 dynamics are unknown, or the charges do not hold one value per site of total 0.

    Examples:
        >>> from skcomplex.systems.physics.waves import LatticeGaugeFieldsSystem
        >>> [element.label for element in LatticeGaugeFieldsSystem(4).prepare().system_.elements]
        ['links']
        >>> system = LatticeGaugeFieldsSystem(4, dynamics='hamiltonian').prepare().system_
        >>> [element.label for element in system.elements]
        ['links', 'charges']
    """

    field = 'physics/waves'
    topics = ('gauge', 'lattice', 'monte carlo', 'maxwell', 'cell complex')
    references = ('Schwichtenberg 2020', 'Wilson 1974')
    until = 5000
    dt = 1

    @staticmethod
    def _get_mean_plaquette(faces: scipy.sparse.csr_array, t: float, values: Mapping[str, object]) -> float:
        """Return the mean cosine of the oriented link angle sums around the plaquettes."""
        del t
        return float(np.cos(faces @ np.ravel(np.asarray(values['links.theta'], dtype=float))).mean())

    @staticmethod
    def _get_gauss_residual(edges: scipy.sparse.csr_array, t: float, values: Mapping[str, object]) -> float:
        """Return the Gauss residual of the electric field.

        The residual is the largest absolute difference of the codifferential of the field and the site charge.
        """
        del t
        electric = -np.ravel(np.asarray(values["links.A'"], dtype=float))
        charges = np.ravel(np.asarray(values['charges.q'], dtype=float))
        return float(np.abs(-(edges.T @ electric) - charges).max())

    @staticmethod
    def _get_field_energy(faces: scipy.sparse.csr_array, t: float, values: Mapping[str, object]) -> float:
        """Return the energy of the electric and magnetic fields.

        The electric field lives on the links and the magnetic field on the plaquettes.
        """
        del t
        velocity = np.ravel(np.asarray(values["links.A'"], dtype=float))
        magnetic = faces @ np.ravel(np.asarray(values['links.A'], dtype=float))
        return float((velocity @ velocity + magnetic @ magnetic) / 2)

    @staticmethod
    def _get_electric_field(space: CellComplexSpace, charges: Array) -> Array:
        """Return the electric field of least norm whose codifferential is the charge.

        The codifferential matches the charge of every site.
        """
        field = scipy.sparse.linalg.lsqr(
            -space.incidences_[0].T,
            charges,
            atol=SOLVER_TOLERANCE,
            btol=SOLVER_TOLERANCE,
            conlim=0.0,
            iter_lim=100 * charges.size,
        )[0]
        return np.asarray(field, dtype=float)

    def __init__(
        self,
        size: int = 32,
        *,
        dimension: int = 2,
        n: int | None = None,
        beta: float = 2.0,
        dynamics: str = 'monte-carlo',
        charges: Sequence[float] | None = None,
        angles: Sequence[float] | None = None,
        amplitude: float = 0.1,
        seed: int = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.size = size
        self.dimension = dimension
        self.n = n
        self.beta = beta
        self.dynamics = dynamics
        self.charges = charges
        self.angles = angles
        self.amplitude = amplitude
        self.seed = seed

    def _get_maxwell_system(self, space: CellComplexSpace) -> System:
        """Return a lattice Maxwell field on the links.

        The field comes from static charges and a transverse wave.
        """
        density = np.zeros(space.size_) if self.charges is None else np.asarray(self.charges, dtype=float)
        if density.size != space.size_ or abs(density.sum()) > NEUTRAL_TOTAL:
            error_msg = (
                f'The charges are {density.size} values of total {density.sum()}, but a periodic lattice takes one '
                f'charge per site of its {space.size_} sites, of total 0.'
            )
            raise ValidationError(error_msg)
        place = cast(LatticeSpace, space.space)
        sources = space.edges_[None][0]
        along_last = space.link_axes_ == place.n_dim_ - 1
        first = np.unravel_index(sources, place.shape_)[0]
        wave = self.amplitude * np.cos(2 * np.pi * first / place.shape_[0]) * along_last
        links = MaxwellLinkElement(
            'links',
            A=wave,
            space=space,
            on='edges',
            values={"A'": -LatticeGaugeFieldsSystem._get_electric_field(space, density)},
        )
        sites = StaticChargeElement('charges', q=density, space=space)
        maxwell = MaxwellInteraction('maxwell', target='links')
        return System(self.label, elements=[links, sites], interactions=[maxwell], solver=MAXWELL_SOLVER)

    def _get_monte_carlo_system(self, space: CellComplexSpace) -> System:
        """Return U(1) or Z_N link angles sampled by the Wilson action under discrete time."""
        rng = np.random.default_rng(self.seed)
        size = space.incidences_[0].shape[0]
        values = () if self.n is None else tuple(2 * np.pi * np.arange(self.n) / self.n)
        drawn = rng.uniform(-np.pi, np.pi, size) if self.n is None else rng.choice(values, size)
        links = GaugeLinkElement(
            'links',
            theta=drawn if self.angles is None else np.asarray(self.angles, dtype=float),
            space=space,
            on='edges',
        )
        sampling = WilsonSamplingInteraction('wilson', target='links', beta=self.beta)
        if self.n is None:
            solver = MetropolisSolver(moves={'links.theta': 'rotate'}, schedule='colored', width=1.5)
        else:
            solver = MetropolisSolver(
                moves={'links.theta': 'random-value'},
                rule='heat-bath',
                schedule='colored',
                values={'links.theta': values},
            )
        return System(self.label, elements=[links], interactions=[sampling], solver=solver)

    def _get_gauge_observables(self, space: CellComplexSpace) -> list[Observable]:
        """Return the observables of the dynamics.

        They are the mean plaquette of a sampled system, or the Gauss residual and the field energy of a Maxwell one.
        """
        if self.dynamics != 'hamiltonian':
            return [
                Observable(
                    'mean_plaquette',
                    function=partial(LatticeGaugeFieldsSystem._get_mean_plaquette, space.incidences_[1]),
                ),
            ]
        return [
            Observable(
                'gauss_residual',
                function=partial(LatticeGaugeFieldsSystem._get_gauss_residual, space.incidences_[0]),
            ),
            Observable(
                'field_energy',
                function=partial(LatticeGaugeFieldsSystem._get_field_energy, space.incidences_[1]),
            ),
        ]

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the link variables on the cell complex of a periodic lattice, sampled or evolved in real time.

        Args:
            context:
                The observables to compile with the problem, or `None` for those of the dynamics.

        Raises:
            ValidationError:
                The dynamics are unknown, or the charges do not hold one value per site of total 0.
        """
        super()._prepare(context)
        if self.dynamics not in DYNAMICS:
            error_msg = f'Unknown dynamics {self.dynamics!r}. Use one of {", ".join(DYNAMICS)}.'
            raise ValidationError(error_msg)
        space = CellComplexSpace(LatticeSpace((self.size,) * self.dimension)).prepare()
        if not context:
            self.observables_ = tuple(self._get_gauge_observables(space))
        if self.dynamics == 'hamiltonian':
            self.system_ = self._get_maxwell_system(space)
        else:
            self.system_ = self._get_monte_carlo_system(space)

    def simulate(
        self,
        until: float | None = None,
        *,
        dt: float | None = None,
        initial_state: Mapping[str, object] | None = None,
        random_state: int | np.random.Generator | None = None,
        observables: Sequence[Observable] = (),
        observers: Sequence[BaseObserver] = (),
        invariants: Mapping[str, float] | None = None,
        schedule: Mapping[str, Callable[[float], float | npt.ArrayLike]] | None = None,
        clock: BaseClock | None = None,
        checked: bool = False,
        record_draws: bool = False,
        replay: Trajectory | None = None,
    ) -> Trajectory:
        """Simulate the prepared system, for 50 units of time every 0.5 with Hamiltonian dynamics by default.

        The arguments are those of `BaseSystem.simulate`, whose end time and time between frames default to those of
        the dynamics.

        Args:
            until:
                The end time, or `None` for 50 with Hamiltonian dynamics and the tuned one otherwise.

            dt:
                The time between frames, or `None` for 0.5 with Hamiltonian dynamics and the tuned one otherwise.

            initial_state:
                Initial values by dotted state name, such as `{'ball.x': 20.0}`, or `None` for the tuned or the declared
                ones.

            random_state:
                The seed or the generator of the random numbers of the run, or `None` for fresh entropy.

            observables:
                The observables to record, or none for the tuned ones.

            observers:
                The observers that watch the run, such as a Rerun recording.

            invariants:
                The tolerance of each observable that must stay constant, or `None` for the tuned ones.

            schedule:
                The functions of time that drive parameters, by dotted name, or `None` for the tuned ones.

            clock:
                The clock that paces the run, or `None` to run as fast as possible.

            checked:
                Whether every frame checks that states stay in their domains.

            record_draws:
                Whether the run records its random draws.

            replay:
                A trajectory whose recorded draws the run replays, or `None`.

        Returns:
            trajectory:
                The states and observables of the run at every frame.
        """
        if self.dynamics == 'hamiltonian':
            until = MAXWELL_UNTIL if until is None else until
            dt = MAXWELL_DT if dt is None else dt
        return super().simulate(
            until,
            dt=dt,
            initial_state=initial_state,
            random_state=random_state,
            observables=observables,
            observers=observers,
            invariants=invariants,
            schedule=schedule,
            clock=clock,
            checked=checked,
            record_draws=record_draws,
            replay=replay,
        )

Components

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

Elements:

Interactions:

  • WilsonSamplingInteraction, from Interaction
class GaugeLinkElement(Element):
    """Link of a lattice with an angle `theta`.

    The angle is the U(1) or Z_N variable of a lattice gauge theory.

    Args:
        label:
            The label of the link or the group on the links.

        theta:
            The angle of the link, or one angle per link, which wraps around the circle.

        space:
            The cell complex of the links, or `None` for one link.

        on:
            `'edges'` for one link on every edge of the complex, or `None`.

    Examples:
        >>> from skcomplex.systems.physics.waves import GaugeLinkElement
        >>> GaugeLinkElement('link', theta=0.5).theta
        0.5
    """

    visual = VisualSpec('cell', {'state': 'theta'})

    def __init__(
        self,
        label: str,
        *,
        theta: Annotated[object, Period(2 * math.pi)] = 0.0,
        space: BaseSpace | None = None,
        on: str | None = None,
    ) -> None:
        super().__init__(label, space=space, on=on)
        self.theta = theta

class WilsonSamplingInteraction(Interaction):
    """Boltzmann weight of link variables under the local Wilson action of the plaquettes of a link.

    For link angles the action is `-beta sum_p cos(theta_p)`, where `theta_p` is the oriented sum of the link angles
    around the plaquette `p`. It is the objective of every link, which the `MetropolisSolver` of the system moves, such
    as `MetropolisSolver(moves={'links.theta': 'rotate'}, schedule='colored', width=1.5)` for U(1) or
    `moves={'links.theta': 'random-value'}` for Z_N. For the matrices of a group `SU(N)` the action is
    `-(beta / N) sum_p Re tr U_p`, where `U_p` is the path-ordered product of the link matrices around `p`, and the
    interaction sweeps the links itself: the move `'rotate'` multiplies a link by a random matrix of the group near the
    identity of spread `width`, and `'random-value'` draws a uniform matrix of the group, `hits` times per link.

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

        target:
            The path of the group on the edges of a cell complex.

        beta:
            The inverse coupling of the Wilson action.

        state:
            The name of the state that holds the link angles or matrices.

        group:
            The matrix group of the links, or `None` for link angles.

        move:
            The move of matrix links, `'rotate'` or `'random-value'`, or a function of the matrices and the random
            generator.

        width:
            The spread of a rotation of matrix links.

        rule:
            The acceptance of the moves of matrix links, `'metropolis'` or `'glauber'`.

        schedule:
            The order of the moves of matrix links, `'colored'` or `'random-sequential'`.

        hits:
            The number of moves proposed per matrix link and sweep.

    Examples:
        >>> from skcomplex.systems.physics.common.fields import WilsonSamplingInteraction
        >>> WilsonSamplingInteraction('wilson', target='links', beta=2.0).beta
        2.0
        >>> from skcomplex.core.components import MatrixGroupSpec
        >>> color = WilsonSamplingInteraction('wilson', target='links', state='U', group=MatrixGroupSpec('SU', 3))
        >>> color.group.degree
        3
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        beta: Annotated[float, RealSet.closed_open(0, oo)] = 2.0,
        state: str = 'theta',
        group: MatrixGroupSpec | None = None,
        move: str | Callable[..., object] = 'rotate',
        width: float = 1.5,
        rule: str = 'metropolis',
        schedule: str = 'colored',
        hits: int = 1,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.beta = beta
        self.state = state
        self.group = group
        self.move = move
        self.width = width
        self.rule = rule
        self.schedule = schedule
        self.hits = hits

    def _get_score(self) -> HolonomyScoreSpec | None:
        """Return the holonomy score of matrix links, or `None` for link angles."""
        return None if self.group is None else HolonomyScoreSpec(self._get_trace_action, self.group, self.hits)

    def _get_action(self, namespace: SimpleNamespace) -> Expression:
        """Return the terms of the Wilson action that hold the angle of a link."""
        theta = getattr(namespace.target, self.state)
        return -namespace.beta * neighbors(cos(exterior_derivative(theta)), over=CofaceNeighborhood())

    def _get_trace_action(self, holonomies: ComplexArray, beta: float) -> Array:
        """Return the Wilson action `-(beta / N) Re tr U_p` of the plaquette holonomies."""
        degree = holonomies.shape[-1]
        return -beta / degree * np.trace(holonomies, axis1=-2, axis2=-1).real

    @staticmethod
    def _get_keywords(function: Callable[..., object], parameters: Mapping[str, object]) -> dict[str, object]:
        """Return the parameters that a function names."""
        try:
            names = inspect.signature(function).parameters
        except (TypeError, ValueError):
            return {}
        return {name: value for name, value in parameters.items() if name in names}

    def _check_arguments(self) -> None:
        """Raise an error for options matrix links do not take.

        Raises:
            ValidationError:
                The holonomy score of matrix links has a move, a rule, or a schedule they do not take.
        """
        super()._check_arguments()
        score = self._get_score()
        if score is not None:
            self._check_holonomy_score(score)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the action or the sweep of the links.

        Args:
            context:
                The namespace of the links, the time `t`, and the parameters.
        """
        super()._prepare(context)
        links = getattr(self._get_member(context, 'target'), self.state)
        if self._get_score() is None:
            self.laws_: list[BaseLaw] = [ObjectiveLaw(self._get_action(context), links)]
        else:
            self.laws_ = [UpdateLaw(links, self._sample_holonomies, label=self.label, arrays=True, stochastic=True)]

    def _check_holonomy_score(self, score: HolonomyScoreSpec) -> None:
        """Raise an error for a holonomy score with options a matrix group does not take.

        The options are a move, a rule, or a schedule.
        """
        score._check()
        if not callable(self.move) and self.move not in HOLONOMY_MOVES:
            error_msg = (
                f'The holonomy score of sampling {self.label!r} moves matrices of a group. Use the move '
                f'{" or ".join(map(repr, HOLONOMY_MOVES))}, or a function of the matrices and the random generator.'
            )
            raise ValidationError(error_msg)
        if self.rule == 'heat-bath':
            error_msg = f"The holonomy score of sampling {self.label!r} takes the rule 'metropolis' or 'glauber'."
            raise ValidationError(error_msg)
        if self.schedule not in HOLONOMY_SCHEDULES:
            error_msg = (
                f'The holonomy score of sampling {self.label!r} updates edges of a cell complex. Use the schedule '
                f'{" or ".join(map(repr, HOLONOMY_SCHEDULES))}.'
            )
            raise ValidationError(error_msg)

    @staticmethod
    @functools.cache
    def _get_staples(space: CellComplexSpace) -> tuple[tuple[Indices, ...], Indices, Array, Array, Array]:
        """Return the tables of the faces around every edge of a cell complex.

        They are read once per complex.

        Args:
            space:
                The prepared cell complex.

        Returns:
            classes:
                The classes of a proper coloring of the graph that joins the edges that share a face.

            edges:
                For every edge and face around it, the other edges of the face in path order after the edge.

            signs:
                The sign of the traversal of every edge of `edges`, 0 for padding.

            orientations:
                The sign of the traversal of the edge itself in every face around it.

            real:
                Whether every face around an edge is a face of the complex and not padding.
        """
        cofaces, boundaries, turns = space.cofaces_[1], space.boundaries_, space.boundary_signs_
        real = cofaces < boundaries.shape[0]
        faces = np.where(real, cofaces, 0)
        around, signs = boundaries[faces], turns[faces]
        lengths = (signs != 0).sum(axis=-1)
        position = np.argmax(around == np.arange(cofaces.shape[0])[:, None, None], axis=-1)
        orientations = np.take_along_axis(signs, position[..., None], axis=-1)[..., 0]
        steps = np.arange(max(boundaries.shape[1] - 1, 0))
        after = (position[..., None] + 1 + steps) % np.maximum(lengths, 1)[..., None]
        kept = (steps < lengths[..., None] - 1) & real[..., None]
        edges = np.where(kept, np.take_along_axis(around, after, axis=-1), 0)
        shared = (abs(space.incidences_[1]).T @ abs(space.incidences_[1])).tocoo()
        graph = nx.Graph()
        graph.add_nodes_from(range(cofaces.shape[0]))
        graph.add_edges_from(zip(shared.row.tolist(), shared.col.tolist(), strict=True))
        graph.remove_edges_from(nx.selfloop_edges(graph))
        colors = nx.greedy_color(graph, strategy=COLORING_STRATEGY)
        found = np.asarray([colors[edge] for edge in range(cofaces.shape[0])], dtype=np.intp)
        classes = tuple(np.flatnonzero(found == color) for color in range(int(found.max(initial=-1)) + 1))
        return classes, edges, np.where(kept, np.take_along_axis(signs, after, axis=-1), 0.0), orientations, real

    def _get_local_scores(
        self,
        matrices: ComplexArray,
        staples: ComplexArray,
        orientations: Array,
        real: Array,
        keywords: Mapping[str, object],
    ) -> Array:
        """Return the local objective of every edge.

        It is the score of the holonomies of its faces that start at it.
        """
        score = self._get_score()
        assert score is not None
        inverse = np.conj(np.swapaxes(matrices, -1, -2))
        oriented = np.where((orientations > 0)[..., None, None], matrices[:, None], inverse[:, None])
        values = np.asarray(score.function(oriented @ staples, **keywords), dtype=float)
        return np.where(real, values, 0.0).sum(axis=-1)

    def _propose_matrices(
        self,
        matrices: ComplexArray,
        group: MatrixGroupSpec,
        rng: np.random.Generator,
    ) -> ComplexArray:
        """Return the proposed matrices of some edges by the move."""
        if callable(self.move):
            return np.asarray(self.move(matrices.copy(), rng), dtype=complex)
        if self.move == 'random-value':
            return group.get_uniform_of(rng, len(matrices))
        return group.get_near_identity_of(rng, self.width, len(matrices)) @ matrices

    def _accept_changes(self, changes: Array, intensity: float, rng: np.random.Generator) -> npt.NDArray[np.bool_]:
        """Return whether the rule accepts every change of an objective at the intensity."""
        exponents = np.where(changes == 0.0, 0.0, changes * np.where(changes == 0.0, 1.0, intensity))
        draws = rng.random(changes.shape)
        with np.errstate(over='ignore'):
            if self.rule == 'metropolis':
                return (exponents <= 0.0) | (draws < np.exp(-np.maximum(exponents, 0.0)))
            return draws < 1.0 / (1.0 + np.exp(exponents))

    def _sample_holonomies(
        self,
        values: Array,
        *,
        random: np.random.Generator,
        time: float,
        space: BaseSpace,
        **parameters: object,
    ) -> Array:
        """Return a matrix group state on the edges of a cell complex after one sweep.

        The sweep makes moves of every edge.
        """
        score = self._get_score()
        if (
            score is None
            or not isinstance(space, CellComplexSpace)
            or values.ndim != MATRIX_AXES
            or values.shape[0] != len(space.cofaces_[1])
        ):
            error_msg = (
                f'The holonomy score of sampling {self.label!r} reads a group on the edges of a CellComplexSpace.'
            )
            raise ValidationError(error_msg)
        intensity = 1.0
        group = score.group
        matrices = group.get_matrices_of(values)
        classes, edges, signs, orientations, real = self._get_staples(space)
        keywords = self._get_keywords(score.function, parameters)
        order = classes if self.schedule == 'colored' else tuple(random.permutation(values.shape[0])[:, None])
        for links in order:
            local = {
                name: (
                    value[links][:, None]
                    if isinstance(value, np.ndarray) and value.shape[:1] == values.shape[:1]
                    else value
                )
                for name, value in keywords.items()
            }
            staples = group.get_holonomy_of(matrices, edges[links], signs[links])
            current = self._get_local_scores(matrices[links], staples, orientations[links], real[links], local)
            for _ in range(score.hits):
                proposal = self._propose_matrices(matrices[links], group, random)
                proposed = self._get_local_scores(proposal, staples, orientations[links], real[links], local)
                accepted = self._accept_changes(proposed - current, intensity, random)
                matrices[links[accepted]] = proposal[accepted]
                current = np.where(accepted, proposed, current)
        return group.get_components_of(group.get_projection_of(matrices))