Crop livestock household
Bala's crop livestock model.
- Class:
CropLivestockHouseholdSystem - Import:
from skcomplex.systems.economics.resources import CropLivestockHouseholdSystem - Field:
economics/resources - Topics:
agriculture,livestock,household,livelihood,stocks and flows,system dynamics,discrete map - 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 CropLivestockHouseholdSystem
trajectory = CropLivestockHouseholdSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
wealth |
10000.0 |
livestock |
4.0 |
crop_area |
0.5 |
yield_normal |
3.2 |
price |
50000.0 |
unit_price |
35000.0 |
purchase_price |
15000.0 |
household_consumption |
75000.0 |
max_livestock |
8.0 |
sale_fraction |
0.2 |
solver |
'auto' |
backend |
'auto' |
Tags
The system with its default parameters has these capability tags, which solvers and analyses check.
| Tag | Values |
|---|---|
| Time | discrete |
| Space | none |
| Laws | update |
| Randomness | deterministic |
| Domains | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class CropLivestockHouseholdSystem(DynamicalSystem):
"""Bala's crop livestock model.
A farming household adds livestock rearing to its crop income. A household with a fixed crop area and a grant or
loan to start rearing livestock earns the crop production times the price and the sales of animals, and spends on
its consumption and on buying animals. Every year it sells the integer part of a fraction of its herd and buys as
many animals as its wealth affords when the herd has room for them, and the animals it buys join the herd after
three years. The equations and the defaults are those of the STELLA model of Bala et al. (2017, Section 4.11.6),
whose `DELAY(purchase_of_livestock, 3)` is a pipeline of three years and whose `INT` truncates, so the model is a
yearly map. The effects of the cropping intensity and the regeneration on the yield are zero. Livestock raises the
income of the household considerably, but only after the maturation delay.
The system has the stocks `household.wealth`, `household.livestock`, and `household.yield_multiplier`, and the
purchases of the previous year `household.purchases`, over years. The observables of the system are
`household.crop_production`, `household.income_from_crop`, `household.income_from_livestock`, `household.sale`, and
`household.purchase`.
Args:
wealth:
The initial wealth of the household.
livestock:
The initial herd.
crop_area:
The crop area, in hectares.
yield_normal:
The normal crop yield, in tonnes per hectare.
price:
The price of a tonne of crop.
unit_price:
The price an animal sells for.
purchase_price:
The price of an animal bought.
household_consumption:
The consumption of the household per year.
max_livestock:
The largest herd the household can rear.
sale_fraction:
The fraction of the herd sold every year.
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 CropLivestockHouseholdSystem
>>> CropLivestockHouseholdSystem(wealth=20000.0).prepare().system_.elements[0].values['wealth']
20000.0
"""
field = 'economics/resources'
topics = (
'agriculture',
'livestock',
'household',
'livelihood',
'stocks and flows',
'system dynamics',
'discrete map',
)
references = ('Bala et al. 2017',)
until = 12
observables = tuple(
[
Observable(name, function, element='household')
for name, function in (
('crop_production', _get_crop_production),
('income_from_crop', _get_income_from_crop),
('income_from_livestock', _get_income_from_livestock),
('sale', _get_sale),
('purchase', _get_purchase),
)
],
)
def __init__(
self,
wealth: float = 10000.0,
livestock: float = 4.0,
*,
crop_area: float = 0.5,
yield_normal: float = 3.2,
price: float = 50000.0,
unit_price: float = 35000.0,
purchase_price: float = 15000.0,
household_consumption: float = 75000.0,
max_livestock: float = 8.0,
sale_fraction: float = 0.2,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label=label, solver=solver, backend=backend)
self.wealth = wealth
self.livestock = livestock
self.crop_area = crop_area
self.yield_normal = yield_normal
self.price = price
self.unit_price = unit_price
self.purchase_price = purchase_price
self.household_consumption = household_consumption
self.max_livestock = max_livestock
self.sale_fraction = sale_fraction
def _get_element_label(self) -> str:
"""Return the label of the element that holds the states."""
return 'household'
def _get_time(self) -> str:
"""Return the discrete time of the yearly steps."""
return 'discrete'
def _get_states(self) -> dict[str, object]:
"""Return the initial value of every state by name."""
sale = int(self.livestock * self.sale_fraction)
affordable = int(self.wealth / self.purchase_price)
purchases = float(affordable if affordable <= self.max_livestock + sale - self.livestock else 0)
return {
'wealth': self.wealth,
'livestock': self.livestock,
'yield_multiplier': 1.0,
'purchases': purchases,
}
def _get_parameters(self) -> dict[str, object]:
"""Return the value of every parameter by name."""
return {
'crop_area': self.crop_area,
'yield_normal': self.yield_normal,
'price': self.price,
'unit_price': self.unit_price,
'purchase_price': self.purchase_price,
'household_consumption': self.household_consumption,
'max_livestock': self.max_livestock,
'sale_fraction': self.sale_fraction,
'yield_regeneration': 0.0,
'cropping_intensity': 0.0,
}
def _get_equations(self) -> Equations:
"""Return the yearly steps of the stocks, the purchases joining the herd three years later."""
return {
'wealth': self._get_wealth,
'livestock': lambda s: s.target.livestock + s.target.purchases(t=s.t - 2) - _get_sale(s.target),
'yield_multiplier': lambda s: (
s.target.yield_multiplier * (1 + s.target.yield_regeneration - s.target.cropping_intensity)
),
'purchases': lambda s: _get_purchase(s.target),
}
@staticmethod
def _get_wealth(s: SimpleNamespace) -> Expression:
"""Return the wealth after the incomes and the spending of the year."""
household = s.target
income = _get_income_from_crop(household) + _get_income_from_livestock(household)
expenditure = _get_purchase(household) * household.purchase_price + household.household_consumption
return household.wealth + income - expenditure
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
AnnotatedElement, fromElement, through the shared recipeAnnotatedElement
Interactions:
EquationInteraction, fromInteraction, through the shared recipeEquationInteraction
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
Equations
The equations are those that symbolic returns for the system with its default parameters.
household.wealth: wealth_household(t + 1) == crop_area_household*price_household*yield_normal_household*yield_multiplier_household(t) + unit_price_household*floor(sale_fraction_household*livestock_household(t)) - purchase_price_household*where(floor(wealth_household(t)/purchase_price_household) <= max_livestock_household + floor(sale_fraction_household*livestock_household(t)) - livestock_household(t), floor(wealth_household(t)/purchase_price_household), 0) - household_consumption_household + wealth_household(t)
household.livestock: livestock_household(t + 1) == -floor(sale_fraction_household*livestock_household(t)) + livestock_household(t) + purchases_household(t - 2)
household.yield_multiplier: yield_multiplier_household(t + 1) == -(cropping_intensity_household - yield_regeneration_household - 1)*yield_multiplier_household(t)
household.purchases: purchases_household(t + 1) == where(floor(wealth_household(t)/purchase_price_household) <= max_livestock_household + floor(sale_fraction_household*livestock_household(t)) - livestock_household(t), floor(wealth_household(t)/purchase_price_household), 0)