"""Independent check (standard library, written separately) of weekly_deaths.py's primary numbers. Reads the SODA JSON copy of the United States rows rather than the CSV export. usage: python3 -I weekly_deaths_check.py """ import json import statistics import sys rows = json.load(open(sys.argv[1], encoding="utf-8")) D = {} for r in rows: if r["jurisdiction_of_occurrence"] != "United States": continue D[(int(r["mmwryear"]), int(r["mmwrweek"]))] = {"heart": int(float(r["diseases_of_heart_i00_i09"])), "all": int(float(r["allcause"])), "end": r["weekendingdate"][:10]} print("rows", len(D)) years = range(2014, 2020) def fit_line(xs, ys): mx, my = statistics.mean(xs), statistics.mean(ys) b = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs) return lambda x: my + b * (x - mx) for key in ("heart", "all"): tot = {y: sum(D[(y, w)][key] for w in range(1, 53)) for y in years} line = fit_line(list(years), [tot[y] for y in years]) def expected(Y, w): return statistics.mean(D[(y, w)][key] * line(Y) / line(y) for y in years if y != Y) def change(Y, weeks): o = sum(D[(Y, w)][key] for w in weeks) e = sum(expected(Y, w) for w in weeks) return o, e, 100 * (o / e - 1) storm_weeks = {2015: [11, 25], 2017: [36]} placebo = [] for Y in years: for w in range(1, 52): if any(s - 2 <= x <= s + 4 for s in storm_weeks.get(Y, []) for x in (w, w + 1)): continue placebo.append(change(Y, [w, w + 1])[2]) placebo.sort() n = len(placebo) q05 = placebo[int(0.05 * (n - 1))] print("==", key, "annual totals", tot) for label, Y, weeks in (("S1 W2", 2015, [12, 13]), ("S1 W2s", 2015, [11, 12]), ("S2 W2", 2015, [26, 27]), ("S3 W2", 2017, [37, 38])): o, e, d = change(Y, weeks) p = (1 + sum(1 for x in placebo if x <= d)) / (1 + n) print(f" {label} weeks {weeks} ({D[(Y, weeks[0])]['end']} end of first week) O {o} E {e:.1f} " f"delta {d:.3f}% p_lower {p:.4f}") print(f" placebo n {n}, about-5th-percentile {q05:.3f}, sd {statistics.stdev(placebo):.3f}, " f"share <= -6.4%: {sum(1 for x in placebo if x <= -6.4) / n:.4f}")