Skip to content

Allen-Cahn non-conserved relaxation (System A)

The Allen-Cahn equation, System A.

  • Class: AllenCahnSystem
  • Import: from skcomplex.systems.physics.pattern_formation import AllenCahnSystem
  • Field: physics/pattern_formation
  • Topics: field, phase ordering, coarsening, system a, spectral, pde
  • References:
    • Brauns and Marchetti 2024
    • Allen and Cahn 1979
    • Cahn and Hilliard 1958
    • Bray 1994

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.pattern_formation import AllenCahnSystem

trajectory = AllenCahnSystem().prepare().simulate()

Parameters

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

Parameter Default
shape (128, 128)
length 128.0
mean 0.0
kappa 1.0
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 continuous
Space lattice
Laws rate
Randomness deterministic
Domains real
Structure fixed

Class

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

class AllenCahnSystem(BaseSystem):
    """The Allen-Cahn equation, System A.

    It is the non-conserved relaxation of an order parameter in a double well.

    The order parameter follows `phi_t = phi - phi^3 + kappa laplacian(phi)`, the gradient descent of the free energy
    density `-phi^2 / 2 + phi^4 / 4 + kappa |grad(phi)|^2 / 2`. From small noise, domains of `phi = 1` and `phi = -1`
    form and coarsen as their walls move by curvature, so their size grows as `t^(1/2)`. The mean of `phi` is not
    conserved, and a domain shrinks away instead of exchanging material with its neighbours. The system has the field
    `mixture.phi`.

    Args:
        shape:
            The number of sites along every axis of the periodic lattice.

        length:
            The side of the domain.

        mean:
            The mean of the initial noise.

        kappa:
            The stiffness of the domain walls.

        random_state:
            The seed or generator of the initial noise of amplitude 0.05.

        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 exponential steps of 0.5.

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

    Examples:
        >>> from skcomplex.systems.physics.pattern_formation import AllenCahnSystem
        >>> AllenCahnSystem((8, 8), kappa=2.0).prepare().system_.interactions[0].kappa
        2.0
    """

    field = 'physics/pattern_formation'
    topics = ('field', 'phase ordering', 'coarsening', 'system a', 'spectral', 'pde')
    references = REFERENCES
    until = 100.0
    dt = 1.0

    @staticmethod
    def _get_ordering(
        label: str,
        *,
        shape: Sequence[int],
        length: float,
        mean: float,
        kappa: float,
        random_state: int | np.random.Generator | None,
        conserved: bool,
        step: float,
        temperature: float = 0.0,
    ) -> System:
        """Return a system of a label with a phase field that relaxes.

        The field starts from small noise around a mean, and exponential steps of a size solve it.

        A positive temperature adds the conserved thermal noise, on finite differences instead of the spectral lattice,
        and leaves the solver to the system.
        """
        shape = tuple(shape)
        rng = np.random.default_rng(random_state)
        phi = mean + 0.05 * rng.uniform(-1.0, 1.0, shape)
        discretization = 'finite-difference' if temperature else 'spectral'
        space = LatticeSpace(shape, spacing=length / shape[0], discretization=discretization)
        interactions: list[BaseInteraction] = [
            LandauEnergyInteraction('energy', target='mixture', kappa=kappa, conserved=conserved),
        ]
        if temperature:
            noise = Interaction(
                'noise',
                roles={'target': 'mixture'},
                laws=lambda s: [NoiseLaw(s.target.phi, math.sqrt(2 * temperature), conserved=True)],
            )
            interactions.append(noise)
        return System(
            label,
            elements=[PhaseFieldElement('mixture', phi=phi.ravel(), space=space)],
            interactions=interactions,
            solver='auto' if temperature else ETDRK4Solver(dt=step),
        )

    def __init__(
        self,
        shape: Sequence[int] = (128, 128),
        *,
        length: float = 128.0,
        mean: float = 0.0,
        kappa: float = 1.0,
        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.shape = shape
        self.length = length
        self.mean = mean
        self.kappa = kappa
        self.random_state = random_state

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of a phase field that relaxes without conserving its mean.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        self.system_ = AllenCahnSystem._get_ordering(
            self.label,
            shape=self.shape,
            length=self.length,
            mean=self.mean,
            kappa=self.kappa,
            random_state=self.random_state,
            conserved=False,
            step=0.5,
        )

Components

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

Elements:

Interactions:

class PhaseFieldElement(Element):
    """Sites of a phase field.

    Every site holds the order parameter `phi` that free energies and noise move.

    Args:
        label:
            The label of the field.

        phi:
            The initial order parameter, one value per site or one for all.

        space:
            The lattice of the sites, or `None` for one site.

    Examples:
        >>> from skcomplex.systems.physics.pattern_formation._ordering import PhaseFieldElement
        >>> PhaseFieldElement('site', phi=0.5).phi
        0.5
    """

    def __init__(self, label: str, *, phi: object = 0.0, space: BaseSpace | None = None) -> None:
        super().__init__(label, space=space)
        self.phi = phi

class LandauEnergyInteraction(GradientInteraction):
    """Gradient flow of a field `phi` in the Landau free energy of a double well.

    The energy has a cost of gradients.

    The free energy is `F = integral -phi^2 / 2 + phi^4 / 4 + kappa |grad phi|^2 / 2`. Its functional derivative is
    the chemical potential `mu = -phi + phi^3 - kappa laplacian(phi)`. A non-conserved field relaxes as `phi_t = -mu`,
    the Allen-Cahn equation of system A, and a conserved field as `phi_t = laplacian(mu)`, the Cahn-Hilliard equation of
    system B, whose total stays constant.

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

        target:
            The path of the field.

        state:
            The name of the state of the field that holds the order parameter.

        kappa:
            The cost of gradients, the square of the width of the interfaces.

        conserved:
            Whether the order parameter is conserved.

    Examples:
        >>> from types import SimpleNamespace
        >>> from sage.all__sagemath_symbolics import var
        >>> from skcomplex.systems.physics.pattern_formation._ordering import LandauEnergyInteraction
        >>> energy = LandauEnergyInteraction('energy', target='mixture')
        >>> namespace = SimpleNamespace(target=SimpleNamespace(phi=var('phi')), kappa=var('kappa'))
        >>> [law.value for law in energy.prepare(namespace).laws_]
        [-phi^3 + kappa*laplacian(phi) + phi]
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str = 'phi',
        kappa: Annotated[float, RealSet.open(0, oo)] = 1.0,
        conserved: bool = False,
    ) -> None:
        super().__init__(label, target=target, states=state, variational=True, conserved=conserved)
        self.state = state
        self.kappa = kappa

    def _get_potential(self, namespace: SimpleNamespace) -> Expression:
        """Return the density `-phi^2 / 2 + phi^4 / 4 - kappa phi laplacian(phi) / 2`.

        The gradient term is taken by parts.

        Args:
            namespace:
                The namespace of the symbols the density can use.

        Returns:
            density:
                The density of the free energy.
        """
        phi = getattr(namespace.target, self.state)
        return -(phi**2) / 2 + phi**4 / 4 - namespace.kappa * phi * laplacian(phi) / 2