# How close to the threshold are the classifications, and how noisy are the consumption estimates
# of the economies whose classification differs by boundary?
import csv, math, statistics, sys
b = sys.argv[1]
rows = [r for r in csv.DictReader(open(b + "/results/endpoint-classifications.csv")) if r["start"] == "2015" and r["end"] == "2023"]
print("economies in the primary window:", len(rows))
for band in (1, 2, 5):
    t = sum(abs(float(r["territorial_change_pct"])) < band for r in rows)
    c = sum(abs(float(r["consumption_change_pct"])) < band for r in rows)
    g = sum(abs(float(r["gdp_change_pct"])) < band for r in rows)
    print(f"  within ±{band}% of zero change: territorial {t}, consumption {c}, GDP {g}")
for label, key in (("territorial-only", ("True", "False")), ("consumption-only", ("False", "True"))):
    names = [r for r in rows if (r["territorial_absolute"], r["consumption_absolute"]) == key]
    print(label, [(r["name"], round(float(r["territorial_change_pct"]), 1), round(float(r["consumption_change_pct"]), 1)) for r in names])
panel = {}
for r in csv.DictReader(open(b + "/results/panel.csv")):
    panel.setdefault(r["name"], {})[int(r["year"])] = (float(r["territorial_mtc"]), float(r["consumption_mtc"]))
def vol(name, which):
    s = [math.log(panel[name][y][which] / panel[name][y - 1][which]) for y in range(2006, 2024)]
    return statistics.pstdev(s)
both_vol = {n: (vol(n, 0), vol(n, 1)) for n in panel}
med_t = statistics.median(v[0] for v in both_vol.values()); med_c = statistics.median(v[1] for v in both_vol.values())
print(f"median year-to-year sd of log emissions, all economies: territorial {med_t:.3f}, consumption {med_c:.3f}")
for label, key in (("territorial-only", ("True", "False")), ("consumption-only", ("False", "True"))):
    names = [r["name"] for r in rows if (r["territorial_absolute"], r["consumption_absolute"]) == key]
    print(f"  {label}: median sd territorial {statistics.median(both_vol[n][0] for n in names):.3f}, consumption {statistics.median(both_vol[n][1] for n in names):.3f}")
