Skip to content

Food security systems

A food security system, the rice self-sufficiency of a country.

  • Class: FoodSecuritySystem
  • Import: from skcomplex.systems.economics.resources import FoodSecuritySystem
  • Field: economics/resources
  • Topics: food security, agriculture, stocks and flows, system dynamics, ode
  • References:
    • Bala et al. 2017

Use this system

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

from skcomplex.systems.economics.resources import FoodSecuritySystem

trajectory = FoodSecuritySystem().prepare().simulate()

Parameters

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

Parameter Default
subsidy 0.67
bio_target 0.0
research 0.0
training_target 0.0
intensity_target 1.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 unknown
Domains real
Structure fixed

Class

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

class FoodSecuritySystem(BaseSystem):
    """A food security system, the rice self-sufficiency of a country.

    The country acts by subsidy, research, and extension. The land suitable for rice is developed into rice area over
    eight years, and the rice area is discarded for housing, roads, and industry at a small fraction per year. The
    production is the milled share of the productivity times the area times the cropping intensity. The productivity is
    the potential yield, which research raises towards a limit, times a table of the input ratio, the soil quality,
    which chemical fertiliser degrades and fallow regenerates, and the farming practice, which training and extension
    improve through a learning table. The input ratio is the share of the recommended fertiliser that the farmers apply,
    which the subsidy raises, and a target share of bio-fertiliser replaces the chemical one without degrading the soil.
    The requirement is the per capita consumption of a population growing exponentially, and the self-sufficiency level
    is the production over the requirement. Land is conserved, so the rice area peaks once the suitable land is
    developed and then declines, and without research and extension the self-sufficiency falls as the population grows.
    The structure and the initial values follow the food security system of Malaysia of Bala, Arshad and Noh (2017,
    Chapter 10), and the table functions and the rates are illustrative, with the land in millions of hectares, the
    population in millions, the productivity in tonnes of paddy per hectare, the rice in millions of tonnes, and time in
    years.

    The system has the land stocks `rice.available_land` and `rice.rice_area`, the population `rice.population`, the
    factors `rice.potential`, `rice.soil_quality`, `rice.practice`, `rice.training`, `rice.bio_fraction`, and
    `rice.cropping_intensity`, and the flows `rice.development`, `rice.discard`, and `rice.population_growth` per year,
    over years. The observables of the system are `rice.input_ratio`, `rice.productivity`, `rice.production`,
    `rice.requirement`, and `rice.self_sufficiency`.

    Args:
        subsidy:
            The share of the recommended fertiliser that the subsidy pays for.

        bio_target:
            The target share of bio-fertiliser in the inputs.

        research:
            The funding of research for high-yielding varieties, relative to its normal level.

        training_target:
            The target coverage of the farmers by training and extension, from 0 to 1.

        intensity_target:
            The target cropping intensity, the crops per year on the rice area.

        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.economics.resources import FoodSecuritySystem
        >>> FoodSecuritySystem(subsidy=0.0).prepare().system_.elements[0].subsidy
        0.0
    """

    field = 'economics/resources'
    topics = ('food security', 'agriculture', 'stocks and flows', 'system dynamics', 'ode')
    references = ('Bala et al. 2017',)
    until = 50.0
    dt = 0.25
    observables = tuple(
        [
            Observable(name, expression, element='rice')
            for name, expression in (
                ('input_ratio', _get_input_ratio),
                ('productivity', _get_productivity),
                ('production', _get_production),
                ('requirement', _get_requirement),
                ('self_sufficiency', _get_self_sufficiency),
            )
        ],
    )

    def __init__(
        self,
        *,
        subsidy: float = 0.67,
        bio_target: float = 0.0,
        research: float = 0.0,
        training_target: float = 0.0,
        intensity_target: float = 1.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.subsidy = subsidy
        self.bio_target = bio_target
        self.research = research
        self.training_target = training_target
        self.intensity_target = intensity_target

    @staticmethod
    def _get_rice_laws(namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the yield potential, the soil, and the practice of the sector."""
        s = namespace.target
        chemical = 1 - s.bio_fraction
        return [
            RateLaw(s.potential, s.research * (s.potential_limit - s.potential) / s.research_time),
            RateLaw(
                s.soil_quality,
                (1 - s.soil_quality) / s.regeneration_time
                - s.degradation * chemical * _get_input_ratio(s) * s.cropping_intensity * s.soil_quality,
            ),
            RateLaw(s.practice, series(s.training, *LEARNING_EFFECT) * (1 - s.practice) / s.learning_time),
        ]

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the components built from the model parameters."""
        super()._prepare(context)
        sector = RiceSectorElement(
            'rice',
            subsidy=self.subsidy,
            bio_target=self.bio_target,
            research=self.research,
            training_target=self.training_target,
            intensity_target=self.intensity_target,
        )
        transfers = [
            Interaction('sector', roles={'target': 'rice'}, laws=self._get_rice_laws),
            Interaction(
                'land_use',
                roles={'target': 'rice'},
                laws=lambda s: [
                    RateLaw(
                        {s.target.available_land: -1, s.target.rice_area: +1},
                        s.target.available_land / s.target.conversion_time,
                        label='development',
                    ),
                    RateLaw({s.target.rice_area: -1}, s.target.discard_rate * s.target.rice_area, label='discard'),
                ],
            ),
            Interaction(
                'births',
                roles={'target': 'rice'},
                laws=lambda s: [
                    RateLaw(
                        {s.target.population: +1},
                        s.target.growth_rate * s.target.population,
                        label='population_growth',
                    ),
                ],
            ),
        ]
        relaxations = [
            PartialAdjustmentInteraction(
                'training',
                target='rice',
                state='training',
                goal=lambda s: s.target.training_target,
                time=lambda s: s.target.extension_time,
            ),
            PartialAdjustmentInteraction(
                'bio_fraction',
                target='rice',
                state='bio_fraction',
                goal=lambda s: s.target.bio_target,
                time=lambda s: s.target.transition_time,
            ),
            PartialAdjustmentInteraction(
                'cropping_intensity',
                target='rice',
                state='cropping_intensity',
                goal=lambda s: s.target.intensity_target,
                time=lambda s: s.target.implementation_time,
            ),
        ]
        self.system_ = System(self.label, elements=[sector], interactions=[*transfers, *relaxations])

Components

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

Elements:

Interactions:

  • Interaction
  • PartialAdjustmentInteraction, from Interaction
class RiceSectorElement(Element):
    """Rice sector of a country.

    It holds its land, population, and the factors of the productivity of its rice land. The suitable land is developed
    into rice area and the rice area is discarded, and the population grows exponentially, through transfers within the
    sector of the system. Research raises the potential yield towards a limit, chemical fertiliser degrades the soil and
    fallow regenerates it, and training improves the farming practice through a learning table. The training, the share
    of bio-fertiliser, and the cropping intensity relax towards their targets through relaxation interactions of the
    system, which read the targets and times of the sector.

    Args:
        label:
            The label of the sector.

        available_land:
            The initial land suitable for rice and not yet developed.

        rice_area:
            The initial rice area.

        population:
            The initial population.

        potential:
            The initial potential yield.

        soil_quality:
            The initial soil quality, from 0 to 1.

        practice:
            The initial quality of the farming practice, from 0 to 1.

        training:
            The initial coverage of the farmers by training and extension, from 0 to 1.

        bio_fraction:
            The initial share of bio-fertiliser in the inputs.

        cropping_intensity:
            The initial number of crops per year on the rice area.

        conversion_time:
            The time to develop the suitable land.

        discard_rate:
            The fraction of the rice area discarded per year.

        growth_rate:
            The growth rate of the population.

        consumption:
            The rice consumption per capita, in kilograms per year.

        milling_rate:
            The share of paddy that milling turns into rice.

        subsidy:
            The share of the recommended fertiliser that the subsidy pays for.

        farmer_inputs:
            The share of the unsubsidised fertiliser that the farmers buy.

        research:
            The funding of research for high-yielding varieties, relative to its normal level.

        potential_limit:
            The potential yield that research approaches.

        research_time:
            The time research takes to reach the limit at its normal funding.

        regeneration_time:
            The time fallow takes to regenerate the soil.

        degradation:
            The rate at which chemical fertiliser degrades the soil.

        learning_time:
            The time training takes to improve the practice.

        training_target:
            The target coverage of training and extension.

        extension_time:
            The time the training takes to reach its target.

        bio_target:
            The target share of bio-fertiliser.

        transition_time:
            The time the share of bio-fertiliser takes to reach its target.

        intensity_target:
            The target cropping intensity.

        implementation_time:
            The time the cropping intensity takes to reach its target.

    Examples:
        >>> from skcomplex.systems.economics.resources import RiceSectorElement
        >>> RiceSectorElement('rice', subsidy=0.5).subsidy
        0.5
    """

    def __init__(
        self,
        label: str,
        *,
        available_land: Annotated[object, RealSet.closed_open(0, oo), Quantity('land')] = 0.088,
        rice_area: Annotated[object, RealSet.closed_open(0, oo), Quantity('land')] = 0.680647,
        population: Annotated[object, RealSet.closed_open(0, oo), Quantity('people')] = 18.1024,
        potential: Annotated[object, RealSet.closed_open(0, oo)] = 6.0,
        soil_quality: Annotated[object, RealSet.closed_open(0, oo)] = 0.99,
        practice: Annotated[object, RealSet.closed_open(0, oo)] = 0.61,
        training: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        bio_fraction: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        cropping_intensity: Annotated[object, RealSet.closed_open(0, oo)] = 1.0,
        conversion_time: Annotated[object, RealSet.open(0, oo)] = 8.0,
        discard_rate: Annotated[object, RealSet.closed_open(0, oo)] = 0.0085,
        growth_rate: object = 0.021,
        consumption: Annotated[object, RealSet.closed_open(0, oo)] = 80.0,
        milling_rate: Annotated[object, RealSet.closed_open(0, oo)] = 0.65,
        subsidy: Annotated[object, RealSet.closed_open(0, oo)] = 0.67,
        farmer_inputs: Annotated[object, RealSet.closed_open(0, oo)] = 0.3,
        research: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        potential_limit: Annotated[object, RealSet.open(0, oo)] = 10.0,
        research_time: Annotated[object, RealSet.open(0, oo)] = 20.0,
        regeneration_time: Annotated[object, RealSet.open(0, oo)] = 10.0,
        degradation: Annotated[object, RealSet.closed_open(0, oo)] = 0.002,
        learning_time: Annotated[object, RealSet.open(0, oo)] = 5.0,
        training_target: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        extension_time: Annotated[object, RealSet.open(0, oo)] = 5.0,
        bio_target: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
        transition_time: Annotated[object, RealSet.open(0, oo)] = 10.0,
        intensity_target: Annotated[object, RealSet.open(0, oo)] = 1.0,
        implementation_time: Annotated[object, RealSet.open(0, oo)] = 10.0,
    ) -> None:
        super().__init__(label)
        self.available_land = available_land
        self.rice_area = rice_area
        self.population = population
        self.potential = potential
        self.soil_quality = soil_quality
        self.practice = practice
        self.training = training
        self.bio_fraction = bio_fraction
        self.cropping_intensity = cropping_intensity
        self.conversion_time = conversion_time
        self.discard_rate = discard_rate
        self.growth_rate = growth_rate
        self.consumption = consumption
        self.milling_rate = milling_rate
        self.subsidy = subsidy
        self.farmer_inputs = farmer_inputs
        self.research = research
        self.potential_limit = potential_limit
        self.research_time = research_time
        self.regeneration_time = regeneration_time
        self.degradation = degradation
        self.learning_time = learning_time
        self.training_target = training_target
        self.extension_time = extension_time
        self.bio_target = bio_target
        self.transition_time = transition_time
        self.intensity_target = intensity_target
        self.implementation_time = implementation_time

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

class PartialAdjustmentInteraction(Interaction):
    """Partial adjustment of a quantity towards a target over an adjustment time.

    Economics names it partial adjustment, as of a policy or an investment that closes a gap to its target at a rate.
    The rate is `(goal(ns) - x) / time(ns)` of a state `x` of a target, with optional noise. With a constant goal and
    time and an additive noise of amplitude `sigma`, the state follows the Ornstein-Uhlenbeck process `dx = (goal - x) /
    time dt + sigma dW`, whose stationary variance is `sigma**2 time / 2`. A goal, a time, or a noise function takes the
    namespace of the interaction, whose `target` holds the values of the target, and a number stands for a constant. A
    goal that is a number applies to every component of a vector state.

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

        target:
            The path of the element or group whose state relaxes.

        state:
            The name of the state of the target that relaxes.

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

        time:
            A function of the namespace that returns the relaxation time, or a positive number.

        noise:
            A function of the namespace that returns the amplitude of the noise, a number, or `None` for no noise.

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

    Examples:
        >>> from skcomplex.systems.general.elements import NonnegativeElement
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.economics.resources import PartialAdjustmentInteraction
        >>> relaxation = PartialAdjustmentInteraction('relaxation', target='stock', goal=10.0, time=0.5)
        >>> system = System(elements=[NonnegativeElement('stock')], interactions=[relaxation])
        >>> trajectory = system.prepare().simulate(until=5.0, dt=0.01)
        >>> round(float(trajectory.get_values('stock.x')[-1]), 3)
        10.0
    """

    law_classes = (RateLaw, NoiseLaw)

    def _get_tags(self) -> Tags:
        """Return the tags of the rate law, with a noise law for a noise."""
        return self._get_variant_tags((RateLaw, NoiseLaw) if self.noise is not None else (RateLaw,))

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

    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 neither callable nor a number.
        """
        super()._check_arguments()
        self._check_functions()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the relaxation of the state and its noise as the laws.

        Args:
            context:
                The namespace of the target.
        """
        super()._prepare(context)
        state = getattr(context.target, self.state)
        laws: list[BaseLaw] = [RateLaw(state, self._broadcast(self._get_rate(context), state))]
        if self.noise is not None:
            laws.append(NoiseLaw(state, self._evaluate(self.noise, context)))
        self.laws_ = laws

    @staticmethod
    def _evaluate(value: object, namespace: SimpleNamespace) -> object:
        """Return a number, or the value of a function of the namespace."""
        return value(namespace) if callable(value) else value

    @staticmethod
    def _broadcast(value: object, state: object) -> object:
        """Return a value with one component per component of a vector state, repeating a number."""
        if isinstance(state, FreeModuleElement) and not isinstance(value, FreeModuleElement | list | tuple):
            return vector(SR, [value] * len(state))
        if isinstance(value, list | tuple):
            return vector(SR, value)
        return value

    def _check_functions(self) -> None:
        """Raise an error for a state that is not a name, or a bad function.

        A bad function is neither callable nor a number.
        """
        if not isinstance(self.state, str):
            error_msg = f'The state of {self.label!r} is {self.state!r}. Give the name of a state of the target.'
            raise ValidationError(error_msg)
        if self.noise is not None and not (callable(self.noise) or isinstance(self.noise, int | float)):
            error_msg = f'The noise of {self.label!r} is {self.noise!r}. Give a function of the namespace or a number.'
            raise ValidationError(error_msg)
        for name in ('goal', 'time'):
            value = getattr(self, name)
            if not (callable(value) or isinstance(value, int | float)):
                error_msg = f'The {name} of {self.label!r} is {value!r}. Give a function of the namespace or a number.'
                raise ValidationError(error_msg)

    def _get_goal(self, namespace: SimpleNamespace) -> object:
        """Return the goal, the hook a subclass overrides to derive it from its parameters."""
        return self._evaluate(self.goal, namespace)

    def _get_time(self, namespace: SimpleNamespace) -> object:
        """Return the relaxation time.

        This is the hook a subclass overrides to derive it from its parameters.
        """
        return self._evaluate(self.time, namespace)

    def _get_rate(self, namespace: SimpleNamespace) -> object:
        """Return the relaxation `(goal - x) / time` of the state.

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

        Returns:
            rate:
                The rate of the state.
        """
        state = getattr(namespace.target, self.state)
        goal = self._broadcast(self._get_goal(namespace), state)
        return (goal - state) / self._get_time(namespace)

Equations

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

rice.available_land: diff(available_land_rice(t), t) == -available_land_rice(t)/conversion_time_rice
rice.rice_area: diff(rice_area_rice(t), t) == -discard_rate_rice*rice_area_rice(t) + available_land_rice(t)/conversion_time_rice
rice.population: diff(population_rice(t), t) == growth_rate_rice*population_rice(t)
rice.potential: diff(potential_rice(t), t) == (potential_limit_rice - potential_rice(t))*research_rice/research_time_rice
rice.soil_quality: diff(soil_quality_rice(t), t) == ((farmer_inputs_rice*(subsidy_rice - 1) - subsidy_rice)*(bio_fraction_rice(t) - 1) + bio_fraction_rice(t))*degradation_rice*(bio_fraction_rice(t) - 1)*cropping_intensity_rice(t)*soil_quality_rice(t) - (soil_quality_rice(t) - 1)/regeneration_time_rice
rice.practice: diff(practice_rice(t), t) == -(practice_rice(t) - 1)*where(training_rice(t) < 0.0, 0.0, where(training_rice(t) < 0.5, where(training_rice(t) < 0.25, 1.6*training_rice(t), 1.1999999999999997*training_rice(t) + 0.10000000000000009), where(training_rice(t) < 0.75, 0.8000000000000003*training_rice(t) + 0.2999999999999998, where(training_rice(t) < 1.0, 0.3999999999999999*training_rice(t) + 0.6000000000000001, 1.0))))/learning_time_rice
rice.training: diff(training_rice(t), t) == (training_target_rice - training_rice(t))/extension_time_rice
rice.bio_fraction: diff(bio_fraction_rice(t), t) == (bio_target_rice - bio_fraction_rice(t))/transition_time_rice
rice.cropping_intensity: diff(cropping_intensity_rice(t), t) == (intensity_target_rice - cropping_intensity_rice(t))/implementation_time_rice