Skip to content

Commit f923fad

Browse files
Merge pull request #277 from SciML/spatial
Move spatial tutorial from SciMLTutorials
2 parents 833194d + e4722fb commit f923fad

File tree

2 files changed

+217
-1
lines changed

2 files changed

+217
-1
lines changed

docs/pages.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
pages = ["index.md",
44
"Tutorials" => Any["tutorials/simple_poisson_process.md",
55
"tutorials/discrete_stochastic_example.md",
6-
"tutorials/jump_diffusion.md"],
6+
"tutorials/jump_diffusion.md",
7+
"tutorials/spatial.md"],
78
"FAQ" => "faq.md",
89
"Type Documentation" => Any["Jump types and JumpProblem" => "jump_types.md",
910
"Jump solvers" => "jump_solve.md"],

docs/src/tutorials/spatial.md

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
# Spatial SSAs with JumpProcesses.jl
2+
3+
This tutorial shows how to use spatial solvers.
4+
5+
## Reversible binding model on a grid
6+
7+
A 5 by 5 Cartesian grid:
8+
9+
| <!-- --> | <!-- --> | <!-- --> | <!-- --> | <!-- --> |
10+
|---|---|---|---|---|
11+
| . | . | . | . | B |
12+
| . | . | . | . | . |
13+
| . | . | . | . | . |
14+
| . | . | . | . | . |
15+
| A | . | . | . | . |
16+
17+
Suppose we have a reversible binding system described by $$A+B \to C$$ at rate $$k_1$$ and $$C \to A+B$$ at rate $$k_2$$. Further suppose that all $$A$$ molecules start in the lower left corner, while all $$B$$ molecules start in the upper right corner of a 5 by 5 grid. There are no $$C$$ molecules at the start.
18+
19+
We first create the grid:
20+
21+
```@example spatial
22+
using JumpProcesses
23+
dims = (5,5)
24+
num_nodes = prod(dims) # number of sites
25+
grid = CartesianGrid(dims) # or use Graphs.grid(dims)
26+
```
27+
28+
Now we set the initial state of the simulation. It has to be a matrix with entry $$(s,i)$$ being the number of species $$s$$ at site $$i$$ (with the standard column-major ordering of the grid).
29+
30+
```@example spatial
31+
num_species = 3
32+
starting_state = zeros(Int, num_species, num_nodes)
33+
starting_state[1,1] = 25
34+
starting_state[2,end] = 25
35+
starting_state
36+
```
37+
38+
We now set the time-span of the simulation and the reaction rates. These can be chosen arbitrarily.
39+
40+
```@example spatial
41+
tspan = (0.0, 3.0)
42+
rates = [6.0, 0.05] # k_1 = rates[1], k_2 = rates[2]
43+
```
44+
45+
Now we can create the `DiscreteProblem`:
46+
47+
```@example spatial
48+
prob = DiscreteProblem(starting_state, tspan, rates)
49+
```
50+
51+
Since both reactions are [massaction reactions](https://en.wikipedia.org/wiki/Law_of_mass_action), we put them together in a `MassActionJump`. In order to do that we create two stoichiometry vectors. The net stoichiometry vector describes which molecules change in number and how much after each reaction; for example, `[1 => -1]` is the first molecule disappearing. The reaction stoichiometry vector describes what the reactants of each reaction are; for example, `[1 => 1, 2 => 1]` would mean that the reactants are one molecule of type 1 and one molecule of type 2.
52+
53+
```@example spatial
54+
netstoch = [[1 => -1, 2 => -1, 3 => 1],[1 => 1, 2 => 1, 3 => -1]]
55+
reactstoch = [[1 => 1, 2 => 1],[3 => 1]]
56+
majumps = MassActionJump(rates, reactstoch, netstoch)
57+
```
58+
59+
The last thing to set up is the hopping constants -- the probability per time of an individual molecule of each species hopping from one site to another site. In practice this parameter, as well as reaction rates, are obtained empirically. Suppose that molecule $$C$$ cannot diffuse, while molecules $$A$$ and $$B$$ diffuse at probability per time 1 (i.e. the time of the diffusive hop is exponentially distributed with mean 1). Entry $$(s,i)$$ of `hopping_constants` is the hopping rate of species $$s$$ at site $$i$$ to any of its neighboring sites (diagonal hops are not allowed).
60+
61+
```@example spatial
62+
hopping_constants = ones(num_species, num_nodes)
63+
hopping_constants[3, :] .= 0.0
64+
hopping_constants
65+
```
66+
67+
We are now ready to set up the `JumpProblem` with the Next Subvolume Method.
68+
69+
```@example spatial
70+
alg = NSM()
71+
jump_prob = JumpProblem(prob, alg, majumps, hopping_constants=hopping_constants, spatial_system = grid, save_positions=(true, false))
72+
```
73+
74+
The `save_positions` keyword tells the solver to save the positions just before the jumps. To solve the jump problem do
75+
76+
```@example spatial
77+
solution = solve(jump_prob, SSAStepper())
78+
```
79+
80+
## Animation
81+
82+
Visualizing solutions of spatial jump problems is best done with animations.
83+
84+
```@example spatial
85+
using Plots
86+
is_static(spec) = (spec == 3) # true if spec does not hop
87+
"get frame k"
88+
function get_frame(k, sol, linear_size, labels, title)
89+
num_species = length(labels)
90+
h = 1/linear_size
91+
t = sol.t[k]
92+
state = sol.u[k]
93+
xlim=(0,1+3h/2); ylim=(0,1+3h/2);
94+
plt = plot(xlim=xlim, ylim=ylim, title = "$title, $(round(t, sigdigits=3)) seconds")
95+
96+
species_seriess_x = [[] for i in 1:num_species]
97+
species_seriess_y = [[] for i in 1:num_species]
98+
CI = CartesianIndices((linear_size, linear_size))
99+
for ci in CartesianIndices(state)
100+
species, site = Tuple(ci)
101+
x,y = Tuple(CI[site])
102+
num_molecules = state[ci]
103+
sizehint!(species_seriess_x[species], num_molecules)
104+
sizehint!(species_seriess_y[species], num_molecules)
105+
if !is_static(species)
106+
randsx = rand(num_molecules)
107+
randsy = rand(num_molecules)
108+
else
109+
randsx = zeros(num_molecules)
110+
randsy = zeros(num_molecules)
111+
end
112+
for k in 1:num_molecules
113+
push!(species_seriess_x[species], x*h - h/4 + 0.5h*randsx[k])
114+
push!(species_seriess_y[species], y*h - h/4 + 0.5h*randsy[k])
115+
end
116+
end
117+
for species in 1:num_species
118+
scatter!(plt, species_seriess_x[species], species_seriess_y[species], label = labels[species], marker = 6)
119+
end
120+
xticks!(plt, range(xlim...,length = linear_size+1))
121+
yticks!(plt, range(ylim...,length = linear_size+1))
122+
xgrid!(plt, 1, 0.7)
123+
ygrid!(plt, 1, 0.7)
124+
return plt
125+
end
126+
127+
"make an animation of solution sol in 2 dimensions"
128+
function animate_2d(sol, linear_size; species_labels, title, verbose = true)
129+
num_frames = length(sol.t)
130+
anim = @animate for k=1:num_frames
131+
verbose && println("Making frame $k")
132+
get_frame(k, sol, linear_size, species_labels, title)
133+
end
134+
anim
135+
end
136+
# animate
137+
anim=animate_2d(solution, 5, species_labels = ["A", "B", "C"], title = "A + B <--> C", verbose = false)
138+
fps = 5
139+
gif(anim, fps = fps)
140+
```
141+
142+
## Making changes to the model
143+
144+
Now suppose we want to make some changes to the reversible binding model above. There are three "dimensions" that can be changed: the topology of the system, the structure of hopping rates and the solver. The supported topologies are `CartesianGrid` -- used above, and any `AbstractGraph` from `Graphs`. The supported forms of hopping rates are $$D_{s,i}, D_{s,i,j}, D_s * L_{i,j}$$, and $$D_{s,i} * L_{i,j}$$, where $$s$$ denotes the species, $$i$$ -- the source site, and $$j$$ -- the destination. The supported solvers are `NSM`, `DirectCRDirect` and any of the standard non-spatial solvers.
145+
146+
### Topology
147+
148+
If our mesh is a grid (1D, 2D and 3D are supported), we can create the mesh as follows.
149+
150+
```@example spatial
151+
dims = (2,3,4) # can pass in a 1-Tuple, a 2-Tuple or a 3-Tuple
152+
num_nodes = prod(dims)
153+
grid = CartesianGrid(dims)
154+
```
155+
156+
The interface is the same as for [`Graphs.grid`](https://juliagraphs.org/Graphs.jl/dev/core_functions/simplegraphs_generators/#Graphs.SimpleGraphs.grid-Union{Tuple{AbstractVector{T}},%20Tuple{T}}%20where%20T%3C:Integer). If we want to use an unstructured mesh, we can simply use any `AbstractGraph` from `Graphs` as follows:
157+
158+
```@example spatial
159+
using Graphs
160+
graph = cycle_digraph(5) # directed cyclic graph on 5 nodes
161+
```
162+
163+
Now either `graph` or `grid` can be used as `spatial_system` in creation of the `JumpProblem`.
164+
165+
### Hopping rates
166+
167+
The most general form of hopping rates that is supported is $$D_{s,i,j}$$ -- each (species, source, destination) triple gets its own independent hopping rate. To use this, `hopping_constants` must be of type `Matrix{Vector{F}} where F <: Number` (usually `F` is `Float64`) with `hopping_constants[s,i][j]` being the hopping rate of species $$s$$ at site $$i$$ to neighbor at index $$j$$. Note that neighbors are in ascending order, like in `Graphs`. Here is an example where only hopping up and left is allowed.
168+
169+
```@example spatial
170+
hopping_constants = Matrix{Vector{Float64}}(undef, num_species, num_nodes)
171+
for ci in CartesianIndices(hopping_constants)
172+
(species, site) = Tuple(ci)
173+
hopping_constants[species, site] = zeros(outdegree(grid, site))
174+
for (n, nb) in enumerate(neighbors(grid, site))
175+
if nb < site
176+
hopping_constants[species, site][n] = 1.0
177+
end
178+
end
179+
end
180+
```
181+
182+
To pass in `hopping_constants` of form $$D_s * L_{i,j}$$ we need two vectors -- one for $$D_s$$ and one for $$L_{i,j}$$. Here is an example.
183+
184+
```@example spatial
185+
species_hop_constants = ones(num_species)
186+
site_hop_constants = Vector{Vector{Float64}}(undef, num_nodes)
187+
for site in 1:num_nodes
188+
site_hop_constants[site] = ones(outdegree(grid, site))
189+
end
190+
hopping_constants=Pair(species_hop_constants, site_hop_constants)
191+
```
192+
193+
We must combine both vectors into a pair as in the last line above.
194+
195+
Finally, to use in `hopping_constants` of form $$D_{s,i} * L_{i,j}$$ we construct a matrix instead of a vector for $$D_{s,j}$$.
196+
197+
```@example spatial
198+
species_hop_constants = ones(num_species, num_nodes)
199+
site_hop_constants = Vector{Vector{Float64}}(undef, num_nodes)
200+
for site in 1:num_nodes
201+
site_hop_constants[site] = ones(outdegree(grid, site))
202+
end
203+
hopping_constants=Pair(species_hop_constants, site_hop_constants)
204+
```
205+
206+
We can use either of the four versions of `hopping_constants` to construct a `JumpProblem` with the same syntax as in the original example. The different forms of hopping rates are supported not only for convenience but also for better memory usage and performance. So it is recommended that the most specialized form of hopping rates is used.
207+
208+
### Solvers
209+
210+
There are currently two specialized "spatial" solvers: `NSM` and `DirectCRDirect`. The former stands for Next Subvolume Method [^1]. The latter employs Composition-Rejection to sample the next site to fire, similar to the ordinary DirectCR method. For larger networks `DirectCRDirect` is expected to be faster. Both methods can be used interchangeably.
211+
212+
Additionally, all standard solvers are supported as well, although they are expected to use more memory and be slower. They "flatten" the problem, i.e. turn all hops into reactions, resulting in a much larger system. For example, to use the Next Reaction Method (`NRM`), simply pass in `NRM()` instead of `NSM()` in the construction of the `JumpProblem`. Importantly, you *must* pass in `hopping_constants` in the `D_{s,i,j}` or `D_{s,i}` form to use any of the non-specialized solvers.
213+
214+
## References
215+
[^1]: Elf, Johan and Ehrenberg, Mäns. “Spontaneous separation of bi-stable biochemical systems into spatial domains of opposite phases”. In: _Systems biology_ 1.2 (2004), pp. 230–236.

0 commit comments

Comments
 (0)