Skip to content

Kuramoto

Kuramoto oscillators coupled all to all.

  • Class: KuramotoSystem
  • Import: from skcomplex.systems.physics.synchronization import KuramotoSystem
  • Field: physics/synchronization
  • Topics: synchronization, oscillators, phase, mean field
  • References:
    • Kuramoto 1984
    • Datseris and Parlitz 2022
    • Gros 2015
    • 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.synchronization import KuramotoSystem

trajectory = KuramotoSystem().prepare().simulate()

Parameters

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

Parameter Default
n_oscillators 50
K 4.0
sigma 1.0
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 continuous
Space none
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 KuramotoSystem(BaseSystem):
    """Kuramoto oscillators coupled all to all.

    The oscillators follow `theta_i' = omega_i + (K / N) sum_j sin(theta_j - theta_i)`.

    Every oscillator reads the group means of `cos theta` and `sin theta`, so the coupling costs time linear in the
    number of oscillators. The natural frequencies are drawn from a normal distribution of width `sigma`, and the phases
    uniformly from the circle. Above the critical coupling `K_c = 2 sigma sqrt(2 / pi)` a synchronized cluster forms,
    and the order parameter `r`, the modulus of the mean of `exp(i theta)`, grows from about `1 / sqrt(N)` towards 1.
    The system has the phases `oscillators.theta` and the order parameter `order`.

    Args:
        n_oscillators:
            The number of oscillators.

        K:
            The coupling strength.

        sigma:
            The standard deviation of the natural frequencies.

        seed:
            The seed of the natural frequencies and the initial phases.

        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.synchronization import KuramotoSystem
        >>> system = KuramotoSystem(10).prepare().system_
        >>> system.elements[0].size, system.space
        (10, None)
    """

    field = 'physics/synchronization'
    topics = ('synchronization', 'oscillators', 'phase', 'mean field')
    references = ('Kuramoto 1984', 'Datseris and Parlitz 2022', 'Gros 2015', 'Jensen 2023')
    until = 50.0
    dt = 0.5
    observables = tuple(order_parameter('order', 'oscillators'))

    @staticmethod
    def _spread_phases(size: int, seed: int) -> list[float]:
        """Return phases drawn uniformly from the circle with a seed."""
        return [float(phase) for phase in np.random.default_rng(seed).uniform(0, 2 * math.pi, size)]

    def __init__(
        self,
        n_oscillators: int = 50,
        *,
        K: float = 4.0,
        sigma: float = 1.0,
        seed: int = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.n_oscillators = n_oscillators
        self.K = K
        self.sigma = sigma
        self.seed = seed

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of Kuramoto oscillators coupled all to all.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        rng = np.random.default_rng(self.seed)
        oscillators = PhaseOscillatorElement(
            'oscillators',
            theta=KuramotoSystem._spread_phases(self.n_oscillators, self.seed),
            omega=rng.normal(0.0, self.sigma, self.n_oscillators),
            size=self.n_oscillators,
        )
        interactions = [
            PhaseRotationInteraction('rotation', target='oscillators'),
            KuramotoCouplingInteraction('coupling', target='oscillators', K=self.K, reduce='mean', include_self=True),
        ]
        self.system_ = System(self.label, elements=[oscillators], interactions=interactions)

Components

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

Elements:

  • PhaseOscillatorElement, from Element

Interactions:

  • PhaseRotationInteraction, from Interaction
  • KuramotoCouplingInteraction, from Interaction
class PhaseOscillatorElement(Element):
    """Phase oscillator, a phase `theta` on the circle with a natural frequency `omega`.

    The phase wraps around the circle, and `PhaseRotationInteraction` turns it at the natural frequency, as for a
    clock, a firefly, or a generator of a power grid. Couplings to other oscillators add to the rate of the phase.

    Args:
        label:
            The label of the oscillator or the group.

        theta:
            The initial phase, or one phase per member.

        omega:
            The natural frequency, or one frequency per member.

        size:
            The number of oscillators, or `None` for one or one per site of the space.

        space:
            The space of the oscillators, or `None` for none.

        on:
            `'edges'` or `'hyperedges'` for one oscillator on every link of a network, or `None` for its sites.

        values:
            Further values by name, or `None`.

    Examples:
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.oscillators import PhaseOscillatorElement, PhaseRotationInteraction
        >>> clock = PhaseOscillatorElement('clock', omega=2.0)
        >>> system = System(elements=[clock], interactions=[PhaseRotationInteraction('turn', target='clock')])
        >>> float(system.prepare().simulate(until=1.0, dt=0.5).get_values('clock.theta')[-1])
        2.0
    """

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

class PhaseRotationInteraction(Interaction):
    """Rotation of the phase `theta` of an oscillator at its natural frequency `omega`, `theta' = omega`.

    The target holds the phase and the frequency, one of each per member of a group. Couplings to other oscillators add
    to the rate of the phase, as for a clock, a firefly, or a generator of a power grid.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the oscillator or the group of oscillators.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.oscillators import PhaseRotationInteraction
        >>> clocks = Element('clocks', values={'theta': 0.0, 'omega': [1.0, 2.0]}, size=2)
        >>> system = System(elements=[clocks], interactions=[PhaseRotationInteraction('turn', target='clocks')])
        >>> system.prepare().simulate(until=1.0, dt=0.5).get_values('clocks.theta')[-1].tolist()
        [1.0, 2.0]
    """

    law_classes = (RateLaw,)

    def __init__(self, label: str, *, target: Role) -> None:
        super().__init__(label)
        self.target = target

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate of the phase of the target.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        oscillator = context.target
        self.laws_ = [RateLaw(oscillator.theta.diff(context.t), oscillator.omega)]

class KuramotoCouplingInteraction(Interaction):
    """Kuramoto coupling `theta_i' += K sum_j sin(theta_j - theta_i - alpha)` of the phases of a group.

    The sum, or the mean, runs over every other member of the group, or over the members within a neighbourhood such
    as `RadiusNeighborhood(r)`. With `include_self` it also runs over `j = i`, whose term `-K sin(alpha)` slows every
    phase. Over the whole group, the coupling reads the group sums of `sin theta` and `cos theta` once, so it costs time
    linear in the size of the group, as for fireflies that all see each other or the generators of one grid.

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

        target:
            The path of the group of oscillators.

        K:
            The coupling strength of one pair.

        alpha:
            The phase lag.

        reduce:
            `'sum'` or `'mean'`.

        include_self:
            Whether the sum also runs over the member itself.

        neighborhood:
            The neighbourhood of every member, or `None` for the whole group.

    Raises:
        ValidationError:
            The reduction is neither `'sum'` nor `'mean'`.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.oscillators import PhaseOscillatorElement
        >>> from skcomplex.systems.physics.synchronization import KuramotoCouplingInteraction
        >>> phases = PhaseOscillatorElement('phases', theta=[0.0, 1.0, 2.0, 3.0], size=4)
        >>> coupling = KuramotoCouplingInteraction('coupling', target='phases', K=2.0, reduce='mean')
        >>> system = System(elements=[phases], interactions=[coupling]).prepare()
        >>> theta = system.simulate(until=20.0, dt=1.0).get_values('phases.theta')
        >>> round(float(np.ptp(theta[-1])), 6)
        0.0
    """

    law_classes = (RateLaw,)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        K: float = 1.0,
        alpha: float = 0.0,
        reduce: str = 'sum',
        include_self: bool = False,
        neighborhood: BaseNeighborhood | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.K = K
        self.alpha = alpha
        self.reduce = reduce
        self.include_self = include_self
        self.neighborhood = neighborhood

    def _get_group_sum(self, context: SimpleNamespace) -> tuple[Expression, Expression]:
        """Return the sum of the sines over the whole group and the number of terms, from the group sums."""
        theta = context.target.theta
        shifted = theta + context.alpha
        sines, cosines = total(sin(theta)), total(cos(theta))
        summed = sines * cos(shifted) - cosines * sin(shifted)
        if self.include_self:
            return summed, count()
        return summed + sin(context.alpha), count() - 1

    def _get_neighbour_sum(self, context: SimpleNamespace) -> tuple[Expression, Expression]:
        """Return the sum of the sines over the neighbourhood and the number of terms."""
        theta, other = context.target.theta, context.target.other.theta
        summed = neighbors(sin(other - theta - context.alpha), over=self.neighborhood)
        terms = neighbors(SR(1), over=self.neighborhood)
        if self.include_self:
            return summed - sin(context.alpha), terms + 1
        return summed, terms

    def _check_arguments(self) -> None:
        """Raise an error for an argument the interaction cannot take.

        Raises:
            ValidationError:
                The reduction is neither `'sum'` nor `'mean'`.
        """
        super()._check_arguments()
        if self.reduce not in REDUCTIONS:
            error_msg = f'Unknown reduction {self.reduce!r}. Use one of {", ".join(REDUCTIONS)}.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate of the phases from the lagged sines of the other phases.

        Args:
            context:
                The namespace of the target, the time `t`, and the parameters.
        """
        super()._prepare(context)
        get_sum = self._get_group_sum if self.neighborhood is None else self._get_neighbour_sum
        summed, terms = get_sum(context)
        rate = context.K * summed if self.reduce == 'sum' else context.K * summed / terms
        self.laws_ = [RateLaw(context.target.theta.diff(context.t), rate)]

Equations

The equations are those that symbolic returns for the system with its default parameters.

oscillators.theta[i]: diff(theta_oscillators(t), t) == (_reduced_1*cos(alpha_coupling + theta_oscillators(t)) - _reduced_2*sin(alpha_coupling + theta_oscillators(t)))*K_coupling/_reduced_0 + omega_oscillators