Skip to content

Size-structured forest with shading and seed dispersal

The McKendrick-von Foerster density of trees over position and height.

  • Class: ForestSizeStructureSystem
  • Import: from skcomplex.systems.biology.ecology import ForestSizeStructureSystem
  • Field: biology/ecology
  • Topics: field, size structure, forest, integral operator, dispersal, pde
  • References:
    • Grilletta et al. 2026

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.biology.ecology import ForestSizeStructureSystem

trajectory = ForestSizeStructureSystem().prepare().simulate()

Parameters

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

Parameter Default
positions 40
heights 100
width 10.0
dispersal 1.0
hurst 1.0
sapling 0.1
top 50.0
shading 1.0
fecundity 0.01
resources 125.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 phase space
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 ForestSizeStructureSystem(BaseSystem):
    """The McKendrick-von Foerster density of trees over position and height.

    The position runs across a strip.

    The density `f(x, h)` of trees of height `h` at position `x` across a forest strip grows in height at the rate `I (1
    - h / top)`, where the light `I = exp(-shading int_h^top f(x, h') h'^(2H) dh')` falls through the canopy of taller
    trees by the Beer-Lambert law. Trees die from competition for canopy space at the rate `I h^(2H) f` and for
    resources at the rate `I (1 - h / top) a / h`, where `a = R / resources` and `R = int h^(1+2H) f dh` is the resource
    consumption of the trees at `x`. Saplings enter at the height `sapling` from the seeds `int K(x - x') R(x') dx'` of
    the trees around, dispersed by the exponential kernel `K` of length `dispersal` and integral `fecundity`, and no
    seed comes from beyond the edges of the strip, where the forest was removed. Time and density are rescaled so that
    the growth rate and the canopy mortality are one (Grilletta et al. 2026, arXiv 2608.11918 Eq. 9, 10, 16, and 25).
    The kernel is the exponential of Eq. 35 along the axis across the strip, normalized in one dimension. The system has
    the density `forest.x` over position and height.

    Args:
        positions:
            The number of positions across the strip.

        heights:
            The number of cells of the height axis.

        width:
            The width `L` of the strip.

        dispersal:
            The dispersal length `xi`.

        hurst:
            The Hurst exponent `H` of the crown radius, which scales as `h^H`.

        sapling:
            The height `h0` at which saplings enter.

        top:
            The asymptotic height `h_u`.

        shading:
            The light attenuation `gamma`.

        fecundity:
            The integral `kappa` of the dispersal kernel.

        resources:
            The resource flux `R_a`.

        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.biology.ecology import ForestSizeStructureSystem
        >>> ForestSizeStructureSystem(8, 12).prepare().system_.elements[0].space.prepare().shape_
        (8, 12)
    """

    field = 'biology/ecology'
    topics = ('field', 'size structure', 'forest', 'integral operator', 'dispersal', 'pde')
    references = ('Grilletta et al. 2026',)
    until = 200.0
    dt = 5.0

    def __init__(
        self,
        positions: int = 40,
        heights: int = 100,
        *,
        width: float = 10.0,
        dispersal: float = 1.0,
        hurst: float = 1.0,
        sapling: float = 0.1,
        top: float = 50.0,
        shading: float = 1.0,
        fecundity: float = 0.01,
        resources: float = 125.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.positions = positions
        self.heights = heights
        self.width = width
        self.dispersal = dispersal
        self.hurst = hurst
        self.sapling = sapling
        self.top = top
        self.shading = shading
        self.fecundity = fecundity
        self.resources = resources

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the McKendrick-von Foerster density of trees.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        step = (self.top - self.sapling) / self.heights
        position = LatticeSpace(
            (self.positions,),
            spacing=self.width / self.positions,
            boundary='fixed',
            discretization='finite-volume',
            scheme=FiniteVolumeSpec(limiter=None),
        )
        space = PhaseSpace(position, [AxisSpec('h', self.heights, self.sapling, self.top)])
        centres = space.prepare().coordinates_['h']
        start = np.tile(0.1 * (centres / self.sapling) ** -2.0, (self.positions, 1))
        forest = PopulationDensityElement('forest', x=start, space=space)
        h = coordinate('h')
        growth = 1 - h / self.top
        kernel = self.fecundity / (2 * self.dispersal) * exp(-abs(displacement(0)) / self.dispersal)

        def light(s: SimpleNamespace) -> Expression:
            return exp(
                -self.shading * cumulative_integral(s.target.x * h ** (2 * self.hurst), HEIGHT_AXIS, reverse=True),
            )

        def demography(s: SimpleNamespace) -> Expression:
            consumption = reduce_axes(s.target.x * h ** (1 + 2 * self.hurst), ('h',))
            recruits = where(h < self.sapling + step, light(s) * growth * convolve(consumption, kernel) / step, 0)
            mortality = light(s) * (h ** (2 * self.hurst) * s.target.x + growth * consumption / (self.resources * h))
            return recruits - mortality * s.target.x

        grow = SizeGrowthInteraction(
            'growth',
            target='forest',
            state='x',
            drift=lambda s: [0, light(s) * growth],
        )
        demographics = Interaction(
            'demography',
            roles={'target': 'forest'},
            laws=lambda s: [RateLaw(s.target.x, demography(s))],
        )
        self.system_ = System(
            self.label,
            elements=[forest],
            interactions=[grow, demographics],
            solver=RK4Solver(dt=0.1),
        )

Components

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

Elements:

Interactions:

  • SizeGrowthInteraction, from Interaction
  • Interaction
class PopulationDensityElement(NonnegativeElement):
    """Value `x` of the density of a structured population at one class.

    A structured population is this element on a lattice of classes, such as sizes or activities, with one value per
    class, and growth, encounters, and transport change it. The element has no laws of its own.

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

        x:
            The initial density, a nonnegative number.

        size:
            The number of members, or `None` for one.

        space:
            The space with one member per site, such as a lattice of classes, or `None` for none.

    Examples:
        >>> from skcomplex.core.components.spaces import LatticeSpace
        >>> from skcomplex.systems.biology.common.populations import PopulationDensityElement
        >>> classes = LatticeSpace(5, boundary='fixed')
        >>> PopulationDensityElement('cells', x=[0.2] * 5, space=classes).x
        [0.2, 0.2, 0.2, 0.2, 0.2]
    """

    def __init__(
        self,
        label: str,
        *,
        x: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        size: int | None = None,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, x=x, size=size, space=space)

class SizeGrowthInteraction(Interaction):
    """Size growth `du/dt + divergence(a u) = source(ns)` of a size density `u` by a growth rate.

    Ecology names it the growth of individuals along a size axis, the transport term of a size-structured population.
    The drift field is `a(ns)`. The interaction sets the rate `-divergence(a u)` of the drift times the state, in
    conservative form, so the total of the state on a periodic field stays constant and a finite-volume field takes
    the differences of the flux between cells under its scheme. 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.

        sources:
            The paths of other elements the drift and the source read, as the namespaces `sources`. A field over the
            position lattice of a target on a phase space is read broadcast along the class axes.

    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.biology.ecology import SizeGrowthInteraction
        >>> space = LatticeSpace((50,), spacing=0.1, boundary='periodic', discretization='finite-volume')
        >>> values = {'u': np.exp(-((np.arange(50) - 25) / 5.0) ** 2)}
        >>> field = Element('tracer', values=values, space=space)
        >>> drift = SizeGrowthInteraction('drift', target='tracer', state='u', drift=lambda s: 1.0)
        >>> system = System(elements=[field], interactions=[drift]).prepare()
        >>> trajectory = system.simulate(1.0, dt=0.01)
        >>> total = trajectory.get_values('tracer.u')[-1].sum()
        >>> round(float(total), 6) == round(float(values['u'].sum()), 6)
        True
    """

    law_classes = (RateLaw,)

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

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

        Raises:
            ValidationError:
                The state is not a name, or a function is not callable.
        """
        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 and of the source.

        Args:
            context:
                The namespace of the target and the sources, the time `t`, and the parameters.
        """
        super()._prepare(context)
        state = 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(state, -divergence([SR(component) * state for component in components]))]
        if self.source is not None:
            self.laws_.append(RateLaw(state, self.source(context)))

