-
Notifications
You must be signed in to change notification settings - Fork 218
/
base.py
1705 lines (1339 loc) · 60.4 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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
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
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
'''
Base classes for Covasim. These classes handle a lot of the boilerplate of the
People and Sim classes (e.g. loading, saving, key lookups, etc.), so those classes
can be focused on the disease-specific functionality.
'''
import numpy as np
import pandas as pd
import sciris as sc
import datetime as dt
from . import version as cvv
from . import utils as cvu
from . import misc as cvm
from . import defaults as cvd
from . import parameters as cvpar
# Specify all externally visible classes this file defines
__all__ = ['ParsObj', 'Result', 'BaseSim', 'BasePeople', 'Person', 'FlexDict', 'Contacts', 'Layer']
#%% Define simulation classes
class FlexPretty(sc.prettyobj):
'''
A class that supports multiple different display options: namely obj.brief()
for a one-line description and obj.disp() for a full description.
'''
def __repr__(self):
''' Use brief repr by default '''
try:
string = self._brief()
except Exception as E:
string = sc.objectid(self)
string += f'Warning, something went wrong printing object:\n{str(E)}'
return string
def _disp(self):
''' Verbose output -- use Sciris' pretty repr by default '''
return sc.prepr(self)
def disp(self, output=False):
''' Print or output verbose representation of the object '''
string = self._disp()
if not output:
print(string)
else:
return string
def _brief(self):
''' Brief output -- use a one-line output, a la Python's default '''
return sc.objectid(self)
def brief(self, output=False):
''' Print or output a brief representation of the object '''
string = self._brief()
if not output:
print(string)
else:
return string
class ParsObj(FlexPretty):
'''
A class based around performing operations on a self.pars dict.
'''
def __init__(self, pars):
self.update_pars(pars, create=True)
return
def __getitem__(self, key):
''' Allow sim['par_name'] instead of sim.pars['par_name'] '''
try:
return self.pars[key]
except:
all_keys = '\n'.join(list(self.pars.keys()))
errormsg = f'Key "{key}" not found; available keys:\n{all_keys}'
raise sc.KeyNotFoundError(errormsg)
def __setitem__(self, key, value):
''' Ditto '''
if key in self.pars:
self.pars[key] = value
else:
all_keys = '\n'.join(list(self.pars.keys()))
errormsg = f'Key "{key}" not found; available keys:\n{all_keys}'
raise sc.KeyNotFoundError(errormsg)
return
def update_pars(self, pars=None, create=False):
'''
Update internal dict with new pars.
Args:
pars (dict): the parameters to update (if None, do nothing)
create (bool): if create is False, then raise a KeyNotFoundError if the key does not already exist
'''
if pars is not None:
if not isinstance(pars, dict):
raise TypeError(f'The pars object must be a dict; you supplied a {type(pars)}')
if not hasattr(self, 'pars'):
self.pars = pars
if not create:
available_keys = list(self.pars.keys())
mismatches = [key for key in pars.keys() if key not in available_keys]
if len(mismatches):
errormsg = f'Key(s) {mismatches} not found; available keys are {available_keys}'
raise sc.KeyNotFoundError(errormsg)
self.pars.update(pars)
return
class Result(object):
'''
Stores a single result -- by default, acts like an array.
Args:
name (str): name of this result, e.g. new_infections
npts (int): if values is None, precreate it to be of this length
scale (bool): whether or not the value scales by population scale factor
color (str/arr): default color for plotting (hex or RGB notation)
n_strains (int): the number of strains the result is for (0 for results not by strain)
**Example**::
import covasim as cv
r1 = cv.Result(name='test1', npts=10)
r1[:5] = 20
print(r1.values)
'''
def __init__(self, name=None, npts=None, scale=True, color=None, n_strains=0):
self.name = name # Name of this result
self.scale = scale # Whether or not to scale the result by the scale factor
if color is None:
color = cvd.get_default_colors()['default']
self.color = color # Default color
if npts is None:
npts = 0
npts = int(npts)
if n_strains>0:
self.values = np.zeros((n_strains, npts), dtype=cvd.result_float)
else:
self.values = np.zeros(npts, dtype=cvd.result_float)
self.low = None
self.high = None
return
def __repr__(self, *args, **kwargs):
''' Use pretty repr, like sc.prettyobj, but displaying full values '''
output = sc.prepr(self, skip=['values', 'low', 'high'], use_repr=False)
output += 'values:\n' + repr(self.values)
if self.low is not None:
output += '\nlow:\n' + repr(self.low)
if self.high is not None:
output += '\nhigh:\n' + repr(self.high)
return output
def __getitem__(self, *args, **kwargs):
''' To allow e.g. result[5] instead of result.values[5] '''
return self.values.__getitem__(*args, **kwargs)
def __setitem__(self, *args, **kwargs):
''' To allow e.g. result[:] = 1 instead of result.values[:] = 1 '''
return self.values.__setitem__(*args, **kwargs)
def __len__(self):
''' To allow len(result) instead of len(result.values) '''
return len(self.values)
@property
def npts(self):
return len(self.values)
def set_metadata(obj):
''' Set standard metadata for an object '''
obj.created = sc.now()
obj.version = cvv.__version__
obj.git_info = cvm.git_info()
return
class BaseSim(ParsObj):
'''
The BaseSim class stores various methods useful for the Sim that are not directly
related to simulating the epidemic. It is not used outside of the Sim object,
so the separation of methods into the BaseSim and Sim classes is purely to keep
each one of manageable size.
'''
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs) # Initialize and set the parameters as attributes
return
def _disp(self):
'''
Print a verbose display of the sim object. Used by repr(). See sim.disp()
for the user version. Equivalent to sc.prettyobj().
'''
return sc.prepr(self)
def _brief(self):
'''
Return a one-line description of a sim -- used internally and by repr();
see sim.brief() for the user version.
'''
# Try to get a detailed description of the sim...
try:
if self.results_ready:
infections = self.summary['cum_infections']
deaths = self.summary['cum_deaths']
results = f'{infections:n}⚙, {deaths:n}☠'
else:
results = 'not run'
# Set label string
labelstr = f'"{self.label}"' if self.label else '<no label>'
start = sc.date(self['start_day'], as_date=False)
if self['end_day']:
end = sc.date(self['end_day'], as_date=False)
else:
end = sc.date(self['n_days'], start_date=start)
pop_size = self['pop_size']
pop_type = self['pop_type']
string = f'Sim({labelstr}; {start} to {end}; pop: {pop_size:n} {pop_type}; epi: {results})'
# ...but if anything goes wrong, return the default with a warning
except Exception as E: # pragma: no cover
string = sc.objectid(self)
string += f'Warning, sim appears to be malformed; use sim.disp() for details:\n{str(E)}'
return string
def update_pars(self, pars=None, create=False, **kwargs):
''' Ensure that metaparameters get used properly before being updated '''
# Merge everything together
pars = sc.mergedicts(pars, kwargs)
if pars:
# Define aliases
mapping = dict(
n_agents = 'pop_size',
init_infected = 'pop_infected',
)
for key1,key2 in mapping.items():
if key1 in pars:
pars[key2] = pars.pop(key1)
# Handle other special parameters
if pars.get('pop_type'):
cvpar.reset_layer_pars(pars, force=False)
if pars.get('prog_by_age'):
pars['prognoses'] = cvpar.get_prognoses(by_age=pars['prog_by_age'], version=self._default_ver) # Reset prognoses
# Call update_pars() for ParsObj
super().update_pars(pars=pars, create=create)
return
def set_metadata(self, simfile):
''' Set the metadata for the simulation -- creation time and filename '''
set_metadata(self)
if simfile is None:
datestr = sc.getdate(obj=self.created, dateformat='%Y-%b-%d_%H.%M.%S')
self.simfile = f'covasim_{datestr}.sim'
return
def set_seed(self, seed=-1):
'''
Set the seed for the random number stream from the stored or supplied value
Args:
seed (None or int): if no argument, use current seed; if None, randomize; otherwise, use and store supplied seed
'''
# Unless no seed is supplied, reset it
if seed != -1:
self['rand_seed'] = seed
cvu.set_seed(self['rand_seed'])
return
@property
def n(self):
''' Count the number of people -- if it fails, assume none '''
try: # By default, the length of the people dict
return len(self.people)
except: # pragma: no cover # If it's None or missing
return 0
@property
def scaled_pop_size(self):
''' Get the total population size, i.e. the number of agents times the scale factor -- if it fails, assume none '''
try:
return self['pop_size']*self['pop_scale']
except: # pragma: no cover # If it's None or missing
return 0
@property
def npts(self):
''' Count the number of time points '''
try:
return int(self['n_days'] + 1)
except: # pragma: no cover
return 0
@property
def tvec(self):
''' Create a time vector '''
try:
return np.arange(self.npts)
except: # pragma: no cover
return np.array([])
@property
def datevec(self):
'''
Create a vector of dates
Returns:
Array of `datetime` instances containing the date associated with each
simulation time step
'''
try:
return self['start_day'] + self.tvec * dt.timedelta(days=1)
except: # pragma: no cover
return np.array([])
def day(self, day, *args):
'''
Convert a string, date/datetime object, or int to a day (int).
Args:
day (str, date, int, or list): convert any of these objects to a day relative to the simulation's start day
Returns:
days (int or str): the day(s) in simulation time
**Example**::
sim.day('2020-04-05') # Returns 35
'''
return sc.day(day, *args, start_day=self['start_day'])
def date(self, ind, *args, dateformat=None, as_date=False):
'''
Convert one or more integer days of simulation time to a date/list of dates --
by default returns a string, or returns a datetime Date object if as_date is True.
See also cv.date(), which provides a partly overlapping set of date conversion
features.
Args:
ind (int, list, or array): the index day(s) in simulation time (NB: strings and date objects are accepted, and will be passed unchanged)
args (list): additional day(s)
dateformat (str): the format to return the date in
as_date (bool): whether to return as a datetime date instead of a string
Returns:
dates (str, Date, or list): the date(s) corresponding to the simulation day(s)
**Examples**::
sim = cv.Sim()
sim.date(34) # Returns '2020-04-04'
sim.date([34, 54]) # Returns ['2020-04-04', '2020-04-24']
sim.date([34, '2020-04-24']) # Returns ['2020-04-04', '2020-04-24']
sim.date(34, 54, as_date=True) # Returns [datetime.date(2020, 4, 4), datetime.date(2020, 4, 24)]
'''
# Handle inputs
if not isinstance(ind, list): # If it's a number, string, or dateobj, convert it to a list
ind = sc.promotetolist(ind)
ind.extend(args)
if dateformat is None:
dateformat = '%Y-%m-%d'
# Do the conversion
dates = []
for raw in ind:
if sc.isnumber(raw):
date_obj = sc.date(self['start_day'], as_date=True) + dt.timedelta(days=int(raw))
else:
date_obj = sc.date(raw, as_date=True)
if as_date:
dates.append(date_obj)
else:
dates.append(date_obj.strftime(dateformat))
# Return a string rather than a list if only one provided
if len(ind)==1:
dates = dates[0]
return dates
def result_keys(self, which='main'):
'''
Get the actual results objects, not other things stored in sim.results.
If which is 'main', return only the main results keys. If 'strain', return
only strain keys. If 'all', return all keys.
'''
keys = []
choices = ['main', 'strain', 'all']
if which in ['main', 'all']:
keys += [key for key,res in self.results.items() if isinstance(res, Result)]
if which in ['strain', 'all'] and 'strain' in self.results:
keys += [key for key,res in self.results['strain'].items() if isinstance(res, Result)]
if which not in choices: # pragma: no cover
errormsg = f'Choice "which" not available; choices are: {sc.strjoin(choices)}'
raise ValueError(errormsg)
return keys
def copy(self):
''' Returns a deep copy of the sim '''
return sc.dcp(self)
def export_results(self, for_json=True, filename=None, indent=2, *args, **kwargs):
'''
Convert results to dict -- see also to_json().
The results written to Excel must have a regular table shape, whereas
for the JSON output, arbitrary data shapes are supported.
Args:
for_json (bool): if False, only data associated with Result objects will be included in the converted output
filename (str): filename to save to; if None, do not save
indent (int): indent (int): if writing to file, how many indents to use per nested level
args (list): passed to savejson()
kwargs (dict): passed to savejson()
Returns:
resdict (dict): dictionary representation of the results
'''
if not self.results_ready: # pragma: no cover
errormsg = 'Please run the sim before exporting the results'
raise RuntimeError(errormsg)
resdict = {}
resdict['t'] = self.results['t'] # Assume that there is a key for time
if for_json:
resdict['timeseries_keys'] = self.result_keys()
for key,res in self.results.items():
if isinstance(res, Result):
resdict[key] = res.values
if res.low is not None:
resdict[key+'_low'] = res.low
if res.high is not None:
resdict[key+'_high'] = res.high
elif for_json:
if key == 'date':
resdict[key] = [str(d) for d in res] # Convert dates to strings
else:
resdict[key] = res
if filename is not None:
sc.savejson(filename=filename, obj=resdict, indent=indent, *args, **kwargs)
return resdict
def export_pars(self, filename=None, indent=2, *args, **kwargs):
'''
Return parameters for JSON export -- see also to_json().
This method is required so that interventions can specify
their JSON-friendly representation.
Args:
filename (str): filename to save to; if None, do not save
indent (int): indent (int): if writing to file, how many indents to use per nested level
args (list): passed to savejson()
kwargs (dict): passed to savejson()
Returns:
pardict (dict): a dictionary containing all the parameter values
'''
pardict = {}
for key in self.pars.keys():
if key == 'interventions':
pardict[key] = [intervention.to_json() for intervention in self.pars[key]]
elif key == 'start_day':
pardict[key] = str(self.pars[key])
else:
pardict[key] = self.pars[key]
if filename is not None:
sc.savejson(filename=filename, obj=pardict, indent=indent, *args, **kwargs)
return pardict
def to_json(self, filename=None, keys=None, tostring=False, indent=2, verbose=False, *args, **kwargs):
'''
Export results and parameters as JSON.
Args:
filename (str): if None, return string; else, write to file
keys (str or list): attributes to write to json (default: results, parameters, and summary)
tostring (bool): if not writing to file, whether to write to string (alternative is sanitized dictionary)
indent (int): if writing to file, how many indents to use per nested level
verbose (bool): detail to print
args (list): passed to savejson()
kwargs (dict): passed to savejson()
Returns:
A unicode string containing a JSON representation of the results,
or writes the JSON file to disk
**Examples**::
json = sim.to_json()
sim.to_json('results.json')
sim.to_json('summary.json', keys='summary')
'''
# Handle keys
if keys is None:
keys = ['results', 'pars', 'summary']
keys = sc.promotetolist(keys)
# Convert to JSON-compatible format
d = {}
for key in keys:
if key == 'results':
resdict = self.export_results(for_json=True)
d['results'] = resdict
elif key in ['pars', 'parameters']:
pardict = self.export_pars()
d['parameters'] = pardict
elif key == 'summary':
d['summary'] = dict(sc.dcp(self.summary))
else: # pragma: no cover
try:
d[key] = sc.sanitizejson(getattr(self, key))
except Exception as E:
errormsg = f'Could not convert "{key}" to JSON: {str(E)}; continuing...'
print(errormsg)
if filename is None:
output = sc.jsonify(d, tostring=tostring, indent=indent, verbose=verbose, *args, **kwargs)
else:
output = sc.savejson(filename=filename, obj=d, indent=indent, *args, **kwargs)
return output
def to_df(self, date_index=False):
'''
Export results to a pandas dataframe
Args:
date_index (bool): if True, use the date as the index
'''
resdict = self.export_results(for_json=False)
df = pd.DataFrame.from_dict(resdict)
df['date'] = self.datevec
new_columns = ['t','date'] + df.columns[1:-1].tolist() # Get column order
df = df.reindex(columns=new_columns) # Reorder so 't' and 'date' are first
if date_index:
df = df.set_index('date')
return df
def to_excel(self, filename=None, skip_pars=None):
'''
Export parameters and results as Excel format
Args:
filename (str): if None, return string; else, write to file
skip_pars (list): if provided, a custom list parameters to exclude
Returns:
An sc.Spreadsheet with an Excel file, or writes the file to disk
'''
if skip_pars is None:
skip_pars = ['strain_map', 'vaccine_map'] # These include non-string keys so fail at sc.flattendict()
# Export results
result_df = self.to_df(date_index=True)
# Export parameters
pars = {k:v for k,v in self.pars.items() if k not in skip_pars}
par_df = pd.DataFrame.from_dict(sc.flattendict(pars, sep='_'), orient='index', columns=['Value'])
par_df.index.name = 'Parameter'
# Convert to spreadsheet
spreadsheet = sc.Spreadsheet()
spreadsheet.freshbytes()
with pd.ExcelWriter(spreadsheet.bytes, engine='xlsxwriter') as writer:
result_df.to_excel(writer, sheet_name='Results')
par_df.to_excel(writer, sheet_name='Parameters')
spreadsheet.load()
if filename is None:
output = spreadsheet
else:
output = spreadsheet.save(filename)
return output
def shrink(self, skip_attrs=None, in_place=True):
'''
"Shrinks" the simulation by removing the people, and returns
a copy of the "shrunken" simulation. Used to reduce the memory required
for saved files.
Args:
skip_attrs (list): a list of attributes to skip in order to perform the shrinking; default "people"
Returns:
shrunken_sim (Sim): a Sim object with the listed attributes removed
'''
# By default, skip people (~90% of memory), the popdict (which is usually empty anyway), and _orig_pars (which is just a backup)
if skip_attrs is None:
skip_attrs = ['popdict', 'people', '_orig_pars']
# Create the new object, and copy original dict, skipping the skipped attributes
if in_place:
for attr in skip_attrs:
setattr(self, attr, None)
return
else:
shrunken_sim = object.__new__(self.__class__)
shrunken_sim.__dict__ = {k:(v if k not in skip_attrs else None) for k,v in self.__dict__.items()}
return shrunken_sim
def save(self, filename=None, keep_people=None, skip_attrs=None, **kwargs):
'''
Save to disk as a gzipped pickle.
Args:
filename (str or None): the name or path of the file to save to; if None, uses stored
kwargs: passed to sc.makefilepath()
Returns:
filename (str): the validated absolute path to the saved file
**Example**::
sim.save() # Saves to a .sim file with the date and time of creation by default
'''
# Set keep_people based on whether or not we're in the middle of a run
if keep_people is None:
if self.initialized and not self.results_ready:
keep_people = True
else:
keep_people = False
# Handle the filename
if filename is None:
filename = self.simfile
filename = sc.makefilepath(filename=filename, **kwargs)
self.filename = filename # Store the actual saved filename
# Handle the shrinkage and save
if skip_attrs or not keep_people:
obj = self.shrink(skip_attrs=skip_attrs, in_place=False)
else:
obj = self
cvm.save(filename=filename, obj=obj)
return filename
@staticmethod
def load(filename, *args, **kwargs):
'''
Load from disk from a gzipped pickle.
Args:
filename (str): the name or path of the file to load from
kwargs: passed to cv.load()
Returns:
sim (Sim): the loaded simulation object
**Example**::
sim = cv.Sim.load('my-simulation.sim')
'''
sim = cvm.load(filename, *args, **kwargs)
if not isinstance(sim, BaseSim): # pragma: no cover
errormsg = f'Cannot load object of {type(sim)} as a Sim object'
raise TypeError(errormsg)
return sim
def _get_ia(self, which, label=None, partial=False, as_list=False, as_inds=False, die=True, first=False):
''' Helper method for get_interventions() and get_analyzers(); see get_interventions() docstring '''
# Handle inputs
if which not in ['interventions', 'analyzers']: # pragma: no cover
errormsg = f'This method is only defined for interventions and analyzers, not "{which}"'
raise ValueError(errormsg)
ia_list = self.pars[which] # List of interventions or analyzers
n_ia = len(ia_list) # Number of interventions/analyzers
if label == 'summary': # Print a summary of the interventions
df = pd.DataFrame(columns=['ind', 'label', 'type'])
for ind,ia_obj in enumerate(ia_list):
df = df.append(dict(ind=ind, label=str(ia_obj.label), type=type(ia_obj)), ignore_index=True)
print(f'Summary of {which}:')
print(df)
return
else: # Standard usage case
position = 0 if first else -1 # Choose either the first or last element
if label is None: # Get all interventions if no label is supplied, e.g. sim.get_interventions()
label = np.arange(n_ia)
if isinstance(label, np.ndarray): # Allow arrays to be provided
label = label.tolist()
labels = sc.promotetolist(label)
# Calculate the matches
matches = []
match_inds = []
for label in labels:
if sc.isnumber(label):
matches.append(ia_list[label]) # This will raise an exception if an invalid index is given
label = n_ia + label if label<0 else label # Convert to a positive number
match_inds.append(label)
elif sc.isstring(label) or isinstance(label, type):
for ind,ia_obj in enumerate(ia_list):
if sc.isstring(label) and ia_obj.label == label or (partial and (label in str(ia_obj.label))):
matches.append(ia_obj)
match_inds.append(ind)
elif isinstance(label, type) and isinstance(ia_obj, label):
matches.append(ia_obj)
match_inds.append(ind)
else: # pragma: no cover
errormsg = f'Could not interpret label type "{type(label)}": should be str, int, list, or {which} class'
raise TypeError(errormsg)
# Parse the output options
if as_inds:
output = match_inds
elif as_list: # Used by get_interventions()
output = matches
else:
if len(matches) == 0: # pragma: no cover
if die:
errormsg = f'No {which} matching "{label}" were found'
raise ValueError(errormsg)
else:
output = None
else:
output = matches[position] # Return either the first or last match (usually), used by get_intervention()
return output
def get_interventions(self, label=None, partial=False, as_inds=False):
'''
Find the matching intervention(s) by label, index, or type. If None, return
all interventions. If the label provided is "summary", then print a summary
of the interventions (index, label, type).
Args:
label (str, int, Intervention, list): the label, index, or type of intervention to get; if a list, iterate over one of those types
partial (bool): if true, return partial matches (e.g. 'beta' will match all beta interventions)
as_inds (bool): if true, return matching indices instead of the actual interventions
**Examples**::
tp = cv.test_prob(symp_prob=0.1)
cb1 = cv.change_beta(days=5, changes=0.3, label='NPI')
cb2 = cv.change_beta(days=10, changes=0.3, label='Masks')
sim = cv.Sim(interventions=[tp, cb1, cb2])
cb1, cb2 = sim.get_interventions(cv.change_beta)
tp, cb2 = sim.get_interventions([0,2])
ind = sim.get_interventions(cv.change_beta, as_inds=True) # Returns [1,2]
sim.get_interventions('summary') # Prints a summary
'''
return self._get_ia('interventions', label=label, partial=partial, as_inds=as_inds, as_list=True)
def get_intervention(self, label=None, partial=False, first=False, die=True):
'''
Like get_interventions(), find the matching intervention(s) by label,
index, or type. If more than one intervention matches, return the last
by default. If no label is provided, return the last intervention in the list.
Args:
label (str, int, Intervention, list): the label, index, or type of intervention to get; if a list, iterate over one of those types
partial (bool): if true, return partial matches (e.g. 'beta' will match all beta interventions)
first (bool): if true, return first matching intervention (otherwise, return last)
die (bool): whether to raise an exception if no intervention is found
**Examples**::
tp = cv.test_prob(symp_prob=0.1)
cb = cv.change_beta(days=5, changes=0.3, label='NPI')
sim = cv.Sim(interventions=[tp, cb])
cb = sim.get_intervention('NPI')
cb = sim.get_intervention('NP', partial=True)
cb = sim.get_intervention(cv.change_beta)
cb = sim.get_intervention(1)
cb = sim.get_intervention()
tp = sim.get_intervention(first=True)
'''
return self._get_ia('interventions', label=label, partial=partial, first=first, die=die, as_inds=False, as_list=False)
def get_analyzers(self, label=None, partial=False, as_inds=False):
'''
Same as get_interventions(), but for analyzers.
'''
return self._get_ia('analyzers', label=label, partial=partial, as_list=True, as_inds=as_inds)
def get_analyzer(self, label=None, partial=False, first=False, die=True):
'''
Same as get_intervention(), but for analyzers.
'''
return self._get_ia('analyzers', label=label, partial=partial, first=first, die=die, as_inds=False, as_list=False)
#%% Define people classes
class BasePeople(FlexPretty):
'''
A class to handle all the boilerplate for people -- note that as with the
BaseSim vs Sim classes, everything interesting happens in the People class,
whereas this class exists to handle the less interesting implementation details.
'''
def __getitem__(self, key):
''' Allow people['attr'] instead of getattr(people, 'attr')
If the key is an integer, alias `people.person()` to return a `Person` instance
'''
try:
return self.__dict__[key]
except: # pragma: no cover
if isinstance(key, int):
return self.person(key)
else:
errormsg = f'Key "{key}" is not a valid attribute of people'
raise AttributeError(errormsg)
def __setitem__(self, key, value):
''' Ditto '''
if self._lock and key not in self.__dict__: # pragma: no cover
errormsg = f'Key "{key}" is not a current attribute of people, and the people object is locked; see people.unlock()'
raise AttributeError(errormsg)
self.__dict__[key] = value
return
def lock(self):
''' Lock the people object to prevent keys from being added '''
self._lock = True
return
def unlock(self):
''' Unlock the people object to allow keys to be added '''
self._lock = False
return
def __len__(self):
''' This is just a scalar, but validate() and _resize_arrays() make sure it's right '''
return int(self.pars['pop_size'])
def __iter__(self):
''' Iterate over people '''
for i in range(len(self)):
yield self[i]
def __add__(self, people2):
''' Combine two people arrays '''
newpeople = sc.dcp(self)
keys = list(self.keys())
for key in keys:
npval = newpeople[key]
p2val = people2[key]
if npval.ndim == 1:
newpeople.set(key, np.concatenate([npval, p2val], axis=0), die=False) # Allow size mismatch
elif npval.ndim == 2:
newpeople.set(key, np.concatenate([npval, p2val], axis=1), die=False)
else:
errormsg = f'Not sure how to combine arrays of {npval.ndim} dimensions for {key}'
raise NotImplementedError(errormsg)
# Validate
newpeople.pars['pop_size'] += people2.pars['pop_size']
newpeople.validate()
# Reassign UIDs so they're unique
newpeople.set('uid', np.arange(len(newpeople)))
return newpeople
def __radd__(self, people2):
''' Allows sum() to work correctly '''
if not people2: return self
else: return self.__add__(people2)
def _brief(self):
'''
Return a one-line description of the people -- used internally and by repr();
see people.brief() for the user version.
'''
try:
layerstr = ', '.join([str(k) for k in self.layer_keys()])
string = f'People(n={len(self):0n}; layers: {layerstr})'
except Exception as E: # pragma: no cover
string = sc.objectid(self)
string += f'Warning, multisim appears to be malformed:\n{str(E)}'
return string
def summarize(self, output=False):
''' Print a summary of the people -- same as brief '''
return self.brief(output=output)
def set(self, key, value, die=True):
''' Ensure sizes and dtypes match '''
current = self[key]
value = np.array(value, dtype=self._dtypes[key]) # Ensure it's the right type
if die and len(value) != len(current): # pragma: no cover
errormsg = f'Length of new array does not match current ({len(value)} vs. {len(current)})'
raise IndexError(errormsg)
self[key] = value
return
def get(self, key):
''' Convenience method -- key can be string or list of strings '''
if isinstance(key, str):
return self[key]
elif isinstance(key, list):
arr = np.zeros((len(self), len(key)))
for k,ky in enumerate(key):
arr[:,k] = self[ky]
return arr
def true(self, key):
''' Return indices matching the condition '''
return self[key].nonzero()[0]
def false(self, key):
''' Return indices not matching the condition '''
return (~self[key]).nonzero()[0]
def defined(self, key):
''' Return indices of people who are not-nan '''
return (~np.isnan(self[key])).nonzero()[0]
def undefined(self, key):
''' Return indices of people who are nan '''
return np.isnan(self[key]).nonzero()[0]
def count(self, key):
''' Count the number of people for a given key '''
return (self[key]>0).sum()
def count_by_strain(self, key, strain):
''' Count the number of people for a given key '''
return (self[key][strain,:]>0).sum()
def count_not(self, key):
''' Count the number of people who do not have a property for a given key '''