Note
Go to the end to download the full example code.
2.4.10 Custom PDE class: SIR model
This example implements a spatially coupled SIR model with the following dynamics for the density of susceptible, infected, and recovered individuals:
\[\begin{split}\partial_t s &= D \nabla^2 s - \beta is \\
\partial_t i &= D \nabla^2 i + \beta is - \gamma i \\
\partial_t r &= D \nabla^2 r + \gamma i\end{split}\]
Here, \(D\) is the diffusivity, \(\beta\) the infection rate, and \(\gamma\) the recovery rate.
0%| | 0/50.0 [00:00<?, ?it/s]
Initializing: 0%| | 0/50.0 [00:00<?, ?it/s]
0%| | 0/50.0 [00:00<?, ?it/s]
0%| | 0.03/50.0 [00:00<14:05, 16.92s/it]
0%| | 0.06/50.0 [00:00<07:04, 8.50s/it]
2%|▏ | 0.82/50.0 [00:00<00:34, 1.43it/s]
8%|▊ | 3.83/50.0 [00:01<00:12, 3.78it/s]
17%|█▋ | 8.37/50.0 [00:01<00:07, 5.32it/s]
29%|██▉ | 14.44/50.0 [00:02<00:05, 6.00it/s]
42%|████▏ | 21.08/50.0 [00:03<00:04, 6.39it/s]
56%|█████▌ | 28.11/50.0 [00:03<00:03, 7.26it/s]
75%|███████▍ | 37.4/50.0 [00:04<00:01, 7.81it/s]
94%|█████████▍| 47.1/50.0 [00:05<00:00, 8.21it/s]
94%|█████████▍| 47.1/50.0 [00:06<00:00, 7.69it/s]
100%|██████████| 50.0/50.0 [00:06<00:00, 8.16it/s]
100%|██████████| 50.0/50.0 [00:06<00:00, 8.16it/s]
from pde import FieldCollection, PDEBase, PlotTracker, ScalarField, UnitGrid
class SIRPDE(PDEBase):
"""SIR-model with diffusive mobility."""
def __init__(
self, beta=0.3, gamma=0.9, diffusivity=0.1, bc="auto_periodic_neumann"
):
super().__init__()
self.beta = beta # transmission rate
self.gamma = gamma # recovery rate
self.diffusivity = diffusivity # spatial mobility
self.bc = bc # boundary condition
def get_state(self, s, i):
"""Generate a suitable initial state."""
norm = (s + i).data.max() # maximal density
if norm > 1:
s /= norm
i /= norm
s.label = "Susceptible"
i.label = "Infected"
# create recovered field
r = ScalarField(s.grid, data=1 - s - i, label="Recovered")
return FieldCollection([s, i, r])
def evolution_rate(self, state, t=0):
s, i, r = state
diff = self.diffusivity
ds_dt = diff * s.laplace(self.bc) - self.beta * i * s
di_dt = diff * i.laplace(self.bc) + self.beta * i * s - self.gamma * i
dr_dt = diff * r.laplace(self.bc) + self.gamma * i
return FieldCollection([ds_dt, di_dt, dr_dt])
eq = SIRPDE(beta=2, gamma=0.1)
# initialize state
grid = UnitGrid([32, 32])
s = ScalarField(grid, 1)
i = ScalarField(grid, 0)
i.data[0, 0] = 1
state = eq.get_state(s, i)
# simulate the pde
tracker = PlotTracker(interrupts=10, plot_args={"vmin": 0, "vmax": 1})
sol = eq.solve(state, t_range=50, dt=1e-2, tracker=["progress", tracker])
Total running time of the script: (0 minutes 6.377 seconds)