Zhang sandpile
The Zhang sandpile.
- Class:
ZhangSandpileSystem - Import:
from skcomplex.systems.physics.criticality import ZhangSandpileSystem - Field:
physics/criticality - Topics:
lattice,avalanches,power law,continuous energy,sandpile - References:
- Zhang 1989
- Jensen 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.physics.criticality import ZhangSandpileSystem
trajectory = ZhangSandpileSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
shape |
(32, 32) |
threshold |
1.0 |
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 | real |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class ZhangSandpileSystem(BaseSystem):
"""The Zhang sandpile.
It is a continuous sandpile whose unstable sites give away all their energy.
Every step loads a site chosen at random with a packet of energy of uniform size in `[0, threshold]`. A site whose
energy reaches the threshold relaxes: its energy falls to 0 and each of its four neighbours gains a quarter of it,
all at once, until no site is unstable. Energy that would go beyond the open edges is lost. The pile organizes
itself into a critical state with avalanches of every size, recorded as `avalanche` events with their sizes,
durations, and areas, and the energies of the sites cluster near a few values. The energies start uniformly at
random below the threshold. The system has the energies `pile.energy`.
Args:
shape:
The number of rows and columns.
threshold:
The energy at which a site relaxes, which is also the largest packet.
random_state:
The seed or generator of the initial energies.
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.physics.criticality import ZhangSandpileSystem
>>> ZhangSandpileSystem((8, 8)).prepare().system_.interactions[0].mode
'reset'
"""
field = 'physics/criticality'
topics = ('lattice', 'avalanches', 'power law', 'continuous energy', 'sandpile')
references = ('Zhang 1989', 'Jensen 2023')
until = 10000
dt = 100
def __init__(
self,
shape: Sequence[int] = (32, 32),
*,
threshold: float = 1.0,
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.shape = shape
self.threshold = threshold
self.random_state = random_state
@staticmethod
def _load(packet: float, energies: Array, *, random: np.random.Generator, **kwargs: object) -> Array:
"""Return the energies with a packet added on a random site.
The packet has a uniform size in `[0, packet]`.
"""
rng = random
following = energies.copy()
following[tuple(rng.integers(size) for size in energies.shape)] += rng.uniform(0.0, packet)
return following
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the Zhang sandpile, a continuous sandpile whose unstable sites give away all their energy.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
energies = np.random.default_rng(self.random_state).uniform(0.0, self.threshold, size=tuple(self.shape))
space = LatticeSpace(tuple(self.shape), boundary='fixed')
avalanche = TopplingInteraction(
'avalanche',
target='pile',
state='energy',
threshold=self.threshold,
share=1 / 4,
mode='reset',
drive=partial(self._load, self.threshold),
)
self.system_ = System(
self.label,
elements=[EnergySiteElement('pile', energy=energies.ravel(), space=space)],
interactions=[avalanche],
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
EnergySiteElement, fromElement
Interactions:
TopplingInteraction, fromInteraction
class EnergySiteElement(Element):
"""Sites of the Zhang sandpile.
Every site stores a continuous energy.
A cascade loads the energy in random packets and resets the sites above the threshold.
Args:
label:
The label of the site or the lattice of sites.
energy:
The initial energy, or one value per site.
space:
The lattice of the sites, or `None` for one site.
Examples:
>>> from skcomplex.systems.physics.criticality import EnergySiteElement
>>> EnergySiteElement('site').energy
0.0
"""
def __init__(self, label: str, *, energy: object = 0.0, space: BaseSpace | None = None) -> None:
super().__init__(label, space=space)
self.energy = energy
class TopplingInteraction(Interaction):
"""Cascade of the members whose state reaches a threshold.
These members relax and pass shares to their neighbours. At every step the drive changes the state, and then every
member whose state reaches `threshold` relaxes, all at once, until no member does. In the mode `'redistribute'` a
relaxing member loses `threshold` and each of its neighbours gains `share`. In the mode `'reset'` a relaxing member
falls to 0 and each of its neighbours gains `share` times the state it relaxed from. In the mode `'random'` a
relaxing member loses `threshold` in parcels of `share`, and every parcel goes to one of its neighbours drawn at
random. Neighbours outside a fixed boundary take no share, so it leaves the system, and the mode `'random'` treats
every lattice as bounded. Every cascade is recorded as an event with its size, the number of relaxations, its
duration, and its area.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the group on the nodes or sites.
state:
The name of the state of the members.
threshold:
The value of the state at which a member relaxes, fixed during a run.
share:
What a neighbour of a relaxing member gains, an amount, a fraction of the state in the mode `'reset'`,
or the amount of one parcel in the mode `'random'`, fixed during a run.
mode:
`'redistribute'`, `'reset'`, or `'random'`.
drive:
A function `f(values, *, random, **kwargs)` of the array of the states, the random generator of the
simulation, and the other keywords of a rule of an `UpdateLaw`, that returns the states after the drive of
a step, or `None` for no drive. A cascade with a drive draws numbers.
neighborhood:
The neighbourhood of the member itself first and its neighbours, or `None` for the von Neumann
neighbourhood of a square lattice with its centre. A network takes `AdjacencyNeighborhood(center=True)`,
and the mode `'random'` takes a lattice neighbourhood.
Raises:
ValidationError:
The mode is unknown, the drive is not callable, the neighbourhood leaves out the member itself, or the
mode `'random'` has no lattice neighbourhood or a threshold that is not a whole number of parcels.
Examples:
>>> from skcomplex.systems.physics.common.avalanches import TopplingInteraction
>>> cascade = TopplingInteraction('cascade', target='sites', state='height', threshold=4, share=1)
>>> cascade.mode
'redistribute'
"""
law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (UpdateLaw,)
def _get_draws(self) -> bool:
"""Return whether the cascade draws.
It draws by parcels sent at random, or by a drive, which receives the generator.
"""
return super()._get_draws() or self.mode == 'random' or self.drive is not None
def __init__(
self,
label: str,
*,
target: Role,
state: str = 'x',
threshold: float = 1.0,
share: float = 0.0,
mode: str = 'redistribute',
drive: Callable[..., Array] | None = None,
neighborhood: BaseNeighborhood | None = None,
) -> None:
super().__init__(label)
self.target = target
self.state = state
self.threshold = threshold
self.share = share
self.mode = mode
self.drive = drive
self.neighborhood = neighborhood
def _check_random(self) -> None:
"""Raise an error for a random cascade without lattice neighbours or whole parcels.
The cascade needs a lattice neighbourhood and a whole number of parcels.
"""
if self.mode != 'random':
return
if self.neighborhood is not None and not isinstance(
self.neighborhood,
LatticeNeighborhood | RadiusNeighborhood,
):
error_msg = (
f'The random cascade reads the neighbourhood {self.neighborhood!r}. Give it a lattice neighbourhood.'
)
raise ValidationError(error_msg)
parcels = self.threshold / self.share if self.share > 0 else 0.0
if parcels < 1 or not float(parcels).is_integer():
error_msg = (
f'The random cascade passes the threshold {self.threshold} in parcels of {self.share}. Give a positive '
'share that divides the threshold.'
)
raise ValidationError(error_msg)
def _check_arguments(self) -> None:
"""Raise an error for a mode, drive, neighbourhood, or parcels it cannot take.
Raises:
ValidationError:
The mode is unknown, the drive is not callable, the neighbourhood leaves out the member itself, or the
mode `'random'` has no lattice neighbourhood or a threshold that is not a whole number of parcels.
"""
super()._check_arguments()
self._check_variant('mode', self.mode, MODES, (BaseSpec,))
if self.drive is not None and not callable(self.drive):
error_msg = f'The drive of the cascade must be callable, but it is {self.drive!r}.'
raise ValidationError(error_msg)
if self.neighborhood is not None and not getattr(self.neighborhood, 'center', False):
error_msg = (
f'The cascade reads the neighbourhood {self.neighborhood!r}, which leaves out the member itself. Give '
'it `center=True`.'
)
raise ValidationError(error_msg)
self._check_random()
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the cascade.
Args:
context:
The namespace of the target, the time `t`, and the parameters.
"""
super()._prepare(context)
target = self._get_symbolic(self._get_member(context, 'target'), context.t)
self.laws_ = self._get_cascade(getattr(target, self.state))
def _relax(self, threshold: float, share: float) -> Callable[..., Array]:
"""Return the rule of one relaxation of every member.
The rule reads the state of the member first and the states of its neighbours.
"""
if self.mode not in MODES:
raise self._get_variant_error(self.mode, 'mode', '_relax')
reset = self.mode == 'reset'
def relax(value: Array, *around: Array, **kwargs: object) -> Array:
gains = sum((np.where(item >= threshold, share * (item if reset else 1.0), 0.0) for item in around), 0.0)
relaxing = value >= threshold
remaining = np.where(relaxing, 0.0, value) if reset else value - threshold * relaxing
return np.asarray(remaining + gains, dtype=float)
return relax
def _scatter(self, neighborhood: BaseNeighborhood, threshold: float, share: float) -> Callable[..., Array]:
"""Return the drive that passes parcels of relaxing members to random neighbours.
Every relaxing member passes its parcels to neighbours drawn at random, among the offsets of the neighbourhood
in the dimensions of the lattice.
"""
parcels = round(threshold / share)
def scatter(values: Array, *, random: np.random.Generator, **kwargs: object) -> Array:
offsets = neighborhood._get_offsets(values.ndim) or ()
steps = np.array([offset for offset in offsets if any(offset)])
relaxing = np.argwhere(values >= threshold)
following = values.copy()
following[tuple(relaxing.T)] -= threshold
moves = steps[random.integers(len(steps), size=parcels * len(relaxing))]
targets = np.repeat(relaxing, parcels, axis=0) + moves
inside = np.all((targets >= 0) & (targets < values.shape), axis=1)
np.add.at(following, tuple(targets[inside].T), share)
return following
return scatter
def _get_cascade(self, value: Expression) -> list[BaseLaw]:
"""Return the update of the state of the target, driven and relaxed until stable."""
threshold, share = self.threshold, self.share
drive = [] if self.drive is None else [UpdateLaw(value, self.drive, arrays=True, stochastic=True)]
neighborhood = self.neighborhood
if neighborhood is None:
neighborhood = RadiusNeighborhood(1, metric='manhattan', center=True)
if self.mode == 'random':
rules: list[BaseLaw] = [
UpdateLaw(value, self._scatter(neighborhood, threshold, share), arrays=True, stochastic=True),
]
else:
rules = [UpdateLaw(value, self._relax(threshold, share), neighborhood=neighborhood)]
relaxation = relax(
value,
rules,
lambda values: bool((values < threshold).all()),
drive=drive,
activity=lambda values: values >= threshold,
)
return [UpdateLaw(value, relaxation, label=self.label)]