Toy firm investment
Heterogeneous firms that invest out of past profits and sell at random prices, with entry and exit.
- Name:
toy_firm_investment - Field:
economics/macroeconomics - Formalism: agent-based model
- References: Caiani et al. 2016; Delli Gatti et al. 2010
Factory
@register_model(
field='economics/macroeconomics',
tags=('business cycle', 'agents', 'firms'),
references=('Caiani et al. 2016', 'Delli Gatti et al. 2010'),
defaults={'until': 100},
observables=lambda system: [ObservableSpec('production', group='firms', reduce='sum', variable='Y')],
)
def toy_firm_investment(
n_firms: int = 100,
*,
gamma: float = 1.1,
phi: float = 0.1,
r: float = 0.1,
pbar: float = 0.01,
random_state: int | np.random.Generator | None = 0,
) -> System:
"""Return heterogeneous firms that invest out of past profits and sell at random prices, with entry and exit.
The firms start with net worth and capital 1 and a profit drawn from `pbar + 2 U(0, 1)`, as in the toy model of
Bargigli et al. in Caiani et al. (2016, sect. 2.1). Aggregate production fluctuates as bankrupt firms are replaced.
Args:
n_firms:
The number of firms.
gamma:
The investment accelerator.
phi:
The productivity of capital.
r:
The interest rate.
pbar:
The constant part of the price.
random_state:
The seed or generator of the initial profits.
Returns:
system:
The model, with the group `firms` and the aggregate production `production`.
Examples:
>>> from skcomplex.models.economics.macroeconomics import toy_firm_investment
>>> toy_firm_investment(20).elements[0].check().prepare().size_
20
"""
profits = pbar + 2.0 * np.random.default_rng(random_state).random(n_firms)
firms = GroupElement(
'firms',
element=InvestingFirmElement,
size=n_firms,
values={'Z': profits, 'gamma': gamma, 'phi': phi, 'r': r, 'pbar': pbar},
)
steps = [
MapInteraction(label, target='firms', state=name, function=function, form='agent')
for label, name, function in InvestingFirmElement.get_steps()
]
return System(elements=[firms], interactions=steps, time=DiscreteTime())
Components
class InvestingFirmElement(Element):
"""Firm of the toy business-cycle model, which invests a share of its last profit and sells at a random price.
Every period the firm invests `I = gamma * Z`, accumulates capital `K = K + I`, produces `Y = phi * K`, borrows
`B = max(K - A, 0)`, sells at the price `P = pbar + 2 U(0, 1)`, earns `Z = P * Y - r * K`, and adds the profit to
its net worth `A`. A firm whose net worth turns negative is replaced by an entrant with `A = K = 1` and `Z = 0`.
Args:
label:
The label of the agent or group.
visual:
How the element is drawn, or `None` for `default_visual_`.
A:
The initial net worth.
K:
The initial capital.
Z:
The initial profit.
B:
The initial debt.
Y:
The initial production.
P:
The initial price.
gamma:
The investment accelerator.
phi:
The productivity of capital.
r:
The interest rate.
pbar:
The constant part of the price.
Examples:
>>> from skcomplex.models.economics.macroeconomics import InvestingFirmElement
>>> GroupElement('firms', element=InvestingFirmElement, size=10, values={'gamma': 1.2}).size
10
"""
def __init__(
self,
label: str,
visual: VisualSpec | None = None,
*,
A: Annotated[float, StateSpec()] = 1.0,
K: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 1.0,
Z: Annotated[float, StateSpec()] = 0.0,
B: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
Y: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
P: Annotated[float, StateSpec(domain=RealSet.closed_open(0, oo))] = 0.0,
gamma: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 1.1,
phi: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 0.1,
r: Annotated[float, ParameterSpec(domain=RealSet.open(0, oo))] = 0.1,
pbar: Annotated[float, ParameterSpec(domain=RealSet.closed_open(0, oo))] = 0.01,
) -> None:
super().__init__(label, visual=visual)
self.A = A
self.K = K
self.Z = Z
self.B = B
self.Y = Y
self.P = P
self.gamma = gamma
self.phi = phi
self.r = r
self.pbar = pbar
@classmethod
def _get_view(cls) -> type[InvestingFirmView]:
"""Return the view of a firm, with its states and parameters."""
return InvestingFirmView
@staticmethod
def get_price(agent: InvestingFirmView, model: ModelView) -> float:
"""Return a random price, `pbar + 2 U(0, 1)`.
Args:
agent:
The firm.
model:
The model view of the pricing.
Returns:
price:
The price of the period.
"""
return agent.pbar + 2.0 * float(model.rng.random())
@staticmethod
def get_steps() -> tuple[tuple[str, str, Callable[[InvestingFirmView, ModelView], float]], ...]:
"""Return the steps of a period in their order, each a label, a state, and the function of its next value.
A firm invests, produces, borrows, sells, earns, adds the profit to its net worth, and, when the net worth
turns negative, is replaced by an entrant, whose profit, capital, and net worth the last three steps reset.
Returns:
steps:
The label of every step, the state it sets, and the function of its next value of the firm and the
model view.
"""
return (
('investment', 'K', lambda agent, model: agent.K + agent.gamma * agent.Z),
('production', 'Y', lambda agent, model: agent.phi * agent.K),
('borrowing', 'B', lambda agent, model: max(agent.K - agent.A, 0.0)),
('pricing', 'P', InvestingFirmElement.get_price),
('profit', 'Z', lambda agent, model: agent.P * agent.Y - agent.r * agent.K),
('accumulation', 'A', lambda agent, model: agent.A + agent.Z),
('entry_profit', 'Z', lambda agent, model: 0.0 if agent.A < 0 else agent.Z),
('entry_capital', 'K', lambda agent, model: 1.0 if agent.A < 0 else agent.K),
('entry_worth', 'A', lambda agent, model: 1.0 if agent.A < 0 else agent.A),
)
class MapInteraction(Interaction):
"""Map of a state of discrete time, whose next value is a function, or the state plus it.
In the mode `'replace'` the next value of the state is `f`, and in the mode `'increment'` it is the state plus `f`.
Under the `'synchronous'` schedule every member of a bound group updates at once, from the states at the start of
the step. Under the `'sequential'` schedule the members update one after the other, in their order, and under the
`'random-sequential'` schedule in a new random order every step, each member reading the values the members before
it set. Under the `'member'` schedule of the agent form, every member updates in its own activation, together with
the rules of its element and the other member interactions, in the order the system lists them.
In the `'symbolic'` form, `function(namespace)` returns a symbolic expression, or a vector of them for a vector
state, where `namespace.target` holds the states and parameters of the target, `namespace.sources` the namespaces
of the sources, and `namespace.t` the time, and may hold draws such as `normal('noise')`. In the `'agent'` form,
the target is an agent group and `function(agent, model)` returns the value as a number, or as an array of the
shape of a vector state, so it can read the agent, its neighbours, and the history and storage of the model view.
Args:
label:
The label of the interaction, unique among the parts of its system.
target:
The path of the element or group whose state the map sets.
state:
The name of the state of the target.
function:
The function `f(namespace)` in the symbolic form, or `f(agent, model)` in the agent form.
sources:
The paths of the elements, or members of groups such as `cells[0]`, that the function reads.
mode:
`'replace'` or `'increment'`.
schedule:
`'synchronous'`, `'sequential'`, `'random-sequential'`, or `'member'` for the agent form.
form:
`'symbolic'` for update laws of the states of the target, or `'agent'` for a rule over an agent group.
phase:
The phase of the step the agent form runs in, or `None` for the default phase.
Raises:
ValidationError:
The mode, the schedule, or the form is unknown, the symbolic form has the schedule `'member'`, the
function is not callable, or the agent form returns a value that does not match the state, raised by
`run` of the simulation.
Examples:
>>> from skcomplex.core.elements import Element
>>> from skcomplex.core.interactions import MapInteraction
>>> from skcomplex.core.spaces import DiscreteTime
>>> from skcomplex.core.system import System
>>> from skcomplex.engine.runtime import Simulation
>>> from skcomplex.specs import StateSpec
>>> from typing import Annotated, SupportsFloat
>>> class ValueElement(Element):
... def __init__(self, label, x: Annotated[float, StateSpec()] = 0.5):
... super().__init__(label)
... self.x = x
>>> logistic = MapInteraction(
... 'map', target='value', state='x', function=lambda s: 3 * s.target.x * (1 - s.target.x)
... )
>>> system = System(elements=[ValueElement('value')], interactions=[logistic], time=DiscreteTime())
>>> Simulation(system).check().prepare().run(until=2).trajectory_.values('value.x').tolist()
[0.5, 0.75, 0.5625]
>>> agents = MapInteraction('map', target='walkers', state='x', function=lambda a, m: a.x + 1, form='agent')
>>> type(agents.check().prepare().run(SimpleNamespace()).laws_[0]).__name__
'RuleLaw'
>>> from skcomplex.core.elements import GroupElement
>>> class WeightsElement(Element):
... def __init__(self, label, visual=None, *, w: Annotated[object, StateSpec(vector=True)] = 0.0):
... super().__init__(label, visual=visual)
... self.w = w
>>> group = GroupElement('weights', element=WeightsElement, size=1, values={'w': [1.0, 2.0]})
>>> doubling = MapInteraction(
... 'double', target='weights', state='w', function=lambda a, m: [2 * x for x in a.w], form='agent'
... )
>>> trajectory = Simulation(System(elements=[group], interactions=[doubling])).check().prepare().run(until=2)
>>> trajectory.trajectory_.agents('weights', 2).values['w'].tolist()
[[4.0, 8.0]]
"""
def __init__(
self,
label: str,
*,
target: Annotated[str, RoleSpec()],
state: str,
function: Callable[..., object],
sources: Annotated[Sequence[str], RoleSpec(variadic=True)] = (),
mode: str = 'replace',
schedule: str = 'synchronous',
form: str = 'symbolic',
phase: str | None = None,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.function = function
self.sources = sources
self.mode = mode
self.schedule = schedule
self.form = form
self.phase = phase
def _check(self) -> None:
"""Raise an error for an unknown mode, schedule, or form, or a function that cannot be called.
Raises:
ValidationError:
The mode, the schedule, or the form is unknown, the symbolic form has the schedule `'member'`, or the
function is not callable.
"""
super()._check()
self._check_variant('mode', self.mode, MODES, (BaseSpec,))
for name, value, variants in (
('schedule', self.schedule, SCHEDULES),
('form', self.form, FORMS),
):
if value not in variants:
error_msg = f'The {name} of map {self.label!r} is {value!r}. Use one of {", ".join(variants)}.'
raise ValidationError(error_msg)
if self.schedule == 'member' and self.form != 'agent':
error_msg = (
f'The map {self.label!r} updates every member in its activation, which only the agent form does.'
)
raise ValidationError(error_msg)
if not callable(self.function):
error_msg = f'The function of map {self.label!r} must be callable, but it is {self.function!r}.'
raise ValidationError(error_msg)
def _apply_mode(self, current: Value, value: Value) -> Value:
"""Return the next value of a state from its current value and the value of the function, by the mode."""
if self.mode == 'increment':
return current + value
if self.mode == 'replace':
return value
raise self._get_variant_error(self.mode, 'mode', '_apply_mode')
def _get_vector(self, agent: AgentViewProtocol, model: ModelViewProtocol) -> Value:
"""Return the next value of a vector state of an agent."""
current = np.asarray(getattr(agent, self.state), dtype=np.float64)
value = np.asarray(self.function(agent, model), dtype=np.float64)
if value.shape != current.shape:
error_msg = (
f'The function of map {self.label!r} returns the shape {value.shape} for the state {self.state!r} of '
f'the shape {current.shape}. Return an array of the shape of the state.'
)
raise ValidationError(error_msg)
return self._apply_mode(current, value)
def _get_value(self, agent: AgentViewProtocol, model: ModelViewProtocol) -> Value:
"""Return the next value of the state of an agent, a number or the array of a vector state."""
if np.ndim(getattr(agent, self.state)) > 0:
return self._get_vector(agent, model)
found = self.function(agent, model)
if not isinstance(found, SupportsFloat):
error_msg = f'The function of map {self.label!r} returns {found!r} for an agent. Return a number.'
raise ValidationError(error_msg)
value = float(found)
return self._apply_mode(float(getattr(agent, self.state)), value)
def _set_value(self, agent: AgentViewProtocol, value: Value) -> None:
"""Set the state of an agent to its next value."""
setattr(agent, self.state, value)
def _update_member(self, agent: AgentViewProtocol, model: ModelViewProtocol) -> None:
"""Set the state of one member to its next value."""
if agent.alive:
self._set_value(agent, self._get_value(agent, model))
def update(self, model: ModelViewProtocol) -> None:
"""Set the state of every agent of the target to its next value, by the schedule.
Args:
model:
The model view of the interaction.
"""
self._update_agents(model, self.schedule, self._get_value, self._set_value)
def _get_order(self) -> object:
"""Return the order of the members of the symbolic form: none, their own order, or a uniform draw."""
if self.schedule == 'synchronous':
return None
if self.schedule == 'sequential':
return SR(0)
return uniform(re.sub(r'\W', '_', f'order_{self.label}'))
def _get_laws(self, namespace: SimpleNamespace) -> list[BasePart]:
"""Return the update of the state to its next value, or the rule of the agent form.
Args:
namespace:
The namespace of the symbols the laws can use, with `namespace.target` and `namespace.sources`.
Returns:
laws:
The update law of the state, or the rule that runs the map of the agents.
"""
if self.form == 'agent' and self.schedule == 'member':
return [RuleLaw(self._update_member, phase=self.phase, members=self._get_role('target'))]
if self.form == 'agent':
return [RuleLaw(self.update, phase=self.phase)]
value = getattr(self._get_member(namespace, 'target'), self.state)
mapped = cast(Value, self.function(namespace))
next_value = self._apply_mode(value, mapped)
return [UpdateLaw(value, next_value, increment=self.mode == 'increment', order=self._get_order())]