Skip to content

Pontryagin capital and consumption

The Ramsey economy that chooses its consumption path.

  • Class: OptimalConsumptionSystem
  • Import: from skcomplex.systems.economics.macroeconomics import OptimalConsumptionSystem
  • Field: economics/macroeconomics
  • Topics: optimal control, growth, capital, collocation, ode
  • References:
    • Dilão 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.economics.macroeconomics import OptimalConsumptionSystem

trajectory = OptimalConsumptionSystem().prepare().simulate()

Parameters

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

Parameter Default
k 1.0
A 1.0
alpha 0.3
delta 0.05
rho 0.03
v 0.7
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 objective, rate
Randomness unknown
Domains real
Structure fixed

Class

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

class OptimalConsumptionSystem(DynamicalSystem):
    """The Ramsey economy that chooses its consumption path.

    The path maximises its discounted utility and the value of the capital left at the horizon, the objective law
    `ObjectiveLaw(-utility, controls=[s.target.c], terminal=-value)`. Run with an optimal control solver from little
    capital, consumption rises with capital along the saddle path towards the modified golden rule, and the economy
    saves a falling share of its output. The system has the capital `economy.k`, the consumption `economy.c`, and the
    observable `saving_rate`.

    Args:
        k:
            The initial capital per worker.

        A:
            The total factor productivity.

        alpha:
            The capital share of output.

        delta:
            The depreciation rate.

        rho:
            The discount rate.

        v:
            The value per unit of capital left at the horizon.

        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.macroeconomics import OptimalConsumptionSystem
        >>> OptimalConsumptionSystem(rho=0.05).prepare().system_.elements[0].get_params()['rho']
        0.05
    """

    field = 'economics/macroeconomics'
    topics = ('optimal control', 'growth', 'capital', 'collocation', 'ode')
    references = ('Dilão 2023',)
    until = 40.0
    dt = 0.5
    observables = (Observable('saving_rate', _get_saving_rate),)

    def __init__(
        self,
        k: float = 1.0,
        *,
        A: float = 1.0,
        alpha: float = 0.3,
        delta: float = 0.05,
        rho: float = 0.03,
        v: float = 0.7,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label=label, solver=solver, backend=backend)
        self.k = k
        self.A = A
        self.alpha = alpha
        self.delta = delta
        self.rho = rho
        self.v = v

    def _get_solver(self) -> BaseSolver:
        """Return the solver the system is tuned to."""
        return CollocationSolver(nodes=81)

    @staticmethod
    def _get_utility(s: SimpleNamespace) -> Expression:
        """Return the discounted utility of consumption per unit time.

        It is `exp(-rho t) log(c)`.
        """
        economy = s.target
        utility: Expression = exp(-economy.rho * s.t) * log(economy.c)
        return utility

    @staticmethod
    def _get_capital_value(s: SimpleNamespace) -> Expression:
        """Return the discounted value of the capital left at the horizon.

        It is `exp(-rho T) v k(T)`.
        """
        economy = s.target
        value: Expression = exp(-economy.rho * s.t) * economy.v * economy.k
        return value

    def _get_interactions(self) -> list[BaseInteraction]:
        """Return the net saving, and the utility and capital value that the consumption maximises."""
        welfare = Interaction(
            'welfare',
            roles={'target': self._get_element_label()},
            laws=lambda s: [
                ObjectiveLaw(-self._get_utility(s), controls=[s.target.c], terminal=-self._get_capital_value(s)),
            ],
        )
        return [*super()._get_interactions(), welfare]

    @staticmethod
    def _get_net_saving(s: SimpleNamespace) -> Expression:
        """Return the output not consumed minus depreciation, `A k^alpha - delta k - c`."""
        economy = s.target
        rate: Expression = economy.A * economy.k**economy.alpha - economy.delta * economy.k - economy.c
        return rate

    def _get_element_label(self) -> str:
        """Return the label of the element that holds the states."""
        return 'economy'

    def _get_states(self) -> dict[str, object]:
        """Return the initial value of every state by name."""
        return {
            'k': self.k,
        }

    def _get_parameters(self) -> dict[str, object]:
        """Return the consumption, which the welfare steers, and the parameters of the model."""
        return {'c': 0.5, 'A': self.A, 'alpha': self.alpha, 'delta': self.delta, 'rho': self.rho, 'v': self.v}

    def _get_allowed(self) -> dict[str, object]:
        """Return the allowed values of the capital, the consumption, and the parameters."""
        positive, nonnegative = RealSet.open(0, oo), RealSet.closed_open(0, oo)
        return {
            'k': positive,
            'c': RealSet.closed(MIN_CONSUMPTION, MAX_CONSUMPTION),
            'A': positive,
            'alpha': positive,
            'delta': nonnegative,
            'rho': positive,
            'v': nonnegative,
        }

    def _get_equations(self) -> Equations:
        """Return the components of the system built from its model parameters."""
        return {
            'k': self._get_net_saving,
        }

Components

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

Elements:

Interactions:

  • EquationInteraction, from Interaction, through the shared recipe EquationInteraction
  • Interaction
