Solvers
Define the solvers that move compiled problems forward in time.
A system picks the solver of the form its laws make, such as ScipyODESolver for the growth of a population or
GillespieSolver for the jumps of a few molecules, and takes another with solver=, such as
LogisticGrowthSystem(solver=RK4Solver(dt=0.01)).
AgentView(agent, stepper)
A view of one agent as agent rules see it.
It shows the values of the agent as attributes, such as agent.wealth of a trader, and its group's parameters, its
neighbours, and its place. Reading a value reads the agent, and setting it sets the agent, at the end of the phase
when all agents move at once. Parameters can only be read, and an unknown name raises AttributeError. A primed
value, such as the velocity x' of a bird, is no attribute, so get_value and set_value read and set it. It
shows a trader its money, a bird its heading, and a resident its neighbours.
Read more in the user guide, under Agents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent
|
Agent
|
The Mesa agent. |
required |
stepper
|
MesaSolver
|
The stepper that runs the system. |
required |
See Also
SystemView: The view of the whole system.
Examples:
>>> from skcomplex.core.engine.solvers import AgentView, MesaSolver, SystemView
>>> from skcomplex.systems.economics.econophysics import BoltzmannWealthSystem
>>> problem = BoltzmannWealthSystem(n_agents=5).prepare().simulate(until=0).problem
>>> agent = SystemView(MesaSolver().prepare(problem), 'traders').get_agents('traders')[0]
>>> isinstance(agent, AgentView), agent.wealth
(True, 1.0)
Source code in src/skcomplex/core/engine/solvers/_mesa.py
702 703 704 | |
alive
property
Whether the agent has not been removed.
group
property
Path of the agent's group.
group_label
property
Label of the agent's group, the last part of its path.
id
property
Unique id of the agent.
location
property
Grid coordinates, network node, or position of the agent.
location_key
property
Location of the agent as a key.
The key is a tuple of integers for a cell, a tuple of floats for a position, or a node. The key equals the
coordinates neighbor_cells gives for the agent's cell or node, so rules compare the cells around an agent with
the places of other agents.
create(group=None, location=None, **values)
Create an agent of a group.
By default, it is of the agent's own group at the agent's location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
str | None
|
The path of the group, or |
None
|
location
|
object
|
The location of the new agent, or |
None
|
**values
|
object
|
The initial values of states, with the element type's defaults for the others. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
agent |
AgentView
|
The new agent. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
The group is not variable, so its size cannot change. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 | |
get_agents_here(group=None)
Return the other agents in the agent's cell or node.
They are of one group or of every group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
str | None
|
The path of a group, or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
agents |
list[AgentView]
|
The other agents at the same place. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 | |
get_displacement_to(other)
Return the vector from the agent to another agent or a location.
On a torus, it is the shortest one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
AgentView | object
|
An agent, or grid coordinates or a position. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
displacement |
NDArray[float64]
|
One component per axis of the space. |
Raises:
| Type | Description |
|---|---|
SpaceError
|
The agents live on a network or in no space. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 | |
get_distance_to(other)
Return the distance to another agent or a location.
On a network, it is the number of hops.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
AgentView | object
|
An agent, or a network node, grid coordinates, or a position. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
distance |
float
|
The Euclidean length of the shortest displacement, or the length of the shortest path on a network. |
Raises:
| Type | Description |
|---|---|
SpaceError
|
The agents live in no space. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 | |
get_lags(state, window=None)
Return the past values of a state of an agent.
They are the values at the ends of the last steps, the last one last. An agent remembers the past values of a
state that a law reads at earlier steps, such as x(t=t - m): the agent stepper keeps its last m values in
the companion states <state>_lag1 to <state>_lag<m>, which rules may also read one by one. Before the first
steps the lags hold their starting values, given as 'x[-k]', or else the starting value of the state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
str
|
The name of a state with lags. |
required |
window
|
int | None
|
The number of last values, or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
values |
NDArray[float64]
|
The values, the oldest first. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The state of the agent keeps no lags. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 | |
get_neighbor_cells()
Return the coordinates of the cells or nodes around the agent's cell or node.
Returns:
| Name | Type | Description |
|---|---|---|
locations |
list[object]
|
The neighbouring cell coordinates or network nodes. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
853 854 855 856 857 858 859 860 | |
get_neighbors(radius=None, layer=None, group=None, over=None)
Return the agents around the agent.
They are the agents in the cells or nodes around it, within a radius, around it in a layer, or joined to it by
an edge of the Delaunay triangulation of the positions of its group, or of group, in a continuous space. The
triangulation is that of the positions when the group is first read in a step, or after agents of the group are
created or removed, so the agents of a step read the same one, and in a periodic box it covers the periodic
images. Agents of a
variable group placed on the nodes of a network make a set of members per node that grows and shrinks during a
run, such as the balls of an urn on every node, and an agent on a node reads the sets of the neighbouring nodes
as the neighbours of one group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
radius
|
float | None
|
The distance within which agents are neighbours in a continuous space. |
None
|
layer
|
str | None
|
The layer of a network space whose edges join the agent to its neighbours, or |
None
|
group
|
str | None
|
The path of a group whose agents alone are returned, or |
None
|
over
|
DelaunayNeighborhood | None
|
A Delaunay neighbourhood of a continuous space, or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
agents |
list[AgentView]
|
The neighbouring agents. |
Raises:
| Type | Description |
|---|---|
SpaceError
|
A Delaunay neighbourhood is read outside a continuous space. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 | |
get_referenced(state)
Return the member of another group that a reference state of the agent names.
The state names it by its id. A value annotated as Annotated[int, Member('firms')] holds the id of a member
of the group, or -1 for none, such as the bank of a customer or the employer of a worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
str
|
The name of a reference state. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
agent |
AgentView | None
|
The member the state names, or |
Raises:
| Type | Description |
|---|---|
KeyError
|
The state of the agent names no member of a group. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 | |
get_regions_here(layer)
Return the indices of the regions of a layer that contain the agent.
Regions with the agent on their boundaries count too.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer
|
str
|
The name of the layer. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
indices |
list[int]
|
The indices of the regions, in increasing order. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
The space has no such layer. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 | |
get_value(name)
Return a value of the agent by the name users read, such as x'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of a state or a parameter, primed for a derivative, such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
object
|
The value. |
Raises:
| Type | Description |
|---|---|
AttributeError
|
The agent has no value of that name. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 | |
move_to(location)
Move the agent to a cell, a node, or a position.
It may also move to a uniform point inside a polygon.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
location
|
object
|
The cell coordinates, network node, or position, or a polygon in a continuous space. |
required |
Raises:
| Type | Description |
|---|---|
SpaceError
|
The location does not fit the space. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 | |
remove()
Remove the agent from the system.
The agent is first checked to hold none of a conserved quantity.
Raises:
| Type | Description |
|---|---|
ConservationError
|
A state tagged with a quantity is not zero, so removing the agent would destroy it. Settle the holdings with transfers first. |
SimulationError
|
The agent's group is not variable, so its size cannot change. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 | |
set_value(name, value)
Set a state of the agent by the name users read, such as x'.
It sets the agent at the end of the phase in a simultaneous phase.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of a state, primed for a derivative, such as |
required |
value
|
object
|
The new value. |
required |
Raises:
| Type | Description |
|---|---|
AttributeError
|
The agent has no state of that name. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 | |
BaseSolver(*, random_state=None, until=math.inf)
Bases: BaseConfig[P, StepSpec]
An abstract solver, which moves a compiled problem forward in time.
A system turns its laws into a problem of one form, such as ordinary differential equations, and a solver moves that
problem from one time to the next, such as the ScipyODESolver that LogisticGrowthSystem picks.
prepare(problem) readies it for a problem, and run(step) moves the state of a StepSpec from its time to its
end time and keeps the state there in state_. The last call run(step, final=True) frees what prepare took,
such as an outside program. A subclass writes the private methods _get_form, _get_support, and _advance. A
solver that draws random numbers whatever laws it solves, such as a Monte Carlo run of particles, sets the class
attribute draws. Solvers move the populations of an ecosystem, the spins of a magnet, and the prices of a market.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. A seed starts a stream spawned from
|
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped, which solvers that plan or draw a whole run read. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
problem_ |
P
|
The problem the solver is prepared to. |
rng_ |
Generator
|
The random number generator of stochastic solvers. |
initial_state_ |
Array
|
The state vector of the first frame, which solvers that derive states fill in. |
events_ |
list[BaseRecordSpec]
|
The events of the last run, in the order they happened. |
stopped_at_ |
float | None
|
The time at which a terminal event ended the run, or |
snapshot_ |
object | None
|
The state the solver keeps outside the state vector, such as agents, after the last run, or |
agents_ |
Mapping[str, list[object]]
|
The views of the agents alive after the last run, as rules receive them, by path of their agent group. |
state_ |
Array
|
The state vector at the end time of the last step. |
draw_recorder_ |
DrawRecorder | None
|
The recorder that keeps or replays the named draws and jump firings of the run, which the simulation sets
after preparing the solver, or |
See Also
Solver: The base of the solvers of the general compiler. StepSpec: The step a solver moves.
Examples:
>>> from skcomplex.core.engine.solvers import BaseSolver
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> solver = LogisticGrowthSystem().prepare().system_.solver_
>>> isinstance(solver, BaseSolver), type(solver).__name__
(True, 'ScipyODESolver')
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
draws = False
class-attribute
Whether the solver draws random numbers whatever the laws it solves.
get_supported_tags()
classmethod
Return the capability tags the solver supports.
They come from the classes of time, space, and laws it supports.
Returns:
| Name | Type | Description |
|---|---|---|
tags |
Tags
|
The supported times, spaces, and law kinds, where an empty field supports any value. |
Examples:
>>> from skcomplex.core.engine.solvers import GillespieSolver
>>> sorted(GillespieSolver.get_supported_tags().laws)
['jump', 'update']
Source code in src/skcomplex/core/engine/solvers/_base.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
CaputoSolver(*, random_state=None, until=math.inf)
Bases: Solver
An abstract solver of Caputo fractional differential equations on a fixed grid.
A state of order alpha follows D^alpha x = f(t, x), whose rate remembers the whole past of the state, such as
the slow relaxation of a polymer, and a state of order 1 follows dx/dt = f(t, x). The solver keeps the history of
the run on the grid t0 + k dt from the start of the run. A change of a fractional state between frames starts a
new history from the changed state, and a change of a state of order 1 goes on. It is the base of the solvers of
materials with memory, anomalous diffusion, and epidemics with memory.
Read more in the user guide, under Solvers.
See Also
FractionalABMSolver: The default fractional solver. L1Solver: Weighs the past steps by the L1 scheme. GrunwaldLetnikovSolver: Weighs the past steps by Grünwald-Letnikov.
Examples:
>>> from skcomplex.core.engine.solvers import CaputoSolver, L1Solver
>>> isinstance(L1Solver(dt=0.01), CaputoSolver)
True
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
CoSimulationSolver(solvers=None, sync_dt=None, scheme='gauss-seidel', split=False, *, random_state=None, until=math.inf)
Bases: Solver
A solver that moves every component of a system with a solver of its own.
Every component is moved to each meeting time, every sync_dt, and between meeting times it holds the values of the
other components at their last values, so the split adds an error of the order of sync_dt. Gauss-Seidel moves the
components in order, each reading what the components before it already moved, and Jacobi moves every component from
the same values. A law that reads a total over the agents of another component reads the value at the last meeting
time. Choose it when components need different solvers, such as cars on a road beside their exhaust, cells beside
the food they eat, or farmers beside their crops.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
solvers
|
Mapping[str, BaseSolver] | None
|
The solver of a partition by its name, with the solver of its nested system or the default solver of its form for the others. |
None
|
sync_dt
|
float | None
|
The time between synchronisation points, which must divide the frame duration, or |
None
|
scheme
|
str
|
|
'gauss-seidel'
|
split
|
bool
|
Whether to split a problem of one form into one partition per subsystem. |
False
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
steppers_ |
The stepper of every partition by partition name. |
See Also
Solver: The base of the solvers each component may take.
Examples:
>>> from skcomplex.core.engine.solvers import CoSimulationSolver
>>> from skcomplex.core.systems import System
>>> from skcomplex.systems.biology.ecology import LogisticGrowthSystem
>>> system = System(systems=[LogisticGrowthSystem(label='a'), LogisticGrowthSystem(label='b')])
>>> system.set_params(solver=CoSimulationSolver(split=True)).prepare().simulate(until=1, dt=1).states.shape
(2, 2)
Source code in src/skcomplex/core/engine/solvers/_cosimulation.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
CollocationSolver(objective=None, *, terminal=0.0, sense='min', nodes=101, scheme='hermite-simpson', method='SLSQP', tolerance=1e-10, max_iterations=1000, random_state=None, until=math.inf)
Bases: OptimalControlSolver
A solver of optimal control by direct collocation.
The states and controls at the points of a time grid become the unknowns of one large optimisation. The trapezoidal
scheme asks the states of neighbouring points to differ by the trapezoidal integral of their rates, and the
Hermite-Simpson scheme adds a midpoint to every interval. The cost is the sum of the running cost over the points
plus the terminal cost, the controls stay within their bounds, and states that cannot be negative stay nonnegative.
SciPy's minimize solves it with the slope of the cost and of the constraints derived by Sage, such as the fishing
effort of 1 that a fishery keeps at the start. Choose it for controls that minimise a cost under constraints, in
vaccination, the harvest of a fishery, and the path of a rocket.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
Cost | None
|
The running cost, a function of the namespace |
None
|
terminal
|
Cost
|
The terminal cost at the horizon, a function of the same namespace or a number. |
0.0
|
sense
|
str
|
|
'min'
|
nodes
|
int
|
The number of times of the grid, from the start to the horizon. |
101
|
scheme
|
str
|
|
'hermite-simpson'
|
method
|
str
|
The method of |
'SLSQP'
|
tolerance
|
float
|
The tolerance of the optimiser. |
1e-10
|
max_iterations
|
int
|
The largest number of iterations of the optimiser. |
1000
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
solution_ |
The optimal solution of the run. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The sense, the scheme, or the method is unknown, or the grid has fewer than 2 nodes. |
SolverError
|
The solver has no objective, or the optimiser does not converge. |
See Also
PontryaginSolver: Solves smooth problems by the maximum principle.
Examples:
>>> from skcomplex.systems.economics.resources import OptimalHarvestingSystem
>>> system = OptimalHarvestingSystem().prepare()
>>> trajectory = system.simulate(until=5.0)
>>> type(system.system_.solver_).__name__, float(trajectory.get_values('resource.effort')[0].round(3))
('CollocationSolver', 1.0)
Source code in src/skcomplex/core/engine/solvers/_collocation.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
CrankNicolsonSolver(dt=0.01, *, random_state=None, until=math.inf)
Bases: SplitSolver
A solver that steps the linear part by Crank-Nicolson and the rest by Heun.
A predictor takes a Crank-Nicolson step, the trapezoidal rule for the linear part, with the rest at the start of the step, and a corrector repeats it with the rest averaged over the start and the predicted end, so the scheme is of order 2. For a linear field, such as the heat of a plate, it is the trapezoidal rule. Choose it for stiff diffusion with a mild nonlinear part, in models of heat flow, reaction and diffusion, and option prices.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed internal step. |
0.01
|
See Also
IMEX2Solver: Guesses the rest from the last two steps.
Examples:
>>> from skcomplex.core.engine.solvers import CrankNicolsonSolver
>>> from skcomplex.systems.physics.heat import HeatDiffusionSystem
>>> solver = CrankNicolsonSolver(dt=0.5)
>>> u = HeatDiffusionSystem((16, 16), solver=solver).prepare().simulate(until=2).get_values('plate.u')
>>> round(float(u[0].sum()), 6), round(float(u[-1].sum()), 6)
(16.0, 16.0)
Source code in src/skcomplex/core/engine/solvers/_split.py
99 100 101 102 103 104 105 106 107 108 | |
ETDRK4Solver(dt=0.01, *, random_state=None, until=math.inf)
Bases: SplitSolver
A solver of order 4 by the exponential time differencing of Cox and Matthews.
It solves the linear part of a spectral field exactly per Fourier mode and steps the rest with a scheme of order 4, with the weights computed by contour integrals as Kassam and Trefethen propose, so stiff patterns take large steps. Linked states of a field use a small matrix exponential per mode, and states outside spectral fields take classical Runge-Kutta steps. Choose it for stiff fields on a periodic grid, such as the stripes of Swift-Hohenberg, the chaos of Kuramoto-Sivashinsky, and the flow of a heated film.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed internal step. |
0.01
|
See Also
IMEX2Solver: Steps the linear part of any field implicitly.
Examples:
>>> from skcomplex.core.engine.solvers import ETDRK4Solver
>>> from skcomplex.systems.physics.pattern_formation import SwiftHohenbergSystem
>>> system = SwiftHohenbergSystem(shape=(32, 32), solver=ETDRK4Solver(dt=0.25)).prepare()
>>> system.simulate(until=1, dt=1).get_values('cells.u').shape
(2, 1024)
Source code in src/skcomplex/core/engine/solvers/_split.py
99 100 101 102 103 104 105 106 107 108 | |
EulerMaruyamaSolver(dt=0.001, *, random_state=None, until=math.inf)
Bases: SDESolver
A solver that steps stochastic differential equations by Euler-Maruyama.
Every step of length h sets x + f(x) h + g(x) dW, the drift f plus the noise g times a normal increment dW
of variance h, such as a stock price of 100 that ends near 131 after a year in one run. Choose it as the default
for noise in continuous time, in stock prices, diffusing particles, and noisy gene expression.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest internal time step. |
0.001
|
See Also
HeunSolver: Averages the drift over each step. MilsteinSolver: Corrects noise whose size depends on the state.
Examples:
>>> from skcomplex.core.engine.solvers import EulerMaruyamaSolver
>>> from skcomplex.systems.economics.finance import GeometricBrownianMotionSystem
>>> system = GeometricBrownianMotionSystem(solver=EulerMaruyamaSolver(dt=0.01)).prepare()
>>> system.simulate(until=1, dt=1, random_state=0).get_values('asset.price').round(2).tolist()
[100.0, 131.0]
Source code in src/skcomplex/core/engine/solvers/_sde.py
55 56 57 58 59 60 61 62 63 64 | |
EulerSolver(dt=0.001, *, random_state=None, until=math.inf)
Bases: Solver
A solver that steps ordinary differential equations by the explicit Euler rule.
Every step of length h sets x + h f(t, x), so a population that doubles its rate grows from 1 to 2.25 over one
time unit in two steps of 0.5. It is the rule that Vensim and Stella use by default, so a run with the time step of
a model file of those tools matches it step by step. Choose it for teaching and for quick checks with a small step,
in models of populations, stocks and flows, and cooling.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest internal time step. |
0.001
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
See Also
RK4Solver: Steps with the classical Runge-Kutta rule of fourth order. ScipyODESolver: Steps with adaptive steps of SciPy.
Examples:
>>> from skcomplex.core.engine.solvers import EulerSolver
>>> from skcomplex.systems.biology.ecology import ExponentialGrowthSystem
>>> system = ExponentialGrowthSystem(n=1.0, r=1.0, solver=EulerSolver(dt=0.5)).prepare()
>>> system.simulate(until=1, dt=1).get_values('population.x').tolist()
[1.0, 2.25]
Source code in src/skcomplex/core/engine/solvers/_euler.py
71 72 73 74 75 76 77 78 79 80 | |
ExternalSolver(*, random_state=None, until=math.inf)
Bases: Solver
An abstract solver that runs a compiled problem in another program.
It translates the problem for an outside library, such as Mesa for agents or LAMMPS for atoms. Before the first
frame prepare checks every element, interaction, and law, and raises one error that lists everything the library
cannot run. A subclass writes the private methods _get_name, _get_form, _unsupported, _build, and
_advance. It runs the traders of a market, the atoms of a liquid, and the birds of a flock in tools made for them.
Read more in the user guide, under Solvers.
See Also
MesaSolver: Runs agents in Mesa. LammpsSolver: Runs particles in LAMMPS.
Examples:
>>> from skcomplex.core.engine.solvers import ExternalSolver, MesaSolver
>>> isinstance(MesaSolver(), ExternalSolver)
True
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
FractionalABMSolver(dt=0.01, *, random_state=None, until=math.inf)
Bases: CaputoSolver
A solver of fractional equations by the Adams-Bashforth-Moulton method.
It solves x(t) = x_0 + (1 / Gamma(alpha)) int_0^t (t - s)^(alpha - 1) f(s, x(s)) ds, the same equation written as
an integral over the past, as Diethelm, Ford, and Freed propose: a rectangle rule over the whole run predicts the
next state, and a trapezoidal rule corrects it, so it is of order 1 + alpha. States of order 1 take Heun steps.
Choose it for fractional equations of moderate size, such as the relaxation of a polymer from 1 to 0.43 in one time
unit, the spread of a drug in tissue, and epidemics with memory.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed step. Frames must fall on multiples of it. |
0.01
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
orders_ |
The order of every state component. |
See Also
L1Solver: An explicit scheme of order 1. GrunwaldLetnikovSolver: An explicit scheme of order 1.
Examples:
>>> from skcomplex.core.engine.solvers import FractionalABMSolver
>>> from skcomplex.systems.mathematics.fractional_dynamics import FractionalRelaxationSystem
>>> system = FractionalRelaxationSystem(order=0.5, solver=FractionalABMSolver(dt=0.001)).prepare()
>>> system.simulate(until=1, dt=1).get_values('relaxation.x').round(2).tolist()
[1.0, 0.43]
Source code in src/skcomplex/core/engine/solvers/_fractional_abm.py
53 54 55 56 57 58 59 60 61 62 | |
FractionalEulerMaruyamaSolver(dt=0.001, horizon=None, max_increments=MAX_INCREMENTS, *, random_state=None, until=math.inf)
Bases: Solver
A solver of stochastic equations driven by fractional and ordinary noise.
Fractional noise has long memory set by a Hurst index, so a step up makes the next step up more likely when the
index is above 0.5. The solver draws the linked increments of every fractional noise for the whole run when it first
moves, on the grid t0 + k dt up to the horizon, and adds each step's increment times its size. Ordinary noise
takes independent increments, and a run passes its end time as the horizon when the solver has none. Choose it for
rough prices in finance, river flows, and network traffic.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed internal step. Frames must fall on multiples of it. |
0.001
|
horizon
|
float | None
|
The last time the run reaches, or |
None
|
max_increments
|
int
|
The largest number of stored increments, one per step, fractional noise row, and group member. |
MAX_INCREMENTS
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
horizon_ |
The horizon of the drawn increments. |
|
hurst_ |
The Hurst index of every noise row the increments were drawn with. |
See Also
EulerMaruyamaSolver: Steps noise without memory.
Examples:
>>> from skcomplex.systems.physics.soft_matter import FractionalBrownianMotionSystem
>>> system = FractionalBrownianMotionSystem(n_walkers=10).prepare()
>>> type(system.system_.solver_).__name__, system.simulate(until=1, dt=1).get_values('walkers.x').shape
('FractionalEulerMaruyamaSolver', (2, 10, 2))
Source code in src/skcomplex/core/engine/solvers/_fractional_euler_maruyama.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
GillespieSolver(*, random_state=None, until=math.inf)
Bases: Solver
A solver that runs jump processes exactly by the direct method of Gillespie.
It draws the time to the next jump from the total rate and picks the jump in proportion to its rate, one jump at a
time, such as each count of three counters that each tick at rate 1. A jump that would come after until is
dropped, which is exact because the waiting times have no memory. A run that records its draws keeps the time and
law of every jump, and a run that replays them gives the log likelihood of the path. Choose it when the units are
few and each jump matters, such as molecules in a cell, a small outbreak, or a queue.
Read more in the user guide, under Solvers.
See Also
RenewalSolver: Runs jumps whose waiting times have memory.
Examples:
>>> from skcomplex.core.engine.solvers import GillespieSolver
>>> from skcomplex.systems.mathematics.stochastic_processes import PoissonProcessSystem
>>> system = PoissonProcessSystem(n_processes=3, solver=GillespieSolver()).prepare()
>>> system.simulate(until=10, dt=10, random_state=0).get_values('counters.count')[-1].tolist()
[6.0, 11.0, 5.0]
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
GradientDescentSolver(precision='float64', *, random_state=None, until=math.inf)
Bases: BaseSolver[LearningProblemSpec]
A solver that trains the parameters of a nested system by gradient steps.
Every unit of time is one epoch on JAX and Optax. The solver shuffles the sequences of the dataset, splits them into
batches, and for every batch runs the nested system over each sequence, writing the values of the dataset into its
parameters before every inner step. The loss is the weighted mean of the loss observable over the steps, its
gradient comes from jax.value_and_grad, and an Optax optimizer updates the trained parameters. Backpropagation
through time stops every truncation steps. The mean loss of every epoch and each metric are recorded as reporters,
such as <interaction path>/loss. It trains a recurrent network on text, a model of an epidemic on case counts, and
a controller of a pendulum.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
precision
|
str
|
|
'float64'
|
random_state
|
int | Generator | None
|
The seed or generator of the shuffling of the sequences. |
None
|
until
|
float
|
The end time of the run the solver prepares for. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
theta_ |
TracedArray
|
The trained parameters after the last epoch, as a JAX array. |
optimizer_state_ |
OptState
|
The state of the Optax optimizer, such as the moments of Adam. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The precision is unknown. |
See Also
GradientFlowSolver: Follows the slope of an objective without data.
Examples:
>>> from skcomplex.core.engine.solvers import GradientDescentSolver
>>> GradientDescentSolver(precision='float32').precision
'float32'
Source code in src/skcomplex/core/engine/solvers/_gradient_descent.py
81 82 83 84 85 86 87 88 89 | |
GradientFlowSolver(*, dt=0.01, random_state=None, until=np.inf)
Bases: BaseObjectiveSolver
A solver that follows the steepest descent of an objective over time.
It steps the flow x' = -grad U(x) of the objective U over its target states with explicit steps of size dt,
which is gradient descent with the learning rate dt, such as a ball in the well (x - 2)^2 that rolls from 0
towards 2. The trajectory shows the path to a minimum, such as a ball rolling into a well, a network of springs
relaxing, or the weights of a model as its loss falls.
Read more in the user guide, under Solvers.
See Also
MinimizeSolver: Finds the minimum of the objective in one frame.
Examples:
>>> from skcomplex.core.engine.solvers import GradientFlowSolver
>>> solver = GradientFlowSolver(dt=0.1)
>>> solver.dt
0.1
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The size of a step of the flow, the learning rate of gradient descent. |
0.01
|
random_state
|
int | Generator | None
|
The seed or generator of the solver, which draws nothing. |
None
|
until
|
float
|
The end time of the run the solver prepares for. |
inf
|
Source code in src/skcomplex/core/engine/solvers/_gradient_flow.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
GrunwaldLetnikovSolver(dt=0.01, memory=None, *, random_state=None, until=math.inf)
Bases: ConvolutionSolver
A solver of Caputo fractional equations by the Grünwald-Letnikov scheme.
A step sets dt^alpha f(t_(k-1), x_(k-1)) = sum_(j=0)^k w_j (x_(k-j) - x_0) with the weights
w_j = (-1)^j binomial(alpha, j), so it is of order 1. States of order 1 take explicit Euler steps. Choose it for a
simple explicit fractional scheme with a small step, such as the relaxation of a polymer, anomalous diffusion, and
fractional chaotic flows.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed step. Frames must fall on multiples of it. |
0.01
|
memory
|
float | None
|
The length of time over which the history enters with its exact weights, or |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
orders_ |
The order of every state component. |
See Also
L1Solver: Another explicit scheme of order 1.
FractionalABMSolver: A predictor and corrector of order 1 + alpha.
Examples:
>>> from skcomplex.core.engine.solvers import GrunwaldLetnikovSolver
>>> from skcomplex.systems.mathematics.fractional_dynamics import FractionalRelaxationSystem
>>> system = FractionalRelaxationSystem(order=0.5, solver=GrunwaldLetnikovSolver(dt=0.001)).prepare()
>>> system.simulate(until=1, dt=1).get_values('relaxation.x').round(2).tolist()
[1.0, 0.43]
Source code in src/skcomplex/core/engine/solvers/_convolution.py
57 58 59 60 61 62 63 64 65 66 67 68 | |
HeunSolver(dt=0.001, *, random_state=None, until=math.inf)
Bases: SDESolver
A solver of stochastic differential equations by a predictor and a corrector.
The predictor X~ = X + f(X) h + g(X) dW gives the corrector X + (f(X) + f(X~)) h / 2 + g(X) dW, which averages
the drift over the step and keeps the noise of the start, so it is of strong order 1 for noise of fixed size. Choose
it for smoother paths than Euler-Maruyama at the same step, in models of Brownian particles, noisy oscillators, and
prices.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed internal step. |
0.001
|
See Also
EulerMaruyamaSolver: The default solver of noise in continuous time.
Examples:
>>> from skcomplex.core.engine.solvers import HeunSolver
>>> from skcomplex.systems.economics.finance import GeometricBrownianMotionSystem
>>> system = GeometricBrownianMotionSystem(solver=HeunSolver(dt=0.01)).prepare()
>>> system.simulate(until=1, dt=1, random_state=0).get_values('asset.price').round(2).tolist()
[100.0, 131.01]
Source code in src/skcomplex/core/engine/solvers/_sde.py
55 56 57 58 59 60 61 62 63 64 | |
HorizonError
Bases: SolverError
An error raised when a solver with a fixed horizon is asked to go beyond it.
A solver that draws its noise for the whole run in advance, such as fractional noise up to a horizon of 1, cannot move past that horizon, and raises it with the times. It guards the runs of rough prices, river flows, and network traffic.
Read more in the user guide, under Troubleshooting.
See Also
FractionalEulerMaruyamaSolver: Draws its noise up to a horizon.
Examples:
>>> from skcomplex.core.engine.solvers import HorizonError
>>> from skcomplex.core.errors import SolverError
>>> issubclass(HorizonError, SolverError)
True
IMEX2Solver(dt=0.01, *, random_state=None, until=math.inf)
Bases: SplitSolver
A solver of order 2 that steps stiff parts implicitly and the rest explicitly.
Every step solves (I - h L / 2) x_{n+1} = (I + h L / 2) x_n + h (3 N_n - N_{n-1}) / 2, the trapezoidal rule for
the linear part L and a guess of the rest N from the last two steps. It starts with one Crank-Nicolson step, and
a call that does not go on from the time and state of the last call starts again. Choose it for fields with stiff
diffusion and reactions, such as the Gray-Scott patterns of chemistry, the pulses of a nerve, and the heat of a
plate.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed internal step. |
0.01
|
See Also
IMEXEulerSolver: The same split with order 1.
Examples:
>>> from skcomplex.core.engine.solvers import IMEX2Solver
>>> from skcomplex.systems.physics.heat import HeatDiffusionSystem
>>> system = HeatDiffusionSystem((16, 16), solver=IMEX2Solver(dt=0.5)).prepare()
>>> u = system.simulate(until=2).get_values('plate.u')
>>> round(float(u[0].sum()), 6), round(float(u[-1].sum()), 6)
(16.0, 16.0)
Source code in src/skcomplex/core/engine/solvers/_split.py
99 100 101 102 103 104 105 106 107 108 | |
IMEXEulerSolver(dt=0.01, *, random_state=None, until=math.inf)
Bases: SplitSolver
A solver of order 1 that steps stiff parts implicitly and the rest explicitly.
Every step solves (I - h L) x_{n+1} = x_n + h N(x_n) for the linear part L, such as diffusion, and the rest N,
such as a reaction, so a large step stays stable where an explicit step would blow up. It solves sparse systems for
finite differences and finite elements and divides per Fourier mode for spectral fields. Choose it as a stable first
try on a stiff field, in models of heat flow, patterns, and the spread of a species.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed internal step. |
0.01
|
See Also
IMEX2Solver: The same split with order 2. CrankNicolsonSolver: Steps the linear part by the trapezoidal rule.
Examples:
>>> from skcomplex.core.engine.solvers import IMEXEulerSolver
>>> from skcomplex.systems.physics.heat import HeatDiffusionSystem
>>> system = HeatDiffusionSystem((16, 16), solver=IMEXEulerSolver(dt=0.5)).prepare()
>>> u = system.simulate(until=2).get_values('plate.u')
>>> round(float(u[0].sum()), 6), round(float(u[-1].sum()), 6)
(16.0, 16.0)
Source code in src/skcomplex/core/engine/solvers/_split.py
99 100 101 102 103 104 105 106 107 108 | |
IterationSolver(*, phases=(), random_state=None, until=math.inf)
Bases: Solver
A solver that applies a discrete map once per unit of time.
Every step applies the update laws once, such as x ← r x (1 - x) of the logistic map, which takes 0.2 to 0.592 and
then 0.894 at r = 3.7. A map that draws random numbers takes them from the solver's generator at every step, and a
step may run its laws in named phases, each reading what the phases before it set, such as a count in the phase
count and its copy in the phase copy. It runs the logistic map of a population, the cobweb of a market, and the
layers of a neural network.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phases
|
Sequence[PhaseSpec]
|
The named phases of a step after the default one, such as |
()
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic maps. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
See Also
LatticeSolver: Applies the laws of a lattice once per step. MesaSolver: Runs agents one step per unit of time.
Examples:
>>> from skcomplex.core.engine.solvers import IterationSolver
>>> from skcomplex.systems.mathematics.dynamical_systems import LogisticMapSystem
>>> system = LogisticMapSystem(solver=IterationSolver()).prepare()
>>> system.simulate(until=2).get_values('map.x').round(3).tolist()
[0.2, 0.592, 0.894]
Source code in src/skcomplex/core/engine/solvers/_maps.py
60 61 62 63 64 65 66 67 68 | |
KineticSolver(n=10000, dt=0.01, *, random_state=None, until=math.inf)
Bases: Solver
A solver that runs encounter laws with a finite number of particles.
Every density is held as counts of particles of one mass, chosen so that the largest starting density has n
particles. In each step a particle meets the field with a chance that grows with the density it meets, and picks an
outcome in proportion to its rate, so the run carries the noise of a finite population and approaches the gain and
loss equations as n grows, such as 1000 traders that swap money. It runs kinetic models of wealth, of opinions,
and of thin gases.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
The number of particles of the largest initial density. |
10000
|
dt
|
float
|
The largest time step. |
0.01
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
See Also
GillespieSolver: Runs jumps of counted units exactly.
Examples:
>>> from skcomplex.core.engine.solvers import KineticSolver
>>> solver = KineticSolver(n=1000, dt=0.1)
>>> solver.n, solver.dt
(1000, 0.1)
Source code in src/skcomplex/core/engine/solvers/_kinetics.py
75 76 77 78 79 80 81 82 83 84 85 86 | |
L1Solver(dt=0.01, memory=None, *, random_state=None, until=math.inf)
Bases: ConvolutionSolver
A solver of Caputo fractional equations by the L1 scheme of order 1.
It draws the state as straight lines between grid points inside the fractional integral, so a step sets
Gamma(2 - alpha) dt^alpha f(t_(k-1), x_(k-1)) = sum_(j=0)^(k-1) b_j (x_(k-j) - x_(k-j-1)) with the weights
b_j = (j + 1)^(1 - alpha) - j^(1 - alpha). States of order 1 take explicit Euler steps. Choose it for fractional
orders below 1 with a smooth solution, such as the relaxation of a polymer, subdiffusion in a cell, and the creep of
a material.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed step. Frames must fall on multiples of it. |
0.01
|
memory
|
float | None
|
The length of time over which the history enters with its exact weights, or |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
orders_ |
The order of every state component. |
See Also
GrunwaldLetnikovSolver: Another explicit scheme of order 1.
FractionalABMSolver: A predictor and corrector of order 1 + alpha.
Examples:
>>> from skcomplex.core.engine.solvers import L1Solver
>>> from skcomplex.systems.mathematics.fractional_dynamics import FractionalRelaxationSystem
>>> system = FractionalRelaxationSystem(order=0.5, solver=L1Solver(dt=0.001)).prepare()
>>> system.simulate(until=1, dt=1).get_values('relaxation.x').round(2).tolist()
[1.0, 0.43]
Source code in src/skcomplex/core/engine/solvers/_convolution.py
57 58 59 60 61 62 63 64 65 66 67 68 | |
LammpsFixSpec(name, group, value, mass, seed)
dataclass
Bases: BaseSpec
A spec of the values that the native fix of an interaction reads in LAMMPS.
It names the fix, such as 'langevin' for a heat bath, the group of atoms it acts on, and functions that give a
value by name, the mass, and the seed, which the LAMMPS solver reads when it writes the command of the fix. It sets
the heat bath of a liquid, the drag of a colloid, and the push of active particles.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The unique name of the fix. |
required |
group
|
str
|
The LAMMPS group of the atoms the fix acts on. |
required |
value
|
Callable[[str], Array]
|
The function that returns the current value of a parameter of the interaction by name. |
required |
mass
|
Callable[[], float]
|
The function that returns the mass of the atoms of the interaction's target. |
required |
seed
|
Callable[[], int]
|
The function that draws a random seed. |
required |
See Also
LammpsSolver: Writes the commands of the fixes.
Examples:
>>> from skcomplex.core.engine.solvers import LammpsFixSpec
>>> fix = LammpsFixSpec('langevin', 'gas', lambda name: 1.0, lambda: 1.0, lambda: 7)
>>> fix.name, fix.group
('langevin', 'gas')
LammpsSolver(dt=0.005, pairs=None, fixes=None, *, random_state=None, until=math.inf)
Bases: ExternalSolver
A solver that runs systems of points in the LAMMPS program by velocity Verlet.
A group whose members have a vector position whose second derivative a law sets, such as the atoms of a gas, becomes
an atom type, with the mass m of its members or 1. Boxes become LAMMPS walls, an interaction whose class names a
native pair style or fix becomes that style or fix, such as a Lennard-Jones pair within RadiusNeighborhood(2.5),
and a pair energy ObjectiveLaw(V) without a native style becomes a Lepton expression. Any other interaction that
only sets accelerations runs through fix external, computed by the library. Choose it for large systems of
particles, such as liquids, solids, and polymers.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest LAMMPS time step. |
0.005
|
pairs
|
Mapping[type[BaseInteraction], tuple[str, PairArguments]] | None
|
The native LAMMPS pair style of pair potential classes, with the function of the parameter values that
returns the coefficients of |
None
|
fixes
|
Mapping[type[BaseInteraction], FixCommand] | None
|
The function that returns the native LAMMPS fix command of interaction classes from the values of the fix. |
None
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
lammps_ |
The LAMMPS instance, which the final run |
|
atom_elements_ |
The elements and groups of points, each a LAMMPS atom type. |
|
atom_numbers_ |
The LAMMPS atom type of every element and group of points, by path. |
|
position_indices_ |
The flat state indices of the position of every atom, of shape |
|
velocity_indices_ |
The flat state indices of the velocity of every atom, of shape |
|
atom_types_ |
The LAMMPS atom type of every atom. |
|
n_dim_ |
The number of dimensions of the space of the atoms. |
|
released_ |
Whether the LAMMPS instance is closed. |
See Also
VelocityVerletSolver: Runs the same scheme in the library itself. LammpsFixSpec: The values a native fix reads.
Examples:
>>> from skcomplex.core.engine.solvers import ExternalSolver, LammpsSolver
>>> solver = LammpsSolver(dt=0.005)
>>> isinstance(solver, ExternalSolver), solver.dt
(True, 0.005)
Source code in src/skcomplex/core/engine/solvers/_lammps.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 | |
LatticeSolver(*, random_state=None, until=math.inf)
Bases: Solver
A solver that applies every law of a lattice once per step.
The laws are local rules, drives, and relaxations, such as rule 30 that sets each cell from itself and its two neighbours. They apply in the order they are declared and read the time at the start of the step, as maps do. The boundary laws apply after every step at its end time, and a relaxation records the size, duration, and area of every cascade as an event. It runs cellular automata, the sandpiles of earthquakes, and the fires of a forest.
Read more in the user guide, under Solvers.
See Also
MonteCarloSolver: Samples the sites of a lattice at random. IterationSolver: Applies a map without a lattice.
Examples:
>>> from skcomplex.core.engine.solvers import LatticeSolver
>>> from skcomplex.systems.computer_science.automata import ElementaryAutomatonSystem
>>> system = ElementaryAutomatonSystem(30, size=11, solver=LatticeSolver()).prepare()
>>> system.simulate(until=1).get_values('cells.alive')[-1].astype(int).tolist()
[0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0]
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
MesaSolver(*, activation='random', phases=(), random_state=None, until=math.inf)
Bases: ExternalSolver
A solver that runs agents in Mesa, one step per unit of time.
An agent is a member of a group whose interactions give it rules, such as UpdateLaw(s.target, move) with
def move(agent, system): agent.x += system.rng.normal(). Every step moves Mesa's clock by one and activates the
agents by activation, and each agent runs its rules in the order the interactions give them. A rule may add
members with agent.create() and remove them with agent.remove(), and a step may run in named phases, such as
traders that quote before a clerk settles. It runs walkers, flocks, traders, and growing populations, with no space
or on a lattice, a network, or a box.
Read more in the user guide, under Agents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
activation
|
str
|
The order in which the agents run their rules at every step: |
'random'
|
phases
|
Sequence[PhaseSpec]
|
The named phases of a step after the default one, such as |
()
|
random_state
|
int | Generator | None
|
The seed or generator of the random numbers, or |
None
|
until
|
float
|
The end time of the run the solver prepares for. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
system_ |
The Mesa system. |
|
members_ |
Every agent created in the run by its id, which reference states name. |
See Also
GillespieSolver: The solver of jump processes, for populations counted rather than followed one by one.
Examples:
>>> from skcomplex.core.engine.solvers import MesaSolver
>>> from skcomplex.systems.economics.econophysics import BoltzmannWealthSystem
>>> system = BoltzmannWealthSystem(n_agents=10, solver=MesaSolver(activation='random')).prepare()
>>> int(system.simulate(until=5, random_state=0).get_agents('traders', 5).values['wealth'].sum())
10
Source code in src/skcomplex/core/engine/solvers/_mesa.py
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 | |
MetropolisSolver(*, temperature=1.0, step=0.1, moves=None, rule='metropolis', schedule='checkerboard', neighborhood=None, values=None, width=1.0, random_state=None, until=np.inf)
Bases: BaseObjectiveSolver
A solver that samples states by the Boltzmann weight of an objective.
Every unit of time is one sweep in which each target state takes a proposal x + step * N(0, 1), kept with the
chance min(1, exp(-(U_new - U) / T)) at the temperature T, so states with low objective come up often and high
ones rarely. With moves it samples the members of a group on a lattice, a network, or the edges of a cell complex
one by one, such as the spins of a magnet flipped by moves={'spins.spin': 'flip'}, where the objective is the
local energy of a member over the temperature. Each move, 'flip', 'random-value', 'rotate', 'gaussian',
'cluster', or a function move(values, random), is kept by rule, 'metropolis', 'glauber', or 'heat-bath',
in the order of schedule. It samples a particle in a well, the spins of a magnet, and the parameters of a model
from a posterior.
Read more in the user guide, under Solvers.
See Also
MinimizeSolver: Finds the minimum of the objective, the limit of zero temperature.
Examples:
>>> from skcomplex.core.engine.solvers import MetropolisSolver
>>> from skcomplex.systems.physics.statistical_mechanics import IsingSystem
>>> solver = MetropolisSolver(moves={'spins.spin': 'flip'})
>>> system = IsingSystem(size=8, temperature=1.0, solver=solver).prepare()
>>> abs(float(system.simulate(until=50).get_values('spins.spin')[-1].mean()))
1.0
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
temperature
|
float
|
The temperature |
1.0
|
step
|
float
|
The width of a proposal. |
0.1
|
moves
|
Mapping[str, str | Callable[..., object]] | None
|
The move of every state of the members of a group that the solver samples member by member, by its
dotted name, such as |
None
|
rule
|
str
|
The acceptance of the moves of members, |
'metropolis'
|
schedule
|
str
|
The order of the moves of members, |
'checkerboard'
|
neighborhood
|
BaseNeighborhood | None
|
The neighbourhood the local objective of a member reduces over, or |
None
|
values
|
Mapping[str, Sequence[float]] | None
|
The values a random-value move draws from, by the dotted name of the state. |
None
|
width
|
float
|
The largest change of a rotation, or the deviation of a Gaussian move. |
1.0
|
random_state
|
int | Generator | None
|
The seed or generator of the proposals and acceptances. |
None
|
until
|
float
|
The end time of the run the solver prepares for. |
inf
|
Source code in src/skcomplex/core/engine/solvers/_metropolis.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
MilsteinSolver(dt=0.001, *, random_state=None, until=math.inf)
Bases: SDESolver
A solver of stochastic differential equations by the Milstein scheme of Platen.
It takes a helper value Y = X + f h + g sqrt(h) and corrects the noise by
(g(Y) - g(X)) (dW^2 - h) / (2 sqrt(h)), which needs no derivative of the noise and is of strong order 1. Choose it
for noise whose size depends on the state, such as a price whose shocks grow with it, where it is closer to the
exact path than Euler-Maruyama, in models of interest rates, populations, and stock prices.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The fixed internal step. |
0.001
|
See Also
EulerMaruyamaSolver: The default solver of noise in continuous time.
Examples:
>>> from skcomplex.core.engine.solvers import MilsteinSolver
>>> from skcomplex.systems.economics.finance import GeometricBrownianMotionSystem
>>> system = GeometricBrownianMotionSystem(solver=MilsteinSolver(dt=0.01)).prepare()
>>> system.simulate(until=1, dt=1, random_state=0).get_values('asset.price').round(2).tolist()
[100.0, 130.8]
Source code in src/skcomplex/core/engine/solvers/_sde.py
55 56 57 58 59 60 61 62 63 64 | |
MinimizeSolver(*, method=None, tolerance=1e-09, random_state=None, until=np.inf)
Bases: BaseObjectiveSolver
A solver that finds the minimum of the objective of a static system once.
It minimises the sum of the objective laws over their target states with scipy.optimize.minimize and the exact
slope of the objective, such as the ball of ObjectiveLaw((x - 2) ** 2, x) that settles at 2. The constraint laws
hold at the minimum as equalities, which the SLSQP method keeps, and the states they set move with the targets. It
finds the rest shape of a loaded structure, the purchase that maximises a utility under a budget, and the weights of
a model at its least loss.
Read more in the user guide, under Solvers.
Attributes:
| Name | Type | Description |
|---|---|---|
initial_state_ |
Array
|
The state vector at the minimum, the one frame of the run. |
See Also
RootSolver: Solves the constraint laws of a static system that has no objective.
Examples:
>>> from skcomplex.core.engine.solvers import MinimizeSolver
>>> from skcomplex.core.engine.solvers._objective import BaseObjectiveSolver
>>> isinstance(MinimizeSolver(), BaseObjectiveSolver)
True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str | None
|
The method of |
None
|
tolerance
|
float
|
The tolerance of the minimisation, and the largest residual of a constraint at the minimum. |
1e-09
|
random_state
|
int | Generator | None
|
The seed or generator of the solver, which draws nothing. |
None
|
until
|
float
|
The end time of the run the solver prepares for, which a static system does not read. |
inf
|
Source code in src/skcomplex/core/engine/solvers/_minimize.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
MonteCarloSolver(*, random_state=None, until=math.inf)
Bases: LatticeSolver
A solver of Monte Carlo sampling that sweeps a lattice once per unit of time.
Every unit of time visits each site once and redraws its value by the sampling law of the lattice, such as a spin of a magnet that flips with the Boltzmann weight of its neighbours, so a cold magnet of 64 spins lines up within 50 sweeps. It samples magnets, lattice gases, and the opinions of voters on a grid.
Read more in the user guide, under Solvers.
See Also
LatticeSolver: Applies the laws of a lattice in order. MetropolisSolver: Samples states by the Boltzmann weight of an objective.
Examples:
>>> from skcomplex.core.engine.solvers import MonteCarloSolver, StepSpec
>>> from skcomplex.systems.physics.statistical_mechanics import IsingSystem
>>> problem = IsingSystem(size=8, temperature=1.0).prepare().simulate(until=0).problem
>>> step = StepSpec(0.0, problem.initial_state, problem.initial_parameters, 50.0)
>>> bool(abs(MonteCarloSolver(random_state=0).prepare(problem).run(step).state_.mean()) > 0.9)
True
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
OptimalControlSolver(*, random_state=None, until=math.inf)
Bases: Solver
An abstract solver that finds the controls of a run that minimise a cost.
A system states the cost with an objective law that names its controls, such as
ObjectiveLaw(s.plant.x**2 + s.plant.u**2, controls=[s.plant.u], terminal=...), whose running cost adds up over the
run and whose terminal cost counts at the end time until. The bounds of a control are the allowed values of its
element. Without such a law the solver takes the bounded adaptive parameters as controls and the costs from its
arguments objective and terminal, minimised for sense='min' and maximised for 'max'. It solves the whole run
from the starting values and then hands it on frame by frame. A subclass writes the private method _solve. It is
the base of the solvers of vaccination plans, harvests of a fishery, and the growth of an economy.
Read more in the user guide, under Solvers.
Attributes:
| Name | Type | Description |
|---|---|---|
control_problem_ |
The optimal control problem of the compiled system. |
|
horizon_ |
The end of the run, the horizon of the objective. |
|
solution_ |
The optimal solution of the run. |
See Also
CollocationSolver: Solves the problem as one large optimisation. PontryaginSolver: Solves the problem by the maximum principle.
Examples:
>>> from skcomplex.core.engine.solvers import OptimalControlSolver, PontryaginSolver
>>> isinstance(PontryaginSolver(), OptimalControlSolver)
True
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
PontryaginSolver(objective=None, *, terminal=0.0, sense='min', nodes=201, relaxation=0.5, tolerance=1e-06, max_iterations=1000, random_state=None, until=math.inf)
Bases: OptimalControlSolver
A solver of optimal control by the maximum principle of Pontryagin.
It builds the Hamiltonian H = L + λ · f from the running cost L and the rates f of the states, and derives by
Sage the costate equations λ' = -∂H/∂x with λ(T) = ∂φ/∂x at the end time for the terminal cost φ. The controls
solve ∂H/∂u = 0 within their bounds, or take the bound that minimises H where H is linear in them. A forward
and backward sweep steps the states forward and the costates backward with Runge-Kutta steps, and moves the controls
towards their update until they settle, such as a vaccination rate of 0.153 at the start of an epidemic. Choose it
for smooth control problems with few states, such as the treatment of a tumour, the harvest of a fishery, and the
growth of an economy.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
Cost | None
|
The running cost, a function of the namespace |
None
|
terminal
|
Cost
|
The terminal cost at the horizon, a function of the same namespace or a number. |
0.0
|
sense
|
str
|
|
'min'
|
nodes
|
int
|
The number of times of the grid, from the start to the horizon. |
201
|
relaxation
|
float
|
The initial weight of the update of the controls at every sweep, between 0 and 1. |
0.5
|
tolerance
|
float
|
The largest relative change of the states, costates, and controls between sweeps at convergence. |
1e-06
|
max_iterations
|
int
|
The largest number of sweeps. |
1000
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
solution_ |
The optimal solution of the run. |
Raises:
| Type | Description |
|---|---|
SolverError
|
The solver has no objective, the sweep diverges or does not converge, or the stationarity condition has no unique explicit solution. |
ValidationError
|
The sense is unknown, the grid has fewer than 2 nodes, or the relaxation is not in |
See Also
CollocationSolver: Solves the problem as one large optimisation.
Examples:
>>> from skcomplex.systems.biology.epidemiology import SIRVaccinationSystem
>>> system = SIRVaccinationSystem().prepare()
>>> trajectory = system.simulate(until=5.0)
>>> type(system.system_.solver_).__name__, float(trajectory.get_values('population.u')[0].round(3))
('PontryaginSolver', 0.153)
Source code in src/skcomplex/core/engine/solvers/_pontryagin.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | |
RK4Solver(dt=0.001, *, random_state=None, until=math.inf)
Bases: Solver
A solver of ordinary differential equations by the classical Runge-Kutta rule.
It takes steps of a fixed length dt and evaluates the rates four times per step, so its error falls with the
fourth power of the step, such as e to six places for a population that grows at rate 1 over one time unit. With
the Numba backend every step of a frame runs in compiled code. Choose it for smooth flows with a fixed step, such as
orbits, oscillators, and epidemics.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest internal time step. |
0.001
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
See Also
EulerSolver: Steps with the explicit Euler rule. ScipyODESolver: Steps with adaptive steps of SciPy.
Examples:
>>> from skcomplex.core.engine.solvers import RK4Solver
>>> from skcomplex.systems.biology.ecology import ExponentialGrowthSystem
>>> system = ExponentialGrowthSystem(n=1.0, r=1.0, solver=RK4Solver(dt=0.001)).prepare()
>>> system.simulate(until=1, dt=1).get_values('population.x').round(6).tolist()
[1.0, 2.718282]
Source code in src/skcomplex/core/engine/solvers/_rk4.py
88 89 90 91 92 93 94 95 96 97 | |
RenewalSolver(*, random_state=None, until=math.inf)
Bases: Solver
A solver that runs renewal processes exactly, from renewal to renewal.
Every member renews on its own clock, with waiting times of any law, such as a walker that rests for a heavy tailed time before each jump, and the solver jumps from one renewal to the next without a time grid. A frame holds the values that the last renewal at or before its time set. It runs walkers trapped in a glass, neurons that fire, and machines that fail and are repaired.
Read more in the user guide, under Solvers.
See Also
GillespieSolver: Runs jumps whose waiting times have no memory.
Examples:
>>> from skcomplex.systems.physics.soft_matter import ContinuousTimeRandomWalkSystem
>>> system = ContinuousTimeRandomWalkSystem(n_walkers=3).prepare()
>>> type(system.system_.solver_).__name__, system.simulate(until=10, dt=10).get_values('walkers.x').shape
('RenewalSolver', (2, 3, 2))
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
RootSolver(*, method='auto', tolerance=1e-09, random_state=None, until=np.inf)
Bases: Solver
A solver of the equations of a static system, solved once.
It solves the constraint laws once for the one frame of the run, such as the outputs 3.33 and 2.33 at which two
firms of a market both make their best reply. It takes the exact solution when Sage finds a unique one, and
otherwise solves the equations with scipy.optimize.root and their exact Jacobian from the starting values. A
system without equations keeps its starting values. It finds the equilibria of markets, the balance of forces in a
truss, and the steady state of a reaction.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
The method of |
'auto'
|
tolerance
|
float
|
The largest residual of a solution. |
1e-09
|
random_state
|
int | Generator | None
|
The seed or generator of the solver, which draws nothing. |
None
|
until
|
float
|
The end time of the run the solver prepares for, which a static system does not read. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
initial_state_ |
Array
|
The solved state vector, the one frame of the run. |
See Also
MinimizeSolver: Finds the minimum of an objective.
Examples:
>>> from skcomplex.systems.economics.markets import OligopolyEquilibriaSystem
>>> trajectory = OligopolyEquilibriaSystem().prepare().simulate()
>>> [round(float(trajectory.get_values(name)[0]), 4) for name in ('cournot.q_i', 'cournot.q_j')]
[3.3333, 2.3333]
Source code in src/skcomplex/core/engine/solvers/_root.py
61 62 63 64 65 66 67 68 69 70 71 | |
SDESolver(dt=0.001, *, random_state=None, until=math.inf)
Bases: Solver
An abstract solver of stochastic differential equations with a fixed step.
Each step of length dt adds the drift and one random increment of the noise, such as the daily shocks of a stock
price. The steps stop at breakpoints, read delays by straight lines between steps, and find events within them. A
subclass sets supports and writes the private method _increment. It is the base of the solvers of stock prices,
diffusing particles, and noisy genes.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest internal time step. |
0.001
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
See Also
EulerMaruyamaSolver: The default solver of noise in continuous time. HeunSolver: Averages the drift over each step. MilsteinSolver: Corrects noise whose size depends on the state.
Examples:
>>> from skcomplex.core.engine.solvers import HeunSolver, SDESolver
>>> isinstance(HeunSolver(dt=0.01), SDESolver)
True
Source code in src/skcomplex/core/engine/solvers/_sde.py
55 56 57 58 59 60 61 62 63 64 | |
SSPRKSolver(order=3, cfl=0.4, dt=0.01, *, random_state=None, until=math.inf)
Bases: Solver
A solver by strong stability preserving Runge-Kutta steps of order 2 or 3.
Each step of the schemes of Shu and Osher is an average of Euler steps, so a field with shocks, such as a traffic
jam, gains no new wiggles and keeps its total. With finite volume fields the step is the smaller of cfl * h / s,
for the cell size h and the largest wave speed s, and the stability limit of the diffusion, and otherwise dt.
Choose it for conservation laws with shocks, in models of traffic, gas flows, and shallow water.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
int
|
2 or 3. |
3
|
cfl
|
float
|
The Courant number. |
0.4
|
dt
|
float
|
The largest step, and the step without conservation laws. |
0.01
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
See Also
RK4Solver: Steps smooth flows with the classical Runge-Kutta rule.
Examples:
>>> from skcomplex.core.engine.solvers import SSPRKSolver
>>> from skcomplex.systems.physics.fluids import BurgersSystem
>>> u = BurgersSystem(64, solver=SSPRKSolver()).prepare().simulate(until=1, dt=1).get_values('line.u')
>>> round(float(u[0].sum()), 6), round(float(u[-1].sum()), 6)
(96.0, 96.0)
Source code in src/skcomplex/core/engine/solvers/_ssprk.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
ScipyODESolver(method='auto', rtol=1e-06, atol=1e-09, jacobian='auto', *, random_state=None, until=math.inf)
Bases: Solver
A solver of ordinary differential equations with scipy.integrate.
It runs one integrator of scipy.integrate across the frames of a run with steps it picks to meet the tolerances,
and reads each frame from the smooth curve of the step that covers its time, such as e for a population that grows
at rate 1 over one time unit. The methods BDF, Radau, and LSODA suit stiff problems, whose fast and slow
changes force explicit steps to be tiny, and they receive the pattern of the Jacobian that the compiler derives from
the laws. With delays, a step is at most the shortest delay. It is the default solver of continuous flows, in
epidemics, chemical reactions, and circuits.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
The integration method: |
'auto'
|
rtol
|
float
|
The relative tolerance. |
1e-06
|
atol
|
float
|
The absolute tolerance. |
1e-09
|
jacobian
|
str
|
How implicit methods obtain the Jacobian. |
'auto'
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
method_ |
The method the stepper integrates with, which |
|
jacobian_pattern_ |
The sparsity pattern of the Jacobian that an implicit method uses, or |
|
jacobian_options_ |
The keyword arguments of the pattern or the half bandwidths that the integrator receives. The exact Jacobian
is passed as |
See Also
RK4Solver: Steps with a fixed step. IMEXEulerSolver: Steps stiff fields with an implicit linear part.
Examples:
>>> from skcomplex.core.engine.solvers import ScipyODESolver
>>> from skcomplex.systems.biology.ecology import ExponentialGrowthSystem
>>> system = ExponentialGrowthSystem(n=1.0, r=1.0, solver=ScipyODESolver(rtol=1e-8)).prepare()
>>> system.simulate(until=1, dt=1).get_values('population.x').round(4).tolist()
[1.0, 2.7183]
Source code in src/skcomplex/core/engine/solvers/_scipy_ode.py
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |
SemiLagrangianSolver(dt=0.01, *, random_state=None, until=math.inf)
Bases: Solver
A solver of kinetic equations by the axis by axis shifts of Cheng and Knorr.
It shifts every slice of a field along each axis in turn, such as the density of a gas along its positions and then
its velocities. Every flux must be a drift a u whose speed a does not depend on the state. A shift along a
periodic axis multiplies the Fourier modes of the slices, which keeps the total, and a shift along an interval reads
a cubic spline, so a step may be longer than a cell takes to cross. Rate laws take one midpoint step between two
half shifts. Choose it for transport in phase space, such as the electrons of a plasma, the bacteria of a swarm, and
the stars of a galaxy.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest internal time step. |
0.01
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
See Also
StrangSplittingSolver: Splits transport and collisions.
Examples:
>>> from skcomplex.core.engine.solvers import SemiLagrangianSolver
>>> from skcomplex.systems.physics.fluids import VlasovEquationSystem
>>> system = VlasovEquationSystem(positions=16, velocities=8, solver=SemiLagrangianSolver(dt=0.5)).prepare()
>>> f = system.simulate(until=1, dt=1).get_values('gas.x')
>>> round(float(f[-1].sum() / f[0].sum()), 4)
1.0
Source code in src/skcomplex/core/engine/solvers/_semi_lagrangian.py
85 86 87 88 89 90 91 92 93 94 | |
Solver(*, random_state=None, until=math.inf)
Bases: BaseSolver[ProblemSpec]
An abstract solver of the problems that the general compiler builds.
It runs what every problem of the general compiler may hold besides its laws: events, renewals, delays, and boundary
laws, such as a ball that bounces when its height reaches 0. Every call of run reads the current parameters, so a
change of a parameter applies from the next call, and the boundary laws apply after every inner step. It is the base
of the solvers of epidemics, chemical reactions, and circuits.
Read more in the user guide, under Solvers.
See Also
BaseSolver: The base of every solver. ScipyODESolver: The default solver of continuous flows.
Examples:
>>> from skcomplex.core.engine.solvers import RK4Solver, Solver
>>> isinstance(RK4Solver(), Solver)
True
Source code in src/skcomplex/core/engine/solvers/_base.py
104 105 106 | |
SplitSolver(dt=0.01, *, random_state=None, until=math.inf)
Bases: Solver
An abstract solver that steps the linear part of the rates of fields on its own.
The rates of a field split into a linear part, such as the diffusion D ∇²u of heat, and the rest, such as a
reaction. The linear part is held as a small matrix per Fourier mode for spectral fields and as one sparse matrix
over all states for the other fields, so a subclass can step it implicitly or exactly while it steps the rest
explicitly. It is the base of the solvers of heat flow, of patterns in reaction and diffusion, and of option prices.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest internal time step. |
0.01
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
sparse_ |
The sparse matrix of the linear terms outside spectral fields, or |
|
blocks_ |
The spectral blocks. |
See Also
IMEXEulerSolver: Steps the linear part implicitly with order 1. IMEX2Solver: Steps the linear part implicitly with order 2. ETDRK4Solver: Steps the linear part exactly per Fourier mode.
Examples:
>>> from skcomplex.core.engine.solvers import IMEX2Solver, SplitSolver
>>> isinstance(IMEX2Solver(dt=0.1), SplitSolver)
True
Source code in src/skcomplex/core/engine/solvers/_split.py
99 100 101 102 103 104 105 106 107 108 | |
StepSpec(t, x, p, until)
dataclass
Bases: BaseSpec
A spec of one step of a run, a state at a time and the time to move it to.
It holds the time t, the state x, and the parameters p at the start of a step, and the time until a solver
moves the state to, such as from 0 to 1. A solver reads it in run. It carries a step of a population, a magnet,
and a market alike.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t
|
float
|
The current time. |
required |
x
|
Array
|
The current state vector. |
required |
p
|
Array
|
The parameter vector. |
required |
until
|
float
|
The time to advance to. |
required |
See Also
BaseSolver: Moves the state of a step.
Examples:
>>> import numpy as np
>>> from skcomplex.core.engine.solvers import StepSpec
>>> StepSpec(0.0, np.ones(1), np.zeros(0), 1.0).until
1.0
StrangSplittingSolver(transport=None, collision=None, dt=0.01, *, random_state=None, until=math.inf)
Bases: Solver
A solver that puts a full collision step between two half transport steps.
Every step takes half a step of transport, a full step of collisions, and another half step of transport, which is of order 2. The transport solver moves the flux differences of the finite volume fields, such as a gas streaming along its positions, and the collision solver the source rates, such as its relaxation towards equilibrium, which the problem keeps apart. Choose it for kinetic equations with collisions, in models of rarefied gases, plasmas, and traffic.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transport
|
Solver | None
|
The solver of the flux differences, or |
None
|
collision
|
Solver | None
|
The solver of the source rates, or |
None
|
dt
|
float
|
The largest internal time step, the length of one split step. |
0.01
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
transport_ |
The prepared solver of the flux differences. |
|
collision_ |
The prepared solver of the source rates. |
See Also
SemiLagrangianSolver: Moves transport with any step. SSPRKSolver: Moves transport with shocks.
Examples:
>>> from skcomplex.systems.physics.fluids import BGKEquationSystem
>>> solver = BGKEquationSystem(positions=8, velocities=16).prepare().system_.solver_
>>> type(solver).__name__, type(solver.transport).__name__, type(solver.collision).__name__
('StrangSplittingSolver', 'SSPRKSolver', 'RK4Solver')
Source code in src/skcomplex/core/engine/solvers/_strang_splitting.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 | |
StructureStateSpec(structures=dict(), reporters=dict())
dataclass
Bases: BaseSpec
A spec of the structures of elements kept outside the state vector at a frame.
It holds the structures by the path of their element, such as the word of a rewriting system, and the reporters that measure them, such as its length. It keeps the words of a grammar, the shapes of a growing plant, and the strings of a language.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structures
|
Mapping[str, object]
|
A mapping from element path to its structure, such as a word or a patch. |
dict()
|
reporters
|
Mapping[str, float]
|
A mapping from dotted reporter name, such as |
dict()
|
See Also
BaseSolver: Collects it after a step.
Examples:
>>> from skcomplex.core.engine.solvers import StructureStateSpec
>>> StructureStateSpec().structures
{}
SystemView(stepper, owner='', roles=None)
A view of the system as agent rules see it: its values, time, agents, and space.
Every rule receives the view of the interaction or group that owns it, so it reads the owner's parameters by name
and the groups of the owner's roles, such as system.get_agents('traders') for the traders of a market, also when
the system is nested in another. It shows the traders of a market, the birds of a flock, and the residents of a city
to their rules.
Read more in the user guide, under Agents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stepper
|
MesaSolver
|
The stepper that runs the system. |
required |
owner
|
str
|
The path of the interaction or agent group whose rules receive the view, or |
''
|
roles
|
Mapping[str, str | tuple[str, ...]] | None
|
The paths of the elements and groups the owner's roles bind to, by role. |
None
|
See Also
AgentView: The view of one agent. MesaSolver: Runs the rules that read it.
Examples:
>>> from skcomplex.core.engine.solvers import MesaSolver, SystemView
>>> from skcomplex.systems.economics.econophysics import BoltzmannWealthSystem
>>> problem = BoltzmannWealthSystem(n_agents=5).prepare().simulate(until=0).problem
>>> len(SystemView(MesaSolver().prepare(problem), 'traders').get_agents('traders'))
5
Source code in src/skcomplex/core/engine/solvers/_mesa.py
104 105 106 107 108 109 110 111 112 | |
dimensions
property
Extent of the agent space per axis.
It is cells of a grid or lengths of a continuous space, and None otherwise.
inputs
property
Values of the states of other partitions at the last synchronisation point.
They are keyed by dotted name.
parameters
property
Current values of every parameter by dotted name.
rng
property
Random number generator of the system, seeded by the simulation's random state.
round
property
Index of the current round of a repeated phase, 0 outside repeated phases.
storage
property
Mutable mapping private to the owner that persists across the steps of one run.
An example is an order book.
time
property
Time of Mesa's clock.
It is k during the step that produces frame k, plus i / n at visit i of n.
torus
property
Whether the agent space wraps around at its edges.
count(name)
Return the number of agents of a group bound to a role of the owner.
A group may also be named by path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A role of the owner, the path of a group relative to the owner's system, or the path of a group. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
count |
int
|
The number of agents alive in the group, or in every group of a role that binds several. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
No role or group has that name. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 | |
create(group, location=None, **values)
Create an agent of a group, at a location or at a random place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
str
|
A role of the owner that binds the group, or the path of the group. |
required |
location
|
object
|
The cell coordinates, network node, or position, a polygon for a uniform point inside it, or |
None
|
**values
|
object
|
The initial values of states, with the element type's defaults for the others. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
agent |
AgentView
|
The new agent. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
The group is not variable, so its size cannot change. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |
deposit(name, cell, amount)
Add an amount to a field at a cell at the next synchronisation point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted path of the field state, such as |
required |
cell
|
object
|
The lattice coordinates of the cell or a network node. |
required |
amount
|
float
|
The amount to add. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
The name is not a state of a field. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 | |
draw(name, distribution, **arguments)
Return a value drawn by name from a distribution, which runs record and replay.
The value comes from the generator of the system. A run that records keeps it by the path of the owner and
the name, such as meetings.outcome, with the arguments of the distribution, and a run that replays returns
the recorded value instead and adds its log-probability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the draw, unique among the draws of the owner. |
required |
distribution
|
str
|
|
required |
**arguments
|
ArrayLike
|
The arguments of the distribution by keyword. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
value |
float
|
The drawn value. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
The distribution is unknown or an argument is missing. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
get_agents(name, view=None)
get_agents(name: str) -> list[AgentView]
get_agents(name: str, view: type[V]) -> list[V]
Return the views of the agents of a group bound to a role of the owner.
A group may also be named by path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A role of the owner, the path of a group relative to the owner's system, or the path of a group. |
required |
view
|
type[V] | None
|
The view class of the group, which its element names with |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
agents |
list[V] | list[AgentView]
|
The views of the agents alive in the group, or in every group of a role that binds several. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
No role or group has that name, or the views of a group are not of the view class. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | |
get_composition(name, state)
Return the number of agents of a group that hold every value of a state.
Only the values some agent holds are counted. The stepper keeps the counts as agents are created, removed, and change the state, so reading them costs no pass over the agents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A role of the owner, the path of a group relative to the owner's system, or the path of a group. |
required |
state
|
str
|
The name of a scalar state of the agents of the group. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
counts |
dict[Hashable, int]
|
The number of agents alive in the group, or in every group of a role that binds several, by value. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
No role or group has that name, or its agents have no such state. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | |
get_field(name, cell)
Return the value of a field at a cell.
It is the value at the last synchronisation point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted path of the field state, such as |
required |
cell
|
object
|
The lattice coordinates of the cell, which match the coordinates of a grid of the same shape, or a network node. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
float
|
The value of the field there. |
Raises:
| Type | Description |
|---|---|
KeyError
|
The name is not a state of a field. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 | |
get_groups(name)
Return the paths of the groups a role of the owner binds.
A group may also be named by relative or absolute path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A role of the owner, the path of a group relative to the owner's system, or the path of a group. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
paths |
list[str]
|
The paths of the groups. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
No role or group has that name. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | |
get_history(name, window=None)
Return the past values of a reporter, or of an observable.
An observable gives its values at the end of each earlier step, the last one last.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of a value the owner reports, the full name of any reporter, such as |
required |
window
|
int | None
|
The number of last values, or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
values |
NDArray[float64]
|
The values, at most |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 | |
get_observable(name)
Return the current value of an observable of the system.
An example is an aggregate of a group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The path of the observable. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
object
|
Its value for the current agents and parameters. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
The system has no such observable. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 | |
get_occupancy(name)
Return the number of agents of a group in every cell or node that holds one.
The counts are keyed by the key of the location.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A role of the owner, the path of a group relative to the owner's system, or the path of a group. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
counts |
dict[Hashable, int]
|
The number of agents alive in the group, or in every group of a role that binds several, by the
|
Raises:
| Type | Description |
|---|---|
SimulationError
|
No role or group has that name. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
get_parameter(name)
Return the current value of a parameter of the owner.
One component is read as name[i].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of a scalar parameter, such as |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
float
|
The value. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
The owner has no such parameter, or the parameter has several components and no index. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
get_random_empty_cell()
Return the coordinates of a random empty cell of the grid or network.
Returns:
| Name | Type | Description |
|---|---|---|
location |
object
|
The cell coordinates or the network node. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
520 521 522 523 524 525 526 527 | |
get_region(layer, index)
Return the polygon of a region of a layer of the continuous space.
A rule can pass the polygon to move_to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer
|
str
|
The name of the layer. |
required |
index
|
int
|
The index of the region in its layer. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
polygon |
Polygon
|
The polygon of the region. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
The space has no such layer, or the layer has no region of that index. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 | |
get_regions(layer)
Return the number of regions of a layer of the continuous space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer
|
str
|
The name of the layer. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
count |
int
|
The number of regions of the layer. |
Raises:
| Type | Description |
|---|---|
SimulationError
|
The space has no such layer. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
report(name, value)
Publish a value of the owner as the reporter <owner>.<name>.
The value is added to the reporter's history. The owner declares the names it reports in its class variable
reports, so every frame records them, NaN before the first report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the value, such as |
required |
value
|
float
|
The value. |
required |
Raises:
| Type | Description |
|---|---|
SimulationError
|
The owner does not declare the name in |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
set_parameter(name, value)
Set a parameter of any group or interaction during the run.
The trajectory records it like any parameter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The dotted name of the parameter, such as |
required |
value
|
float
|
The new value. |
required |
Raises:
| Type | Description |
|---|---|
SimulationError
|
No parameter has that name. |
Source code in src/skcomplex/core/engine/solvers/_mesa.py
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 | |
VelocityVerletSolver(dt=0.001, *, random_state=None, until=math.inf)
Bases: Solver
A solver of moving particles by velocity Verlet, stable over long runs.
Every step kicks the velocities by half a step, moves the positions, applies the boundary laws, and kicks the velocities again with the accelerations at the new positions, so a step costs one evaluation of the forces. It keeps the energy of conservative forces from drifting over long runs, such as a spring that swings from 1 to -1 in half a period. With the Numba backend every step of a frame runs in compiled code. Choose it for Newtonian particles over long runs, in molecules, planets, and crowds.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest internal time step. |
0.001
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
See Also
Yoshida4Solver: A symplectic method of order 4. LammpsSolver: Runs large systems of particles in LAMMPS.
Examples:
>>> from skcomplex.core.engine.solvers import VelocityVerletSolver
>>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
>>> system = HarmonicOscillatorSystem(solver=VelocityVerletSolver(dt=0.01)).prepare()
>>> system.simulate(until=3.1416, dt=3.1416).get_values('mass.x').round(3).tolist()
[1.0, -1.0]
Source code in src/skcomplex/core/engine/solvers/_velocity_verlet.py
75 76 77 78 79 80 81 82 83 84 | |
Yoshida4Solver(dt=0.001, *, random_state=None, until=math.inf)
Bases: Solver
A solver of order 4 by the symplectic method of Yoshida.
It splits the states into two blocks whose rates each read only the other block, such as the positions and the
momenta of a planet, and composes three velocity Verlet steps of the lengths w1 h, w0 h, and w1 h, with
w1 = 1 / (2 - 2^(1/3)) and w0 = 1 - 2 w1. The energy of such a split system stays bounded over long runs, such
as a spring that swings from 1 to -1 in half a period. With the Numba backend every step of a frame runs in compiled
code. Choose it for accurate long runs of orbits, particle beams, and molecules.
Read more in the user guide, under Solvers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
float
|
The largest internal time step. |
0.001
|
random_state
|
int | Generator | None
|
The seed or generator of stochastic solvers. |
None
|
until
|
float
|
The end time of the run the solver prepares for, infinite for a run that goes on until it is stopped. |
inf
|
Attributes:
| Name | Type | Description |
|---|---|---|
first_ |
The flat indices of the states of the block that drifts. |
|
second_ |
The flat indices of the states of the block that kicks. |
Raises:
| Type | Description |
|---|---|
SolverError
|
The problem is not an ODE, or its states admit no split into two blocks whose rates read only the other. |
See Also
VelocityVerletSolver: A symplectic method of order 2.
Examples:
>>> from skcomplex.core.engine.solvers import Yoshida4Solver
>>> from skcomplex.systems.physics.mechanics import HarmonicOscillatorSystem
>>> system = HarmonicOscillatorSystem(solver=Yoshida4Solver(dt=0.01)).prepare()
>>> system.simulate(until=3.1416, dt=3.1416).get_values('mass.x').round(3).tolist()
[1.0, -1.0]
Source code in src/skcomplex/core/engine/solvers/_yoshida4.py
89 90 91 92 93 94 95 96 97 98 | |