-
Notifications
You must be signed in to change notification settings - Fork 54
/
update_prevalence.py
executable file
·2055 lines (1738 loc) · 83.5 KB
/
update_prevalence.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
#!/usr/bin/env python3
import sys
if sys.version_info < (3, 6):
sys.exit("This script requires Python 3.6 or later.")
import abc
import collections
import csv
from dataclasses import dataclass
from functools import reduce
import json
import logging
import re
import os
import shutil
from datetime import date, datetime, timedelta
from operator import attrgetter
from pathlib import Path
from time import sleep
from typing import (
Optional,
ClassVar,
Iterator,
List,
Dict,
Generator,
Tuple,
Type,
TypeVar,
Any,
Union,
TypedDict,
Counter,
Iterable,
Literal,
)
from us_state_abbrev import us_state_name_by_abbrev
try:
import pydantic
import requests
import sentry_sdk
from sentry_sdk.integrations.logging import LoggingIntegration
except ImportError:
print("Virtual environment not set up correctly.")
print("Run:")
print(" python3 -m venv .venv")
print(" source .venv/bin/activate")
print(" pip install -r requirements-manual.txt")
print("and then try running this script again.")
print()
raise
logger = logging.getLogger("update_prevalence")
class LogAggregator:
population_affected_by_issue: Dict[str, int] = {}
def add_issue(self, msg: str, place: "PopulationFilteredLogging", *, impact: float = 1.0) -> None:
existing_population = self.population_affected_by_issue.get(msg, 0)
self.population_affected_by_issue[msg] = int(existing_population + place.population_as_int * impact)
def log(self) -> None:
for msg in self.population_affected_by_issue:
population_affected = self.population_affected_by_issue[msg]
level = logging.WARNING
if population_affected < 10000:
level = logging.DEBUG
elif population_affected < 100000:
level = logging.INFO
logger.log(level, f"{population_affected:,d} people affected by {msg}")
log_aggregator = LogAggregator()
class PopulationFilteredLogging(abc.ABC):
@property
@abc.abstractmethod
def population_as_int(self) -> int:
...
def issue(self, category: str, detail: str, *, impact: float = 1.0) -> None:
log_aggregator.add_issue(category, self, impact=impact)
logger.info(f"{category} ({self.population_as_int:,d} people): {detail}")
class ExtraWarningAnnotationFormatter(logging.Formatter):
def __init__(self) -> None:
super().__init__("%(message)s")
def format(self, record: logging.LogRecord) -> str:
s = super().format(record)
if record.levelno >= logging.WARNING:
s = f"{record.levelname}: {s}"
return s
def configure_logging() -> None:
#
# Configure logging so we can treat filter messages from this script
# separately from those from libraries
#
# https://docs.python.org/3/howto/logging.html
logger.setLevel(logging.DEBUG)
#
# Configure how things appear on stdout separately from how sentry
# backend treats things
#
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
# don't decorate messages for readability on console
formatter = ExtraWarningAnnotationFormatter()
ch.setFormatter(formatter)
# use this formatting for all logging; set it on the root handler
logging.getLogger().addHandler(ch)
sentry_logging = LoggingIntegration(
level=logging.WARNING, # Capture warning and above as breadcrumbs
event_level=logging.WARNING, # Send warnings as events
)
if os.environ.get("DAILY_RUN"):
# https://docs.sentry.io/platforms/python/guides/logging/
# https://getsentry.github.io/sentry-python/integrations.html#module-sentry_sdk.integrations.logging
sentry_sdk.init(
dsn="https://2f4e0fbfce7d40b8a0bf134a3c42a716@o4504284257255424.ingest.sentry.io/4504305860804608",
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for performance monitoring.
# We recommend adjusting this value in production.
traces_sample_rate=1.0,
integrations=[sentry_logging],
)
# set which level of logging will also be sent to sentry
sentry_sdk.set_level("warning")
CAN_API_KEY = os.environ.get("CAN_API_KEY")
Model = TypeVar("Model", bound=pydantic.BaseModel)
def print_and_log_to_sentry(message: str) -> None:
logger.warning(message)
@dataclass
class DateSpan:
first_date: date
last_date: date
def __iter__(self) -> Iterator[date]:
num_days = (self.last_date - self.first_date).days + 1
return (self.first_date + timedelta(days=x) for x in range(0, num_days))
@staticmethod
def history_from(last_date: date, total_num_days: int) -> "DateSpan":
first_date = last_date - timedelta(days=(total_num_days - 1))
return DateSpan(first_date=first_date, last_date=last_date)
def calc_effective_date() -> date:
now = datetime.utcnow() - timedelta(days=1)
# JHU daily reports are posted between 04:45 and 05:15 UTC the next day
if now.hour < 6:
now -= timedelta(days=1)
return now.date()
effective_date = calc_effective_date()
def calc_last_two_weeks_evaluation_range() -> DateSpan:
# Upstream data sources offer cumulative case counts for different
# places.
#
# To translate these to the number of cases in the last week and
# the week before that, we need to collect data points for two
# weeks, plus the day before that two week period starts as a
# baseline value.
#
# https://www.microcovid.org/paper/7-basic-method
#
# 7 for the current week
# 7 for the week before
# 1 more to compare numbers from the day before the week before
num_days_of_history = 15
return DateSpan.history_from(effective_date, num_days_of_history)
last_two_weeks_evaluation_range = calc_last_two_weeks_evaluation_range()
def calc_last_month_evaluation_range() -> DateSpan:
return DateSpan.history_from(effective_date - timedelta(days=30), 1)
last_month_evaluation_range = calc_last_month_evaluation_range()
# The list of DateSpans used to determine which dates
# Place#cumulative_cases should contain when we're done
def calc_cumulative_cases_evaluation_ranges() -> List[DateSpan]:
return [last_month_evaluation_range, last_two_weeks_evaluation_range]
cumulative_cases_evaluation_ranges = calc_cumulative_cases_evaluation_ranges()
# Read the Risk Tracker's vaccine table.
# Format:
# Type,0 dose,1 dose,2 dose
def import_vaccine_multipliers() -> Dict[str, Dict[str, float]]:
vaccines = {}
with open("./public/tracker/vaccine_table.csv", newline="") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
vaccine_name = row[0]
if vaccine_name in ["No Vaccine", "Unknown vaccine, unknown date"]:
continue
if vaccine_name == "Johnson & Johnson":
# JHU dataset uses 'Janssen' for this vaccine.
vaccine_name = "Janssen"
elif vaccine_name == "AstraZenica":
# AstraZenEca is mispelled in the csv. Can't change it without
# breaking the risk tracker.
vaccine_name = "AstraZeneca"
vaccines[vaccine_name] = {
"partial": float(row[2]),
"complete": float(row[3]),
}
vaccines["Unknown"] = vaccines["AstraZeneca"]
return vaccines
VACCINE_MULTIPLIERS = import_vaccine_multipliers()
# Johns Hopkins dataset
class JHUCommonFields(pydantic.BaseModel):
FIPS: Optional[int]
Admin2: Optional[str]
Province_State: Optional[str]
Country_Region: str
Lat: Optional[float]
Long_: Optional[float]
Combined_Key: str
class JHUPlaceFacts(JHUCommonFields):
SOURCE: ClassVar[
str
] = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/UID_ISO_FIPS_LookUp_Table.csv"
UID: int
iso2: str
iso3: str
code3: Optional[int]
Population: Optional[int]
class JHUDailyReport(JHUCommonFields):
SOURCE: ClassVar[
str
] = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/%m-%d-%Y.csv"
# Last_Update: datetime, but not always in consistent format - we ignore
Confirmed: int
Deaths: int
Recovered: Optional[int]
Active: Optional[int]
# Incident_Rate: float, was renamed from Incidence_Rate in early November
# Case_Fatality_Ratio: float
class JHUCasesTimeseriesUS(JHUCommonFields):
SOURCE: ClassVar[
str
] = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv"
UID: int
iso2: str
iso3: str
code3: int
cumulative_cases: Dict[date, int] = {}
class JHUCasesTimeseriesGlobal(pydantic.BaseModel):
SOURCE: ClassVar[
str
] = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"
Province_State: Optional[str]
Country_Region: str
Lat: float
Long: float
cumulative_cases: Dict[date, int] = {}
class JHUVaccinesTimeseriesUS(pydantic.BaseModel):
SOURCE: ClassVar[
str
] = "https://raw.githubusercontent.com/govex/COVID-19/master/data_tables/vaccine_data/us_data/time_series/time_series_covid19_vaccine_us.csv"
# Data collection date
Date: date
# Name of the state
Province_State: str
# Name of the country (US)
Country_Region: Literal["US"]
# Cumulative number of doses administered including booster doses
# for states where it is reported as part of the total.
Doses_admin: Optional[int]
# Cumulative number of people who received at least one vaccine
# dose. When the person receives a prescribed second dose it is
# not counted twice
People_at_least_one_dose: Optional[int]
# Cumulative number of people who received a complete primary
# series. This means having received one dose of a single-dose
# vaccine or two doses on different days (regardless of time
# interval) of either a mRNA or a protein-based series. When the
# vaccine manufacturer is not reported the recipient is considered
# fully vaccinated with two doses.
People_fully_vaccinated: Optional[int]
# Cumulative number of all the additional or booster doses
# administered. This metric does not reflect individual people and
# each dose is counted independently
Total_additional_doses: Optional[int]
class JHUVaccinesTimeseriesGlobal(pydantic.BaseModel):
SOURCE: ClassVar[
str
] = "https://raw.githubusercontent.com/govex/COVID-19/master/data_tables/vaccine_data/global_data/time_series_covid19_vaccine_global.csv"
# Data collection date
Date: date
# Country code:
# https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/UID_ISO_FIPS_LookUp_Table.csv
UID: Optional[int]
# Province or State name
Province_State: Optional[str]
# Country or region name
Country_Region: str
# Cumulative number of doses administered. When a vaccine requires
# multiple doses, each one is counted independently
Doses_admin: Optional[int]
# Cumulative number of people who received at least one vaccine
# dose. When the person receives a prescribed second dose, it is
# not counted twice
People_at_least_one_dose: Optional[int]
# Our World in Data dataset:
class OWIDTestingData(pydantic.BaseModel):
# https://ourworldindata.org/coronavirus-testing#download-the-data
SOURCE: ClassVar[
str
] = "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/testing/covid-testing-all-observations.csv"
Entity: str
Date: date
ISO_code: str
Source_URL: str
Source_label: str
Notes: str
Daily_change_in_cumulative_total: Optional[int] # new tests today
Cumulative_total: Optional[int]
Cumulative_total_per_thousand: Optional[float] # "per thousand" means population
Daily_change_in_cumulative_total_per_thousand: Optional[float]
Seven_day_smoothed_daily_change: Optional[float] # 7-day moving average
Seven_day_smoothed_daily_change_per_thousand: Optional[float]
Short_term_tests_per_case: Optional[float] # appears to also be 7-day
Short_term_positive_rate: Optional[float]
# CovidActNow dataset:
class CANMetrics(pydantic.BaseModel):
testPositivityRatio: Optional[float] # 7-day rolling average
caseDensity: Optional[float] # cases per 100k pop, 7-day rolling average
class CANActuals(pydantic.BaseModel):
vaccinationsInitiated: Optional[int] # Raw numbers of people vaccinated
vaccinationsCompleted: Optional[int]
class CANRegionSummary(pydantic.BaseModel):
# https://github.com/covid-projections/covid-data-model/blob/master/api/README.V1.md#RegionSummary
COUNTY_SOURCE: ClassVar[str] = f"https://api.covidactnow.org/v2/counties.json?apiKey={CAN_API_KEY}"
STATE_SOURCE: ClassVar[str] = f"https://api.covidactnow.org/v2/states.json?apiKey={CAN_API_KEY}"
country: str
fips: int
lat: Optional[float]
long_: Optional[float] = pydantic.Field(alias="long")
state: str
county: Optional[str]
# lastUpdatedDate: datetime in nonstandard format, ignored for now
# projections: ignored
actuals: Optional[CANActuals]
metrics: Optional[CANMetrics]
population: int
# Romanian sub-national dataset:
class RomaniaPrevalenceData(pydantic.BaseModel):
SOURCE: ClassVar[
str
] = "https://covid19.geo-spatial.org/external/charts_vasile/assets/json/cazuri_zile_long.json"
Date: date = pydantic.Field(alias="Data")
County: str = pydantic.Field(alias="Judet")
Population: str = pydantic.Field(alias="Populatie")
TotalCases: int = pydantic.Field(alias="Cazuri total")
# Covid Timeline Canada region info dataset:
class CovidTimelineCanadaRegion(pydantic.BaseModel):
SOURCE: ClassVar[str] = "https://raw.githubusercontent.com/ccodwg/CovidTimelineCanada/main/geo/hr.csv"
# two letter province/territory - e.g. AB
region: str
# numeric health region ID - e.g. 4831
hruid: int
# brief health region name - e.g. South
name_short: str
# number of people who live in health region as of last count - e.g. 308346
pop: int
# Canada Health Region cases dataset:
class CanadaOpenCovidCases(pydantic.BaseModel):
SOURCE: ClassVar[
str
] = "https://api.opencovid.ca/timeseries?stat=cases&loc={hr_uid}&geo=hr&ymd=true&fill=true&before={before}&after={after}"
class Data(pydantic.BaseModel):
class Report(pydantic.BaseModel):
# type of reporting returned - always "cases" - with
# Literal type, pydantic will validate that we got only
# cases reports back
name: Literal["cases"]
# date of report - e.g. "2022-05-08"
date: date
# cumulative cases - e.g. 4744
value: int
# cases on this day - e.g. 6
value_daily: int
cases: List[Report]
data: Data
class CovidTimelineCanadaProvinceOrTerritory(pydantic.BaseModel):
SOURCE: ClassVar[str] = "https://raw.githubusercontent.com/ccodwg/CovidTimelineCanada/main/geo/pt.csv"
region: str # PE
name_ccodwg: str # PEI
name_canonical: str # Prince Edward Island
# Canada provincial case and test data
class CanadaOpenCovidProvincialSummary(pydantic.BaseModel):
SOURCE: ClassVar[
str
] = "https://api.opencovid.ca/summary?loc={province}&ymd=true&before={before}&after={after}"
class Report(pydantic.BaseModel):
cases: int
# number of total tests given cumulatively - e.g. 9129
tests_completed: int
# number of tests given on this date - e.g. 0
tests_completed_daily: int
# Note that in Canada it is common for people to have mixed
# shots (e.g. first shot Pfizer second shot Moderna).
# cumulative number of people who have had at least one shot - e.g. 36267
vaccine_administration_dose_1: int
# cumulative number of people who have had at least two shots - e.g. 34945
vaccine_administration_dose_2: int
date_: date = pydantic.Field(alias="date")
data: List[Report]
# Canada Health Region vaccination dataset:
class CanadaRegionalVaccinationReports(pydantic.BaseModel):
SOURCE: ClassVar[
str
] = "https://api.covid19tracker.ca/reports/regions/{hr_uid}?fill_dates=true&after={after}&before={before}"
class Report(pydantic.BaseModel):
date_: date = pydantic.Field(alias="date")
# number of shots administered - e.g. 92155
total_vaccinations: Optional[int]
# number of people who have completed all shots - e.g. 35206
total_vaccinated: Optional[int]
hr_uid: int
last_updated: datetime
data: List[Report]
class CanadaVaccineDistribution(pydantic.BaseModel):
SOURCE: ClassVar[str] = "https://api.covid19tracker.ca/vaccines/distribution/split"
# no qualifier: distributed
# administered: total number of doses given including both first and second
# doses
class Data(pydantic.BaseModel):
province: str # 2-letter abbrev
pfizer_biontech: Optional[int]
pfizer_biontech_administered: Optional[int]
moderna: Optional[int]
moderna_administered: Optional[int]
astrazeneca: Optional[int]
astrazeneca_administered: Optional[int]
johnson: Optional[int]
johnson_administered: Optional[int]
data: List[Data]
# Represents number of people vaccinated.
class Vaccination(pydantic.BaseModel):
partial_vaccinations: int = 0
completed_vaccinations: int = 0
# Our unified representation:
class Place(pydantic.BaseModel, PopulationFilteredLogging):
fullname: str # "San Francisco, California, US"
name: str # "San Francisco"
population: int = 0 # 881549
test_positivity_rate: Optional[float] # 0.05
cumulative_cases: Counter[date] = collections.Counter()
# For some international data we don't get the positivity rate,
# just the number of tests. We can approximate positivity rate
# from that and the known number of cases.
tests_in_past_week: Optional[int]
vaccines_by_type: Optional[Dict[str, Vaccination]]
vaccines_total = Vaccination()
@property
def population_as_int(self) -> int:
return self.population
@property
def recent_daily_cumulative_cases(self) -> List[int]:
"""Returns a list whose last entry is the most recent day's
cumulative case count, and earlier entries are earlier days' counts.
So recent_daily_cumulative_cases[-5] is the total number of cases reported
up to 5 days ago.
"""
daily_cumulative_cases: List[int] = []
for current in reversed(list(last_two_weeks_evaluation_range)):
if current not in self.cumulative_cases:
raise ValueError(
f"Missing data for {self.fullname} on {current:%Y-%m-%d} - {self.cumulative_cases}"
)
daily_cumulative_cases.append(self.cumulative_cases[current])
return daily_cumulative_cases[::-1]
# Makes an estimate of the number of new cases in a slice of daily cumulative
# cases. Nominally is values[-1] - values[0], but sometimes regions post
# corrections which result in the number of cases decreasing.
def cases_in_cum_cases(self, values: List[int]) -> int:
# list of indices right before negative corrections. If values = [3,2,3,0,5],
# then negative_corrections == [0, 2]
negative_corrections = [i for i, val in enumerate(values[:-1]) if val > values[i + 1]]
corrections_within_bounds = min(values) == values[0] and max(values) == values[-1]
if len(negative_corrections) == 0 or corrections_within_bounds:
return values[-1] - values[0]
# Always use values[-1] rather than max(values) because max(values) is
# either values[-1] or there's been a negative correction that should be examined.
if min(values[:-1]) <= values[-1]:
possibly_suspect_correction = False
for correction_index in negative_corrections:
value_before_correction = values[correction_index]
value_correction = values[correction_index + 1]
value_after_correction = (
None if correction_index + 2 >= len(values) else values[correction_index + 2]
)
if value_after_correction is not None:
correction_size = value_before_correction - value_correction # flipped
change_without_correction = value_after_correction - value_before_correction
# arbitrary heuristic to look for cases where the negative correction
# itself might be the data that's wrong. Warn if:
# * removing the negative correction would create usable
# monotonically nondecreasing data,
# * the correction is substantial (more than 5 people) and
# * the correction is proportionally much larger than the change
# ignoring the correction
if value_before_correction <= value_after_correction and correction_size > max(
5, 3 * change_without_correction
):
possibly_suspect_correction = True
break
if values[0] > min(values[:-1]) and possibly_suspect_correction:
self.issue(
"Negative correction is suspect",
f"Check numbers manually for {self.fullname}. {len(negative_corrections)} negative cumulative case corrections {negative_corrections}, values={values}",
)
if min(values[:-1]) == values[-1] and max(values) > values[-1]:
self.issue(
"Endpoints say no new cases and max(values) says new cases",
f"check numbers manually for {self.fullname}. {len(negative_corrections)} negative cumulative case corrections {negative_corrections}, values={values}, discrepancy {max(values) - values[-1]}",
)
return values[-1] - min(values[:-1])
# looks complicated. Print a warning.
self.issue(
"Decreasing cumulative case counts.",
f"Assuming no cases for {self.fullname}. {len(negative_corrections)} negative cumulative case corrections {negative_corrections}, values={values}",
)
return 0
@property
def cases_last_month_rough(self) -> int:
return (
self.cumulative_cases[effective_date]
- self.cumulative_cases[last_month_evaluation_range.first_date]
)
@property
def cases_last_week(self) -> int:
# len([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16][-8:]) == 8
# [9, 10, 11, 12, 13, 14, 15, 16]
last_week = self.recent_daily_cumulative_cases[-8:]
assert len(last_week) == 8
return self.cases_in_cum_cases(last_week)
@property
def cases_week_before(self) -> int:
# len([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16][-15:-7]) == 8
# [2, 3, 4, 5, 6, 7, 8, 9]
week_before = self.recent_daily_cumulative_cases[-15:-7]
assert len(week_before) == 8
return self.cases_in_cum_cases(week_before)
@property
def updatedAt(self) -> date:
cases_from_effective_date_on = self.recent_daily_cumulative_cases[::-1]
last_num_cases = cases_from_effective_date_on[0]
for i in range(len(cases_from_effective_date_on)):
if cases_from_effective_date_on[i] != last_num_cases:
return effective_date - timedelta(days=(i - 1))
last_num_cases = cases_from_effective_date_on[i]
return effective_date - timedelta(days=len(cases_from_effective_date_on))
@property
@abc.abstractmethod
def app_key(self) -> str:
...
def set_total_vaccines(
self, partial_vaccinations: Optional[int], complete_vaccinations: Optional[int]
) -> None:
if partial_vaccinations is None or complete_vaccinations is None:
return
self.vaccines_total.partial_vaccinations = partial_vaccinations
self.vaccines_total.completed_vaccinations = complete_vaccinations
def set_vaccines_of_type(
self, vaccine_type: str, partial: Optional[int], complete: Optional[int]
) -> None:
if partial is None or complete is None:
return
if self.vaccines_by_type is None:
self.vaccines_by_type = {}
self.vaccines_by_type[vaccine_type] = Vaccination()
self.vaccines_by_type[vaccine_type].partial_vaccinations = partial
self.vaccines_by_type[vaccine_type].completed_vaccinations = complete
def completed_vaccination_total(self) -> int:
if self.vaccines_by_type is not None:
return reduce(
lambda x, key: x + self.vaccines_by_type[key].completed_vaccinations, self.vaccines_by_type, 0 # type: ignore
)
return self.vaccines_total.completed_vaccinations
def partial_vaccination_total(self) -> int:
if self.vaccines_by_type is not None:
return reduce(
lambda x, key: x + self.vaccines_by_type[key].partial_vaccinations, self.vaccines_by_type, 0 # type: ignore
)
return self.vaccines_total.partial_vaccinations
# Compute estimated risk ratio for an unvaccinated person vs an average person,
# so that we can convert average risk (which we know from prevalence data) to
# unvaccinated risk if we have sufficiently detailed vaccination information.
#
# Define risk_sum to be
# sum(multiplier_from_vaccination_status) over the entire population
# where the multiplier from being unvaccinated is 1 and the multiplier from
# being vaccinated with e.g. 1 dose of Pfizer is determined from vaccine_table.csv.
#
# risk_sum / population will then be the average vaccine multiplier across the
# entire population, including unvaccinated individuals.
#
# Note that if absolutely nobody were vaccinated, the average vaccine multiplier
# would be 1 (since every person contributes a multiplier of 1 and then it all
# gets divided out by the number of people).
#
# If we then assume that vaccinated and unvaccinated people behave
# identically (have the same patterns of shopping, socializing, etc), then
# average_person_risk
# = average_unvaccinated_person_risk * average_vaccine_multiplier
#
# and so we can compute a conversion factor
# unvaccinated_relative_prevalence
# := average_unvaccinated_person_risk / average_person_risk <-- by definition
# = average_unvaccinated_person_risk / <-- using above assumption
# (average_unvaccinated_person_risk * average_vaccine_multiplier)
# = 1 / avg_vaccine_multiplier
# = 1 / (risk_sum / population)
# = population / risk_sum
#
# that we can use like so:
# estimated_unvaccinated_person_risk
# = unvaccinated_relative_prevalence * average_person_risk_from_prevalence_data
def unvaccinated_relative_prevalence(self) -> Optional[float]:
total_vaccinated = 0 # combined total of partially and fully vaccinated people
risk_sum = 0
if self.vaccines_by_type is not None:
for vaccine_type, vaccine_status in self.vaccines_by_type.items():
total_vaccinated += vaccine_status.completed_vaccinations
total_vaccinated += vaccine_status.partial_vaccinations
risk_sum += round(
VACCINE_MULTIPLIERS[vaccine_type]["complete"] * vaccine_status.completed_vaccinations
)
risk_sum += round(
VACCINE_MULTIPLIERS[vaccine_type]["partial"] * vaccine_status.partial_vaccinations
)
else:
risk_sum = round(
VACCINE_MULTIPLIERS["Unknown"]["complete"] * self.vaccines_total.completed_vaccinations
+ VACCINE_MULTIPLIERS["Unknown"]["partial"] * self.vaccines_total.partial_vaccinations
)
total_vaccinated = (
self.vaccines_total.completed_vaccinations + self.vaccines_total.partial_vaccinations
)
if total_vaccinated == 0:
return None
if total_vaccinated >= self.population:
# This probably means people from other counties have gotten their
# vaccine here. Just assume 100% vaccination.
return total_vaccinated / risk_sum
total_unvaccinated = self.population - total_vaccinated
risk_sum += 1 * total_unvaccinated
return float(self.population) / risk_sum
# Computes the average vaccine multiplier of the region. For use in computing
# "Average vaccinated" person
def average_fully_vaccinated_multiplier(self) -> float:
if self.vaccines_by_type is None:
return VACCINE_MULTIPLIERS["Unknown"]["complete"]
vaccine_multiplier = 0
total_fully_vaccinated = 0
for vaccine_type, vaccine_status in self.vaccines_by_type.items():
total_fully_vaccinated += vaccine_status.completed_vaccinations
vaccine_multiplier += round(
vaccine_status.completed_vaccinations * VACCINE_MULTIPLIERS[vaccine_type]["complete"]
)
if total_fully_vaccinated == 0:
return VACCINE_MULTIPLIERS["Unknown"]["complete"]
return vaccine_multiplier / total_fully_vaccinated
def as_app_data(self) -> "AppLocation":
last_week = self.cases_last_week
week_before = self.cases_week_before
if last_week <= week_before or week_before <= 0:
increase = 0.0
else:
increase = last_week / week_before - 1
if self.population <= 0 and self.name != "Unknown":
raise ValueError(f"Population for {self.name} is {self.population}")
if self.cases_last_week < 0:
raise ValueError(f"Cases for {self.name} is {self.cases_last_week}.")
if self.cases_last_month_rough == 0:
self.issue(
f"No cases noted for a month - {type(self).__name__} level",
f"No cases reported in at least one month in {self.fullname}",
)
last_week_cases_per_million = (1_000_000 * self.cases_last_week) / self.population
if self.cases_last_week != 0 and (last_week_cases_per_million < 1):
self.issue(
f"Less than 1 case per million in last week - {type(self).__name__} level",
f"Only {self.cases_last_week} cases last week when population is {self.population} in {self.name}",
)
last_month_cases_per_million = (1_000_000 * self.cases_last_month_rough) / self.population
if self.cases_last_month_rough != 0 and (last_month_cases_per_million < 4):
self.issue(
f"Less than 4 cases per million in last month - {type(self).__name__} level",
f"Only {self.cases_last_month_rough} cases last month when population is {self.population} in {self.name}",
)
if last_month_cases_per_million >= 4 and self.cases_last_week == 0:
self.issue(
f"No cases noted for last week - but there were some in the last month - {type(self).__name__} level",
f"No cases reported for last week in {self.fullname} despite there being cases in the last month",
)
if self.test_positivity_rate is not None and (
self.test_positivity_rate < 0 or self.test_positivity_rate > 1
):
self.issue(
"Invalid test positivity rate", f"test rate for {self.name} is {self.test_positivity_rate}"
)
self.test_positivity_rate = None
if self.test_positivity_rate is None:
self.issue(
f"No test positivity rate - {type(self).__name__} level",
f"Test positivity rate for {self.name} is not set",
)
return AppLocation(
label=self.name,
population=f"{self.population:,}",
casesPastWeek=self.cases_last_week,
casesIncreasingPercentage=increase * 100,
positiveCasePercentage=(
self.test_positivity_rate * 100 if self.test_positivity_rate is not None else None
),
incompleteVaccinations=self.partial_vaccination_total() or None,
completeVaccinations=self.completed_vaccination_total() or None,
unvaccinatedPrevalenceRatio=self.unvaccinated_relative_prevalence(),
averageFullyVaccinatedMultiplier=self.average_fully_vaccinated_multiplier(),
# we have to format the date like this to get it to be parsed correctly by JS
# Otherwise it assumes UTC time and will sometimes subtract a day
updatedAt=self.updatedAt.strftime("%B %d, %Y"),
)
class County(Place):
country: str
state: str
fips: Optional[str] # US only: 5-digit code
@property
def app_key(self) -> str:
if self.fips is not None:
return f"US_{self.fips.rjust(5, '0')}"
else:
slug = "_".join([self.country, self.state, self.name])
return re.sub(r"[^A-Za-z0-9_]", "_", slug)
class State(Place):
country: str
fips: Optional[str] # US only: 2-digit code
counties: Dict[str, County] = {}
@property
def app_key(self) -> str:
if self.fips is not None:
return f"US_{self.fips.rjust(2, '0')}"
else:
slug = "_".join([self.country, self.name])
return re.sub(r"[^A-Za-z0-9_]", "_", slug)
def as_app_data(self) -> "AppLocation":
result = super().as_app_data()
if self.country == "US":
result.topLevelGroup = "US states"
result.subdivisions = [county.app_key for county in self.counties.values()]
if self.country == "Canada":
# actually provinces, but reflecting that might break the spreadsheet.
result.topLevelGroup = "Canada states"
result.subdivisions = [county.app_key for county in self.counties.values()]
return result
class Country(Place):
iso3: Optional[str] # USA
states: Dict[str, State] = {}
@property
def app_key(self) -> str:
return re.sub(r"[^A-Za-z0-9_]", "_", self.name)
def as_app_data(self) -> "AppLocation":
result = super().as_app_data()
result.topLevelGroup = "Countries"
if self.name == "US":
result.label = "United States (all)"
else:
result.subdivisions = [state.app_key for state in self.states.values() if state.name != "Unknown"]
result.iso3 = self.iso3
return result
class AppLocation(pydantic.BaseModel, PopulationFilteredLogging):
label: str
iso3: Optional[str]
population: str
casesPastWeek: int
casesIncreasingPercentage: float
positiveCasePercentage: Optional[float]
topLevelGroup: Optional[str] = None
subdivisions: List[str] = []
incompleteVaccinations: Optional[int]
completeVaccinations: Optional[int]
unvaccinatedPrevalenceRatio: Optional[float]
averageFullyVaccinatedMultiplier: float
updatedAt: str
# https://covid19-projections.com/estimating-true-infections-revisited/
def prevalenceRatio(self) -> float:
DAY_0 = datetime(2020, 2, 12)
day_i = (datetime.now() - DAY_0).days
positivityRate = self.positiveCasePercentage
if positivityRate is None or positivityRate > 100:
positivityRate = 100
if positivityRate < 0:
self.issue("Positivity rate is negative", f"{positivityRate}")
positivityRate = 0
final: float = (1000 / (day_i + 10)) * (positivityRate / 100) ** 0.5 + 2
return final
@property
def population_as_int(self) -> int:
return int(self.population.replace(",", ""))
def as_csv_data(self) -> Dict[str, str]:
population = self.population_as_int
reported = (self.casesPastWeek + 1) / population
underreporting = self.prevalenceRatio()
delay = min(1.0 + (self.casesIncreasingPercentage / 100), 2.0)
estimated_prevalence = reported * underreporting * delay
return {
"Name": self.label,
# These two columns were replaced after Risk Tracker version 2.2.5 to make room for vax/unvax prevalence
# "Population": str(population),
# "Cases in past week": str(self.casesPastWeek),
"Estimated unvaccinated prevalence": (
str(round(self.unvaccinatedPrevalenceRatio * estimated_prevalence, 6))
if self.unvaccinatedPrevalenceRatio is not None
else "Unknown"
),
"Estimated vaccinated prevalence": (
str(
round(
self.unvaccinatedPrevalenceRatio
* estimated_prevalence
* self.averageFullyVaccinatedMultiplier,
6,
)
)
if self.unvaccinatedPrevalenceRatio is not None
else "Unknown"
),
"Reported prevalence": str(round(reported, 6)),
"Underreporting factor": str(round(underreporting, 4)),
"Delay factor": str(round(delay, 4)),
"Estimated prevalence": str(round(estimated_prevalence, 6)),
}