class AnnotatedElement(Element):
    """An element of values by name, with the allowed values and quantities of some.

    It holds what a class would write in `Annotated`, for values known only as data. The values
    `{'n': 40.0}` with `allowed={'n': RealSet.closed_open(0, oo)}` and `quantities={'n': 'people'}` are read as
    `n: Annotated[float, RealSet.closed_open(0, oo), Quantity('people')] = 40.0`, so a negative `n` is rejected and the
    conservation monitor follows the people. The generic systems that build one element from a mapping of states, such
    as `DynamicalSystem` and `StockFlowSystem`, build this element.

    Unlike `Element`, whose subclass writes the allowed values and quantities in `Annotated` on its arguments, it takes
    them as data. Choose it when the names of the values are known only when a system is built.

    It appears in many fields. The stocks of a bathtub, the people of a diffusion of innovations, and the oil of an
    economy are each its values.

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

        values:
            The values by name, such as `{'n': 40.0, 'r': 0.5}`, or `None` for none.

        allowed:
            The allowed values of some values by name, a `RealSet` such as `RealSet.closed_open(0, oo)` or a set such
            as `{'S', 'I', 'R'}`, or `None` for none.

        quantities:
            The quantity some values hold by name, such as `{'n': 'people'}`, or `None` for none.

    Examples:
        >>> from sage.all__sagemath_symbolics import oo
        >>> from sage.sets.real_set import RealSet
        >>> from skcomplex.systems.general.dynamics import AnnotatedElement
        >>> from skcomplex.core.errors import ValidationError
        >>> from skcomplex.core.systems import System
        >>> tank = AnnotatedElement('tank', values={'level': -1.0}, allowed={'level': RealSet.closed_open(0, oo)})
        >>> try:
        ...     System(elements=[tank]).prepare()
        ... except ValidationError as error:
        ...     print(error)
        The system is not valid, with 1 error(s):
        - tank: tank.level = -1.0 is not in its domain [0, +oo). Correct the component as the message describes. [value]
    """

    def __init__(
        self,
        label: str,
        *,
        values: Mapping[str, object] | None = None,
        allowed: Mapping[str, object] | None = None,
        quantities: Mapping[str, str] | None = None,
    ) -> None:
        super().__init__(label, values=values)
        self.allowed = allowed
        self.quantities = quantities

    def _get_hints(self) -> dict[str, object]:
        """Return the hint of every value with allowed values or a quantity.

        Each hint is what `Annotated` would write. The arguments `allowed` and `quantities` describe the values, so they
        are no values themselves.
        """
        allowed, quantities = self.allowed or {}, self.quantities or {}
        hints: dict[str, object] = {}
        for name in [*allowed, *(name for name in quantities if name not in allowed)]:
            items = [allowed[name]] if name in allowed else []
            items += [Quantity(quantities[name])] if name in quantities else []
            hints[name] = Annotated[object, *items]
        return hints

class EquationInteraction(Interaction):
    """An interaction that gives one state of an element its rate or its next value.

    In continuous time the equation is the rate of the state, or of its derivative of order `k` when the state is named
    with `k` primes, such as `"x''"` for an acceleration, and a noise amplitude adds a noise in the Itô or Stratonovich
    convention. In discrete time the equation is the next value of the state, read from the values at the start of the
    step. An equation and a noise are functions of the namespace whose `target` holds the values of the element and
    whose `t` holds the time.

    Unlike `Interaction`, which a subclass gives laws of its own, it takes the equation as a function. Choose it when
    one state follows one formula, with no class of its own.

    It appears in many fields. The decay of a tank, the logistic map of a population, and the income of an economy are
    each one equation of one state.

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

        target:
            The path of the element whose state the equation changes.

        state:
            The name of the state, with a prime for every order of the derivative the equation gives.

        equation:
            The rate or the next value as a function of the namespace, or `None` for a noise alone.

        noise:
            The noise amplitude as a function of the namespace or a number, or `None` for none.

        convention:
            The stochastic calculus of the noise, `'ito'` or `'stratonovich'`.

        time:
            The time of the equation, `'continuous'` for a rate or `'discrete'` for a next value.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.dynamics import EquationInteraction
        >>> decay = EquationInteraction('decay', target='tank', state='x', equation=lambda s: -s.target.k * s.target.x)
        >>> system = System(elements=[Element('tank', values={'x': 1.0, 'k': 0.5})], interactions=[decay])
        >>> round(float(system.prepare().simulate(until=2.0, dt=2.0).get_values('tank.x')[-1]), 4)
        0.3679
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (RateLaw, NoiseLaw, UpdateLaw)

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str,
        equation: Callable[[SimpleNamespace], object] | None = None,
        noise: Callable[[SimpleNamespace], object] | float | None = None,
        convention: str = 'ito',
        time: str = 'continuous',
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.equation = equation
        self.noise = noise
        self.convention = convention
        self.time = time

    def _get_tags(self) -> Tags:
        """Return the tags of the update, or of the rate and the noise the equation has."""
        if self.time == 'discrete':
            return self._get_variant_tags((UpdateLaw,))
        classes = (RateLaw,) if self.equation is not None else ()
        return self._get_variant_tags((*classes, NoiseLaw) if self.noise is not None else classes)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate and the noise, or the next value, of the state.

        Args:
            context:
                The namespace of the element.
        """
        super()._prepare(context)
        name = self.state.rstrip("'")
        order = len(self.state) - len(name)
        state = getattr(context.target, name)
        laws: list[BaseLaw] = []
        if self.time == 'discrete' and self.equation is not None:
            laws.append(UpdateLaw(state, self.equation(context)))
        elif self.equation is not None:
            laws.append(RateLaw(state.diff(context.t, max(order, 1)), self.equation(context)))
        if self.time != 'discrete' and self.noise is not None:
            noise = self.noise(context) if callable(self.noise) else self.noise
            laws.append(NoiseLaw(state.diff(context.t, max(order, 1)), noise, convention=self.convention))
        self.laws_: list[BaseLaw] = laws

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