class Interaction(BaseInteraction):
    """An interaction whose laws run once for the elements its roles bind.

    It states the laws that change the values of the elements its roles bind, such as gravity on a ball in
    `Interaction('gravity', roles={'target': 'ball'}, laws=lambda s: [RateLaw(s.target.x.diff(s.t, 2), -9.81)])`. When a
    role binds a group, the laws run once for every member, as arrays. With `among` and `along`, they run once for every
    edge of a network and read `s.source` and `s.target`, the members at its two ends, or once for every hyperedge or
    random small group and read `s.member`, `s.others`, and `s.members`. With `within`, they run once for every pair of
    members closer than a radius and read `s.first` and `s.second`. A subclass takes its roles, typed `Role`, and its
    parameters as arguments of its `__init__` and sets `laws_` in its `_prepare`. It states predation between two
    populations, a reaction between two chemicals, and an infection along the contacts of a network.

    Read more in the user guide, under Interactions.

    Args:
        label:
            The name of the interaction, unique among the components of its system, such as `'predation'`.

        roles:
            The element each role binds, by the name of the role, such as `{'target': 'ball'}`, for a rule written
            without a class, or `None`.

        laws:
            The function of the namespace that returns the laws of a rule written without a class, such as
            `lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`, the laws themselves when they read no element, or
            `None`.

        among:
            The group whose members sit at the ends of the edges, such as `'people'`, or `None` to bind elements by
            their roles only. A subclass annotates it as a role, and a rule written without a class binds it as one.

        along:
            `True` for the edges of the network the group lives on, the name of a layer of a network with several, such
            as `'contacts'`, `'hyperedges'` for its hyperedges, `('hyperedges', k)` for its hyperedges of `k` members,
            `RandomPartition(k)` for random groups of `k` members drawn at every step, `'neighborhoods'` for every
            member with the members around it, or `None` for no edges. On the edges, the laws read the member of an
            element that sits on them as `s.edge`, and on the hyperedges as `s.hyperedge`.

        within:
            A `RadiusNeighborhood(r)` for laws that run once for every pair of members of the roles `first` and `second`
            closer than `r`, which read `s.first` and `s.second` and give the laws of both, such as the repulsion of
            walkers of two crowds, or `None` for no pairs. With `among`, both members come from that group. The laws may
            give the energy of the pair as `ObjectiveLaw(V)` in place of its forces, and each member then feels the
            force `-dV/dx` on its position `x`.

    See Also:
        BaseInteraction: The base of every interaction.
        RandomPartition: Groups the members of a group at random at every step.
        TrainingInteraction: Trains the parameters of a nested system.

    Examples:
        >>> from skcomplex.core.components.interactions import Interaction
        >>> from skcomplex.core.components.laws import RateLaw
        >>> birth = Interaction('birth', roles={'target': 'fish'}, laws=lambda s: [RateLaw(s.target.n.diff(s.t), 1)])
        >>> birth.roles
        {'target': 'fish'}
    """

    def __init__(
        self,
        label: str,
        *,
        roles: Mapping[str, object] | None = None,
        laws: Callable[[SimpleNamespace], Sequence[BaseLaw]] | Sequence[BaseLaw] | None = None,
        among: str | None = None,
        along: bool | str | tuple[str, int] | RandomPartition | None = None,
        within: RadiusNeighborhood | None = None,
    ) -> None:
        super().__init__(label)
        self.roles = roles
        self.laws = laws
        self.among = among
        self.along = along
        self.within = within

    def _get_declared(self) -> Mapping[str, _DeclaredVariableSpec]:
        """Return the numeric arguments as parameters, and `roles` and `among` as roles.

        With `within`, `among` binds both members of a pair, `first` and `second`.
        """
        declared = dict(super()._get_declared())
        for name, binding in (self.roles or {}).items():
            declared[name] = _DeclaredVariableSpec(binding, RoleSpec())
        if self.among is not None and self.within is not None:
            for name in PAIR_ROLES:
                declared.setdefault(name, _DeclaredVariableSpec(self.among, RoleSpec()))
        elif self.among is not None and 'among' not in declared and 'among' not in self._get_specs():
            declared['among'] = _DeclaredVariableSpec(self.among, RoleSpec())
        return declared

    @classmethod
    def _get_state_arguments(cls, role: RoleSpec) -> tuple[str, ...]:
        """Return the arguments that name the states a role reads.

        The mapping `roles` of bindings names none.
        """
        return tuple(name for name in super()._get_state_arguments(role) if name != 'roles')

    def _get_binding(self, role: str) -> object:
        """Return what a role binds, from `roles` or from the argument of its name.

        Args:
            role:
                The name of the role.

        Returns:
            binding:
                The label, labels, or entries the role binds, or `None` when it binds nothing.
        """
        if self.roles is not None and role in self.roles:
            return self.roles[role]
        if self.among is not None and self.within is not None and role in PAIR_ROLES:
            return self.among
        return super()._get_binding(role)

    def _check_arguments(self) -> None:
        """Raise an error for roles, laws, or groups the interaction cannot take.

        Raises:
            ValidationError:
                A role of `roles` takes the name of an argument, `laws` is neither a function nor a list of laws, or
                `along` names hyperedges of fewer than two members.
        """
        clashes = sorted(set(self.roles or {}) & {'label', 'roles', 'laws', 'among', 'along'})
        if clashes:
            error_msg = f'The role {clashes[0]!r} of {self.label!r} takes the name of an argument. Rename the role.'
            raise ValidationError(error_msg)
        if self.laws is not None and not callable(self.laws) and not isinstance(self.laws, list | tuple):
            error_msg = (
                f'The laws of {self.label!r} are {self.laws!r}. Give a function that takes the bound elements as '
                '`s` and returns the laws, such as `laws=lambda s: [RateLaw(s.target.n.diff(s.t), s.target.n)]`.'
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, tuple) and not self._is_sized(self.along):
            error_msg = (
                f'{self.label!r} runs along {self.along!r}. Give the hyperedges of one size as a whole number of 2 or '
                "more, such as `along=('hyperedges', 3)`."
            )
            raise ValidationError(error_msg)
        if isinstance(self.along, RandomPartition):
            self.along._check()
        grouped = isinstance(self.along, RandomPartition) or self.along == NEIGHBORHOODS
        if grouped and self.among is None:
            error_msg = f'{self.label!r} runs along groups of members. Name their group with `among`.'
            raise ValidationError(error_msg)
        super()._check_arguments()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the laws of `laws` for a binding.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        if self.laws is not None:
            self.laws_ = list(self.laws(context) if callable(self.laws) else self.laws)

    @staticmethod
    def _is_sized(along: tuple[object, ...]) -> bool:
        """Return whether `along` names hyperedges of a whole size of at least two."""
        if len(along) != MIN_SIZE or along[0] != HYPEREDGES:
            return False
        size = along[1]
        return isinstance(size, int) and not isinstance(size, bool) and size >= MIN_SIZE

    def _get_draws(self) -> bool:
        """Return whether the interaction draws, as it does along random groups."""
        return super()._get_draws() or isinstance(self.along, RandomPartition)

    def _runs_on_edges(self) -> bool:
        """Return whether the interaction runs along edges."""
        grouped = self._runs_on_hyperedges() or self._get_grouping() is not None
        return self.along is not None and self.along is not False and not grouped

    def _runs_on_hyperedges(self) -> bool:
        """Return whether the interaction runs along the hyperedges of a network."""
        return self.along == HYPEREDGES or (isinstance(self.along, tuple) and self.along[0] == HYPEREDGES)

    def _get_hyperedge_size(self) -> int | None:
        """Return the size `along` gives the hyperedges, or `None` for every size."""
        return int(self.along[-1]) if isinstance(self.along, tuple) and self._runs_on_hyperedges() else None

    def _get_within(self) -> RadiusNeighborhood | None:
        """Return the neighbourhood of the pairs the laws run for, or `None` for no pairs."""
        return self.within

    def _get_layer(self) -> str | None:
        """Return the layer `along` names, or `None` for no layer."""
        if not isinstance(self.along, str) or self.along == NEIGHBORHOODS or self._runs_on_hyperedges():
            return None
        return self.along

    def _get_grouping(self) -> tuple[str, int, str] | None:
        """Return the kind, size, and reduction of the groups `along` names, or `None`."""
        if isinstance(self.along, RandomPartition):
            return ('partition', self.along.size, 'sum')
        if self.along == NEIGHBORHOODS:
            return ('neighborhood', 0, 'sum')
        return None