-
Notifications
You must be signed in to change notification settings - Fork 1
/
Community.cpp
1441 lines (1238 loc) · 64.8 KB
/
Community.cpp
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
#include <cstdlib>
#include <cstring>
#include <climits>
#include <iostream>
#include <string>
#include <iterator>
#include <fstream>
#include <sstream>
#include <assert.h>
#include <math.h>
#include <algorithm>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "Person.h"
#include "Location.h"
#include "Community.h"
#include "Parameters.h"
#include "Vac_Campaign.h"
using namespace covid::standard;
using covid::util::mean;
using covid::util::uniform_choice;
using covid::util::weighted_choice;
using covid::util::choose_k;
using covid::util::merge_vectors;
using covid::util::inspect_next_rng_val;
const Parameters* Community::_par;
int mod(int k, int n) { return ((k %= n) < 0) ? k+n : k; } // correct for non-negative n
Community::Community(const Parameters* parameters, Date* date) //:
// _numNewlyInfected(parameters->runLength, 0), // +1 not needed; runLength is already a valid size
// _numNewlySymptomatic(parameters->runLength, 0),
// _numNewlySevere(parameters->runLength, 0),
// _numNewlyCritical(parameters->runLength, 0),
// _numNewlyDead(parameters->runLength, 0),
// _numVaccinatedCases(parameters->runLength, 0),
// _numSeverePrev(parameters->runLength, 0),
// _numHospInc(parameters->runLength, 0),
// _numHospPrev(parameters->runLength, 0),
// _numIcuInc(parameters->runLength, 0),
// _numIcuPrev(parameters->runLength, 0),
// _numDetectedCasesOnset(parameters->runLength, 0),
// _numDetectedCasesReport(parameters->runLength, 0),
// _numDetectedHospitalizations(parameters->runLength, 0),
// //_numDetectedDeaths(parameters->runLength, 0),
// _numDetectedDeathsOnset(parameters->runLength, 0),
// _numDetectedDeathsReport(parameters->runLength, 0),
// _cumulIncByOutcome(NUM_OF_OUTCOME_TYPES, 0),
// _isHot(parameters->runLength)
{
_par = parameters;
_date = date;
_day = 0;
cmty_ledger = new CommunityLedger(_par);
vac_campaign = nullptr;
// for (int strain = 0; strain < (int) NUM_OF_STRAIN_TYPES; ++strain) {
// _numNewInfectionsByStrain[(StrainType) strain] = vector<size_t>(_par->runLength);
// }
//
// vector<string> inf_by_loc_keys = {"home", "social", "work_staff", "patron", "school_staff", "student", "hcw", "patient", "ltcf_staff", "ltcf_resident"};
// for (string key : inf_by_loc_keys) {
// _numNewlyInfectedByLoc[key] = vector<size_t>(_par->runLength, 0);
// }
// for (auto &e: _isHot) {
// for (size_t locType = 0; locType < NUM_OF_LOCATION_TYPES; ++locType) {
// e[(LocationType) locType] = {};
// }
// }
// timedInterventions = _par->timedInterventions;
}
Date* Community::get_date() {
if (_date) {
return _date;
} else {
cerr << "ERROR: Community::_date not defined in Community::get_date()\n";
exit(-1);
}
}
void Community::reset() { // used for r-zero calculations, to reset pop after a single intro
// reset people
for (Person* p: _people) {
/* if (p->isWithdrawn(_day)) {
p->getLocation(WORK_DAY)->addPerson(p,WORK_DAY); // goes back to work
p->getLocation(HOME_MORNING)->removePerson(p,WORK_DAY); // stops staying at home
}*/
p->resetImmunity(); // no past infections, not dead, not vaccinated
}
// reset locations
// for (auto &e: _isHot) e.clear();
if (cmty_ledger) { delete cmty_ledger; }
cmty_ledger = new CommunityLedger(_par);
// clear community queues & tallies
// _exposedQueue.clear();
// _numNewlyInfected.clear();
// _numNewlySymptomatic.clear();
// _numNewlyDead.clear();
// _numVaccinatedCases.clear();
// _exposedQueue.resize(MAX_INCUBATION, vector<Person*>(0));
// _numNewlyInfected.resize(_par->runLength);
// for (int strain = 0; strain < (int) NUM_OF_STRAIN_TYPES; ++strain) {
// _numNewInfectionsByStrain[(StrainType) strain] = vector<size_t>(_par->runLength);
// }
//
// vector<string> inf_by_loc_keys = {"home", "social", "work_staff", "patron", "school_staff", "student", "hcw", "patient", "ltcf_staff", "ltcf_resident"};
// for (string key : inf_by_loc_keys) {
// _numNewlyInfectedByLoc[key] = vector<size_t>(_par->runLength, 0);
// }
//
// _numNewlySymptomatic.resize(_par->runLength);
// _numNewlyDead.resize(_par->runLength);
// _numVaccinatedCases.resize(_par->runLength);
}
Community::~Community() {
if (_date) delete _date;
if (_people.size() > 0) { for (Person* p: _people) delete p; }
if (vac_campaign) { delete vac_campaign; }
Person::reset_ID_counter();
// _isHot.clear();
for (unsigned int i = 0; i < _location.size(); i++ ) delete _location[i];
_location.clear();
Location::reset_ID_counter();
for (auto& kv: _location_map) {
kv.second.clear();
}
_location_map.clear();
// _exposedQueue.clear();
_personAgeCohort.clear();
// _numNewlyInfected.clear();
// _numNewInfectionsByStrain.clear();
// _numNewlyInfectedByLoc.clear();
// _numNewlySymptomatic.clear();
// _numNewlyDead.clear();
// _numVaccinatedCases.clear();
if (cmty_ledger) { delete cmty_ledger; }
}
void Community::load_from_cache(CommunityLedger* cache_ledger, Date* cache_date, map<int, vector<Person*>> cache_hosp_ppl, Vac_Campaign* cache_vc) {
if (cmty_ledger) { delete cmty_ledger; }
cmty_ledger = new CommunityLedger(*cache_ledger);
if (vac_campaign) { delete vac_campaign; }
// vac_campaign = new Vac_Campaign(*cache_vc);
// vac_campaign->copy_doses_available(cache_vc);
vac_campaign = cache_vc->quick_cache();
if (_date) { delete _date; }
_date = new Date(*cache_date);
// revert locations
// for (Location* loc : _location) { loc->revertState(); }
for (Location* hosp : _location_map[HOSPITAL]) { hosp->setPeople(cache_hosp_ppl[hosp->getID()]); }
// revert people
for (Person* p : _people) { p->revertState(_date); }
}
bool Community::loadPopulation(string populationFilename, string comorbidityFilename, string publicActivityFilename, string immunityFilename) {
ifstream iss(populationFilename);
if (!iss) {
cerr << "ERROR: " << populationFilename << " not found." << endl;
return false;
}
string buffer;
// int agecounts[NUM_AGE_CLASSES];
// for (int i=0; i<NUM_AGE_CLASSES; i++) agecounts[i] = 0;
istringstream line;
// per IPUMS, expecting 1 for male, 2 for female for sex
int pid, hid, age, sex, did;//, empstat;
while ( getline(iss, buffer) ) {
line.clear();
line.str(buffer);
/*
pid res_id sex age mov_id
0 1948559 1 21 475292
1 1948559 1 23 475292
2 1948560 2 22 475292
3 1948560 2 20 475292
4 1948560 2 20 481010
5 1948560 2 19 481010
*/
if (line >> pid >> hid >> sex >> age >> did ) { //>> empstat) {
if (pid != (signed) _people.size()) { // ensures indexing stays consistent
cerr << "ERROR: Person ID's must be sequential integers starting at 0" << endl;
return false;
}
assert((signed) _location.size() > hid);
assert((signed) _location.size() > did);
Person* p = new Person();
_people.push_back(p);
p->setAge(age);
p->setSex((SexType) sex);
p->setStartingNaturalEfficacy(_par->sampleStartingNaturalEfficacy(RNG));
p->setImmunityQuantile(gsl_rng_uniform(RNG));
p->setNaturalImmunityDuration(_par->immunityDuration(p->getImmunityQuantile(), p->getStartingNaturalEfficacy()));
p->setCrossProtectionProbability(gsl_rng_uniform(RNG));
// p->setCrossProtectionProbability(p->getNaturalImmunityDuration());
//p->setDaysImmune(_par->sampleDaysImmune(RNG));
p->setHomeLoc(_location[hid]);
_location[hid]->addPerson(p);
if (did >= 0) {
p->setDayLoc(_location[did]); // currently just any non-home daytime location--may be a school; -1 == NA
_location[did]->addPerson(p);
}
if (_location[hid]->getType() == NURSINGHOME) p->setLongTermCare(true);
//assert(age<NUM_AGE_CLASSES);
// agecounts[age]++;
}
}
iss.close();
//_peopleByAge = _people;
//sort(_peopleByAge.begin(), _peopleByAge.end(), PerPtrComp());
if (comorbidityFilename.length() > 0) {
iss.open(comorbidityFilename);
if (!iss) {
cerr << "ERROR: " << comorbidityFilename << " not found." << endl;
return false;
}
bool com;
while ( getline(iss, buffer) ) {
line.clear();
line.str(buffer);
/*
pid sex age undlycond
0 1 33 0
1 2 27 0
2 2 58 0
3 1 63 0
4 2 49 1
*/
if (line >> pid >> sex >> age >> com ) { //>> empstat) {
if (com) { // comorbidity default is false, so only need to handle true
getPersonByID(pid)->setComorbidity(COMORBID);
}
}
}
}
iss.close();
if (publicActivityFilename.length() > 0) {
iss.open(publicActivityFilename);
if (!iss) {
cerr << "ERROR: " << publicActivityFilename << " not found." << endl;
return false;
}
string buffer;
istringstream line;
int pid, locid;
while ( getline(iss, buffer) ) {
line.clear();
line.str(buffer);
/*
pid dest_locid_1 dest_locid_2 dest_locid_3 dest_locid_4 dest_locid_5
0 11321 12073 15279 10654 23786
1 15042 9939 10607 14346 20246
2 18748 24527 20246 16895 21665
*/
if (line >> pid) {
Person* p = getPersonByID(pid);
// underage people and LTCF residents do not engage in commercial activities
if (p->getAge() < 18 or p->getLongTermCare()) { continue; }
while (line >> locid) {
assert((signed) _location.size() > locid);
Location* loc = _location[locid];
const PublicTransmissionType pub_risk = loc->getPublicTransmissionRisk();
assert(pub_risk == LOW_PUBLIC_TRANSMISSION or pub_risk == HIGH_PUBLIC_TRANSMISSION);
p->addPatronizedLocation(loc);
}
}
}
}
iss.close();
if (immunityFilename.length()>0) {
cerr << "ERROR: Reading in immunity file not currently supported." << endl;
return false;
/*
ifstream immiss(immunityFilename);
if (!immiss) {
cerr << "ERROR: " << immunityFilename << " not found." << endl;
return false;
}
int part;
vector<int> parts;
istringstream line;
int line_no = 0;
while ( getline(immiss,buffer) ) {
line_no++;
line.clear();
line.str(buffer);
while (line >> part) parts.push_back(part);
// 1+ without age, 2+ with age
if (parts.size() == 1 + NUM_OF_SEROTYPES or parts.size() == 2 + NUM_OF_SEROTYPES) {
const int id = parts[0];
Person* person = getPersonByID(id);
unsigned int offset = parts.size() - NUM_OF_SEROTYPES;
vector<pair<int,Serotype> > infection_history;
for (unsigned int f=offset; f<offset+NUM_OF_SEROTYPES; f++) {
Serotype s = (Serotype) (f - offset);
const int infection_time = parts[f];
if (infection_time == 0) {
continue; // no infection for this serotype
} else if (infection_time<0) {
infection_history.push_back(make_pair(infection_time, s));
} else {
cerr << "ERROR: Found positive-valued infection time in population immunity file:\n\t";
cerr << "person " << person->getID() << ", serotype " << s+1 << ", time " << infection_time << "\n\n";
cerr << "Infection time should be provided as a negative integer indicated how many days\n";
cerr << "before the start of simulation the infection began.";
exit(-359);
}
}
sort(infection_history.begin(), infection_history.end());
for (auto p: infection_history) person->infect(p.second, p.first + _day);
} else if (parts.size() == 0) {
continue; // skipping blank line, or line that doesn't start with ints
} else {
cerr << "ERROR: Unexpected number of values on one line in population immunity file.\n\t";
cerr << "line num, line: " << line_no << ", " << buffer << "\n\n";
cerr << "Expected " << 1+NUM_OF_SEROTYPES << " values (person id followed by infection time for each serotype),\n";
cerr << "found " << parts.size() << endl;
exit(-361);
}
parts.clear();
}
immiss.close();
*/
}
// keep track of all age cohorts for aging and mortality
_personAgeCohort.clear();
_personAgeCohort.resize(NUM_AGE_CLASSES, vector<Person*>(0));
for (Person* p: _people) {
int age = p->getAge();
assert(age<NUM_AGE_CLASSES);
_personAgeCohort[age].push_back(p);
}
/* if (swapFilename == "") {
_uniformSwap = true;
} else {
iss.open(swapFilename);
if (!iss) {
cerr << "ERROR: " << swapFilename << " not found." << endl;
return false;
}
int id1, id2;
double prob;
istringstream line;
while ( getline(iss, buffer) ) {
line.clear();
line.str(buffer);
if (line >> id1 >> id2 >> prob) {
Person* person = getPersonByID(id1);
if (person) person->appendToSwapProbabilities(make_pair(id2, prob));
}
}
iss.close();
_uniformSwap = false;
}*/
return true;
}
double _calculatePixel(double coord) {
return (floor(coord / 0.01) * 0.01) + 0.005;
}
bool Community::loadLocations(string locationFilename, string networkFilename) {
ifstream iss(locationFilename);
if (!iss) {
cerr << "ERROR: locations file " << locationFilename << " not found." << endl;
return false;
}
_location.clear();
string buffer;
int locid, hfid;
string locTypeStr;
string essentialStr;
double locX, locY;
double compliance;
string publicTransmissionRiskStr;
istringstream line;
map<Location*, int> house_hospitalID_lookup;
map<int, Location*> hospitalPtr_lookup;
while ( getline(iss, buffer) ) {
line.clear();
line.str(buffer);
//if (line >> locid >> locTypeStr >> locX >> locY) {
//if (line >> locid >> locX >> locY >> locTypeStr >> essentialStr) {
if (line >> locid >> locX >> locY >> locTypeStr >> essentialStr >> hfid) {
if (locid != (signed) _location.size()) {
cerr << "ERROR: Location ID's must be sequential integers starting at 0" << endl;
cerr << "locid vs _location.size(): " << locid << " " << _location.size() << endl;
return false;
}
const LocationType locType = (locTypeStr == "h") ? HOUSE :
(locTypeStr == "w") ? WORK :
(locTypeStr == "s") ? SCHOOL :
(locTypeStr == "hf") ? HOSPITAL :
(locTypeStr == "n") ? NURSINGHOME :
NUM_OF_LOCATION_TYPES;
if (locType == NUM_OF_LOCATION_TYPES) {
cerr << "ERROR: Parsed unknown location type: " << locTypeStr << " from location file: " << locationFilename << endl;
return false;
}
const int essential = (essentialStr == "y" or essentialStr == "NA") ? 1 :
(essentialStr == "n") ? 0 : -1;
if (essential == -1) {
cerr << "ERROR: Unknown value for \"essential\" status: " << essentialStr << " from location file: " << locationFilename << endl;
return false;
}
Location* newLoc = new Location();
newLoc->setX(locX);
newLoc->setY(locY);
newLoc->setType(locType); // may be redundant--would save 1 mb per million locations to omit, so probably not worth removing
newLoc->setEssential((bool) essential);
double xPixel = _calculatePixel(locX);
double yPixel = _calculatePixel(locY);
newLoc->setPixel(xPixel, yPixel);
_pixelMap[{xPixel, yPixel}].push_back(newLoc);
if ((line >> compliance) and compliance >= 0) { // predetermined compliance values
assert(compliance <= 1.0);
newLoc->setRiskiness(1.0 - compliance);
} else if (locType == HOUSE) { // compliance values not specified, so determined at runtime
newLoc->setRiskiness(gsl_rng_uniform(RNG));
}
PublicTransmissionType public_transmision_risk = NO_PUBLIC_TRANSMISSION;
if ((line >> publicTransmissionRiskStr) and publicTransmissionRiskStr != "N") {
public_transmision_risk = (publicTransmissionRiskStr == "H") ? HIGH_PUBLIC_TRANSMISSION :
(publicTransmissionRiskStr == "L") ? LOW_PUBLIC_TRANSMISSION :
NUM_OF_PUBLIC_TRANSMISSION_TYPES;
if (public_transmision_risk == NUM_OF_PUBLIC_TRANSMISSION_TYPES) {
cerr << "ERROR: Unknown value for \"public transmission\" status: " << publicTransmissionRiskStr << " from location file: " << locationFilename << endl;
return false;
} else if (public_transmision_risk != NO_PUBLIC_TRANSMISSION) {
_public_locations.push_back(newLoc);
}
}
newLoc->setPublicTransmissionRisk(public_transmision_risk);
_location.push_back(newLoc);
_location_map[locType].insert(newLoc);
// temp look-up structures so we can quickly map houses to their associated hospitals.
// those hospital pointers don't necessarily exist until we're done processing locations
if (locType == HOSPITAL) { hospitalPtr_lookup[newLoc->getID()] = newLoc; }
if (hfid >= 0) { house_hospitalID_lookup[newLoc] = hfid; } // true for houses, nursinghomes, maybe others in the future
}
}
iss.close();
for (const auto& kv: house_hospitalID_lookup) { kv.first->setHospital(hospitalPtr_lookup.at(kv.second)); }
iss.open(networkFilename);
if (!iss) {
cerr << "ERROR: network file " << networkFilename << " not found." << endl;
return false;
}
int locid1, locid2;
while ( getline(iss, buffer) ) {
line.clear();
line.str(buffer);
if (line >> locid1 >> locid2) { // data (non-header) line
// cerr << locid1 << " , " << locid2 << endl;
assert(locid1 >= 0 and locid2 >= 0);
assert(locid1 < (signed) _location.size() and locid2 < (signed) _location.size());
_location[locid1]->addNeighbor(_location[locid2]); // should check for ID
_location[locid2]->addNeighbor(_location[locid1]);
}
}
iss.close();
return true;
}
Person* Community::getPersonByID(int pid) {
if(pid < 0 or pid > (signed) getNumPeople()) {
cerr << "ERROR: failed to find person with id " << pid << " max: " << getNumPeople() << endl;
assert(pid > 0 and pid <= (signed) getNumPeople());
}
assert (_people[pid]->getID() == pid);
return _people[pid];
}
Location* Community::getLocationByID(int lid) {
if(lid < 0 or lid > (signed) getNumLocations()) {
cerr << "ERROR: failed to find location with id " << lid << " max: " << getNumLocations() << endl;
assert(lid > 0 and lid <= (signed) getNumLocations());
}
assert (_location[lid]->getID() == lid);
return _location[lid];
}
// infect - infects person id
Infection* Community::infect(int id, StrainType strain) {
Person* person = getPersonByID(id);
return person->infect(this, _date, strain);
}
void Community::vaccinate() {
// call vac_campaign function to dump eligible people into respective pools if possible
bool new_groups_to_add = true;
while (new_groups_to_add) {
new_groups_to_add = vac_campaign->add_new_eligible_people(_day);
}
// {
// cerr << vac_campaign->get_all_doses_available(STANDARD_ALLOCATION, _day) << " | "
// << vac_campaign->get_all_doses_available(URGENT_ALLOCATION, _day) << " | "
// << vac_campaign->get_pool_size_by_dose(vac_campaign->get_potential_vaccinees(STANDARD_QUEUE), 0) << ' '
// << vac_campaign->get_pool_size_by_dose(vac_campaign->get_potential_vaccinees(STANDARD_QUEUE), 1) << ' '
// << vac_campaign->get_pool_size_by_dose(vac_campaign->get_potential_vaccinees(STANDARD_QUEUE), 2) << " | "
// << vac_campaign->get_pool_size_by_dose(vac_campaign->get_potential_vaccinees(URGENT_QUEUE), 0) << ' '
// << vac_campaign->get_pool_size_by_dose(vac_campaign->get_potential_vaccinees(URGENT_QUEUE), 1) << ' '
// << vac_campaign->get_pool_size_by_dose(vac_campaign->get_potential_vaccinees(URGENT_QUEUE), 2) << endl;
// }
// only continue if any doses are available today
if (not vac_campaign->get_all_doses_available(_day)) { return; }
// create empty eligibility group to add new revaccinations to the queue
vector<Eligibility_Group*> urg_revaccinations = vac_campaign->init_new_eligible_groups(_day);
vector<Eligibility_Group*> std_revaccinations = vac_campaign->init_new_eligible_groups(_day);
// if doses are pooled, multinomially distribute them across dose/bin groups based on the groups' populations
// if there is no pooling, the structure will hold 0s for each std/urg dose/bin group
vector< map<int, map<int, int> > > daily_sampled_doses_available = vac_campaign->multinomially_distribute_pooled_doses(_day);
// for each age bin, dose combination, select new vaccinees until there are no more doses available
for (int dose = 0; dose < _par->numVaccineDoses; ++dose) {
for (int bin : vac_campaign->get_unique_age_bins()) {
Vaccinee* v = vac_campaign->next_vaccinee(_day, dose, bin, daily_sampled_doses_available);
// if there is pooling, vax a maximum of the num of sampled doses for this dose/bin group
// if there is no pooling, keep vaxing unitl there is no vaccinee to draw
// continue if v is valid and if pooling there are doses available
while (v) {
const Person* p = v->get_person();
if (((p->getNumVaccinations() == dose) and p->isSeroEligible() and p->isInfEligible(_day)) // not completely vaccinated & eligible
and vac_campaign->vaccinate(v, _day)) { // and person isn't dead, so got vaccinated
vac_campaign->tally_dose(_day, dose, bin, v, daily_sampled_doses_available); // tally dose used
// add people who are not fully vaccinated to proper eligible group for revaccination
if ((dose + 1) < _par->numVaccineDoses) {
vac_campaign->assign_vaccinee_for_revaccination(v, dose, bin, std_revaccinations, urg_revaccinations);
}
}
// always remove vaccinee from the pool
// either was vaccinated, or was not eliglbe to be vaccinated (fully vaxd, not sero eligible, not alive)
vac_campaign->remove_from_pool(dose, bin, v);
delete v;
v = vac_campaign->next_vaccinee(_day, dose, bin, daily_sampled_doses_available);
}
// roll over unused doses to tomorrow
// vac_campaign->rollover_unused_doses(_day, dose, bin);
// int remaining_doses = vac_campaign->get_doses_available(_day, dose, bin);
// if (remaining_doses and ((_day + 1) < (int) _par->runLength)) {
// vac_campaign->set_doses_available(_day, dose, bin, 0);
// vac_campaign->add_doses_available(_day + 1, dose, bin, remaining_doses);
// }
}
}
for (int bin : vac_campaign->get_unique_age_bins()) {
for (int dose = 0; dose < _par->numVaccineDoses; ++dose) {
// roll over unused doses to tomorrow
vac_campaign->rollover_unused_doses(_day, dose, bin);
}
}
// once all vaccinations complete, reschedule newly filled eligibility group
vac_campaign->schedule_revaccinations(urg_revaccinations, std_revaccinations);
}
vector<pair<size_t,double>> Community::getMeanNumSecondaryInfections() const {
// this is not how many secondary infections occurred on day=index,
// but how many secondary infections will ultimately be caused by each person
// who got infected on day=index
vector<vector<double>> daily_secondary_infections(_par->runLength);
for (Person* p: _people) {
for (const Infection* inf: p->getInfectionHistory()) {
const int infection_onset = inf->getInfectedTime();
if (infection_onset < 0) { continue; } // historical infection
// number of secondary infections resulting from the infection that started on this date
daily_secondary_infections[infection_onset].push_back(inf->secondary_infection_tally());
// Uncomment this to do offspring distribution/dispersion analyses
//cerr << "secondary: " << infection_onset << " " << inf->secondary_infection_tally() << endl;
}
}
vector<pair<size_t, double>> daily_Rt(daily_secondary_infections.size(), {0, 0.0});
for (size_t day = 0; day < daily_secondary_infections.size(); ++day) {
if (daily_secondary_infections[day].size()) {
daily_Rt[day] = make_pair(daily_secondary_infections[day].size(), mean(daily_secondary_infections[day]));
}
// cerr << "day, incidence, Rt: " << day << " " << daily_Rt[day].first << " " << daily_Rt[day].second << endl;
}
return daily_Rt;
}
void Community::reportCase(int onsetDate, long int reportDate, bool hospitalized) { // long int b/c reportDate can be a bit greater than max int
assert(onsetDate >= 0);
assert(reportDate >= 0);
// onset == sample collection date; FL doesn't report when symptoms began
if ((unsigned) onsetDate < cmty_ledger->_numDetectedCasesOnset.size()) { cmty_ledger->_numDetectedCasesOnset[onsetDate]++; }
if ((unsigned) reportDate < cmty_ledger->_numDetectedCasesReport.size()) {
cmty_ledger->_numDetectedCasesReport[reportDate]++;
// it's not clear exactly how to interpret the date on which the state reports a hospitalization
if (hospitalized) { cmty_ledger->_numDetectedHospitalizations[reportDate]++; }
}
}
//void Community::reportDeath(int /*eventDate*/, long int reportDate) {
// assert(reportDate >= 0);
// if ((unsigned) reportDate < _numDetectedDeaths.size()) _numDetectedDeaths[reportDate]++;
//}
void Community::reportDeath(int onsetDate, long int reportDate) {
assert(onsetDate >= 0);
assert(reportDate >= 0);
if ((unsigned) onsetDate < cmty_ledger->_numDetectedDeathsOnset.size()) { cmty_ledger->_numDetectedDeathsOnset[onsetDate]++; }
if ((unsigned) reportDate < cmty_ledger->_numDetectedDeathsReport.size()) { cmty_ledger->_numDetectedDeathsReport[reportDate]++; }
}
void Community::updatePersonStatus() {
// TODO - add support for all disease outcomes
for (Person* p: _people) {
Location* day_loc = p->getDayLoc();
if (p->inHospital(_day)) {
if (p->getHospitalizedTime()==_day) {
// health care employees may already be at the facility where they would receive treatment
if (day_loc != p->getHospital()) { p->goToHospital(); }
}
} else if (_day > 0 and p->inHospital(_day - 1)) { // they were in hospital yeserday, but no longer
if (day_loc != p->getHospital()) { p->leaveHospital(); }
}
if (p->isSurveilledPerson()) {
if (p->getNumNaturalInfections() == 0) {
continue; // no infection/outcomes to tally
} else {
// the methods used with Infection below generally are available for Person, but this should be faster
const Infection* inf = p->getInfection();
if (inf->getInfectedTime()==_day) {
cmty_ledger->_numNewlyInfected[_day]++;
cmty_ledger->_numNewInfectionsByStrain.at(inf->getStrain())[_day]++;
}
if (inf->getSymptomTime()==_day) { // started showing symptoms today
cmty_ledger->_numNewlySymptomatic[_day]++;
if (p->isVaccinated()) { cmty_ledger->_numVaccinatedCases[_day]++; }
}
if (inf->isSevere(_day)) { cmty_ledger->_numSeverePrev[_day]++; }
if (inf->inHospital(_day)) {
cmty_ledger->_numHospPrev[_day]++;
if (inf->getHospitalizedTime()==_day) {
cmty_ledger->_numHospInc[_day]++;
}
if (inf->inIcu(_day)) {
cmty_ledger->_numIcuPrev[_day]++;
if (inf->getIcuTime()==_day) {
cmty_ledger->_numIcuInc[_day]++;
}
}
}
if (inf->getSevereTime()==_day) { cmty_ledger->_numNewlySevere[_day]++; }
if (inf->getCriticalTime()==_day) { cmty_ledger->_numNewlyCritical[_day]++; }
if (p->isNewlyDead(_day)) { cmty_ledger->_numNewlyDead[_day]++; }
/*if (p->getWithdrawnTime()==_day) { // started withdrawing
p->getLocation(HOME_MORNING)->addPerson(p,WORK_DAY); // stays at home at mid-day
p->getLocation(WORK_DAY)->removePerson(p,WORK_DAY); // does not go to work
} else if (p->isWithdrawn(_day-1) and
p->getRecoveryTime()==_day) { // just stopped withdrawing
p->getLocation(WORK_DAY)->addPerson(p,WORK_DAY); // goes back to work
p->getLocation(HOME_MORNING)->removePerson(p,WORK_DAY); // stops staying at home
}*/
}
}
}
return;
}
// void Community::tallyInfectionsByLoc() {
// for (Person* p: _people) {
// if (p->isSurveilledPerson()) {
// if (p->getNumNaturalInfections() == 0) {
// continue; // no infection/outcomes to tally
// } else {
// // the methods used with Infection below generally are available for Person, but this should be faster
// const Infection* inf = p->getInfection();
// if (inf->getInfectedTime()==_day) {
// if (inf->getInfectedPlace()) {
// Location* inf_loc = inf->getInfectedPlace();
// LocationType inf_lt = inf->getInfectedPlace()->getType();
//
// switch (inf_lt) {
// case HOUSE:
// if (inf_loc == p->getHomeLoc()) { _numNewlyInfectedByLoc["home"][_day]++; }
// else { _numNewlyInfectedByLoc["social"][_day]++; }
// break;
// case WORK:
// if (inf_loc == p->getDayLoc()) { _numNewlyInfectedByLoc["work_staff"][_day]++; }
// else { _numNewlyInfectedByLoc["patron"][_day]++; }
// break;
// case SCHOOL:
// if (p->getAge() > 18) { _numNewlyInfectedByLoc["school_staff"][_day]++; }
// else { _numNewlyInfectedByLoc["student"][_day]++; }
// break;
// case HOSPITAL:
// if (inf_loc == p->getDayLoc()) { _numNewlyInfectedByLoc["hcw"][_day]++; }
// else { _numNewlyInfectedByLoc["patient"][_day]++; }
// break;
// case NURSINGHOME:
// if (inf_loc == p->getDayLoc()) { _numNewlyInfectedByLoc["ltcf_staff"][_day]++; }
// else { _numNewlyInfectedByLoc["ltcf_resident"][_day]++; }
// break;
// default:
// break;
// }
// }
// }
// }
// }
// }
// }
void Community::flagInfectedLocation(Person* person, double relInfectiousness, LocationType locType, Location* _pLoc, int day) {
assert(day >= 0);
if ((unsigned) day < _par->runLength) cmty_ledger->_isHot[day][locType][_pLoc][relInfectiousness].push_back(person);
}
//vector<double> trans_type(3, 0.0); // asymptomatic, presymptomatic, symptomatic, for logging transmission type
Infection* Community::trace_contact(Person* &infecter, Location* source_loc, const map<double, vector<Person*>> &infectious_groups) {
// Identify who was the source of an exposure event (tracing backward)
// First we determine which group did the infecting (grouped by infectiousness),
// then we choose the person within the group who is the infecter
vector<double> relInfectiousnessValues;
vector<double> group_weights;
double total = 0.0;
for (const auto& [relInfectiousness, people]: infectious_groups) {
relInfectiousnessValues.push_back(relInfectiousness);
const double group_weight = relInfectiousness * people.size();
total += group_weight;
group_weights.push_back(group_weight);
}
size_t group_idx = weighted_choice(RNG, group_weights);
infecter = uniform_choice(RNG, infectious_groups.at(relInfectiousnessValues[group_idx]));
// sanity check to make sure we've found a legit candidate
const vector<Person*> people = source_loc->getPeople();
//assert(infecter->isInfectious(_day)
// and (not infecter->inHospital(_day) or (source_loc->getType() == HOSPITAL and source_loc == infecter->getHospital()))
// and not infecter->isDead(_day)
// and find(people.begin(), people.end(), infecter) != people.end());
assert(infecter->isInfectious(_day));
assert((not infecter->inHospital(_day) or (source_loc->getType() == HOSPITAL and source_loc == infecter->getHospital())));
assert(not infecter->isDead(_day));
assert((find(people.begin(), people.end(), infecter) != people.end()) or
(find(infecter->getPatronizedLocations().begin(), infecter->getPatronizedLocations().end(), source_loc) != infecter->getPatronizedLocations().end()));
return infecter->getInfection();
}
double Community::social_distancing(int _day) {
return cmty_ledger->_timedInterventions[SOCIAL_DISTANCING][_day];
}
double _tally_infectiousness (const map<double, vector<Person*>> infectious_groups) {
double infectious_weight = 0.0;
for (const auto& [relInfectiousness, people]: infectious_groups) {
infectious_weight += relInfectiousness * people.size();
}
return infectious_weight;
}
void Community::within_household_transmission() {
for (const auto& [loc, infectious_groups]: cmty_ledger->_isHot[_day][HOUSE]) {
const double infectious_weight = _tally_infectiousness(infectious_groups);
const double hazard = _par->household_transmission_haz_mult * _par->seasonality_on(_date) * infectious_weight;
const double T = 1.0 - exp(-hazard);
_transmission(loc, loc->getPeople(), infectious_groups, T);
}
return;
}
void Community::between_household_transmission() {
for (const auto& [loc, infectious_groups]: cmty_ledger->_isHot[_day][HOUSE]) {
const double infectious_weight = _tally_infectiousness(infectious_groups);
// ↓↓↓ this model made it almost impossible to stop transmission using SD
//if (social_distancing(_day) - loc->getRiskiness() < gsl_rng_uniform(RNG)) { // this household is not cautious enough to avoid interactions
// if people are riskier than the current SD level, they interact with friends
// if they are less risky than current SD, they may do so, depending on how much more cautious they are
// ↓↓↓ this household is not cautious enough to avoid interactions
if (loc->getRiskiness() > social_distancing(_day)) {
const int hh_size = loc->getNumPeople();
for (Location* neighbor: loc->getNeighbors()) {
// ↓↓↓ this line needs to match the model above, with neighbor in for loc
if (neighbor->getRiskiness() > social_distancing(_day)) {
const double hazard = _par->social_transmission_haz_mult * _par->seasonality_on(_date) * infectious_weight / hh_size;
const double T = 1.0 - exp(-hazard);
_transmission(loc, neighbor->getPeople(), infectious_groups, T);
}
}
}
}
return;
}
void Community::workplace_transmission() {
// Transmission for school employees is considered school transmission, not workplace transmission
// This includes all other employees, as well as consumer visits to restaurants, bars, retail locations, and religious facilities
for (const auto& [loc, infectious_groups]: cmty_ledger->_isHot[_day][WORK]) {
// if non-essential businesses are closed, skip this workplace
const int workplace_size = loc->getNumPeople() + loc->getNumVisitors();
if (workplace_size < 2 or (loc->isNonEssential() and cmty_ledger->_timedInterventions[NONESSENTIAL_BUSINESS_CLOSURE][_day])) {
continue;
}
const double infectious_weight = _tally_infectiousness(infectious_groups);
const PublicTransmissionType pt_risk = loc->getPublicTransmissionRisk();
const double high_pt_risk_haz_mult = 4.0;
const double norm_pt_risk_haz_mult = 0.25;
if (infectious_weight > 0) {
const double hazard = _par->workplace_transmission_haz_mult
// TODO -- see if we can find a way to motivate how much more risky high risk places are
// TODO -- check to see if high risk places actually are causing 4x as much transmission as other workplaces
//* (pt_risk == HIGH_PUBLIC_TRANSMISSION ? 4.0 : (1.0 - social_distancing(_day))*0.25) // 4.0 and 0.25 b/c/ of 80/20 rule
* (pt_risk == HIGH_PUBLIC_TRANSMISSION ? high_pt_risk_haz_mult : norm_pt_risk_haz_mult) // 4.0 and 0.25 b/c/ of 80/20 rule
* _par->seasonality_on(_date)
* infectious_weight/(workplace_size - 1.0);
const double T = 1.0 - exp(-hazard);
vector<Person*> all_people = loc->getVisitors();
const vector<Person*> workers = loc->getPeople();
all_people.insert( all_people.end(), workers.begin(), workers.end() );
_transmission(loc, all_people, infectious_groups, T);
}
}
return;
}
void Community::school_transmission() {
// Transmission for school employees is considered school transmission, not workplace transmission
const double hazard_coef = (1.0 - cmty_ledger->_timedInterventions[SCHOOL_CLOSURE][_day]) * _par->school_transmission_haz_mult * _par->seasonality_on(_date);
if (hazard_coef != 0.0) {
for (const auto& [loc, infectious_groups]: cmty_ledger->_isHot[_day][SCHOOL]) {
const int school_size = loc->getNumPeople();
if (school_size < 2) { continue; }
const double infectious_weight = _tally_infectiousness(infectious_groups);
const double hazard = hazard_coef * infectious_weight/(school_size - 1.0);
const double T = 1.0 - exp(-hazard);
_transmission(loc, loc->getPeople(), infectious_groups, T);
}
}
return;
}
void Community::hospital_transmission() {
for (const auto& [loc, infectious_groups]: cmty_ledger->_isHot[_day][HOSPITAL]) {
const int hospital_census = loc->getNumPeople(); // workers + patients
if (hospital_census < 2) { continue; }
const double infectious_weight = _tally_infectiousness(infectious_groups);
const double hazard = _par->hospital_transmission_haz_mult * _par->seasonality_on(_date) * infectious_weight/(hospital_census - 1.0);
const double T = 1.0 - exp(-hazard);
_transmission(loc, loc->getPeople(), infectious_groups, T);
}
return;
}
/*
generic_location_transmission(_isHot[_day][HOSPITAL], _par->hospital_transmissibility * _par->seasonality_on(_date));
TODO - switch to this?
void Community::generic_location_transmission(const auto& hot_location_type_data, const double base_T) {
for (const auto& [loc, infectious_groups]: hot_location_type_data) {
const int census = loc->getNumPeople(); // workers + patients
if (census < 2) { continue; }
const double infectious_weight = _tally_infectiousness(infectious_groups);
const double hazard = base_T * infectious_weight/(census - 1.0);
const double T = 1.0 - exp(-hazard);
_transmission(loc, loc->getPeople(), infectious_groups, T);
}
return;
}*/
void Community::nursinghome_transmission() {
for (const auto& [loc, infectious_groups]: cmty_ledger->_isHot[_day][NURSINGHOME]) {
const int nursinghome_census = loc->getNumPeople(); // workers + residents
if (nursinghome_census < 2) { continue; }
const double infectious_weight = _tally_infectiousness(infectious_groups);
const double hazard = _par->nursinghome_transmission_haz_mult * _par->seasonality_on(_date) * infectious_weight/(nursinghome_census - 1.0);
const double T = 1.0 - exp(-hazard);
_transmission(loc, loc->getPeople(), infectious_groups, T);
}
return;
}
void Community::_transmission(Location* source_loc, vector<Person*> at_risk_group, const map<double, vector<Person*>> &infectious_groups, const double T) {
const bool check_susceptibility = true;
for (Person* p: at_risk_group) {
// skip transmission for this person if they are self-quarantining unless it is within their home
if (p->isQuarantining(_date->day()) and not (source_loc == p->getHomeLoc())) { continue; }
if (gsl_rng_uniform(RNG) < T) {
Person* infecter = nullptr;
Infection* source_infection = nullptr;
// because we now support multiple strains, we always have to trace, in order to determine what the infecting strain would be
source_infection = trace_contact(infecter, source_loc, infectious_groups);
// infect() tests for whether person is infectable
Infection* transmission = p->infect(this, infecter, _date, source_loc, source_infection->getStrain(), check_susceptibility);
if (source_infection and transmission) {
source_infection->log_transmission(transmission);
// for logging transmission type
// if (infecter->isSymptomatic(_day)) {
// trans_type[2]++;
// } else if (infecter->getInfection()->symptomatic()) {
// trans_type[1]++;
// } else {
// trans_type[0]++;
// }
} // did we contact trace, and did transmission occur?
}
}
}
void Community::updateHotLocations() {
for (size_t locType = 0; locType < NUM_OF_LOCATION_TYPES; ++locType) {