Skip to content

Oil economy

Meadows' oil economy, capital that grows on a nonrenewable resource.

  • Class: OilEconomySystem
  • Import: from skcomplex.systems.economics.resources import OilEconomySystem
  • Field: economics/resources
  • Topics: nonrenewable resource, system dynamics, ode
  • References:
    • Meadows 2008

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 OilEconomySystem

trajectory = OilEconomySystem().prepare().simulate()

Parameters

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

Parameter Default
resource 1000.0
capital 5.0
price 3.0
cost 0.1
growth_goal 0.1
lifetime 20.0
price_table None
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time continuous
Space none
Laws rate
Randomness deterministic
Domains real
Structure fixed

Class

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

class OilEconomySystem(StockFlowSystem):
    """Meadows' oil economy, capital that grows on a nonrenewable resource.

    The capital collapses as the resource runs out. The capital grows exponentially while extraction is cheap, peaks as
    falling yields cut the profit, and declines with depreciation, leaving part of the resource in the ground. The
    system has the resource `oil.resource` and the capital `oil.capital`.

    Args:
        resource:
            The initial resource stock.

        capital:
            The initial capital.

        price:
            The price of the resource, used without a price table.

        cost:
            The operating cost per unit of capital.

        growth_goal:
            The largest investment per unit of capital.

        lifetime:
            The average lifetime of the capital.

        price_table:
            The price at the yields 0, 0.1, 0.2, 0.4, 0.6, 0.8, and 1, or `None` for a constant price.

        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 OilEconomySystem
        >>> OilEconomySystem(resource=2000.0).prepare().system_.elements[0].values['resource']
        2000.0
    """

    field = 'economics/resources'
    topics = ('nonrenewable resource', 'system dynamics', 'ode')
    references = ('Meadows 2008',)
    until = 100.0
    dt = 1.0

    @staticmethod
    def _get_efficiency(holder: SimpleNamespace, yields: Sequence[float]) -> Expression:
        """Return the yield per unit of capital, a table of the resource stock."""
        return series(holder.resource, RESOURCE_LEVELS, yields)

    @staticmethod
    def _get_investment(holder: SimpleNamespace, revenue: Expression) -> Expression:
        """Return the investment.

        It is the profit of a revenue clipped to the growth goal per unit of capital.
        """
        return clip(revenue - holder.cost * holder.capital, 0, holder.growth_goal * holder.capital)

    @staticmethod
    def _harvest(holder: SimpleNamespace, yields: Sequence[float]) -> Expression:
        """Return the harvest or extraction.

        It is the capital times the yield per unit of capital.
        """
        return holder.capital * OilEconomySystem._get_efficiency(holder, yields)

    def __init__(
        self,
        resource: float = 1000.0,
        capital: float = 5.0,
        *,
        price: float = 3.0,
        cost: float = 0.1,
        growth_goal: float = 0.1,
        lifetime: float = 20.0,
        price_table: Sequence[float] | None = None,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label=label, solver=solver, backend=backend)
        self.resource = resource
        self.capital = capital
        self.price = price
        self.cost = cost
        self.growth_goal = growth_goal
        self.lifetime = lifetime
        self.price_table = price_table

    @staticmethod
    def _get_oil_price(holder: SimpleNamespace, yields: Sequence[float], prices: Sequence[float] | None) -> Expression:
        """Return the price of the oil, constant or a table of the yield."""
        return (
            holder.price
            if prices is None
            else series(OilEconomySystem._get_efficiency(holder, yields), YIELD_LEVELS, prices)
        )

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

    def _get_stocks(self) -> dict[str, object]:
        """Return the initial value of every stock by name."""
        return {
            'resource': self.resource,
            'capital': self.capital,
        }

    def _get_allowed(self) -> dict[str, object]:
        """Return the allowed values of the stocks and parameters that have them, by name."""
        return {
            'resource': RealSet.closed_open(0, oo),
            'capital': RealSet.closed_open(0, oo),
            'price': RealSet.open(0, oo),
            'cost': RealSet.closed_open(0, oo),
            'growth_goal': RealSet.closed_open(0, oo),
            'lifetime': RealSet.open(0, oo),
        }

    def _get_quantities(self) -> dict[str, str]:
        """Return the quantity every stock holds, by name."""
        return {
            'resource': 'oil',
            'capital': 'capital',
        }

    def _get_parameters(self) -> dict[str, object]:
        """Return the value of every parameter by name."""
        return {
            'price': self.price,
            'cost': self.cost,
            'growth_goal': self.growth_goal,
            'lifetime': self.lifetime,
        }

    def _get_flows(self) -> FlowTable:
        """Return the extraction of the resource, the investment in capital, and its depreciation."""
        prices = None if self.price_table is None else tuple(float(value) for value in self.price_table)
        return {
            'extraction': ('resource', None, lambda s: OilEconomySystem._harvest(s.target, OIL_YIELD)),
            'investment': (
                None,
                'capital',
                lambda s: OilEconomySystem._get_investment(
                    s.target,
                    self._get_oil_price(s.target, OIL_YIELD, prices) * OilEconomySystem._harvest(s.target, OIL_YIELD),
                ),
            ),
            'depreciation': ('capital', None, lambda s: s.target.capital / s.target.lifetime),
        }

