CLT Toolkit API Reference
Docstrings and references for clt_toolkit
package.
PROJECT_ROOT = Path(__file__).resolve().parent.parent
module-attribute
Compartment
Bases: StateVariable
Class for epidemiological compartments (e.g. Susceptible, Exposed, Infected, etc...).
Attributes:
Name | Type | Description |
---|---|---|
current_inflow |
np.ndarray of shape (A, R
|
Used to sum up all transition variable realizations incoming to this compartment for age-risk groups. |
current_outflow |
np.ndarray of shape (A, R
|
Used to sum up all transition variable realizations outgoing from this compartment for age-risk groups. |
See StateVariable
docstring for additional attributes
and A, R definitions.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
reset_inflow() -> None
reset_outflow() -> None
update_current_val() -> None
Updates current_val
attribute in-place by adding
current_inflow
(sum of all incoming transition variables'
realizations) and subtracting current outflow (sum of all
outgoing transition variables' realizations).
Source code in CLT_BaseModel/clt_toolkit/base_components.py
DataClassProtocol
DynamicVal
Bases: StateVariable
, ABC
Abstract base class for variables that dynamically adjust
their values based the current values of other StateVariable
instances.
This class should model social distancing (and more broadly, staged-alert policies). For example, if we consider a case where transmission rates decrease when number infected increase above a certain level, we can create a subclass of DynamicVal that models a coefficient that modifies transmission rates, depending on the epi compartments corresponding to infected individuals.
Inherits attributes from StateVariable
.
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
__init__(init_val: Optional[np.ndarray | float] = None, is_enabled: Optional[bool] = False)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
init_val
|
Optional[ndarray | float]
|
starting value(s) at the beginning of the simulation. |
None
|
is_enabled
|
Optional[bool]
|
if |
False
|
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_current_val(state: SubpopState, params: SubpopParams) -> None
abstractmethod
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
SubpopState
|
holds subpopulation simulation state (current values of
|
required |
params
|
SubpopParams
|
holds values of epidemiological parameters. |
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
EpiMetric
Bases: StateVariable
, ABC
Abstract base class for epi metrics in epidemiological model.
This is intended for variables that are aggregate deterministic functions of
the SubpopState
(including Compartment
current_val
's, other parameters,
and time.)
For example, population-level immunity variables should be
modeled as a EpiMetric
subclass, with a concrete
implementation of the abstract method get_change_in_current_val
.
Inherits attributes from StateVariable
.
Attributes:
Name | Type | Description |
---|---|---|
current_val |
np.ndarray of shape (A, R
|
same size as init_val, holds current value of |
change_in_current_val |
(np.ndarray of shape (A, R)):
initialized to None, but during simulation holds change in
current value of |
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
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 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 |
|
__init__(init_val)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
init_val
|
np.ndarray of shape (A, R
|
2D array that contains nonnegative floats, corresponding to initial value of dynamic val, where i,jth entry corresponds to age group i and risk group j. |
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_change_in_current_val(state: SubpopState, params: SubpopParams, num_timesteps: int) -> np.ndarray
abstractmethod
Computes and returns change in current value of dynamic val, based on current state of the simulation and epidemiological parameters.
NOTE
OUTPUT SHOULD ALREADY BE SCALED BY NUM_TIMESTEPS.
Output should be a numpy array of size A x R, where A is number of age groups and R is number of risk groups.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
SubpopState
|
holds subpopulation simulation state (current values of
|
required |
params
|
SubpopParams
|
holds values of epidemiological parameters. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) size A x R, where A is the number of age groups and R is number of risk groups. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_current_val() -> None
Adds change_in_current_val
attribute to
current_val
attribute in-place.
Experiment
Class to manage running multiple simulation replications
on a SubpopModel
or MetapopModel
instance and query its results.
Also allows running a batch of simulation replications on a deterministic sequence of values for a given input (for example, to see how output changes as a function of a given input).
Also handles random sampling of inputs from a uniform distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
experiment_subpop_models
|
tuple
|
tuple of |
required |
results_df
|
DataFrame
|
DataFrame holding simulation results from each
|
required |
has_been_run
|
bool
|
indicates if |
required |
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/experiments.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 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 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 |
|
__init__(model: SubpopModel | MetapopModel, state_variables_to_record: list, database_filename: str)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
SubpopModel | MetapopModel
|
SubpopModel or MetapopModel instance on which to run multiple replications. |
required |
state_variables_to_record
|
list[str]
|
list or list-like of strings corresponding to state variables to record -- each string must match a state variable name on each SubpopModel in the MetapopModel. |
required |
database_filename
|
str
|
must be valid filename with suffix ".db" -- experiment results are saved to this SQL database |
required |
Source code in CLT_BaseModel/clt_toolkit/experiments.py
create_results_sql_table()
Create SQL database and save to self.database_filename
.
Create table named results
with columns subpop_name
,
state_var_name
, age_group
, risk_group
, rep
, timepoint
,
and value
to store results from each replication of experiment.
Source code in CLT_BaseModel/clt_toolkit/experiments.py
get_state_var_df(state_var_name: str, subpop_name: str = None, age_group: int = None, risk_group: int = None, results_filename: str = None) -> pd.DataFrame
Get pandas DataFrame of recorded values of StateVariable
given by
state_var_name
, in the SubpopModel
given by subpop_name
,
for the age-risk group given by age_group
and risk_group
.
If subpop_name
is not specified, then values are summed across all
associated subpopulations. Similarly, if age_group
(or risk_group
)
is not specified, then values are summed across all age groups
(or risk groups).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state_var_name
|
str
|
Name of the |
required |
subpop_name
|
Optional[str]
|
The name of the |
None
|
age_group
|
Optional[int]
|
The age group to select. If None, values are summed across all age groups. |
None
|
risk_group
|
Optional[int]
|
The risk group to select. If None, values are summed across all risk groups. |
None
|
results_filename
|
Optional[str]
|
If provided, saves the resulting DataFrame as a CSV. |
None
|
Returns:
Type | Description |
---|---|
DataFrame
|
A pandas DataFrame where rows represent the replication and columns indicate the |
DataFrame
|
simulation day (timepoint) of recording. DataFrame values are the |
DataFrame
|
current_val or the sum of the |
DataFrame
|
age groups, or risk groups (the combination of what is summed over is |
DataFrame
|
specified by the user -- details are in the part of this docstring describing |
DataFrame
|
this function's parameters). |
Source code in CLT_BaseModel/clt_toolkit/experiments.py
266 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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
|
log_current_vals_to_sql(rep_counter: int, experiment_cursor: sqlite3.Cursor) -> None
For each subpopulation and state variable to record
associated with this Experiment
, save current values to
"results" table in SQL database specified by experiment_cursor
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rep_counter
|
int
|
Current replication ID. |
required |
experiment_cursor
|
Cursor
|
Cursor object connected to the database where results should be inserted. |
required |
Source code in CLT_BaseModel/clt_toolkit/experiments.py
log_inputs_to_sql(experiment_cursor: sqlite3.Cursor)
For each subpopulation, add a new table to SQL
database specified by experiment_cursor
. Each table
contains information on inputs that vary across
replications (either due to random sampling or
user-specified deterministic sequence). Each table
contains inputs information from Experiment
attribute
self.inputs_realizations
for a given subpopulation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
experiment_cursor
|
Cursor
|
Cursor object connected to the database where results should be inserted. |
required |
Source code in CLT_BaseModel/clt_toolkit/experiments.py
run_static_inputs(num_reps: int, simulation_end_day: int, days_between_save_history: int = 1, results_filename: str = None)
Runs the associated SubpopModel
or MetapopModel
for a
given number of independent replications until simulation_end_day
.
Parameter values and initial values are the same across
simulation replications. User can specify how often to save the
history and a CSV file in which to store this history.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_reps
|
positive int
|
number of independent simulation replications to run in an experiment. |
required |
simulation_end_day
|
positive int
|
stop simulation at simulation_end_day (i.e. exclusive, simulate up to but not including simulation_end_day). |
required |
days_between_save_history
|
positive int
|
indicates how often to save simulation results. |
1
|
results_filename
|
str
|
if specified, must be valid filename with suffix ".csv" -- experiment results are saved to this CSV file. |
None
|
Source code in CLT_BaseModel/clt_toolkit/experiments.py
simulate_reps_and_save_results(reps: int, end_day: int, days_per_save: int, inputs_are_static: bool, filename: str = None)
Helper function that executes main loop over
replications in Experiment
and saves results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reps
|
int
|
number of independent simulation replications to run in an experiment. |
required |
end_day
|
int
|
stop simulation at end_day (i.e. exclusive, simulate up to but not including end_day). |
required |
days_per_save
|
int
|
indicates how often to save simulation results. |
required |
inputs_are_static
|
bool
|
indicates if inputs are same across replications. |
required |
filename
|
str
|
if specified, must be valid filename with suffix ".csv" -- experiment results are saved to this CSV file. |
None
|
Source code in CLT_BaseModel/clt_toolkit/experiments.py
ExperimentError
InteractionTerm
Bases: StateVariable
, ABC
Abstract base class for variables that depend on the state of
more than one SubpopModel
(i.e., that depend on more than one
SubpopState
). These variables are functions of how subpopulations
interact.
Inherits attributes from StateVariable
.
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_current_val(subpop_state: SubpopState, subpop_params: SubpopParams) -> None
abstractmethod
Subclasses must provide a concrete implementation of
updating current_val
in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
subpop_params
|
SubpopParams
|
holds values of subpopulation's epidemiological parameters. |
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
JointTransitionTypes
Bases: str
, Enum
Defines available options for transition_type
in TransitionVariableGroup
.
Source code in CLT_BaseModel/clt_toolkit/base_data_structures.py
MetapopModel
Bases: ABC
Abstract base class that bundles SubpopModel
s linked using
a travel model.
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 |
|
current_real_date: datetime.date
property
Returns:
Type | Description |
---|---|
date
|
Current real date corresponding to current simulation day. |
date
|
The current real date of the |
date
|
each individual |
date
|
Otherwise, an error is raised. |
current_simulation_day: int
property
Returns:
Type | Description |
---|---|
int
|
Current simulation day. The current simulation day of the |
int
|
|
int
|
in the |
__getattr__(name)
Called if normal attribute lookup fails.
Delegate to subpop_models
if name matches a key.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
__init__(subpop_models: list[dict], mixing_params: dict, name: str = '')
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
unique identifier for |
''
|
Source code in CLT_BaseModel/clt_toolkit/base_components.py
apply_inter_subpop_updates()
MetapopModel
subclasses can optionally override this method
with a customized implementation. Otherwise, by default does nothing.
Called once a day (not for each discretized timestep), after each subpop model's daily state is prepared, and before discretized transitions are computed.
This method computes quantities that depend on multiple subpopulations (e.g. this is where a travel model should be implemented).
See simulate_until_day
method for more details.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
modify_simulation_settings(updates_dict: dict)
This method applies the changes specified in updates_dict
to the
simulation_settings
attribute of each subpopulation model.
SimulationSettings
is a frozen dataclass to prevent users from
mutating individual subpop settings directly and making subpop
models have different settings within the same metapop model.
Instead, a new instance is created with the requested updates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
updates_dict
|
dict
|
Dictionary specifying values to update in a
|
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
reset_simulation()
Resets MetapopModel
by resetting and clearing
history on all SubpopModel
instances in
subpop_models
.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
simulate_until_day(simulation_end_day: int) -> None
Advance simulation model time until simulation_end_day
in
MetapopModel
.
NOT just the same as looping through each SubpopModel
's
simulate_until_day
method. On the MetapopModel
,
because SubpopModel
instances are linked with InteractionTerm
s
and are not independent of each other, this MetapopModel
's
simulate_until_day
method has additional functionality.
Note: the update order at the beginning of each day is very important!
-
First, each
SubpopModel
updates its daily state (computingSchedule
andDynamicVal
instances). -
Second, the
MetapopModel
computes quantities that depend on more than one subpopulation (i.e. inter-subpop quantities, such as the force of infection to each subpopulation in a travel model, where these terms depend on the number infected in other subpopulations) and then applies the update to eachSubpopModel
according to the user-implemented methodapply_inter_subpop_updates.
-
Third, each
SubpopModel
simulates discretized timesteps (samplingTransitionVariable
s, updatingEpiMetric
s, and updatingCompartment
s).
Note: we only update inter-subpop quantities once a day, not at every timestep -- in other words, the travel model state-dependent values are only updated daily -- this is to avoid severe computation inefficiency
Parameters:
Name | Type | Description | Default |
---|---|---|---|
simulation_end_day
|
positive int
|
stop simulation at |
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 |
|
MetapopModelError
ParamShapes
Bases: str
, Enum
Defines allowed structural shapes for parameter sampling.
Specifies which population dimension(s) a parameter varies across. - "age": an array of length A (one value per age group) - "age_risk": a 2D array of shape (A, R) (values per age × risk group) - "scalar": a single value applied to all subpopulations
Used in UniformSamplingSpec.param_shapes
to reduce the need for
manually expanding arrays.
Source code in CLT_BaseModel/clt_toolkit/sampling.py
Schedule
dataclass
Bases: StateVariable
, ABC
Abstract base class for variables that are functions of real-world dates -- for example, contact matrices (which depend on the day of the week and whether the current day is a holiday), historical vaccination data, and seasonality.
Inherits attributes from StateVariable
.
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
__init__(init_val: Optional[np.ndarray | float] = None, timeseries_df: Optional[dict] = None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
init_val
|
Optional[ndarray | float]
|
starting value(s) at the beginning of the simulation |
None
|
timeseries_df
|
Optional[pd.DataFrame] = None
|
has a "date" column with strings in format |
None
|
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_current_val(params: SubpopParams, current_date: datetime.date) -> None
abstractmethod
Subpop classes must provide a concrete implementation of
updating current_val
in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
params
|
SubpopParams
|
fixed parameters of subpopulation model. |
required |
current_date
|
date
|
real-world date corresponding to model's current simulation day. |
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
SimulationSettings
dataclass
Stores simulation settings.
Attributes:
Name | Type | Description |
---|---|---|
timesteps_per_day |
int
|
number of discretized timesteps within a simulation
day -- more |
transition_type |
str
|
valid value must be from |
start_real_date |
str
|
actual date in string format "YYYY-MM-DD" that aligns with the beginning of the simulation. |
save_daily_history |
bool
|
set to |
transition_variables_to_save |
tuple
|
Names of transition variables whose histories should be saved during the simulation. Saving these can significantly slow execution, so leave this tuple empty for faster performance. |
Source code in CLT_BaseModel/clt_toolkit/base_data_structures.py
StateVariable
Parent class of InteractionTerm
, Compartment
, EpiMetric
,
DynamicVal
, and Schedule
classes. All subclasses have the
attributes init_val
and current_val
.
Dimensions
A (int): Number of age groups. R (int): Number of risk groups.
Attributes:
Name | Type | Description |
---|---|---|
init_val |
np.ndarray of shape (A, R
|
Holds initial value of |
current_val |
np.ndarray of shape (A, R
|
Same size as |
history_vals_list |
list[ndarray]
|
Each element is an A x R array that holds
history of compartment states for age-risk groups --
element t corresponds to previous |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
reset() -> None
Resets current_val
to init_val
and resets
history_vals_list
attribute to empty list.
save_history() -> None
Saves current value to history by appending current_val
attribute
to history_vals_list
in-place..
Deep copying is CRUCIAL because current_val
is a mutable
np.ndarray
-- without deep copying, history_vals_list
would
have the same value for all elements.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
SubpopModel
Bases: ABC
Contains and manages all necessary components for simulating a compartmental model for a given subpopulation.
Each SubpopModel
instance includes compartments,
epi metrics, dynamic vals, a data container for the current simulation
state, transition variables and transition variable groups,
epidemiological parameters, simulation experiment simulation settings
parameters, and a random number generator.
All city-level subpopulation models, regardless of disease type and compartment/transition structure, are instances of this class.
When creating an instance, the order of elements does not matter
within compartments
, epi_metrics
, dynamic_vals
,
transition_variables
, and transition_variable_groups
.
The "flow" and "physics" information are stored on the objects.
Attributes:
Name | Type | Description |
---|---|---|
compartments |
objdict[str, Compartment]
|
objdict of all the subpop model's |
transition_variables |
objdict[str, TransitionVariable]
|
objdict of all the subpop model's |
transition_variable_groups |
objdict[str, TransitionVariableGroup]
|
objdict of all the subpop model's |
epi_metrics |
objdict[str, EpiMetric]
|
objdict of all the subpop model's |
dynamic_vals |
objdict[str, DynamicVal]
|
objdict of all the subpop model's |
schedules |
objdict[str, Schedule]
|
objdict of all the subpop model's |
current_simulation_day |
int
|
tracks current simulation day -- incremented by +1
when |
current_real_date |
date
|
tracks real-world date -- advanced by +1 day when
|
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 |
|
__getattr__(name)
Called if normal attribute lookup fails.
Delegate to all_state_variables
, transition_variables
,
or transition_variable_groups
if name matches a key.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
__init__(state: SubpopState, params: SubpopParams, simulation_settings: SimulationSettings, RNG: np.random.Generator, name: str, metapop_model: MetapopModel = None)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
SubpopState
|
holds current values of |
required |
params
|
SubpopParams
|
data container for the model's epidemiological parameters, such as the "Greek letters" characterizing sojourn times in compartments. |
required |
simulation_settings
|
SimulationSettings
|
data container for the model's simulation settings. |
required |
RNG
|
Generator
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
name
|
str
|
unique identifier of |
required |
metapop_model
|
Optional[MetapopModel]
|
if not |
None
|
Source code in CLT_BaseModel/clt_toolkit/base_components.py
1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 |
|
compute_total_pop_age_risk() -> np.ndarray
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) A x R array, where A is the number of age groups and R is the number of risk groups, corresponding to total population for that age-risk group (summed over all compartments in the subpop model). |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
create_compartments() -> sc.objdict[str, Compartment]
abstractmethod
Create the epidemiological compartments used in the model. Subclasses must override this method to provide model-specific transitions.
Returns:
Type | Description |
---|---|
objdict[str, Compartment]
|
Dictionary mapping compartment names to |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
create_dynamic_vals() -> sc.objdict[str, DynamicVal]
Create dynamic values that change depending on the simulation state. Subclasses can optionally override this method to provide model-specific transitions.
Returns:
Type | Description |
---|---|
objdict[str, DynamicVal]
|
Dictionary mapping names to |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
create_epi_metrics() -> sc.objdict[str, EpiMetric]
Create the epidemiological metrics that track deterministic functions of compartments' current values. Subclasses can optionally override this method to provide model-specific transitions.
See __init__
method -- this method is called after transition_variables
is
assigned via create_transition_variables()
, so it can reference the instance's
transition variables.
Returns:
Type | Description |
---|---|
objdict[str, EpiMetric]
|
Dictionary mapping names to |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
create_schedules() -> sc.objdict[str, Schedule]
Create schedules that are deterministic functions of the real-world simulation date. Subclasses can optionally override this method to provide model-specific transitions.
Returns:
Type | Description |
---|---|
objdict[str, Schedule]
|
Dictionary mapping names to |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
create_transition_variable_groups() -> sc.objdict[str, TransitionVariableGroup]
Create the joint transition variables specifying how transitioning from compartments with multiple outflows is handled. Subclasses can optionally override this method to provide model-specific transitions.
See __init__
method -- this method is called after compartments
is assigned via create_compartments()
and transition_variables
is
assigned via create_transition_variables()
, so it can reference the instance's
compartments and transition variables.
Returns:
Type | Description |
---|---|
objdict[str, TransitionVariableGroup]
|
Dictionary mapping names to |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
create_transition_variables() -> sc.objdict[str, TransitionVariable]
abstractmethod
Create the transition variables specifying how individuals transition between epidemiological compartments in the model. Subclasses must override this method to provide model-specific transitions.
See __init__
method -- this method is called after compartments
is assigned via create_compartments()
, so it can reference the instance's
compartments.
Returns:
Type | Description |
---|---|
objdict[str, TransitionVariable]
|
Dictionary mapping names to |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
find_name_by_compartment(target_compartment: Compartment) -> str
Given Compartment
, returns name of that Compartment
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
target_compartment
|
Compartment
|
Compartment object with a name to look up |
required |
Returns:
Type | Description |
---|---|
str
|
Compartment name, given by the key to look
it up in the |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_start_real_date()
Fetches start_real_date
from simulation_settings
-- converts to
proper datetime.date format if originally given as
string.
Returns:
Name | Type | Description |
---|---|---|
start_real_date |
date
|
real-world date that corresponds to start of simulation. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
increment_simulation_day() -> None
Move day counters to next simulation day, both for integer simulation day and real date.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
modify_random_seed(new_seed_number) -> None
Modifies model's RNG
attribute in-place to new generator
seeded at new_seed_number
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
new_seed_number
|
int
|
used to re-seed model's random number generator. |
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
modify_simulation_settings(updates_dict: dict)
This method lets users safely modify simulation settings;
if this subpop model is associated with a metapop model,
the same updates are applied to all subpop models on the
metapop model. See also modify_simulation_settings
method on
MetapopModel
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
updates_dict
|
dict
|
Dictionary specifying values to update in a
|
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
prepare_daily_state() -> None
At beginning of each day, update current value of interaction terms, schedules, dynamic values -- note that these are only updated once a day, not for every discretized timestep.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
reset_simulation() -> None
Reset simulation in-place. Subsequent method calls of
simulate_until_day
start from day 0, with original
day 0 state.
Returns current_simulation_day
to 0.
Restores state values to initial values.
Clears history on model's state variables.
Resets transition variables' current_val
attribute to 0.
WARNING
DOES NOT RESET THE MODEL'S RANDOM NUMBER GENERATOR TO ITS INITIAL STARTING SEED. RANDOM NUMBER GENERATOR WILL CONTINUE WHERE IT LEFT OFF.
Use method modify_random_seed
to reset model's RNG
to its
initial starting seed.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
sample_transitions() -> None
For each transition variable, sample a random realization
using its current rate. Handle jointly distributed transition
variables first (using TransitionVariableGroup
logic), then
handle marginally distributed transition variables.
Use SubpopModel
's RNG
to generate random variables.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
save_daily_history() -> None
Update history at end of each day, not at end of every
discretization timestep, to be efficient.
Update history of state variables other than Schedule
instances -- schedules do not have history.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
simulate_until_day(simulation_end_day: int) -> None
Advance simulation model time until simulation_end_day
.
Advance time by iterating through simulation days, which are simulated by iterating through discretized timesteps.
Save daily simulation data as history on each Compartment
instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
simulation_end_day
|
positive int
|
stop simulation at |
required |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_compartments() -> None
Update current value of each Compartment
, by
looping through all TransitionVariable
instances
and subtracting/adding their current values
from origin/destination compartments respectively.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_epi_metrics() -> None
Update current value attribute on each associated
EpiMetric
instance.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_transition_rates() -> None
Compute current transition rates for each transition variable, and store this updated value on each variable's current_rate attribute.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
SubpopModelError
SubpopParams
dataclass
Bases: ABC
Data container for pre-specified and fixed epidemiological parameters in model.
Assume that SubpopParams
fields are constant or piecewise
constant throughout the simulation. For variables that
are more complicated and time-dependent, use an EpiMetric
instead.
Source code in CLT_BaseModel/clt_toolkit/base_data_structures.py
SubpopState
dataclass
Bases: ABC
Holds current values of SubpopModel
's simulation state.
Source code in CLT_BaseModel/clt_toolkit/base_data_structures.py
sync_to_current_vals(lookup_dict: dict)
Updates SubpopState
's attributes according to
data in lookup_dict.
Keys of lookup_dict
must match
names of attributes of SubpopState
instance.
Source code in CLT_BaseModel/clt_toolkit/base_data_structures.py
TransitionTypes
Bases: str
, Enum
Defines available options for transition_type
in TransitionVariable
.
Source code in CLT_BaseModel/clt_toolkit/base_data_structures.py
TransitionVariable
Bases: ABC
Abstract base class for transition variables in epidemiological model.
For example, in an S-I-R model, the new number infected
every iteration (the number going from S to I) in an iteration
is modeled as a TransitionVariable
subclass, with a concrete
implementation of the abstract method get_current_rate
.
When an instance is initialized, its get_realization
attribute
is dynamically assigned, just like in the case of
TransitionVariableGroup
instantiation.
Dimensions
A (int): Number of age groups. R (int): Number of risk groups.
Attributes:
Name | Type | Description |
---|---|---|
_transition_type |
str
|
only values defined in |
get_current_rate |
function
|
provides specific implementation for computing current rate as a function of current subpopulation simulation state and epidemiological parameters. |
current_rate |
np.ndarray of shape (A, R
|
holds output from |
current_val |
np.ndarray of shape (A, R
|
holds realization of random variable parameterized by
|
history_vals_list |
list[ndarray]
|
each element is the same size of |
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 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 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 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 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
|
__init__(origin: Compartment, destination: Compartment, transition_type: TransitionTypes, is_jointly_distributed: str = False)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
origin
|
Compartment
|
|
required |
destination
|
Compartment
|
|
required |
transition_type
|
TransitionTypes
|
Specifies probability distribution of transitions between compartments. |
required |
is_jointly_distributed
|
bool
|
Indicates if transition quantity must be jointly computed (i.e. if there are multiple outflows from the origin compartment). |
False
|
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_binom_deterministic_no_round_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
The same as get_binom_deterministic_realization
except no rounding --
so the populations can be non-integer. This is used to test the torch
implementation (because that implementation does not round either).
See get_realization
for parameters. The RNG
parameter is not used
and is only included to maintain a consistent interface.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) (Non-integer) "number of individuals" transitioning compartments in each age-risk group. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_binom_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministically returns mean of binomial distribution
(number of trials x probability), where number of trials
equals population count in the origin Compartment
and
probability is computed from a function of the TransitionVariable
's
current rate -- see the approx_binom_probability_from_rate
function for details.
See get_realization
for parameters. The RNG
parameter is not used
and is only included to maintain a consistent interface.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) Number of individuals transitioning compartments in each age-risk group. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_binom_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Uses RNG
to generate binomial random variable with
number of trials equal to population count in the
origin Compartment
and probability computed from
a function of the TransitionVariable
's current rate
-- see approx_binom_probability_from_rate
function
for details.
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) Element-wise Binomial distributed transitions for each age-risk group, with the probability parameter generated using a conversion from rates to probabilities. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_binom_taylor_approx_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministically returns mean of binomial distribution
(number of trials x probability), where number of trials
equals population count in the origin Compartment
and
probability equals the TransitionVariable
's current_rate
/
num_timesteps
.
See get_realization
for parameters. The RNG
parameter is not used
and is only included to maintain a consistent interface.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) Number of individuals transitioning compartments in each age-risk group. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_binom_taylor_approx_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Uses RNG
to generate binomial random variable with
number of trials equal to population count in the
origin Compartment
and probability equal to
the TransitionVariable
's current_rate
/ num_timesteps
.
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) Element-wise Binomial distributed transitions for each age-risk group, with the probability parameter generated using a Taylor approximation. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_current_rate(state: SubpopState, params: SubpopParams) -> np.ndarray
abstractmethod
Computes and returns current rate of transition variable, based on current state of the simulation and epidemiological parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
SubpopState
|
Holds subpopulation simulation state
(current values of |
required |
params
|
SubpopParams
|
Holds values of epidemiological parameters. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: Holds age-risk transition rate. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_poisson_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministically returns mean of Poisson distribution,
given by (population count in the origin Compartment
x
TransitionVariable
's current_rate
/ num_timesteps
).
See get_realization
for parameters. The RNG
parameter is not used
and is only included to maintain a consistent interface.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) Number of individuals transitioning compartments in each age-risk group. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_poisson_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Generates realizations from a Poisson distribution.
The rate is computed element-wise from each age-risk group as:
(origin compartment population count x current_rate
/ num_timesteps
)
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) Poisson-distributed integers representing number of individuals transitioning in each age-risk group. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Generate a realization of the transition process.
This method is dynamically assigned to the appropriate transition-specific
function (e.g., get_binom_realization
) depending on the transition type.
Provides common interface so realizations can always be obtained via
get_realization
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
Used to generate stochastic transitions in the model and control reproducibility. If deterministic transitions are used, the RNG is passed for a consistent function interface but the RNG is not used. |
required |
num_timesteps
|
int
|
Number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
np.ndarray of shape (A, R)
|
Number of transitions for age-risk groups. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
reset() -> None
Resets history_vals_list
attribute to empty list.
save_history() -> None
Saves current value to history by appending current_val
attribute to history_vals_list
in-place..
Deep copying is CRUCIAL because current_val
is a mutable
np.ndarray -- without deep copying, history_vals_list
would
have the same value for all elements.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_destination_inflow() -> None
Adds current realization of TransitionVariable
to
its destination Compartment
's current_inflow
.
Used to compute total number leaving that
destination Compartment
.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_origin_outflow() -> None
Adds current realization of TransitionVariable
to
its origin Compartment
's current_outflow.
Used to compute total number leaving that
origin Compartment
.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
TransitionVariableGroup
Container for TransitionVariable
objects to handle joint sampling,
when there are multiple outflows from a single compartment.
For example, if all outflows of compartment H
are: R
and D
,
i.e. from the hospital, individuals either recover or die,
a TransitionVariableGroup
that holds both R
and D
handles
the correct correlation structure between R
and D.
When an instance is initialized, its get_joint_realization
attribute
is dynamically assigned to a method according to its transition_type
attribute. This enables all instances to use the same method during
simulation.
Dimensions
M (int): number of outgoing compartments from the origin compartment A (int): number of age groups R (int): number of risk groups
Attributes:
Name | Type | Description |
---|---|---|
origin |
Compartment
|
Specifies origin of |
_transition_type |
str
|
Only values defined in |
transition_variables |
list[`TransitionVariable`]
|
Specifying |
get_joint_realization |
function
|
Assigned at initialization, generates realizations according
to probability distribution given by |
current_vals_list |
list
|
Used to store results from |
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 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 597 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 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 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 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 |
|
__init__(origin: Compartment, transition_type: TransitionTypes, transition_variables: list[TransitionVariable])
Parameters:
Name | Type | Description | Default |
---|---|---|---|
transition_type
|
TransitionTypes
|
Specifies probability distribution of transitions between compartments. |
required |
See class docstring for other parameters.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_current_rates_array() -> np.ndarray
Returns an array of current rates of transition variables in
transition_variables
-- ith element in array
corresponds to current rate of ith transition variable.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (M, A, R)) array of positive floats corresponding to current rate element-wise for an outgoing compartment and age-risk group |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_joint_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
This function is dynamically assigned based on the TransitionVariableGroup
's
transition_type
. It is set to the appropriate distribution-specific method.
See get_realization
for parameters.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_multinom_deterministic_no_round_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
The same as get_multinom_deterministic_realization
except no rounding --
so the populations can be non-integer. This is used to test the torch
implementation (because that implementation does not round either).
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (M + 1, A, R)) contains positive floats with transition realizations for individuals going to compartment m in age-risk group (a, r) -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (not transitioning to any outgoing epi compartment). |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_multinom_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministic counterpart to get_multinom_realization
--
uses mean (n x p, i.e. total counts x probability array) as realization
rather than randomly sampling.
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (M + 1, A, R)) contains positive integers with transition realizations for individuals going to compartment m in age-risk group (a, r) -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (not transitioning to any outgoing epi compartment). |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_multinom_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Returns an array of transition realizations (number transitioning to outgoing compartments) sampled from multinomial distribution.
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (M + 1, A, R)) contains positive floats with transition realizations for individuals going to compartment m in age-risk group (a, r) -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (not transitioning to any outgoing epi compartment). |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_multinom_taylor_approx_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministic counterpart to get_multinom_taylor_approx_realization
--
uses mean (n x p, i.e. total counts x probability array) as realization
rather than randomly sampling.
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (M + 1, A, R)) contains positive floats with transition realizations for individuals going to compartment m in age-risk group (a, r) -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (not transitioning to any outgoing epi compartment). |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_multinom_taylor_approx_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Returns an array of transition realizations (number transitioning to outgoing compartments) sampled from multinomial distribution using Taylor Series approximation for probability parameter.
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (M + 1, A, R)) contains positive integers with transition realizations for individuals going to compartment m in age-risk group (a, r) -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (not transitioning to any outgoing epi compartment). |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_poisson_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministic counterpart to get_poisson_realization
--
uses mean (rate array) as realization rather than randomly sampling.
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) contains positive integers with transition realizations for individuals going to compartment m in age-risk group (a, r) -- |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_poisson_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Returns an array of transition realizations (number transitioning to outgoing compartments) sampled from Poisson distribution.
See get_realization
for parameters.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (M, A, R)) contains positive integers with transition realizations for individuals going to compartment m in age-risk group (a, r) |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_probabilities_array(num_timesteps: int) -> list
Returns an array of probabilities used for joint binomial
(multinomial) transitions (get_multinom_realization
method).
Returns:
Type | Description |
---|---|
list
|
(np.ndarray of shape (M+1, A, R) Contains positive floats <= 1, corresponding to probability of transitioning to a compartment for that outgoing compartment and age-risk group -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (we can think of as transitioning to the same compartment). |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
get_total_rate() -> np.ndarray
Return the age-risk-specific total transition rate, which is the sum of the current rate of each transition variable in this transition variable group.
Used to properly scale multinomial probabilities vector so that elements sum to 1.
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) Array with values corresponding to sum of current rates of transition variables in transition variable group, where elements correspond to age-risk groups. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
update_transition_variable_realizations() -> None
Updates current_val attribute on all TransitionVariable
instances contained in this TransitionVariableGroup
.
Source code in CLT_BaseModel/clt_toolkit/base_components.py
UniformSamplingSpec
dataclass
Holds Uniform distribution info to randomly sample a
subpop model's SubpopParams
attribute.
Attributes:
Name | Type | Description |
---|---|---|
lower_bound |
[ndarray | float]
|
Lower bound(s) of the uniform distribution. Can be a scalar,
shape (A,) array, or shape (A, R) array depending on |
upper_bound |
[ndarray | float]
|
Upper bound(s) of the uniform distribution. Must have the same shape
as |
param_shape |
ParamShapes
|
Describes how the parameter varies across subpopulations (scalar, by age, or by age and risk). |
num_decimals |
positive int
|
Optional number of decimals to keep after rounding -- default is 2. |
Source code in CLT_BaseModel/clt_toolkit/sampling.py
aggregate_daily_tvar_history(metapop_model: MetapopModel, transition_var_name: str) -> np.ndarray
Sum the history values of a given transition variable across all subpopulations and across timesteps per day, so that we have the total number that transitioned compartments in a day.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metapop_model
|
MetapopModel
|
The metapopulation model containing subpopulations. |
required |
transition_var_name
|
str
|
Name of the transition variable to sum. |
required |
Returns:
Name | Type | Description |
---|---|---|
total |
ndarray
|
Array of shape (num_days, A, R) containing the sum across all subpopulations, where A = number of age groups, and R = number of risk groups. Each element contains the total number of individuals who transitioned that day for the given age and risk group. |
Source code in CLT_BaseModel/clt_toolkit/sampling.py
approx_binom_probability_from_rate(rate: np.ndarray, interval_length: int) -> np.ndarray
Converts a rate (events per time) to the probability of any event
occurring in the next time interval of length interval_length
,
assuming the number of events occurring in time interval
follows a Poisson distribution with given rate parameter.
The probability of 0 events in interval_length
is
e^(-rate
* interval_length
), so the probability of any event
in interval_length
is 1 - e^(-rate
* interval_length
).
Rate must be A x R np.ndarray
, where A is the number of
age groups and R is the number of risk groups. Rate is transformed to
A x R np.ndarray
corresponding to probabilities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rate
|
np.ndarray of shape (A, R
|
Rate parameters in a Poisson distribution per age-risk group. |
required |
interval_length
|
positive int
|
Length of time interval in simulation days. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray of shape (A, R): Array of positive scalars corresponding to probability that any individual in an age-risk group transitions compartments. |
Source code in CLT_BaseModel/clt_toolkit/base_components.py
check_is_subset_list(listA: list, listB: list) -> bool
Parameters:
Name | Type | Description | Default |
---|---|---|---|
listA
|
list
|
list-like of elements to check if subset of listB. |
required |
listB
|
list
|
list-like of elements. |
required |
Returns:
Type | Description |
---|---|
bool
|
True if listA is a subset of listB, and False otherwise. |
Source code in CLT_BaseModel/clt_toolkit/experiments.py
convert_dict_vals_lists_to_arrays(d: dict) -> dict
Converts dictionary of lists to dictionary of arrays
to support numpy
operations.
Source code in CLT_BaseModel/clt_toolkit/input_parsers.py
daily_sum_over_timesteps(x: np.ndarray, num_timesteps: int) -> np.ndarray
For example, used for transition variable history, which is saved for every timestep, but we generally would like converted to daily totals.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
np.ndarray of shape (N, A, R
|
Array to aggregate -- N is the number of timesteps, A is the number of age groups, R is the number of risk groups. |
required |
num_timesteps
|
int
|
Number of timesteps per day. Must divide
N (length of |
required |
Returns:
Type | Description |
---|---|
np.ndarray of shape (N/n, A, R
|
Array of daily totals, where each block of |
Source code in CLT_BaseModel/clt_toolkit/utils.py
format_current_val_for_sql(subpop_model: SubpopModel, state_var_name: str, rep: int) -> list
Processes current_val of given subpop_model's StateVariable
specified by state_var_name
. Current_val is an A x R
numpy array (for age-risk) -- this function "unpacks" it into an
(A x R, 1) numpy array (a column vector). Converts metadata
(subpop_name, state_var_name, rep
, and current_simulation_day)
into list of A x R rows, where each row has 7 elements, for
consistent row formatting for batch SQL insertion.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
subpop_model
|
SubpopModel
|
SubpopModel to record. |
required |
state_var_name
|
str
|
StateVariable name to record. |
required |
rep
|
int
|
replication counter to record. |
required |
Returns:
Name | Type | Description |
---|---|---|
data |
list
|
list of A x R rows, where each row is a list of 7 elements corresponding to subpop_name, state_var_name, age_group, risk_group, rep, current_simulation_day, and the scalar element of current_val corresponding to that age-risk group. |
Source code in CLT_BaseModel/clt_toolkit/experiments.py
get_sql_table_as_df(conn: sqlite3.Connection, sql_query: str, sql_query_params: tuple[str] = None, chunk_size: int = int(10000.0)) -> pd.DataFrame
Returns a pandas DataFrame containing data from specified SQL table,
retrieved using the provided database connection. Reads in SQL rows
in batches of size chunk_size
to avoid memory issues for very large
tables.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
conn
|
Connection
|
connection to SQL database. |
required |
sql_query
|
str
|
SQL query/statement to execute on database. |
required |
sql_query_params
|
tuple[str]
|
tuple of strings to pass as parameters to SQL query -- used to avoid SQL injections. |
None
|
chunk_size
|
positive int
|
number of rows to read in at a time. |
int(10000.0)
|
Returns:
Type | Description |
---|---|
DataFrame
|
DataFrame containing data from specified SQL table, |
DataFrame
|
or empty DataFrame if table does not exist. |
Source code in CLT_BaseModel/clt_toolkit/experiments.py
load_json_augment_dict(json_filepath: str, d: dict) -> dict
Augments pre-existing dictionary with information
from JSON
file -- if keys already exist, the previous values
are overriden, otherwise the new key-value pairs are added.
Lists are automatically converted to numpy arrays for
computational compatibility, since JSON
does not natively
support np.ndarray
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_filepath
|
str
|
Full |
required |
d
|
dict
|
Dictionary to be augmented with new |
required |
Returns:
Type | Description |
---|---|
dict
|
Dictionary loaded with |
Source code in CLT_BaseModel/clt_toolkit/input_parsers.py
load_json_new_dict(json_filepath: str) -> dict
Loads specified JSON
file into new dictionary.
Lists are automatically converted to numpy arrays for
computational compatibility, since JSON
does not natively
support np.ndarray
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_filepath
|
str
|
Full |
required |
Returns:
Type | Description |
---|---|
dict
|
Dictionary loaded with |
Source code in CLT_BaseModel/clt_toolkit/input_parsers.py
make_dataclass_from_dict(dataclass_ref: Type[DataClassProtocol], d: dict) -> DataClassProtocol
Create instance of class dataclass_ref, based on information in dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataclass_ref
|
Type[DataClassProtocol]
|
(class, not instance) from which to create instance -- must have dataclass decorator. |
required |
d
|
dict
|
all keys and values respectively must match name and datatype of dataclass_ref instance attributes. |
required |
Returns:
Name | Type | Description |
---|---|---|
DataClassProtocol |
DataClassProtocol
|
instance of dataclass_ref with attributes dynamically assigned by json_filepath file contents. |
Source code in CLT_BaseModel/clt_toolkit/input_parsers.py
make_dataclass_from_json(json_filepath: str, dataclass_ref: Type[DataClassProtocol]) -> DataClassProtocol
Create instance of class dataclass_ref, based on information in json_filepath.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
json_filepath
|
str
|
path to json file (path includes actual filename with suffix ".json") -- all json fields must match name and datatype of dataclass_ref instance attributes. |
required |
dataclass_ref
|
Type[DataClassProtocol]
|
(class, not instance) from which to create instance -- must have dataclass decorator. |
required |
Returns:
Name | Type | Description |
---|---|---|
DataClassProtocol |
DataClassProtocol
|
instance of dataclass_ref with attributes dynamically assigned by json_filepath file contents. |
Source code in CLT_BaseModel/clt_toolkit/input_parsers.py
plot_metapop_basic_compartment_history(metapop_model: MetapopModel, axes: matplotlib.axes.Axes = None)
Plots the compartment data for a metapopulation model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metapop_model
|
MetapopModel
|
Metapopulation model containing compartments. |
required |
axes
|
Axes
|
Matplotlib axes to plot on. |
None
|
Source code in CLT_BaseModel/clt_toolkit/plotting.py
plot_metapop_decorator(plot_func)
Decorator to handle common metapopulation plotting tasks.
Source code in CLT_BaseModel/clt_toolkit/plotting.py
plot_metapop_epi_metrics(metapop_model: MetapopModel, axes: matplotlib.axes.Axes)
Plots the EpiMetric data for a metapopulation model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metapop_model
|
MetapopModel
|
Metapopulation model containing compartments. |
required |
axes
|
Axes
|
Matplotlib axes to plot on. |
required |
Source code in CLT_BaseModel/clt_toolkit/plotting.py
plot_metapop_total_infected_deaths(metapop_model: MetapopModel, axes: matplotlib.axes.Axes)
Plots the total infected (IP+IS+IA) and deaths data for a metapopulation model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metapop_model
|
MetapopModel
|
Metapopulation model containing compartments. |
required |
axes
|
Axes
|
Matplotlib axes to plot on. |
required |
Source code in CLT_BaseModel/clt_toolkit/plotting.py
plot_subpop_basic_compartment_history(subpop_model: SubpopModel, ax: matplotlib.axes.Axes = None)
Plots data for a single subpopulation model on the given axis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
subpop_model
|
SubpopModel
|
Subpopulation model containing compartments. |
required |
ax
|
Axes
|
Matplotlib axis to plot on. |
None
|
Source code in CLT_BaseModel/clt_toolkit/plotting.py
plot_subpop_decorator(plot_func)
Decorator to handle common subpopulation plotting tasks.
Source code in CLT_BaseModel/clt_toolkit/plotting.py
plot_subpop_epi_metrics(subpop_model: SubpopModel, ax: matplotlib.axes.Axes = None)
Plots EpiMetric history for a single subpopulation model on the given axis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
subpop_model
|
SubpopModel
|
Subpopulation model containing compartments. |
required |
ax
|
Axes
|
Matplotlib axis to plot on. |
None
|
Source code in CLT_BaseModel/clt_toolkit/plotting.py
plot_subpop_total_infected_deaths(subpop_model: SubpopModel, ax: matplotlib.axes.Axes = None)
Plots data for a single subpopulation model on the given axis.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
subpop_model
|
SubpopModel
|
Subpopulation model containing compartments. |
required |
ax
|
Axes
|
Matplotlib axis to plot on. |
None
|
Source code in CLT_BaseModel/clt_toolkit/plotting.py
sample_uniform_matrix(lb: [np.ndarray | float], ub: [np.ndarray | float], RNG: np.random.Generator, A: int, R: int, param_shape: str) -> [np.ndarray | float]
Sample a matrix X of shape (A,R) such that X[a,r] ~ (independent) Uniform(low[a,r], high[a,r]). We assume each element is independent, so we do not assume any correlation structure:
Parameters:
Name | Type | Description | Default |
---|---|---|---|
lb
|
np.ndarray of shape (A,) or (A, R) or float
|
Array or scalar of lower bounds |
required |
ub
|
np.ndarray of shape (A,) or (A, R) or float
|
Array or scalar of upper bounds |
required |
RNG
|
Generator
|
Used to generate Uniform random variables. |
required |
Returns:
Name | Type | Description |
---|---|---|
X |
np.ndarray of shape (A,) or (A, R) or float
|
Random matrix or scalar realization where each
element is independently sampled from a Uniform distribution
with parameters given element-wise by |
Source code in CLT_BaseModel/clt_toolkit/sampling.py
sample_uniform_metapop_params(metapop_model: MetapopModel, sampling_RNG: np.random.Generator, sampling_info: dict[str, dict[str, UniformSamplingSpec]]) -> dict[str, dict[str, np.ndarray]]
Draw parameter realizations from uniform distributions for a metapopulation model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metapop_model
|
MetapopModel
|
The metapop model whose subpopulation parameters are sampled. |
required |
sampling_RNG
|
Generator
|
Random number generator for Uniform sampling. |
required |
sampling_info
|
dict[str, dict[str, UniformSamplingSpec]]
|
Nested dictionary with sampling information.
- Outer keys:
Either "all_subpop" (apply to all subpopulations)
or the name of a subpopulation, matching the |
required |
Returns:
Name | Type | Description |
---|---|---|
pending_param_updates |
dict[str, dict[str, ndarray | float]]
|
Nested dictionary of sampled parameter values.
- Outer keys: subpop names -- similar to description for
outer keys of |
Source code in CLT_BaseModel/clt_toolkit/sampling.py
120 121 122 123 124 125 126 127 128 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 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
|
serialize_dataclass(dc) -> dict
Convert a dataclass or dict to a JSON-serializable dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dc
|
obj | dict
|
The object to serialize.
- If a dataclass, it will be converted using |
required |
Returns:
Type | Description |
---|---|
dict
|
dict Dictionary representation of the object, fully JSON-serializable. |
Source code in CLT_BaseModel/clt_toolkit/utils.py
serialize_value(value)
Convert a value into a JSON-serializable format.
value (any):
The value to serialize. Supported types:
- np.ndarray
is converted to list
- Scalars and None
remain unchanged
- dict
, list
, or tuple
gets recursively serialized
(i.e. in case it's a nested object, etc...)
- Any other type is converted to str
as a fallback
Returns:
Type | Description |
---|---|
A version of the input that can be safely serialized to JSON. |
Source code in CLT_BaseModel/clt_toolkit/utils.py
to_AR_array(x, A, R) -> np.ndarray
Convert scalar, 1D (A,) or 2D (A,R) to a (A,R) array.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
float | ndarray
|
Float or array to convert to (A, R) array. |
required |
A
|
int
|
number of age groups. |
required |
R
|
int
|
number of risk groups. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
(np.ndarray of shape (A, R)) |
Source code in CLT_BaseModel/clt_toolkit/utils.py
updated_dataclass(original: dataclass, updates: dict) -> object
Return a new dataclass based on original
, with fields in updates
replaced/added.
updated_dict(original: dict, updates: dict) -> dict
Return a new dictionary based on original
, with keys in updates
replaced/added.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
original
|
dict
|
Original dictionary. |
required |
updates
|
dict
|
Dictionary of updates to apply. |
required |
Returns:
Type | Description |
---|---|
dict
|
New dictionary with updates applied. |