Skip to content

Commit 9c86a65

Browse files
committedApr 16, 2020
single runner and multi runner example. Needs to integrate simulation.py, but that requires a re-write of simulation
1 parent 194edb8 commit 9c86a65

File tree

3 files changed

+153
-0
lines changed

3 files changed

+153
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#!/usr/bin/env python3
2+
3+
4+
"""
5+
This example sets up a model from the base line parameters, sets a random rng seed
6+
and then runs for 50 days, after 50 days lock down is turned on
7+
"""
8+
9+
10+
from COVID19.model import Parameters, Model
11+
import json
12+
from pathlib import Path
13+
import covid19
14+
from random import randint
15+
from tqdm import tqdm
16+
17+
import pandas as pd
18+
base_path = Path(__file__).parent.absolute()
19+
print(base_path)
20+
21+
BASELINE_PARAMS = base_path / "../tests/data/baseline_parameters.csv"
22+
HOUSEHOLDS = base_path / "../tests/data/baseline_household_demographics.csv"
23+
import logging
24+
25+
26+
def setup_params(updated_params: dict = None):
27+
"""[summary]
28+
set up a parameters object from the baseline file
29+
Customise any parameters supplied in the updated params dict
30+
Keyword Arguments:
31+
updated_params {dict} -- [description] (default: {None})
32+
Returns:
33+
Parameter set
34+
"""
35+
p = Parameters(
36+
input_param_file=str(BASELINE_PARAMS),
37+
output_file_dir="./results",
38+
param_line_number=1,
39+
input_household_file=str(HOUSEHOLDS),
40+
read_param_file=True,
41+
)
42+
43+
if updated_params:
44+
for k, v in updated_params.items():
45+
p.set_param(k, v)
46+
return p
47+
48+
49+
if __name__ == "__main__":
50+
updates = {"rng_seed": randint(0, 65000)}
51+
params = setup_params(updates)
52+
# Create an instance of the Model
53+
model = Model(params)
54+
m_out = []
55+
# Run for 300 days
56+
for step in tqdm(range(300)):
57+
# Evaluate each step and save the results
58+
model.one_time_step()
59+
# print(model.one_time_step_results()) # If we want to see the results as we go uncomment this line
60+
m_out.append(model.one_time_step_results())
61+
if step == 50:
62+
model.update_running_params("lockdown_on", 1)
63+
print("turning on lock down")
64+
print("lockdown_house_interaction_multiplier", params.get_param("lockdown_house_interaction_multiplier"))
65+
print("lockdown_random_network_multiplier",params.get_param("lockdown_random_network_multiplier"))
66+
print("lockdown_work_network_multiplier",params.get_param("lockdown_work_network_multiplier"))
67+
df = pd.DataFrame(m_out)
68+
model.write_output_files()
69+
df.to_csv("results/timeseries_lockdown_at_50.csv")
70+
print(df)

‎examples/multi_run_simulator.py

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#!/usr/bin/env python3
2+
"""Example script to evaluate models over time range with changes from the default parameter set
3+
This example sets different random seeds for each evaulation and collects the data into pandas dataframes
4+
Note that individual traces, interactions etc are not saved due to the large number of them.
5+
This is designed to be run to generate a stochastic window to gain a staticial interpretation of the model
6+
Run the senario once with full output on to enable detailed knowledge of the model
7+
"""
8+
from COVID19.model import Parameters, Model
9+
from tqdm import tqdm
10+
from multiprocessing.pool import ThreadPool
11+
from concurrent.futures import ProcessPoolExecutor
12+
import pandas as pd
13+
import random
14+
from pathlib import Path
15+
16+
base_path = Path(__file__).parent.absolute()
17+
print(base_path)
18+
19+
BASELINE_PARAMS = base_path / "../tests/data/baseline_parameters.csv"
20+
HOUSEHOLDS = base_path / "../tests/data/baseline_household_demographics.csv"
21+
22+
def setup_parameters(d: dict=None, output_dir: str="./"):
23+
# Set up Parameters
24+
# Override defaults that we pass in input dict
25+
p = Parameters(
26+
input_param_file=str(BASELINE_PARAMS),
27+
param_line_number=1,
28+
output_file_dir=output_dir,
29+
input_household_file=str(HOUSEHOLDS),
30+
read_param_file=True,
31+
)
32+
if d:
33+
for k, v in d.items():
34+
p.set_param(k, v)
35+
return p
36+
37+
38+
def setup_model(d: dict=None, di:str=None):
39+
params = setup_parameters(di, d)
40+
params.set_param("sys_write_individual", 0)
41+
model = Model(params)
42+
return model
43+
44+
45+
def run_model(d: dict=None, di:str = None):
46+
m = setup_model(di,d)
47+
results = []
48+
for _ in range(100):
49+
m.one_time_step()
50+
results.append(m.one_time_step_results())
51+
return pd.DataFrame(results)
52+
53+
54+
def run_many_inline(parameter_set_list, processes=None, progress_bar=True):
55+
if progress_bar:
56+
progress_monitor = tqdm
57+
else:
58+
progress_monitor = lambda x: x
59+
60+
# Create a pool and evaluate models concurrently
61+
with ThreadPool(processes=processes) as pool:
62+
63+
outputs = list(
64+
progress_monitor(
65+
pool.imap(run_model, parameter_set_list), total=len(parameter_set_list)
66+
67+
)
68+
)
69+
return outputs
70+
71+
72+
if __name__ == "__main__":
73+
74+
print(BASELINE_PARAMS, HOUSEHOLDS)
75+
# Edit so we only run over 100k people, default is 1m but 10x speed increase for testing.
76+
# Remove n_total setting to run over larger population.
77+
params_list = [{"rng_seed": random.randint(0, 2**32 -1), "n_total": 100000} for x in range(100)]
78+
79+
results_dataframes = run_many_inline(params_list, processes=None)
80+
81+
# Ouput individual dataframes as CSVs
82+
for p, df in zip(params_list, results_dataframes):
83+
df.to_csv(f"./results/model_rng_seed_{p['rng_seed']}.csv")

‎examples/results/.gitkeep

Whitespace-only changes.

0 commit comments

Comments
 (0)
Please sign in to comment.