Components

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

Elements:

Interactions:

  • FlowInteraction, from Interaction, through the shared recipe FlowInteraction
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 FlowInteraction(Interaction):
    """An interaction that moves an amount from one stock of an element to another.

    The flow `f` takes `f` from the stock it leaves and gives `f` to the stock it enters, as the one rate law
    `RateLaw({leaves: -1, enters: +1}, f, label=label)`, so the total of the stocks is kept and the trajectory records
    `f` as `<element>.<label>`. A flow from outside the system enters a stock and leaves none, and a
    flow out of the system leaves a stock and enters none. The amount is a function of the namespace whose `target`
    holds the values of the element and whose `t` holds the time.

    Unlike `EquationInteraction`, which gives one state its rate, it changes two stocks by one amount, so what leaves
    one enters the other. Choose it when an amount moves between stocks, as in system dynamics.

    It appears in many fields. Water drains from a bathtub, people adopt a product in a diffusion of innovations, and
    capital depreciates in an economy.

    Args:
        label:
            The label of the interaction and the name of its flow, such as `'births'`.

        target:
            The path of the element that holds the stocks.

        leaves:
            The stock the flow leaves, or `None` for a flow from outside the system.

        enters:
            The stock the flow enters, or `None` for a flow out of the system.

        amount:
            The amount per unit of time as a function of the namespace, or a number.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.general.dynamics import FlowInteraction
        >>> drain = FlowInteraction('drain', target='tub', leaves='water', amount=lambda s: s.target.k * s.target.water)
        >>> system = System(elements=[Element('tub', values={'water': 10.0, 'k': 0.5})], interactions=[drain])
        >>> trajectory = system.prepare().simulate(until=2.0, dt=2.0)
        >>> [round(float(value), 4) for value in trajectory.get_values('tub.drain')]
        [5.0, 1.8394]
    """

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

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        leaves: str | None = None,
        enters: str | None = None,
        amount: Callable[[SimpleNamespace], object] | float,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.leaves = leaves
        self.enters = enters
        self.amount = amount

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

        Raises:
            ValidationError:
                The flow neither leaves nor enters a stock.
        """
        super()._check_arguments()
        if self.leaves is None and self.enters is None:
            error_msg = f'The flow {self.label!r} neither leaves nor enters a stock. Give `leaves`, `enters`, or both.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate law of the flow, which maps its stocks to signs.

        Args:
            context:
                The namespace of the element.
        """
        super()._prepare(context)
        amount = SR(self.amount(context) if callable(self.amount) else self.amount)
        signs = {self.leaves: -1, self.enters: 1}
        stocks = {getattr(context.target, name): sign for name, sign in signs.items() if name is not None}
        self.laws_: list[BaseLaw] = [RateLaw(stocks, amount, label=self.label)]

Equations

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

