Carrying capacity of a meadow
Cows that graze a meadow for a summer of 25 weeks.
- Class:
MeadowCapacitySystem - Import:
from skcomplex.systems.biology.ecology import MeadowCapacitySystem - Field:
biology/ecology - Topics:
carrying capacity,agents,grid,grazing,commons - References:
- Hamill and Gilbert 2016
Use this system
The block imports the class and simulates the system with its default parameters and its tuned run settings.
from skcomplex.systems.biology.ecology import MeadowCapacitySystem
trajectory = MeadowCapacitySystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
width |
40 |
height |
40 |
cows |
80 |
growth |
0.2 |
bite |
0.75 |
threshold |
0.9 |
random_state |
0 |
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 | lattice |
| Laws | update |
| Randomness | stochastic |
| Domains | integer, real |
| Structure | variable membership |
Class
The source of the class shows how it builds its components from its model parameters.
class MeadowCapacitySystem(BaseSystem):
"""Cows that graze a meadow for a summer of 25 weeks.
It shows how many cows the meadow can carry.
Every week the grass regrows logistically, each cow eats `bite` of the grass of its patch, and each cow moves to the
nearest patch that no other cow occupies and whose grass reaches `threshold`. A cow that finds none dies. Without
regrowth a cow grazes its first patch and 25 more over the summer, so the meadow feeds about `width * height / 26`
cows, and regrowth raises its carrying capacity. The cows graze the patches down at the same pace, so a herd above
the capacity runs out of grown patches all at once and dies out within a week, instead of shrinking to the capacity.
The system has the groups `pasture` and `cows`.
Args:
width:
The number of columns of the meadow.
height:
The number of rows of the meadow.
cows:
The initial number of cows.
growth:
The weekly growth rate of the grass.
bite:
The grass a cow eats in a week.
threshold:
The least grass a patch needs for a cow to move there.
random_state:
The seed or generator of the initial cells of the cows.
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.biology.ecology import MeadowCapacitySystem
>>> [group.size for group in MeadowCapacitySystem(10, 10, cows=5).prepare().system_.elements]
[100, 5]
"""
field = 'biology/ecology'
topics = ('carrying capacity', 'agents', 'grid', 'grazing', 'commons')
references = ('Hamill and Gilbert 2016',)
until = 25
def __init__(
self,
width: int = 40,
height: int = 40,
*,
cows: int = 80,
growth: float = 0.2,
bite: float = 0.75,
threshold: float = 0.9,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.width = width
self.height = height
self.cows = cows
self.growth = growth
self.bite = bite
self.threshold = threshold
self.random_state = random_state
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of cows that graze a summer of 25 weeks on a meadow.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
rng = np.random.default_rng(self.random_state)
cells = [(column, row) for column in range(self.width) for row in range(self.height)]
picks = rng.choice(len(cells), size=self.cows, replace=False)
space = LatticeSpace((self.width, self.height), boundary='fixed')
self.system_ = System(
self.label,
elements=[
PastureElement(
'pasture',
growth=self.growth,
values={'x': [cell[0] for cell in cells], 'y': [cell[1] for cell in cells]},
size=len(cells),
space=space,
),
CowElement(
'cows',
bite=self.bite,
values={'x': [cells[int(pick)][0] for pick in picks], 'y': [cells[int(pick)][1] for pick in picks]},
size=self.cows,
space=space,
),
],
interactions=[
PastureRegrowthInteraction('regrowth', pasture='pasture'),
GrazingInteraction('grazing', cows='cows', pasture='pasture'),
HerdingInteraction('herding', cows='cows', pasture='pasture', threshold=self.threshold),
],
space=space,
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
Interactions:
PastureRegrowthInteraction, fromInteractionGrazingInteraction, fromInteractionHerdingInteraction, fromInteraction, through the shared recipeMovementInteraction
class PastureElement(Element):
"""Patch of grass that regrows logistically every week, `G' = G + g G (1 - G)`.
Args:
label:
The label of the agent or group.
grass:
The amount of grass, between 0 and 1.
growth:
The weekly growth rate `g` of the grass.
values:
Further values by name, such as the cells `x` and `y` of the patches, or `None`.
size:
The number of patches, or `None` for one.
space:
The lattice of the meadow, whose axes `x` and `y` place the patches, or `None`.
Examples:
>>> from skcomplex.systems.biology.ecology import PastureElement
>>> PastureElement('pasture', growth=0.1, size=4).size
4
"""
visual = VisualSpec('agents', {'color_by': 'grass', 'color_range': (0.0, 1.0)})
def __init__(
self,
label: str,
*,
grass: Annotated[float | Array, RealSet.closed_open(0, oo)] = 1.0,
growth: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.2,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.grass = grass
self.growth = growth
class CowElement(Element):
"""Cow of the meadow.
The grazing and herding interactions feed and move it every week.
Args:
label:
The label of the agent or group.
bite:
The grass a cow eats in a week.
values:
Further values by name, such as the cells `x` and `y` of the cows, or `None`.
size:
The number of cows, or `None` for one.
space:
The lattice of the meadow, whose axes `x` and `y` place the cows, or `None`.
Examples:
>>> from skcomplex.systems.biology.ecology import CowElement
>>> CowElement('cows', size=10).size
10
"""
visual = VisualSpec('agents', {'radius': 0.4})
def __init__(
self,
label: str,
*,
bite: Annotated[float | Array, RealSet.closed_open(0, oo)] = 0.75,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, values=values, size=size, space=space)
self.bite = bite
class PastureRegrowthInteraction(Interaction):
"""Weekly logistic regrowth of the grass of every patch of a pasture, `G' = G + g G (1 - G)`.
Args:
label:
The label of the interaction.
pasture:
The path of the group of patches.
Examples:
>>> from skcomplex.systems.biology.ecology import PastureRegrowthInteraction
>>> PastureRegrowthInteraction('regrowth', pasture='pasture').pasture
'pasture'
"""
law_classes = (UpdateLaw,)
def __init__(self, label: str, *, pasture: Role) -> None:
super().__init__(label)
self.pasture = pasture
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the regrowth rule of every patch.
Args:
context:
The namespace of the group of patches.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context.pasture, self.regrow)]
@staticmethod
def regrow(agent: PastureView, system: SystemView) -> None:
"""Grow the grass by one week of logistic growth.
Args:
agent:
The patch.
system:
The system.
"""
del system
agent.grass += agent.growth * agent.grass * (1 - agent.grass)
class GrazingInteraction(Interaction):
"""Weekly meal of every cow, a bite of the grass of the patch in its cell.
Every patch loses the bite of the cow in its cell, or what grass is left. The pairs of patches and cows eat in
random order.
Args:
label:
The label of the interaction.
cows:
The path of the group of cows.
pasture:
The path of the group of patches.
Examples:
>>> from skcomplex.systems.biology.ecology import GrazingInteraction
>>> GrazingInteraction('grazing', cows='cows', pasture='pasture').pasture
'pasture'
"""
law_classes = (UpdateLaw,)
def __init__(self, label: str, *, cows: Role, pasture: Role) -> None:
super().__init__(label)
self.cows = cows
self.pasture = pasture
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the meal, a rule of the whole system.
Args:
context:
The namespace of the system.
"""
super()._prepare(context)
self.laws_: list[BaseLaw] = [UpdateLaw(context, self.feed)]
def feed(self, system: SystemViewProtocol) -> None:
"""Let every cow eat its bite of the grass of the patch in its cell, or what grass is left.
Args:
system:
The system.
"""
patches, cows = system.get_agents('pasture'), system.get_agents('cows')
found = list(pairs(patches, cows, system.rng, PartnerSpec('cell', 'all'), capacity=1))
for index in system.rng.permutation(len(found)):
patch, cow = found[int(index)]
if patch.alive and cow.alive:
pasture = cast(PastureView, patch)
pasture.grass -= min(pasture.grass, cast(CowView, cow).bite)
class HerdingInteraction(MovementInteraction):
"""Weekly move of every cow to the nearest free patch with enough grass, or death.
The cows move in random order.
It is a movement of the cows whose step leads every cow to the patch nearest to it that no other cow occupies and
whose grass reaches `threshold`, and removes a cow that finds none. Every cow moves every week, the probability
of movement fixed to 1 without a parameter.
Args:
label:
The label of the interaction.
cows:
The path of the group of cows.
pasture:
The path of the group of patches.
threshold:
The least grass a patch needs for a cow to move there.
Examples:
>>> from skcomplex.systems.biology.ecology import HerdingInteraction
>>> HerdingInteraction('herding', cows='cows', pasture='pasture').threshold
0.9
"""
def __init__(
self,
label: str,
*,
cows: Role,
pasture: Role,
threshold: Annotated[float, RealSet.closed_open(0, oo)] = 0.9,
) -> None:
super().__init__(label, target=cows, step=self._herd)
self.cows = cows
self.pasture = pasture
self.threshold = threshold
def _get_role(self, role: str) -> str:
"""Return the cows as the target of the movement."""
return 'cows' if role == 'target' else role
@staticmethod
def _get_cell(agent: AgentViewProtocol) -> tuple[int, ...]:
"""Return the cell of an agent as a tuple of integers."""
location = agent.location
if not isinstance(location, tuple):
error_msg = (
f'The agent is located at a {type(location).__name__}, not at the coordinates of a lattice cell.'
)
raise TypeError(error_msg)
return tuple(int(item) for item in location)
def _herd(self, agent: AgentViewProtocol, system: SystemViewProtocol) -> tuple[int, ...] | None:
"""Return the cell of the nearest free patch with enough grass.
It removes the cow that finds none.
"""
patches = [cast(PastureView, patch) for patch in system.get_agents('pasture')]
cells = [self._get_cell(patch) for patch in patches]
index = {cell: number for number, cell in enumerate(cells)}
occupied = np.zeros(len(cells), dtype=bool)
occupied[
[index[self._get_cell(cow)] for cow in system.get_agents('cows') if cow.alive and cow.id != agent.id]
] = True
free = (np.asarray([patch.grass for patch in patches]) >= system.get_parameter('threshold')) & ~occupied
if not free.any():
agent.remove()
return None
distances = np.hypot(*(np.asarray(cells, dtype=float) - np.asarray(self._get_cell(agent), dtype=float)).T)
return cells[int(np.argmin(np.where(free, distances, np.inf)))]