Skip to content

Lattice Yang-Mills and pure lattice QCD

SU(2) or SU(3) matrices on the links of a periodic lattice.

  • Class: LatticeYangMillsSystem
  • Import: from skcomplex.systems.physics.waves import LatticeYangMillsSystem
  • Field: physics/waves
  • Topics: gauge, lattice, monte carlo, yang-mills, qcd, cell complex
  • References:
    • Satz 2022
    • Schwichtenberg 2020
    • Wilson 1974
    • Creutz 1980

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 LatticeYangMillsSystem

trajectory = LatticeYangMillsSystem().prepare().simulate()

Parameters

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

Parameter Default
size 6
dimension 4
extent None
colors 2
beta 2.3
width 0.5
hits 4
links None
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 update
Randomness unknown
Domains matrix group
Structure fixed

Class

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

class LatticeYangMillsSystem(BaseSystem):
    """SU(2) or SU(3) matrices on the links of a periodic lattice.

    The matrices are sampled by the Wilson action.

    The link matrices sample the Wilson action `-(beta / N) sum_p Re tr U_p` under discrete time, where `U_p` is the
    ordered product of the link matrices around the plaquette `p`, with the inverse of a link traversed against its
    orientation. Every sweep proposes `hits` Metropolis moves per link, each a product with a random matrix of the group
    near the identity, and projects the links back onto the group. SU(2) is the isospin connection of the weak force,
    and SU(3) the color connection of the strong force, so that SU(3) is pure lattice QCD. The last axis has `extent`
    sites, the inverse temperature of the lattice, along which the Polyakov loop winds. In two dimensions the plaquettes
    are independent, and the SU(2) mean plaquette at large size is `I_2(beta) / I_1(beta)`.

    Args:
        size:
            The number of sites along every axis but the last.

        dimension:
            The number of axes of the lattice.

        extent:
            The number of sites along the last axis, or `None` for `size`.

        colors:
            The degree `N` of the group SU(N), 2 or 3.

        beta:
            The inverse coupling of the Wilson action, `2 N / g^2`.

        width:
            The spread around the identity of the matrices that move a link.

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

        links:
            The initial link matrices, one `N` by `N` complex matrix per link, or `None` for matrices drawn from the
            Haar measure of the group.

        seed:
            The seed of the initial link matrices.

        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 number of colors is not 2 or 3, or the initial links do not hold one matrix of the group per link.

    Examples:
        >>> from skcomplex.systems.physics.waves import LatticeYangMillsSystem
        >>> [element.label for element in LatticeYangMillsSystem(2, dimension=2).prepare().system_.elements]
        ['links']
        >>> type(LatticeYangMillsSystem(2, dimension=2, colors=3).prepare().system_.elements[0]).__name__
        'ColorLinkElement'
    """

    field = 'physics/waves'
    topics = ('gauge', 'lattice', 'monte carlo', 'yang-mills', 'qcd', 'cell complex')
    references = ('Satz 2022', 'Schwichtenberg 2020', 'Wilson 1974', 'Creutz 1980')
    until = 100
    dt = 1

    @staticmethod
    def _get_mean_plaquette(
        space: CellComplexSpace,
        group: MatrixGroupSpec,
        t: float,
        values: Mapping[str, object],
    ) -> float:
        """Return the mean of `Re tr U_p / N` over the plaquettes."""
        del t
        matrices = group.get_matrices_of(np.reshape(np.asarray(values['links.U'], dtype=float), (-1, group.size)))
        plaquettes = group.get_holonomy_of(matrices, space.boundaries_, space.boundary_signs_)
        return float(np.trace(plaquettes, axis1=-2, axis2=-1).real.mean() / group.degree)

    @staticmethod
    def _get_polyakov_loop(
        space: CellComplexSpace,
        group: MatrixGroupSpec,
        t: float,
        values: Mapping[str, object],
    ) -> float:
        """Return the modulus of the mean of `tr P / N` over the loops along the last axis.

        The loops wind along the last axis.
        """
        del t
        links = np.reshape(np.asarray(values['links.U'], dtype=float), (-1, group.size))
        return float(gauge_observables(links, kind='polyakov', space=space, group=group).value[0])

    def __init__(
        self,
        size: int = 6,
        *,
        dimension: int = 4,
        extent: int | None = None,
        colors: int = 2,
        beta: float = 2.3,
        width: float = 0.5,
        hits: int = 4,
        links: npt.ArrayLike | None = None,
        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.extent = extent
        self.colors = colors
        self.beta = beta
        self.width = width
        self.hits = hits
        self.links = links
        self.seed = seed

    @staticmethod
    def _get_yang_mills_observables(space: CellComplexSpace, group: MatrixGroupSpec) -> list[Observable]:
        """Return the mean plaquette and the Polyakov loop of the links."""
        return [
            Observable(
                'mean_plaquette',
                function=partial(LatticeYangMillsSystem._get_mean_plaquette, space, group),
            ),
            Observable('polyakov_loop', function=partial(LatticeYangMillsSystem._get_polyakov_loop, space, group)),
        ]

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to SU(2) or SU(3) matrices on the links of a periodic lattice, sampled by the Wilson action.

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

        Raises:
            ValidationError:
                The number of colors is not 2 or 3, or the initial links do not fit the lattice and the group.
        """
        super()._prepare(context)
        if self.colors not in LINKS:
            error_msg = f'The lattice gauge group is SU(2) or SU(3), so colors is 2 or 3, but got {self.colors!r}.'
            raise ValidationError(error_msg)
        element, group = LINKS[self.colors]
        shape = (self.size,) * (self.dimension - 1) + (self.size if self.extent is None else self.extent,)
        space = CellComplexSpace(LatticeSpace(shape)).prepare()
        count = space.incidences_[0].shape[0]
        if self.links is None:
            matrices = group.get_uniform_of(np.random.default_rng(self.seed), count)
        else:
            matrices = np.asarray(self.links, dtype=complex)
        if matrices.shape != (count, self.colors, self.colors) or not np.allclose(
            group.get_projection_of(matrices),
            matrices,
        ):
            error_msg = (
                f'The initial links are {matrices.shape[0]} matrices of the shape {matrices.shape[1:]}, but the '
                f'lattice takes {count} matrices of SU({self.colors}), one per link.'
            )
            raise ValidationError(error_msg)
        group_links = element('links', U=group.get_components_of(matrices), space=space, on='edges')
        sampling = WilsonSamplingInteraction(
            'wilson',
            target='links',
            beta=self.beta,
            state='U',
            width=self.width,
            group=group,
            hits=self.hits,
        )
        self.system_ = System(self.label, elements=[group_links], interactions=[sampling])
        self.observables_ = tuple(self._get_yang_mills_observables(space, group))

Components

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

Elements:

Interactions:

  • WilsonSamplingInteraction, from Interaction
class IsospinLinkElement(Element):
    """Link of a lattice with an SU(2) matrix `U`.

    The matrix is the parallel transport of isospin along the link.

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

        U:
            The real components of the matrix of the link, the identity by default.

        space:
            The cell complex whose edges hold one link each, or `None` for one link.

        on:
            `'edges'` for one link per edge of the space.

    Examples:
        >>> from skcomplex.systems.physics.waves import IsospinLinkElement
        >>> len(IsospinLinkElement('link').U)
        8
    """

    def __init__(
        self,
        label: str,
        *,
        U: Annotated[object, ISOSPIN] = tuple(ISOSPIN.identity),
        space: BaseSpace | None = None,
        on: str | None = None,
    ) -> None:
        super().__init__(label, space=space, on=on)
        self.U = U

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))