CLT Base Package Code API Reference
Docstrings and references for clt_base
package.
Compartment
Bases: StateVariable
Class for epidemiological compartments (e.g. Susceptible, Exposed, Infected, etc...).
Inherits attributes from StateVariable
.
Attributes:
Name | Type | Description |
---|---|---|
current_inflow |
ndarray
|
same size as |
current_outflow |
ndarray
|
same size of |
Source code in CLT_BaseModel/clt_base/base_components.py
reset_inflow() -> None
Resets self.current_inflow
attribute to np.ndarray of zeros.
reset_outflow() -> None
Resets self.current_outflow
attribute to np.ndarray of zeros.
update_current_val() -> None
Updates self.current_val
attribute in-place by adding
self.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_base/base_components.py
Config
Stores simulation configuration values.
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 |
date
|
actual date that aligns with the beginning of the simulation. |
save_daily_history |
bool
|
set to |
Source code in CLT_BaseModel/clt_base/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 people.
Inherits attributes from StateVariable
.
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_base/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_base/base_components.py
update_current_val(state: SubpopState, params: SubpopParams) -> None
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_base/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 self.get_change_in_current_val
.
Inherits attributes from StateVariable
.
Attributes:
Name | Type | Description |
---|---|---|
current_val |
ndarray
|
same size as init_val, holds current value of |
change_in_current_val |
(np.ndarray):
initialized to None, but during simulation holds change in
current value of |
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_base/base_components.py
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 |
|
__init__(init_val)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
init_val
|
ndarray
|
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_base/base_components.py
get_change_in_current_val(state: SubpopState, params: SubpopParams, num_timesteps: int) -> np.ndarray
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: 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_base/base_components.py
update_current_val() -> None
Adds self.change_in_current_val
attribute to
self.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.
NOTE
If an input is an |A| x |R| array (for age-risk),
the current functionality does not support sampling individual
age-risk elements separately. Instead, a single scalar value
is sampled at a time for the entire input.
See self.sample_random_inputs
method for more details.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
experiment_subpop_models
|
tuple
|
tuple of |
required |
inputs_realizations
|
dict
|
dictionary of dictionaries that stores user-specified deterministic
sequences for inputs or realizations of random input sampling --
keys are |
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_base/experiments.py
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 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 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 |
|
__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_base/experiments.py
apply_inputs_to_model(rep_counter: int)
Changes inputs (parameters or initial values) for a given
replication according to self.inputs_realizations
attribute.
Specifically, for each subpopulation, this function retrieves
the corresponding values from self.inputs_realizations
and applies them to either:
(a) the subpopulation's StateVariable
, if the input corresponds to a state variable,
or (b) the subpopulation's params
attribute, if the input corresponds to a model
parameter. If the parameter or state variable is multidimensional
(e.g., varies across age or risk groups), it is assigned a numpy array of
the appropriate shape with the replicated input value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rep_counter
|
int
|
Replication ID, used to retrieve the correct realizations of inputs for the current run. |
required |
Source code in CLT_BaseModel/clt_base/experiments.py
create_inputs_realizations_sql_tables()
Create tables in SQL database given by self.database_filename
to store realizations of inputs that change across
replications. There is one table per associated subpopulation.
Source code in CLT_BaseModel/clt_base/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_base/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_base/experiments.py
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 |
|
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_base/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_base/experiments.py
run_random_inputs(num_reps: int, simulation_end_day: int, random_inputs_RNG: np.random.Generator, random_inputs_spec: dict, days_between_save_history: int = 1, results_filename: str = None, inputs_filename_suffix: str = None)
Runs the associated SubpopModel
or MetapopModel
for a
given number of independent replications until simulation_end_day
,
where certain parameter values or initial values are
independently randomly sampled for each replication.
Random sampling details (which inputs to sample and what
Uniform distribution lower and upper bounds to use for each input)
are specified in random_inputs_spec
, and random sampling of inputs
uses random_inputs_RNG
. User can specify how often to save the
history and a CSV file in which to store this history.
User can also specify a filename suffix to name CSV files
in which to store realizations of inputs.
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 |
random_inputs_RNG
|
Generator
|
random number generator used to sample random inputs -- for reproducibility, it is recommended to use a distinct RNG for sampling random inputs different from the RNG for simulating the experiment/model. |
required |
random_inputs_spec
|
dict
|
random inputs' specification -- stores details
for random input sampling -- keys are strings
corresponding to input names (they must match
names in each |
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
|
inputs_filename_suffix
|
str
|
if specified, must be a valid filename with suffix ".csv" --
one inputs CSV is generated for each |
None
|
Source code in CLT_BaseModel/clt_base/experiments.py
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 |
|
run_sequences_of_inputs(num_reps: int, simulation_end_day: int, sequences_of_inputs: dict, days_between_save_history: int = 1, results_filename: str = None, inputs_filename_suffix: str = None)
Runs the associated SubpopModel
or MetapopModel
for a
given number of independent replications until simulation_end_day
,
where certain parameter values or initial values deterministically
change between replications, according to sequences_of_inputs
.
User can specify how often to save the history and a CSV file
in which to store this history. User can also specify a filename
suffix to name CSV files in which to store sequences of inputs.
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 |
required |
sequences_of_inputs
|
dict
|
dictionary of dictionaries that stores user-specified deterministic
sequences for inputs -- must follow specific structure.
Keys are |
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
|
inputs_filename_suffix
|
str
|
if specified, must be a valid filename with suffix ".csv" --
one inputs CSV is generated for each |
None
|
Source code in CLT_BaseModel/clt_base/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_base/experiments.py
sample_random_inputs(total_reps: int, RNG: np.random.Generator, spec: dict)
Randomly and independently samples inputs specified by keys of
spec
according to uniform distribution with lower
and upper bounds specified by values of spec
.
Stores random realizations in self.inputs_realizations
attribute.
Uses RNG
to sample inputs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
total_reps
|
positive int
|
number of independent simulation replications to run in an experiment -- corresponds to number of Uniform random variables to draw for each state variable. |
required |
RNG
|
Generator
|
random number generator used to sample random inputs -- for reproducibility, it is recommended to use a distinct RNG for sampling random inputs different from the RNG for simulating the experiment/model. |
required |
spec
|
dict
|
random inputs' specification -- stores details
for random input sampling -- keys are strings
corresponding to input names (they must match
names in each |
required |
NOTE
If an input is an |A| x |R| array (for age-risk), the current functionality does not support sampling individual age-risk elements separately. Instead, a single scalar value is sampled at a time for the entire input. Consequently, if an |A| x |R| input is chosen to be randomly sampled, all its elements will have the same sampled value.
If a user wants to sample some age-risk elements separately,
they should create new inputs for these elements. "Inputs"
refers to both parameters (in SubpopParams
) and initial values
of Compartment
and EpiMetric
instances. For example, if the model
has a parameter H_to_R_rate
that is 2x1 (2 age groups, 1 risk group)
and the user wants to sample each element separately, they should create
two parameters: H_to_R_rate_age_group_1
and H_to_R_rate_age_group_2.
These should be added to the relevant SubpopParams
instance and
input dictionary/file used to create the SubpopParams
instance.
The user can then specify both parameters to be randomly sampled
and specify the lower and upper bounds accordingly.
TODO: allow sampling individual age-risk elements separately without creating new parameters for each element.
(Developer note: the difficulty is not with randomly sampling arrays, but rather storing arrays in SQL -- SQL tables only support atomic values.)
Source code in CLT_BaseModel/clt_base/experiments.py
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 |
|
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_base/experiments.py
write_inputs_csvs(suffix: str)
For each subpopulation, writes a CSV (with a filename based on provided suffix) containing values of inputs across replications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
suffix
|
str
|
Common suffix used to generate CSV filenames. |
required |
Source code in CLT_BaseModel/clt_base/experiments.py
ExperimentError
InterSubpopRepo
Bases: ABC
Holds collection of SubpopState
instances, with
actions to query and interact with them.
Attributes:
Name | Type | Description |
---|---|---|
subpop_models |
objdict
|
keys are unique names of subpopulation models,
values are their respective |
Source code in CLT_BaseModel/clt_base/base_components.py
compute_shared_quantities()
Subclasses must provide concrete implementation. This method
is called by the MetapopModel
instance at the beginning of
each simulation day, before each SubpopModel
simulates that day.
Note: often, InteractionTerm
s across SubpopModel
s share similar
terms in their computation. This self.compute_shared_quantities
method computes such similar terms up front to reduce redundant
computation.
Source code in CLT_BaseModel/clt_base/base_components.py
update_all_interaction_terms()
Updates SubpopState
of each SubpopModel
in
self.subpop_models
to reflect current values of each
InteractionTerm
on that SubpopModel
.
Source code in CLT_BaseModel/clt_base/base_components.py
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.
In contrast to other state variables, each InteractionTerm
takes in an InterSubpopRepo
instance to update its self.current_val
.
Other state variables that are "local" and depend on
exactly one subpopulation only need to take in one SubpopState
and one SubpopParams
instance to update its current value.
Inherits attributes from StateVariable
.
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_base/base_components.py
update_current_val(inter_subpop_repo: InterSubpopRepo, subpop_params: SubpopParams) -> None
Subclasses must provide a concrete implementation of
updating self.current_val
in-place.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
inter_subpop_repo
|
InterSubpopRepo
|
manages collection of subpop models with methods for querying information. |
required |
subpop_params
|
SubpopParams
|
holds values of subpopulation's epidemiological parameters. |
required |
Source code in CLT_BaseModel/clt_base/base_components.py
JointTransitionTypes
Bases: str
, Enum
Source code in CLT_BaseModel/clt_base/base_components.py
MetapopModel
Bases: ABC
Abstract base class that bundles SubpopModel
s linked using
a travel model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
inter_subpop_repo
|
InterSubpopRepo
|
Accesses and manages |
required |
See __init__
docstring for other attributes.
Source code in CLT_BaseModel/clt_base/base_components.py
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 1308 1309 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 |
|
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 |
__init__(inter_subpop_repo, name: str = '')
Parameters:
Name | Type | Description | Default |
---|---|---|---|
inter_subpop_repo
|
InterSubpopRepo
|
manages collection of subpopulation models with methods for querying information. |
required |
name
|
str
|
unique identifier for |
''
|
Source code in CLT_BaseModel/clt_base/base_components.py
display()
Prints structure (compartments and linkages), transition variables,
epi metrics, schedules, and dynamic values for each SubpopModel
instance in self.subpop_models
.
Source code in CLT_BaseModel/clt_base/base_components.py
extract_states_dict_from_models_dict(models_dict: sc.objdict) -> sc.objdict
(Currently unused utility function.)
Takes objdict of subpop models, where keys are subpop model names and
values are the subpop model instances, and returns objdict of
subpop model states, where keys are subpop model names and
values are the subpop model SubpopState
instances.
Source code in CLT_BaseModel/clt_base/base_components.py
reset_simulation()
Resets MetapopModel
by resetting and clearing
history on all SubpopModel
instances in
self.subpop_models
.
Source code in CLT_BaseModel/clt_base/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
'sInterSubpopRepo
computes any shared terms used across subpopulations (to reduce computational overhead), and then updates eachSubpopModel
's associatedInteractionTerm
instances. - Third, each
SubpopModel
simulates discretized timesteps (samplingTransitionVariable
s, updatingEpiMetric
s, and updatingCompartment
s).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
simulation_end_day
|
positive int
|
stop simulation at |
required |
Source code in CLT_BaseModel/clt_base/base_components.py
MetapopModelError
Schedule
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_base/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_base/base_components.py
update_current_val(params: SubpopParams, current_date: datetime.date) -> None
Subpop classes must provide a concrete implementation of
updating self.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_base/base_components.py
StateVariable
Parent class of InteractionTerm
, Compartment
, EpiMetric
,
DynamicVal
, and Schedule
classes. All subclasses have the
common attributes self.init_val
and self.current_val
.
Attributes:
Name | Type | Description |
---|---|---|
init_val |
ndarray
|
holds initial value of |
current_val |
ndarray
|
same size as |
history_vals_list |
list[ndarray]
|
each element is the same size of |
Source code in CLT_BaseModel/clt_base/base_components.py
reset() -> None
Resets self.current_val
to self.init_val
and resets self.history_vals_list
attribute to empty list.
Source code in CLT_BaseModel/clt_base/base_components.py
save_history() -> None
Saves current value to history by appending self.current_val
attribute
to self.history_vals_list
in place.
Deep copying is CRUCIAL because self.current_val
is a mutable
np.ndarray
-- without deep copying, self.history_vals_list
would
have the same value for all elements.
Source code in CLT_BaseModel/clt_base/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 configuration
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 self.compartments
, self.epi_metrics
, self.dynamic_vals
,
self.transition_variables
, and self.transition_variable_groups
.
The "flow" and "physics" information are stored on the objects.
Attributes:
Name | Type | Description |
---|---|---|
interaction_terms |
objdict
|
objdict of all the subpop model's |
compartments |
objdict
|
objdict of all the subpop model's |
transition_variables |
objdict
|
objdict of all the subpop model's |
transition_variable_groups |
objdict
|
objdict of all the subpop model's |
epi_metrics |
objdict
|
objdict of all the subpop model's |
dynamic_vals |
objdict
|
objdict of all the subpop model's |
schedules |
objdict
|
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_base/base_components.py
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 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 |
|
__init__(state: SubpopState, params: SubpopParams, config: Config, 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 |
config
|
Config
|
data container for the model's simulation configuration values. |
required |
RNG
|
Generator
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
name
|
str
|
unique identifier of |
''
|
metapop_model
|
Optional[MetapopModel]
|
if not |
None
|
Source code in CLT_BaseModel/clt_base/base_components.py
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 |
|
compute_total_pop_age_risk() -> np.ndarray
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: |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_base/base_components.py
display() -> None
Prints structure of model (compartments and linkages), transition variables, epi metrics, schedules, and dynamic values.
Source code in CLT_BaseModel/clt_base/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:
Name | Type | Description |
---|---|---|
str |
str
|
Compartment name, given by the key to look
it up in the |
Source code in CLT_BaseModel/clt_base/base_components.py
get_start_real_date()
Fetches start_real_date
from self.config
-- 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_base/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_base/base_components.py
modify_random_seed(new_seed_number) -> None
Modifies model's self.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_base/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_base/base_components.py
reset() -> None
Resets self.history_vals_list
attribute of each InteractionTerm
,
Compartment
, EpiMetric
, and DynamicVal
to an empty list.
Clears current rates and current values of
TransitionVariable
and TransitionVariableGroup
instances.
Source code in CLT_BaseModel/clt_base/base_components.py
reset_simulation() -> None
Reset simulation in-place. Subsequent method calls of
self.simulate_until_day
start from day 0, with original
day 0 state.
Returns self.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 self.modify_random_seed
to reset model's RNG
to its
initial starting seed.
Source code in CLT_BaseModel/clt_base/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_base/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
TransitionVariableGroup
instances also do not
have history, so do not include.
Source code in CLT_BaseModel/clt_base/base_components.py
simulate_timesteps(num_timesteps: int) -> None
Subroutine for self.simulate_until_day
.
Iterates through discretized timesteps to simulate next
simulation day. Granularity of discretization is given by
attribute self.config.timesteps_per_day
.
Properly scales transition variable realizations and changes in dynamic vals by specified timesteps per day.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Source code in CLT_BaseModel/clt_base/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_base/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_base/base_components.py
update_epi_metrics() -> None
Update current value attribute on each associated
EpiMetric
instance.
Source code in CLT_BaseModel/clt_base/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_base/base_components.py
SubpopModelError
SubpopParams
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_base/base_components.py
SubpopState
Bases: ABC
Holds current values of SubpopModel
's simulation state.
Source code in CLT_BaseModel/clt_base/base_components.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_base/base_components.py
TransitionTypes
Bases: str
, Enum
Source code in CLT_BaseModel/clt_base/base_components.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 self.get_current_rate
.
When an instance is initialized, its self.get_realization
attribute
is dynamically assigned, just like in the case of
TransitionVariableGroup
instantiation.
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 |
ndarray
|
holds output from |
current_val |
ndarray
|
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_base/base_components.py
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 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 |
|
__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
|
str
|
only values defined in |
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_base/base_components.py
get_binomial_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_binomial_probability_from_rate
function for details.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
NOT USED -- only included so that get_realization has the same function arguments regardless of transition type. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: 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_base/base_components.py
get_binomial_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 the approx_binomial_probability_from_rate
function for details.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: 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_base/base_components.py
get_binomial_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
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
NOT USED -- only included so that get_realization has the same function arguments regardless of transition type. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: 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_base/base_components.py
get_binomial_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
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: size |A| x |R|, where |A| is the number of age groups and L is number of risk groups. |
Source code in CLT_BaseModel/clt_base/base_components.py
get_current_rate(state: SubpopState, params: SubpopParams) -> np.ndarray
Computes and returns current rate of transition variable, based on current state of the simulation and epidemiological parameters. Output should be a numpy array of size |A| x |R|, where |A| is the 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 |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: holds age-risk transition rate, must be same shape as origin.init_val, i.e. be 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_base/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
).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
NOT USED -- only included so that get_realization has the same function arguments regardless of transition type. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: 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_base/base_components.py
get_poisson_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Uses RNG
to generate Poisson random variable with
rate equal to (population count in the
origin Compartment
x the TransitionVariable
's
current_rate
/ num_timesteps
)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: 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_base/base_components.py
get_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
This method gets assigned to one of the following methods
based on the TransitionVariable
transition type:
self.get_binomial_realization
, self.get_binomial_taylor_approx_realization
,
self.get_poisson_realization
, self.get_binomial_deterministic_realization
,
self.get_binomial_taylor_approx_deterministic_realization
,
self.get_poisson_deterministic_realization
. This is done so that
the same method self.get_realization
can be called regardless of
transition type.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Source code in CLT_BaseModel/clt_base/base_components.py
reset() -> None
save_history() -> None
Saves current value to history by appending self.current_val
attribute to self.history_vals_list
in place.
Deep copying is CRUCIAL because self.current_val
is a mutable
np.ndarray -- without deep copying, self.history_vals_list
would
have the same value for all elements.
Source code in CLT_BaseModel/clt_base/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_base/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_base/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, people 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 self.get_joint_realization
attribute
is dynamically assigned to a method according to its self.transition_type
attribute. This enables all instances to use the same method during
simulation.
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_base/base_components.py
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 879 880 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 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 |
|
__init__(origin: Compartment, transition_type: TransitionTypes, transition_variables: list[TransitionVariable])
Parameters:
Name | Type | Description | Default |
---|---|---|---|
transition_type
|
str
|
only values defined in |
required |
See class docstring for other parameters.
Source code in CLT_BaseModel/clt_base/base_components.py
get_current_rates_array() -> np.ndarray
Returns an array of current rates of transition variables in self.transition_variables -- ith element in array corresponds to current rate of ith transition variable.
Returns:
Type | Description |
---|---|
ndarray
|
array of positive floats, size equal to (length of outgoing |
ndarray
|
transition variables list x number of age groups x number of risk groups). |
Source code in CLT_BaseModel/clt_base/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
-- this function is set to
one of the following methods: self.get_multinomial_realization
,
self.get_multinomial_taylor_approx_realization
,
self.get_poisson_realization
, self.get_multinomial_deterministic_realization
,
self.get_multinomial_taylor_approx_deterministic_realization
,
self.get_poisson_deterministic_realization
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Source code in CLT_BaseModel/clt_base/base_components.py
get_multinomial_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministic counterpart to self.get_multinomial_realization
--
uses mean (n x p, i.e. total counts x probability array) as realization
rather than randomly sampling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
NOT USED -- only included so that get_realization has the same function arguments regardless of transition type. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: contains positive floats, size equal to (length of outgoing transition variables list + 1) x number of age groups x number of risk groups -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (not transitioning to any outgoing compartment). |
Source code in CLT_BaseModel/clt_base/base_components.py
get_multinomial_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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: contains positive floats, size equal to ((length of outgoing transition variables list + 1) x number of age groups x number of risk groups) -- 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_base/base_components.py
get_multinomial_taylor_approx_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministic counterpart to self.get_multinomial_taylor_approx_realization
--
uses mean (n x p, i.e. total counts x probability array) as realization
rather than randomly sampling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
NOT USED -- only included so that get_realization has the same function arguments regardless of transition type. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: contains positive floats, size equal to (length of outgoing transition variables list + 1) x number of age groups x number of risk groups -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (not transitioning to any outgoing compartment). |
Source code in CLT_BaseModel/clt_base/base_components.py
get_multinomial_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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: size equal to (length of outgoing transition variables list + 1) x number of age groups x number of risk groups -- note the "+1" corresponds to the multinomial outcome of staying in the same compartment (not transitioning to any outgoing compartment). |
Source code in CLT_BaseModel/clt_base/base_components.py
get_poisson_deterministic_realization(RNG: np.random.Generator, num_timesteps: int) -> np.ndarray
Deterministic counterpart to self.get_poisson_realization
--
uses mean (rate array) as realization rather than randomly sampling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
NOT USED -- only included so that get_realization has the same function arguments regardless of transition type. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: contains positive floats, size equal to (length of outgoing transition variables list x number of age groups x number of risk groups). |
Source code in CLT_BaseModel/clt_base/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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
RNG
|
np.random.Generator object
|
used to generate stochastic transitions in the model and control reproducibility. |
required |
num_timesteps
|
int
|
number of timesteps per day -- used to determine time interval length for discretization. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: contains positive floats, size equal to length of (outgoing transition variables list x number of age groups x number of risk groups). |
Source code in CLT_BaseModel/clt_base/base_components.py
get_probabilities_array(num_timesteps: int) -> list
Returns an array of probabilities used for joint binomial
(multinomial) transitions (get_multinomial_realization
method).
Returns:
Type | Description |
---|---|
list
|
contains positive floats <= 1, size equal to |
list
|
((length of outgoing transition variables list + 1) |
list
|
x number of age groups x number of risk groups) -- |
list
|
note the "+1" corresponds to the multinomial outcome of staying |
list
|
in the same epi compartment (not transitioning to any outgoing |
list
|
epi compartment). |
Source code in CLT_BaseModel/clt_base/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
|
numpy array of positive floats with size equal to number |
ndarray
|
of age groups x number of risk groups, and with value |
ndarray
|
corresponding to sum of current rates of transition variables in |
ndarray
|
transition variable group. |
Source code in CLT_BaseModel/clt_base/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_base/base_components.py
approx_binomial_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
|
ndarray
|
dimension |A| x |R| (number of age groups x number of risk groups), rate parameters in a Poisson distribution. |
required |
interval_length
|
positive int
|
length of time interval in simulation days. |
required |
Returns:
Type | Description |
---|---|
ndarray
|
np.ndarray: array of positive scalars, dimension |A| x |R| |
Source code in CLT_BaseModel/clt_base/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_base/experiments.py
convert_dict_vals_lists_to_arrays(d: dict) -> dict
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_base/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_base/experiments.py
load_json_augment_dict(json_filepath: str, d: dict) -> dict
Source code in CLT_BaseModel/clt_base/input_parsers.py
load_json_new_dict(json_filepath: str) -> dict
Source code in CLT_BaseModel/clt_base/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_base/input_parsers.py
make_dataclass_from_json(dataclass_ref: Type[DataClassProtocol], json_filepath: str) -> DataClassProtocol
Create instance of class dataclass_ref, based on information in json_filepath.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataclass_ref
|
Type[DataClassProtocol]
|
(class, not instance) from which to create instance -- must have dataclass decorator. |
required |
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 |
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_base/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_base/plotting.py
plot_metapop_decorator(plot_func)
Decorator to handle common metapopulation plotting tasks.
Source code in CLT_BaseModel/clt_base/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_base/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_base/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_base/plotting.py
plot_subpop_decorator(plot_func)
Decorator to handle common subpopulation plotting tasks.
Source code in CLT_BaseModel/clt_base/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_base/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
|