Olami-Feder-Christensen
The Olami-Feder-Christensen earthquake system with open edges.
- Class:
EarthquakesSystem - Import:
from skcomplex.systems.physics.seismology import EarthquakesSystem - Field:
physics/seismology - Topics:
lattice,earthquakes,power law - References:
- Olami, Feder, and Christensen 1992
- 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.seismology import EarthquakesSystem
trajectory = EarthquakesSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
shape |
(50, 50) |
alpha |
0.2 |
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 EarthquakesSystem(BaseSystem):
"""The Olami-Feder-Christensen earthquake system with open edges.
The system starts from random forces.
The fault is a cascade that resets a slipping block to zero and passes the fraction `alpha` of its force to each of
its four neighbours. With `alpha` below 1/4 the system is dissipative and its earthquake sizes still follow a power
law. Its earthquakes are recorded as `earthquake` events with their sizes, the number of slips, their durations, and
their areas. The system has the forces `fault.force`.
Args:
shape:
The number of rows and columns.
alpha:
The fraction of force passed to each neighbour.
random_state:
The seed or generator of the initial forces.
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.seismology import EarthquakesSystem
>>> EarthquakesSystem((10, 10), alpha=0.15).prepare().system_.interactions[0].share
0.15
"""
field = 'physics/seismology'
topics = ('lattice', 'earthquakes', 'power law')
references = ('Olami, Feder, and Christensen 1992', 'Jensen 2023')
until = 5000
dt = 100
def __init__(
self,
shape: Sequence[int] = (50, 50),
*,
alpha: float = 0.2,
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.alpha = alpha
self.random_state = random_state
@staticmethod
def _load(force: Array, *, random: np.random.Generator, **kwargs: object) -> Array:
"""Return the forces after the uniform loading.
The loading brings the most loaded block to the threshold.
"""
following = force + (THRESHOLD - force.max())
following[np.unravel_index(np.argmax(force), force.shape)] = THRESHOLD
return following
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the Olami-Feder-Christensen earthquakes with open edges, from random forces.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
forces = np.random.default_rng(self.random_state).random(tuple(self.shape))
space = LatticeSpace(tuple(self.shape), boundary='fixed')
self.system_ = System(
self.label,
elements=[FaultElement('fault', force=forces.ravel(), space=space)],
interactions=[
TopplingInteraction(
'earthquake',
target='fault',
state='force',
threshold=THRESHOLD,
share=self.alpha,
mode='reset',
drive=self._load,
neighborhood=RadiusNeighborhood(1, metric='manhattan', center=True),
),
],
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
FaultElement, fromElement
Interactions:
TopplingInteraction, fromInteraction
class FaultElement(Element):
"""Blocks of the Olami-Feder-Christensen earthquake system, the forces on them.
The cascade of `EarthquakesSystem` loads every block uniformly until one reaches the threshold force, and a slipping
block passes a fraction of its force to each of its four neighbours and drops to zero.
Args:
label:
The label of the blocks.
force:
The initial force, one value or one per block.
space:
The lattice of the blocks, or `None` for one block.
Examples:
>>> from skcomplex.systems.physics.seismology import FaultElement
>>> FaultElement('block').force
0.0
"""
def __init__(
self,
label: str,
*,
force: Annotated[object, RealSet.closed_open(0, oo)] = 0.0,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, space=space)
self.force = force
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)]