oil.resource: diff(resource_oil(t), t) == -capital_oil(t)*where(resource_oil(t) < 0.0, 0.0, where(resource_oil(t) < 500.0, where(resource_oil(t) < 200.0, where(resource_oil(t) < 100.0, 0.001*resource_oil(t), 0.0015*resource_oil(t) - 0.04999999999999999), where(resource_oil(t) < 300.0, 0.002*resource_oil(t) - 0.15000000000000002, where(resource_oil(t) < 400.0, 0.002*resource_oil(t) - 0.14999999999999997, 0.0015000000000000002*resource_oil(t) + 0.04999999999999993))), where(resource_oil(t) < 800.0, where(resource_oil(t) < 600.0, 0.0009999999999999998*resource_oil(t) + 0.30000000000000016, where(resource_oil(t) < 700.0, 0.0004999999999999994*resource_oil(t) + 0.6000000000000004, 0.0003000000000000003*resource_oil(t) + 0.7399999999999998)), where(resource_oil(t) < 900.0, 0.00020000000000000017*resource_oil(t) + 0.8199999999999998, 1.0))))
oil.capital: diff(capital_oil(t), t) == -capital_oil(t)/lifetime_oil + where(price_oil*capital_oil(t)*where(resource_oil(t) < 0.0, 0.0, where(resource_oil(t) < 500.0, where(resource_oil(t) < 200.0, where(resource_oil(t) < 100.0, 0.001*resource_oil(t), 0.0015*resource_oil(t) - 0.04999999999999999), where(resource_oil(t) < 300.0, 0.002*resource_oil(t) - 0.15000000000000002, where(resource_oil(t) < 400.0, 0.002*resource_oil(t) - 0.14999999999999997, 0.0015000000000000002*resource_oil(t) + 0.04999999999999993))), where(resource_oil(t) < 800.0, where(resource_oil(t) < 600.0, 0.0009999999999999998*resource_oil(t) + 0.30000000000000016, where(resource_oil(t) < 700.0, 0.0004999999999999994*resource_oil(t) + 0.6000000000000004, 0.0003000000000000003*resource_oil(t) + 0.7399999999999998)), where(resource_oil(t) < 900.0, 0.00020000000000000017*resource_oil(t) + 0.8199999999999998, 1.0)))) - cost_oil*capital_oil(t) < 0, 0, where(price_oil*capital_oil(t)*where(resource_oil(t) < 0.0, 0.0, where(resource_oil(t) < 500.0, where(resource_oil(t) < 200.0, where(resource_oil(t) < 100.0, 0.001*resource_oil(t), 0.0015*resource_oil(t) - 0.04999999999999999), where(resource_oil(t) < 300.0, 0.002*resource_oil(t) - 0.15000000000000002, where(resource_oil(t) < 400.0, 0.002*resource_oil(t) - 0.14999999999999997, 0.0015000000000000002*resource_oil(t) + 0.04999999999999993))), where(resource_oil(t) < 800.0, where(resource_oil(t) < 600.0, 0.0009999999999999998*resource_oil(t) + 0.30000000000000016, where(resource_oil(t) < 700.0, 0.0004999999999999994*resource_oil(t) + 0.6000000000000004, 0.0003000000000000003*resource_oil(t) + 0.7399999999999998)), where(resource_oil(t) < 900.0, 0.00020000000000000017*resource_oil(t) + 0.8199999999999998, 1.0)))) - cost_oil*capital_oil(t) > growth_goal_oil*capital_oil(t), growth_goal_oil*capital_oil(t), price_oil*capital_oil(t)*where(resource_oil(t) < 0.0, 0.0, where(resource_oil(t) < 500.0, where(resource_oil(t) < 200.0, where(resource_oil(t) < 100.0, 0.001*resource_oil(t), 0.0015*resource_oil(t) - 0.04999999999999999), where(resource_oil(t) < 300.0, 0.002*resource_oil(t) - 0.15000000000000002, where(resource_oil(t) < 400.0, 0.002*resource_oil(t) - 0.14999999999999997, 0.0015000000000000002*resource_oil(t) + 0.04999999999999993))), where(resource_oil(t) < 800.0, where(resource_oil(t) < 600.0, 0.0009999999999999998*resource_oil(t) + 0.30000000000000016, where(resource_oil(t) < 700.0, 0.0004999999999999994*resource_oil(t) + 0.6000000000000004, 0.0003000000000000003*resource_oil(t) + 0.7399999999999998)), where(resource_oil(t) < 900.0, 0.00020000000000000017*resource_oil(t) + 0.8199999999999998, 1.0)))) - cost_oil*capital_oil(t)))