Skip to content

Quasi-geostrophic double gyre

The quasi-geostrophic double gyre.

  • Class: DoubleGyreSystem
  • Import: from skcomplex.systems.physics.oceanography import DoubleGyreSystem
  • Field: physics/oceanography
  • Topics: quasi-geostrophic, gyre, western boundary current, field, inversion, pde
  • References:
    • Munk 1950
    • arXiv:1910.00583

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.oceanography import DoubleGyreSystem

trajectory = DoubleGyreSystem().prepare().simulate()

Parameters

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

Parameter Default
n_sites 64
length 1.0
beta 1.0
Rd 1.0
nu 0.000125
tau0 1e-05
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 unknown
Domains real
Structure fixed

Class

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

class DoubleGyreSystem(BaseSystem):
    """The quasi-geostrophic double gyre.

    It is the wind-driven circulation of a closed ocean basin.

    The potential vorticity `q = laplacian(psi) - psi / Rd**2 + beta y` of a square basin of side `length` is carried by
    the geostrophic velocity `(-psi_y, psi_x)` of the streamfunction `psi`, driven by the curl of the wind stress
    `-tau0 cos(2 pi y / length)`, and damped by the viscosity `nu`. The state is the relative potential vorticity
    `zeta = q - beta y`, held at zero on the walls for free slip, so that

        zeta_t + divergence(u zeta) = -beta psi_x - tau0 (2 pi / length) sin(2 pi y / length) + nu laplacian(zeta),

    with `psi = inverse_helmholtz(zeta, 1 / Rd, ('fixed', 0))`. In the viscous steady regime the interior follows the
    Sverdrup balance `beta psi_x = curl(tau)`, and the return flow closes in Munk western boundary layers of width `(nu
    / beta) ** (1 / 3)`, so the streamfunction forms a subtropical and a subpolar gyre of opposite sign whose extrema
    lie close to the western wall. The defaults keep the wind weak, so the boundary layers stay viscous rather than
    inertial, and the circulation is steady after a few hundred units of time. The catalog entry streams the
    streamfunction as the observable `psi`. The system has the relative potential vorticity `basin.zeta`.

    Args:
        n_sites:
            The number of sites along each side of the basin.

        length:
            The side of the basin.

        beta:
            The gradient of the planetary vorticity.

        Rd:
            The deformation radius.

        nu:
            The viscosity.

        tau0:
            The amplitude of the wind stress.

        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.oceanography import DoubleGyreSystem
        >>> DoubleGyreSystem(16).prepare().system_.elements[0].beta
        1.0
    """

    field = 'physics/oceanography'
    topics = ('quasi-geostrophic', 'gyre', 'western boundary current', 'field', 'inversion', 'pde')
    references = ('Munk 1950', 'arXiv:1910.00583')
    until = 400.0
    dt = 0.4
    observables = (Observable('psi', _get_streamfunction, group='basin', reduce=_get_sites),)

    def __init__(
        self,
        n_sites: int = 64,
        *,
        length: float = 1.0,
        beta: float = 1.0,
        Rd: float = 1.0,
        nu: float = 1.25e-4,
        tau0: float = 1e-5,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.n_sites = n_sites
        self.length = length
        self.beta = beta
        self.Rd = Rd
        self.nu = nu
        self.tau0 = tau0

    @staticmethod
    def _get_velocity(s: SimpleNamespace) -> list[Expression]:
        """Return the geostrophic velocity of a site, `(-psi_y, psi_x)`."""
        streamfunction = _get_streamfunction(s.target)
        return [-partial(streamfunction, 1), partial(streamfunction, 0)]

    @staticmethod
    def _get_beta_drift(s: SimpleNamespace) -> Expression:
        """Return the advection of the planetary vorticity, `-beta psi_x`."""
        drift: Expression = -s.target.beta * partial(_get_streamfunction(s.target), 0)
        return drift

    @staticmethod
    def _get_viscosity(s: SimpleNamespace) -> Expression:
        """Return the viscosity of a site."""
        viscosity: Expression = s.target.nu
        return viscosity

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the wind-driven circulation of a closed ocean basin.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        spacing = self.length / self.n_sites
        latitudes = (np.arange(self.n_sites) + 0.5) * spacing
        curl = -self.tau0 * (2 * np.pi / self.length) * np.sin(2 * np.pi * latitudes / self.length)
        basin = QuasiGeostrophicSiteElement(
            'basin',
            zeta=np.zeros(self.n_sites**2),
            beta=self.beta,
            Rd=self.Rd,
            nu=self.nu,
            curl=np.broadcast_to(curl, (self.n_sites, self.n_sites)).ravel(),
            space=LatticeSpace((self.n_sites, self.n_sites), spacing=spacing, boundary='fixed'),
        )
        transport = AdvectionInteraction(
            'transport',
            target='basin',
            state='zeta',
            drift=self._get_velocity,
            source=self._get_beta_drift,
        )
        wind = WindStressInteraction('wind', target='basin')
        viscosity = DiffusivityInteraction('viscosity', target='basin', state='zeta', coefficient=self._get_viscosity)
        self.system_ = System(
            self.label,
            elements=[basin],
            interactions=[transport, wind, viscosity],
            solver=RK4Solver(dt=0.4),
        )

Components

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

Elements:

  • QuasiGeostrophicSiteElement, from Element

Interactions:

  • AdvectionInteraction, from Interaction
  • WindStressInteraction, from Interaction
  • DiffusivityInteraction, from Interaction
class QuasiGeostrophicSiteElement(Element):
    """Sites of a quasi-geostrophic ocean basin.

    Every site holds the relative potential vorticity of the water column at one position.

    A site holds the relative potential vorticity `zeta = laplacian(psi) - psi / Rd**2`, the potential vorticity
    without the planetary part `beta y`, with the planetary vorticity gradient `beta`, the deformation radius `Rd`, the
    viscosity `nu`, and the curl of the wind stress `curl` at the site.

    Args:
        label:
            The label of the basin.

        zeta:
            The initial relative potential vorticity, one value or one per site.

        beta:
            The gradient of the planetary vorticity.

        Rd:
            The deformation radius.

        nu:
            The viscosity.

        curl:
            The curl of the wind stress, one value or one per site.

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

    Examples:
        >>> from skcomplex.systems.physics.oceanography import QuasiGeostrophicSiteElement
        >>> QuasiGeostrophicSiteElement('site').beta
        1.0
    """

    def __init__(
        self,
        label: str,
        *,
        zeta: object = 0.0,
        beta: Annotated[float, RealSet.open(0, oo)] = 1.0,
        Rd: Annotated[float, RealSet.open(0, oo)] = 1.0,
        nu: Annotated[float, RealSet.open(0, oo)] = 1e-4,
        curl: object = 0.0,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.zeta = zeta
        self.beta = beta
        self.Rd = Rd
        self.nu = nu
        self.curl = curl

class AdvectionInteraction(Interaction):
    """Advection `du/dt + divergence(a u) = source(ns)` of a state `u` of a field by a drift.

    Physics names it advection, the transport of a state by a flow or by the streaming of a phase-space density.
    The drift field is `a(ns)`. The flux of the conservation law is the drift times the state, written in conservative
    form, so the total of the state on a periodic field stays constant and, on a spectral field, the dealiasing of
    products applies to it. The drift is one expression for a field of one dimension, or one per dimension, of the
    states and parameters of the field, and may read other states than the one it carries, such as the flow of a fluid
    derived from a streamfunction, or the drift of a probability density in a Fokker-Planck equation.

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

        target:
            The path of the field whose state is carried.

        state:
            The name of the carried state of the field.

        drift:
            A function of the namespace that returns the drift, or one drift per dimension.

        source:
            A function of the namespace that returns the source, or `None` for none.

    Raises:
        ValidationError:
            The state is not a name, or a function is not callable.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.components.spaces import LatticeSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.fields import AdvectionInteraction
        >>> space = LatticeSpace((50,), spacing=0.1, boundary='periodic', discretization='finite-volume')
        >>> values = {'u': np.exp(-((np.arange(50) - 25) / 5.0) ** 2)}
        >>> tracer = Element('tracer', values=values, space=space)
        >>> drift = AdvectionInteraction('drift', target='tracer', state='u', drift=lambda s: 1.0)
        >>> trajectory = System(elements=[tracer], interactions=[drift]).prepare().simulate(until=1.0, dt=0.01)
        >>> total = trajectory.get_values('tracer.u')[-1].sum()
        >>> round(float(total), 6) == round(float(values['u'].sum()), 6)
        True
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str = 'u',
        drift: Callable[[SimpleNamespace], object] | None = None,
        source: Callable[[SimpleNamespace], object] | None = None,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.drift = drift
        self.source = source

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

        Raises:
            ValidationError:
                The state is not a name, the drift is not callable, or the source is neither callable nor `None`.
        """
        super()._check_arguments()
        if not isinstance(self.state, str) or not self.state.isidentifier():
            error_msg = f'{type(self).__name__} {self.label!r} carries the state {self.state!r}, which is no name.'
            raise ValidationError(error_msg)
        if not callable(self.drift):
            error_msg = f'The drift of {self.label!r} is {self.drift!r}. Give a function of the namespace.'
            raise ValidationError(error_msg)
        if self.source is not None and not callable(self.source):
            error_msg = f'The source of {self.label!r} is {self.source!r}. Give a function of the namespace.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate of the divergence of the flux `a u` and the rate of the source.

        Args:
            context:
                The namespace of the field, the time `t`, and the parameters.
        """
        super()._prepare(context)
        u = getattr(context.target, self.state)
        drift = cast('Callable[[SimpleNamespace], object]', self.drift)(context)
        components = drift if isinstance(drift, FreeModuleElement | list | tuple) else [drift]
        self.laws_ = [RateLaw(u, -divergence([SR(component) * u for component in components]))]
        if self.source is not None:
            self.laws_.append(RateLaw(u, self.source(context)))

class WindStressInteraction(Interaction):
    """Input of vorticity into a basin by the curl of the wind stress.

    The relative potential vorticity `zeta` of every site of the target grows at the curl `curl` of the wind stress at
    the site, `zeta' = curl`.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the basin.

    Examples:
        >>> from skcomplex.systems.physics.oceanography import WindStressInteraction
        >>> WindStressInteraction('wind', target='basin').target
        'basin'
    """

    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 vorticity of the basin to the curl of the wind stress.

        Args:
            context:
                The namespace of the basin and the time `t`.
        """
        super()._prepare(context)
        zeta = context.target.zeta
        self.laws_ = [RateLaw(zeta.diff(context.t), context.target.curl)]

class DiffusivityInteraction(Interaction):
    """Diffusion `du/dt = D laplacian(u)` of a state `u` of a field by a diffusivity `D`.

    Physics names the coefficient a diffusivity, as the thermal diffusivity of heat conduction or the kinematic
    viscosity of the vorticity of a fluid. The diffusivity is uniform in space, a number or a function of the namespace
    that returns an expression of parameters and time. The rate is the Laplacian of the field, which its discretization
    evaluates, so the total of the state on a periodic field stays constant and a point mass spreads as the heat kernel.

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

        target:
            The path of the field whose state diffuses.

        state:
            The name of the state of the field that diffuses.

        coefficient:
            A function of the namespace that returns the diffusivity, or a number.

    Raises:
        ValidationError:
            The state is not a name, or the coefficient is neither callable nor a number.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.components.spaces import LatticeSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.fields import DiffusivityInteraction
        >>> space = LatticeSpace((40,), spacing=0.1, boundary='periodic')
        >>> rod = Element('rod', values={'u': np.eye(40)[20]}, space=space)
        >>> heat = DiffusivityInteraction('heat', target='rod', state='u', coefficient=0.1)
        >>> trajectory = System(elements=[rod], interactions=[heat]).prepare().simulate(until=1.0, dt=0.01)
        >>> round(float(trajectory.get_values('rod.u')[-1].sum()), 6)
        1.0
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str = 'u',
        coefficient: Callable[[SimpleNamespace], object] | float = 1.0,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.coefficient = coefficient

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

        Raises:
            ValidationError:
                The state is not a name, or the coefficient is neither callable nor a number.
        """
        super()._check_arguments()
        if not isinstance(self.state, str) or not self.state.isidentifier():
            error_msg = f'{type(self).__name__} {self.label!r} diffuses the state {self.state!r}, which is no name.'
            raise ValidationError(error_msg)
        if not (callable(self.coefficient) or isinstance(self.coefficient, int | float)):
            error_msg = f'The coefficient of {self.label!r} is {self.coefficient!r}. Give a function or a number.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate `D laplacian(u)` of the state.

        Args:
            context:
                The namespace of the field, the time `t`, and the parameters.
        """
        super()._prepare(context)
        u = getattr(context.target, self.state)
        coefficient = self.coefficient(context) if callable(self.coefficient) else self.coefficient
        self.laws_ = [RateLaw(u, coefficient * laplacian(u))]