Skip to content

Commit 823fdbb

Browse files
committed
location npis (tutorial 10)
1 parent d06d482 commit 823fdbb

1 file changed

Lines changed: 296 additions & 0 deletions

File tree

tutorial10.py

Lines changed: 296 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
1+
import marimo
2+
3+
__generated_with = "0.19.11"
4+
app = marimo.App(width="medium")
5+
6+
7+
@app.cell
8+
def _():
9+
import marimo as mo
10+
import matplotlib.pyplot as plt
11+
import numpy as np
12+
13+
return mo, np, plt
14+
15+
16+
@app.cell(hide_code=True)
17+
def _(mo):
18+
mo.md(r"""
19+
# Location-specific Contact Patterns and NPIs
20+
21+
## Introduction
22+
23+
In Tutorial 3, we applied contact reductions (`Dampings`) uniformly to a single contact matrix. In reality, contacts between individuals occur in different locations: **at home**, **at school**, **at work**, and in **other** places such as transport. Different non-pharmaceutical interventions (NPIs) target different settings, for instance a school closure reduces school contacts, while a home-office mandate mainly reduces work contacts.
24+
25+
Large-scale studies, such as the POLYMOD project, have measured social contact patterns across different locations (like home, school, work, and others) in various countries. For instance, see
26+
27+
* **Mossong2008**: Mossong J, Hens N, Jit M, Beutels P, Auranen K, et al. (2008) *Social Contacts and Mixing Patterns Relevant to the Spread of Infectious Diseases*. PLoS Med 5(3): e74. https://doi.org/10.1371/journal.pmed.0050074
28+
* **Prem2017**: Prem K, Cook AR, Jit M (2017) *Projecting social contact matrices in 152 countries using contact surveys and demographic data*. PLoS Comput Biol 13(9): e1005697. https://doi.org/10.1371/journal.pcbi.1005697
29+
30+
In this tutorial, we extend the approach from Tutorial 3 by splitting the contact matrix into **location-specific contact matrices** using `ContactMatrixGroup`. This allows us to apply NPIs to individual locations, allowing a more realistic and detailed representation of intervention effects.
31+
""")
32+
return
33+
34+
35+
@app.cell(hide_code=True)
36+
def _(mo):
37+
mo.md(r"""
38+
## Model Setup
39+
40+
We first import the needed functions from the memilio-simulation package:
41+
""")
42+
return
43+
44+
45+
@app.cell
46+
def _():
47+
import memilio.simulation as mio
48+
import memilio.simulation.osecir as osecir
49+
from memilio.simulation import AgeGroup, Damping, LogLevel, set_log_level
50+
set_log_level(LogLevel.Off)
51+
return AgeGroup, Damping, mio, osecir
52+
53+
54+
@app.cell(hide_code=True)
55+
def _(mo):
56+
mo.md(r"""
57+
We define four contact locations and use an `IntEnum` to refer to them. We also set the basic simulation parameters - population size, time horizon, and step size - as in Tutorial 3:
58+
""")
59+
return
60+
61+
62+
@app.cell
63+
def _():
64+
from enum import IntEnum
65+
66+
class Location(IntEnum):
67+
Home = 0
68+
School = 1
69+
Work = 2
70+
Other = 3
71+
72+
total_population = 100000
73+
t0 = 0
74+
tmax = 100
75+
dt = 0.1
76+
return Location, dt, t0, tmax, total_population
77+
78+
79+
@app.cell(hide_code=True)
80+
def _(mo):
81+
mo.md(r"""
82+
## Location-specific Contact Matrices
83+
84+
Instead of a single contact matrix, we now use a `ContactMatrixGroup`, containing one `ContactMatrix` per location. Each `ContactMatrix` has two components:
85+
86+
- **Baseline**: the typical number of daily contacts at the location under regular conditions.
87+
- **Minimum**: the minimal contact rate even under the strictest restrictions, as some contacts, especially at home, cannot be fully avoided.
88+
89+
The effective contact rate at simulation time $t$ for a location $\ell$ is:
90+
91+
$$C_\ell(t) = C_{\ell,\text{baseline}} - D_\ell(t) \cdot \left(C_{\ell,\text{baseline}} - C_{\ell,\text{minimum}}\right)$$
92+
93+
where $D_\ell(t) \leq 1$ is the damping coefficient. For $D > 0$ contacts are reduced; for $D = 1$ they reach the minimum; and for $D < 0$ contacts are **increased above the baseline**. The upper bound $D \leq 1$ is enforced by MEmilio's C++ core. The ODE model uses the **sum** of all location-specific matrices as the total contact rate.
94+
95+
The total baseline contact rate (sum over all locations) equals $4 + 3 + 2 + 1 = 10$ contacts/day, matching Tutorial 3.
96+
""")
97+
return
98+
99+
100+
@app.cell
101+
def _(AgeGroup, Location, mio, np, osecir, total_population):
102+
def create_model():
103+
"""Create an OSECIR model with location-specific contact matrices."""
104+
m = osecir.Model(1)
105+
g = AgeGroup(0)
106+
107+
# Set infection state stay times (in days)
108+
m.parameters.TimeExposed[g] = 3.2
109+
m.parameters.TimeInfectedNoSymptoms[g] = 2.
110+
m.parameters.TimeInfectedSymptoms[g] = 6.
111+
m.parameters.TimeInfectedSevere[g] = 12.
112+
m.parameters.TimeInfectedCritical[g] = 8.
113+
114+
# Set infection state transition probabilities
115+
m.parameters.RelativeTransmissionNoSymptoms[g] = 0.67
116+
m.parameters.TransmissionProbabilityOnContact[g] = 0.1
117+
m.parameters.RecoveredPerInfectedNoSymptoms[g] = 0.2
118+
m.parameters.RiskOfInfectionFromSymptomatic[g] = 0.25
119+
m.parameters.SeverePerInfectedSymptoms[g] = 0.2
120+
m.parameters.CriticalPerSevere[g] = 0.25
121+
m.parameters.DeathsPerCritical[g] = 0.3
122+
123+
# Create ContactMatrixGroup: 4 location matrices, each of size 1x1 (one age group)
124+
contacts = mio.ContactMatrixGroup(4, 1)
125+
126+
# Home contacts: baseline 4/day, minimum 1/day (irreducible household contacts)
127+
contacts[Location.Home] = mio.ContactMatrix(
128+
np.array([[4.0]]), np.array([[1.0]]))
129+
# School contacts: baseline 3/day
130+
contacts[Location.School] = mio.ContactMatrix(
131+
np.array([[3.0]]), np.array([[0.0]]))
132+
# Work contacts: baseline 2/day
133+
contacts[Location.Work] = mio.ContactMatrix(
134+
np.array([[2.0]]), np.array([[0.0]]))
135+
# Other contacts: baseline 1/day
136+
contacts[Location.Other] = mio.ContactMatrix(
137+
np.array([[1.0]]), np.array([[0.0]]))
138+
139+
m.parameters.ContactPatterns.cont_freq_mat = contacts
140+
141+
# Initial populations: 0.5% Exposed, 0.5% InfectedNoSymptoms, rest Susceptible
142+
m.populations[g,
143+
osecir.InfectionState.Exposed] = 0.005 * total_population
144+
m.populations[g, osecir.InfectionState.InfectedNoSymptoms] = 0.005 * total_population
145+
m.populations.set_difference_from_total(
146+
(g, osecir.InfectionState.Susceptible), total_population)
147+
148+
return m
149+
150+
return (create_model,)
151+
152+
153+
@app.cell(hide_code=True)
154+
def _(mo):
155+
mo.md(r"""
156+
## Baseline Simulation Without NPIs
157+
158+
We first create and simulate the model without any interventions to obtain a baseline:
159+
""")
160+
return
161+
162+
163+
@app.cell
164+
def _(create_model, dt, osecir, t0, tmax):
165+
model_no_npi = create_model()
166+
result_no_npi = osecir.simulate(t0, tmax, dt, model_no_npi)
167+
return (result_no_npi,)
168+
169+
170+
@app.cell(hide_code=True)
171+
def _(mo):
172+
mo.md(r"""
173+
## Adding Location-specific NPIs
174+
175+
We now model a lockdown scenario in which three NPIs are activated simultaneously on **day 20**:
176+
177+
| Intervention | Location | Damping $D$ | Effect |
178+
|--------------------------|----------|-------------|--------------------------------------------|
179+
| School closure | School | 1.0 | All school contacts eliminated |
180+
| Home-office mandate | Work | 0.5 | Work contacts reduced by 50 % |
181+
| Public transport restriction | Other | 0.8 | Other contacts reduced by 80 % |
182+
183+
The key difference from Tutorial 3 is that each `Damping` is applied to a **specific location matrix** by indexing `cont_freq_mat[location_index]` before calling `add_damping`. In Tutorial 3, `add_damping` was called on the whole group, reducing **all** contact matrices simultaneously. Home contacts are left unrestricted here, but they cannot fall below the minimum of 1 contact/day regardless.
184+
""")
185+
return
186+
187+
188+
@app.cell
189+
def _(Damping, Location, create_model, np):
190+
t_npi_start = 20.0 # day at which interventions start
191+
192+
model_with_npi = create_model()
193+
194+
# School closure: damping of 1.0 -> effective school contacts reach the minimum (0)
195+
model_with_npi.parameters.ContactPatterns.cont_freq_mat[Location.School].add_damping(
196+
Damping(coeffs=np.ones((1, 1)) * 1.0, t=t_npi_start, level=0, type=0))
197+
# Home-office mandate: damping of 0.5 -> work contacts halved
198+
model_with_npi.parameters.ContactPatterns.cont_freq_mat[Location.Work].add_damping(
199+
Damping(coeffs=np.ones((1, 1)) * 0.5, t=t_npi_start, level=0, type=0))
200+
# Restrictions in public transport: damping of 0.8 -> other contacts reduced by 80 %
201+
model_with_npi.parameters.ContactPatterns.cont_freq_mat[Location.Other].add_damping(
202+
Damping(coeffs=np.ones((1, 1)) * 0.8, t=t_npi_start, level=0, type=0))
203+
return model_with_npi, t_npi_start
204+
205+
206+
@app.cell(hide_code=True)
207+
def _(mo):
208+
mo.md(r"""
209+
We can verify the effective total contact rates before and after the NPIs by evaluating the contact matrix group at a specific point in time:
210+
""")
211+
return
212+
213+
214+
@app.cell
215+
def _(model_with_npi, t_npi_start):
216+
contacts_before = model_with_npi.parameters.ContactPatterns.cont_freq_mat.get_matrix_at(
217+
t_npi_start - 1)
218+
contacts_after = model_with_npi.parameters.ContactPatterns.cont_freq_mat.get_matrix_at(
219+
t_npi_start + 1)
220+
print(
221+
f"Total contacts before NPIs (day {t_npi_start - 1:.0f}): {contacts_before[0, 0]} / day")
222+
print(
223+
f"Total contacts after NPIs (day {t_npi_start + 1:.0f}): {contacts_after[0, 0]} / day")
224+
return
225+
226+
227+
@app.cell(hide_code=True)
228+
def _(mo):
229+
mo.md(r"""
230+
We simulate the NPI scenario from `t0` to `tmax`:
231+
""")
232+
return
233+
234+
235+
@app.cell
236+
def _(dt, model_with_npi, osecir, t0, tmax):
237+
result_with_npi = osecir.simulate(t0, tmax, dt, model_with_npi)
238+
return (result_with_npi,)
239+
240+
241+
@app.cell(hide_code=True)
242+
def _(mo):
243+
mo.md(r"""
244+
## Visualization of Model Output
245+
246+
We plot and compare the `InfectedSymptoms` trajectories from both scenarios. The vertical dashed line marks the onset of the NPIs on day 20:
247+
""")
248+
return
249+
250+
251+
@app.cell
252+
def _(osecir, plt, result_no_npi, result_with_npi, t_npi_start):
253+
arr_no_npi = result_no_npi.as_ndarray()
254+
arr_with_npi = result_with_npi.as_ndarray()
255+
256+
inf_idx = 1 + int(osecir.InfectionState.InfectedSymptoms)
257+
258+
fig, ax = plt.subplots()
259+
ax.plot(arr_no_npi[0], arr_no_npi[inf_idx],
260+
label='Without NPIs', color='tab:blue')
261+
ax.plot(
262+
arr_with_npi[0],
263+
arr_with_npi[inf_idx],
264+
label='With location-specific NPIs', linestyle='--',
265+
color='tab:orange')
266+
ax.axvline(x=t_npi_start, color='gray', linestyle=':',
267+
label=f'NPI start (day {int(t_npi_start)})')
268+
ax.set_xlabel('Time [days]')
269+
ax.set_ylabel('Individuals [#]')
270+
ax.set_title('Effect of Location-specific NPIs on InfectedSymptoms')
271+
ax.legend()
272+
plt.show()
273+
return
274+
275+
276+
@app.cell(hide_code=True)
277+
def _(mo):
278+
mo.md(r"""
279+
The NPIs substantially flatten the infection curve. After day 20, school contacts drop to zero, work contacts are halved, and other contacts are reduced by 80 %. Only household contacts remain, bounded from below by their minimum of 1 contact/day.
280+
281+
## Summary and Next Steps
282+
283+
In this tutorial, we have introduced location-specific contact patterns via `ContactMatrixGroup` and applied targeted NPIs to individual location matrices. Key takeaways:
284+
285+
- A `ContactMatrixGroup` collects one `ContactMatrix` per location (Home, School, Work, Other).
286+
- Each `ContactMatrix` has a **baseline** (normal contacts) and a **minimum** (irreducible lower bound).
287+
- Location-specific NPIs are applied with `cont_freq_mat[location_index].add_damping(...)`. In contrast, Tutorial 3 used `cont_freq_mat.add_damping(...)` which applies to **all** matrices simultaneously.
288+
- The effective contact rate per location is $C_\text{eff} = C_\text{baseline} - D \cdot (C_\text{baseline} - C_\text{minimum})$, and the ODE model receives the **sum** over all locations.
289+
290+
In the next tutorial, we will extend this framework with **dynamic NPIs** that are triggered automatically when infection thresholds are exceeded.
291+
""")
292+
return
293+
294+
295+
if __name__ == "__main__":
296+
app.run()

0 commit comments

Comments
 (0)