"""New York's road deaths per resident against other big cities', 2007-2024: the analysis behind a SparkyData article.

    py src/build_article.py road-deaths-in-big-cities

Each city's official count of the people killed on its roads, by year (card ``world_city_road_deaths``, loader
``nycdata.world_roads``): New York, Chicago and Los Angeles from NHTSA's Fatality Analysis Reporting System (FARS, the
same files and codes every year); London from the Department for Transport's casualty file; Paris from the Interior
Ministry's injury-crash files; Berlin, Vienna and the Comunidad de Madrid from their statistics offices and the DGT;
Toronto from the City's collision records; Tokyo from the Metropolitan Police's yearly table (deaths within 24 hours)
and the National Police Agency's 30-day table. Each is divided by the city's residents in the same year
(``nycdata.world_population``; Chicago and Los Angeles from the Census Bureau's city series), so a rate is deaths per
100,000 residents: how dangerous the roads are for the people who live there, not per mile driven, which no city
here publishes on one footing.

The comparison is each city against itself: 2022-2024, the last three years every count covers (FARS's latest is
2024), against 2007-2009, the first three years every city's open records cover (Hong Kong's open files start in 2007).
A change is the ratio of the two
periods' rates with an approximate 90% range from the counts as Poisson counts (``sparkylib.stats.count_change``),
named only when the range excludes no change, and named in the story only when it survives the extra year-to-year
swing of the city's own series (``Article.recheck``). Whether New York's rate fell less than another city's is the
ratio of the two cities' changes (``sparkylib.stats.change_contrast``), with its range widened for the more variable
of the two series. Which city's rate is higher in 2022-2024 is the ratio of the two rates, tested the same way. The
order of the cities is the observed order. New York's long view runs from 1995 (FARS), and its current year is the
NYPD's count of people killed, January to October 2026 against the same months of 2025, from the police's
person-level crash file, a different count from FARS that is never set beside it; the crash-level table's own monthly
count is read beside it as a check that no month is short.

Definitions differ (``world_roads.AREAS``): most cities count a death within 30 days of the crash, Tokyo's long series
within 24 hours (its 30-day count, about 30% higher, exists from 2016 and is used for its 2022-2024 level); the
Comunidad de Madrid's counts before 2011 are 24-hour counts raised by the DGT's correction factors; Toronto's records
leave out the provincial highways inside the city. Each is named where its number is printed. What each city does
about road deaths comes from its own plans and laws, quoted (``RESPONSES``), never from the counts, and never as a
cause.

Writes results.json, viz.json, charts.json, data.csv and build.json into output/articles/road_deaths_in_big_cities/
and site/public/articles/road-deaths-in-big-cities/, and copies this script there as analysis.py. Deterministic: no
sampling, and SEED is kept for any resampling.
"""

from __future__ import annotations

import math

import pandas as pd

from _paths import RAW
import article_kit as K
from article_kit import Article, lines, r, strip
from nycdata import world_roads as R
from sparkylib.stats import change_contrast, change_size, count_change, dispersion, rate_ratio

SLUG = "road-deaths-in-big-cities"
SEED = 20261116
EARLY = (2007, 2009)           # the first three years every city's open count covers (Hong Kong's open files start in 2007)
LATE = (2022, 2024)            # the last three years every city's count covers (FARS's latest file is 2024)
LOW = (2017, 2019)             # New York's three lowest-rate years before 2020
PRE_VZ = (2011, 2013)          # the three years before Vision Zero's launch in 2014
VZ_BEFORE, VZ_AFTER = (2009, 2013), (2015, 2019)   # the five years before Vision Zero's first full year, and five after (2014 left out)
WIDER_LOW = (2015, 2019)       # the five years before 2020, a base not chosen at New York's lowest point
#: Baselines after a city's own recording change: Vienna's police recording changed in 2012, and the DGT's counts before
#: 2011 are estimates.
POST_BREAK = {"vienna": (2013, 2015), "madrid": (2011, 2013)}
#: The police's person-level file as it stood on 9 June 2026 (source nyc_collisions_persons_killed, kept as fetched for the
#: published street-deaths article): read here only to measure how much a recent month grows.
NYPD_JUNE = RAW / "safety" / "nyc_collisions_persons_killed.csv"
LONG_FROM = 1995               # New York's long view: the first year of the FARS extract
PER = 100_000
#: The cities, New York first: (key in world_roads, the page's label, short label).
CITIES = [("new_york", "New York", "New York"), ("chicago", "Chicago", "Chicago"), ("los_angeles", "Los Angeles", "Los Angeles"),
          ("toronto", "Toronto", "Toronto"), ("london", "London", "London"), ("paris", "Paris", "Paris"),
          ("berlin", "Berlin", "Berlin"), ("vienna", "Vienna", "Vienna"), ("madrid", "Madrid region", "Madrid region"),
          ("tokyo", "Tokyo", "Tokyo"), ("hong_kong", "Hong Kong", "Hong Kong"), ("singapore", "Singapore", "Singapore")]
OTHERS = [k for k, _, _ in CITIES if k != "new_york"]
US = ("new_york", "chicago", "los_angeles")
#: The level each city's 2022-2024 rate is read from, where its long series is on another definition.
LEVEL_AREA = {"tokyo": "tokyo_30d"}
#: The NYPD's person-level crash file from 2024 (source nyc_collisions_persons_killed_2024_on).
NYPD = RAW / "world_cities" / "roads" / "nyc_collisions_persons_killed_2024_on.csv"
#: The crash-level table's count of people killed by month (source nyc_collisions_crashes_killed_monthly_2024_on): a
#: second table of the same police records, read only to check the person file's months.
NYPD_CRASH_MONTHS = RAW / "world_cities" / "roads" / "nyc_collisions_crashes_killed_monthly_2024_on.csv"
NYPD_RETRIEVED = "14 November 2026"   # the day both police files were fetched (their crashes run to 10 November)
#: All five vehicle-type fields of each crash with a death, 2022 to 2024 (source
#: nyc_collisions_fatal_crashes_vehicle_types_2022_2024): the library's injury-crash extract keeps the first two.
NYPD_FATAL_VEHICLES = RAW / "world_cities" / "roads" / "nyc_collisions_fatal_crashes_vehicle_types_2022_2024.csv"
#: What the person file held for May 2026 when it ended on 9 June 2026 (the copy fetched on 26 September 2026, which the
#: City's files no longer serve): a recorded observation, so a rebuild on a later download still runs and prints it.
MAY_2026_IN_JUNE_FILE = 23
NOW_YEAR, NOW_MONTHS = 2026, 10   # January to October: the last complete month in the file
#: Vehicles FARS still collects as motor vehicles: a crash with one of these stays in the federal file after 2022.
MOTOR = ("motor vehicle", "motorcycle", "moped")
WORLD_LINES = ["new_york", "london", "vienna", "madrid", "tokyo", "hong_kong", "singapore"]


def span(s: pd.Series, a: tuple[int, int]) -> pd.Series:
    return s.loc[a[0]:a[1]]


def period(d: pd.DataFrame, a: tuple[int, int]) -> dict:
    """A city's deaths and residents summed over the years of ``a``, and its rate per 100,000."""
    x = d.set_index("year").loc[a[0]:a[1]]
    if len(x) != a[1] - a[0] + 1:
        raise ValueError(f"missing years in {a}: {list(x.index)}")
    deaths, pop = int(x["deaths"].sum()), int(x["pop"].sum())
    return {"years": f"{a[0]}-{a[1]}", "deaths": deaths, "person_years": pop, "rate": r(deaths / pop * PER, 4)}


def rate_text(node: dict) -> str:
    """A period's rate as the page prints it, one decimal, made from its counts (not from the stored rate)."""
    return f"{node['deaths'] / node['person_years'] * PER:.1f}"


def signed(x: float) -> str:
    """A signed whole percentage for the FAQ's tables, with a true minus sign (a change that rounds to nothing is 0%)."""
    return "0%" if round(x) == 0 else f"{x:+.0f}%".replace("-", "−")


def main(argv: list[str] | None = None) -> int:
    """Run the analysis and write every file (no options)."""
    A = Article(SLUG, __file__, seed=SEED)
    rate = {k: R.death_rate(k) for k, _, _ in CITIES}
    rate.update({LEVEL_AREA[k]: R.death_rate(LEVEL_AREA[k]) for k in LEVEL_AREA})
    counts = {k: d.set_index("year")["deaths"] for k, d in rate.items()}
    phi = {k: max(1.0, dispersion(span(counts[k], (EARLY[0], LATE[1])).tolist())) for k, _, _ in CITIES}

    # ---- each city: the two periods, the change between them, the latest year
    cities = {}
    for k, label, _ in CITIES:
        d = rate[k]
        e, l = period(d, EARLY), period(d, LATE)
        lv = period(rate[LEVEL_AREA.get(k, k)], LATE)
        last = d.iloc[-1]
        cities[k] = {"label": label, "area": R.AREAS[k][0], "counted_by": R.AREAS[k][1], "definition": R.AREAS[k][2],
                     "first_year": int(d["year"].min()), "early": e, "late": l, "level": lv,
                     "level_definition": R.AREAS[LEVEL_AREA.get(k, k)][2],
                     "latest": {"year": int(last["year"]), "deaths": int(last["deaths"]), "rate": r(last["per_100k"], 2)},
                     "change": count_change(l["deaths"], e["deaths"], exposure_now=l["person_years"] / PER,
                                            exposure_before=e["person_years"] / PER),
                     "dispersion": r(phi[k], 2)}
    A.results["cities"] = cities
    for k in cities:
        A.recheck(f"cities.{k}.change", span(counts[k], (EARLY[0], LATE[1])).tolist(),
                  exposure_now=cities[k]["late"]["person_years"] / PER, exposure_before=cities[k]["early"]["person_years"] / PER)
        if cities[k]["change"]["direction"] in ("up", "down") and \
                A.results["robustness"]["changes"][f"cities_{k}_change"]["direction"] == cities[k]["change"]["direction"]:
            A.claim(f"cities.{k}.change", cities[k]["change"]["direction"])

    # the observed orders: by 2022-2024 level (each city's 30-day count where it has one), and by change
    A.results["order"] = {
        "level": sorted(cities, key=lambda k: -cities[k]["level"]["rate"]),
        "change": sorted(cities, key=lambda k: cities[k]["change"]["change_pct"]),
        "level_outside_us": sorted([k for k in cities if k not in US], key=lambda k: -cities[k]["level"]["rate"])}
    A.results["order"]["new_york_level_rank"] = A.results["order"]["level"].index("new_york") + 1
    A.results["order"]["new_york_change_rank_from_largest_fall"] = A.results["order"]["change"].index("new_york") + 1
    A.results["order"]["n_cities"] = len(cities)
    A.results["order"]["n_others"] = len(OTHERS)
    A.results["order"]["outside_us_above_new_york"] = [k for k in A.results["order"]["level_outside_us"]
                                                       if cities[k]["level"]["rate"] > cities["new_york"]["level"]["rate"]]

    # ---- New York against each city: the level in 2022-2024, and the change since 2007-2009
    ny = cities["new_york"]
    vs, contrast = {}, {}
    for k in OTHERS:
        o = cities[k]
        vs[k] = count_change(ny["level"]["deaths"], o["level"]["deaths"], exposure_now=ny["level"]["person_years"] / PER,
                             exposure_before=o["level"]["person_years"] / PER)
        ratio = lambda a, b: (a["deaths"] / a["person_years"]) / (b["deaths"] / b["person_years"])   # noqa: E731
        vs[k]["ratio"] = r(ratio(ny["level"], o["level"]), 4)          # the level, 30-day counts where they exist
        # the gap then and now on each city's own long series (Tokyo's 24-hour count at both ends)
        vs[k]["ratio_early"] = r(ratio(ny["early"], o["early"]), 4)
        vs[k]["ratio_late"] = r(ratio(ny["late"], o["late"]), 4)
        plain = change_contrast(ny["late"]["deaths"], ny["early"]["deaths"], o["late"]["deaths"], o["early"]["deaths"],
                                exposures_a=(ny["late"]["person_years"], ny["early"]["person_years"]),
                                exposures_b=(o["late"]["person_years"], o["early"]["person_years"]))
        wide = change_contrast(ny["late"]["deaths"], ny["early"]["deaths"], o["late"]["deaths"], o["early"]["deaths"],
                               exposures_a=(ny["late"]["person_years"], ny["early"]["person_years"]),
                               exposures_b=(o["late"]["person_years"], o["early"]["person_years"]),
                               dispersion=max(phi["new_york"], phi[k]))
        contrast[k] = {**plain, "allowing_for_swing": wide}
    A.results["vs_new_york"] = vs
    A.results["contrast"] = contrast
    for k in OTHERS:
        # the level: rechecked with the more variable of the two cities' yearly series
        more_variable = max(("new_york", k), key=lambda c: phi[c])
        A.recheck(f"vs_new_york.{k}", span(counts[more_variable], (EARLY[0], LATE[1])).tolist(),
                  exposure_now=ny["level"]["person_years"] / PER, exposure_before=cities[k]["level"]["person_years"] / PER)
        if vs[k]["direction"] in ("up", "down") and \
                A.results["robustness"]["changes"][f"vs_new_york_{k}"]["direction"] == vs[k]["direction"]:
            A.claim(f"vs_new_york.{k}", vs[k]["direction"])
        if contrast[k]["direction"] in ("up", "down") and contrast[k]["allowing_for_swing"]["direction"] == contrast[k]["direction"]:
            A.claim(f"contrast.{k}", contrast[k]["direction"])
    # the level in 2007-2009 too, for the two cities whose order with New York changed
    early_vs = {}
    for k in ("singapore", "madrid"):
        o = cities[k]
        early_vs[k] = count_change(ny["early"]["deaths"], o["early"]["deaths"], exposure_now=ny["early"]["person_years"] / PER,
                                   exposure_before=o["early"]["person_years"] / PER)
    A.results["vs_new_york_early"] = early_vs
    for k in early_vs:
        more_variable = max(("new_york", k), key=lambda c: phi[c])
        A.recheck(f"vs_new_york_early.{k}", span(counts[more_variable], (EARLY[0], LATE[1])).tolist(),
                  exposure_now=ny["early"]["person_years"] / PER, exposure_before=cities[k]["early"]["person_years"] / PER)
        again = A.results["robustness"]["changes"][f"vs_new_york_early_{k}"]
        if early_vs[k]["direction"] in ("up", "down") and again["direction"] == early_vs[k]["direction"]:
            A.claim(f"vs_new_york_early.{k}", early_vs[k]["direction"])
    A.results["contrast_summary"] = {
        "new_york_fell_less_than": [k for k in OTHERS if contrast[k]["direction"] == "up"
                                    and contrast[k]["allowing_for_swing"]["direction"] == "up"],
        "new_york_fell_more_than": [k for k in OTHERS if contrast[k]["direction"] == "down"
                                    and contrast[k]["allowing_for_swing"]["direction"] == "down"],
        "not_separated": [k for k in OTHERS if contrast[k]["allowing_for_swing"]["direction"] == "unclear"]}
    for key in ("new_york_fell_less_than", "new_york_fell_more_than", "not_separated"):
        A.results["contrast_summary"][key + "_n"] = len(A.results["contrast_summary"][key])

    # the level ratios' ranges, with and without the swing allowance (the FAQ's table)
    for k in OTHERS:
        more_variable = max(("new_york", k), key=lambda c: phi[c])
        o = cities[k]
        for name, disp in (("plain", 1.0), ("swing", max(phi["new_york"], phi[k]))):
            ratio_, lo_, hi_ = rate_ratio(ny["level"]["deaths"], o["level"]["deaths"], ny["level"]["person_years"],
                                          o["level"]["person_years"], dispersion=disp)
            vs[k][f"ratio_{name}"] = [r(ratio_, 4), r(lo_, 4), r(hi_, 4)]

    # ---- sensitivities the local review asked for
    sens = {}
    for k, base in POST_BREAK.items():
        b, la = period(rate[k], base), cities[k]["late"]
        sens[f"{k}_post_break"] = {"base": b, "change": count_change(la["deaths"], b["deaths"], exposure_now=la["person_years"] / PER,
                                                                      exposure_before=b["person_years"] / PER)}
    # the same windows for New York, and whether its fall is separated from the city's on counts made one way throughout
    for k, base in POST_BREAK.items():
        node = sens[f"{k}_post_break"]
        b, la, nb, nla = node["base"], cities[k]["late"], period(rate["new_york"], base), cities["new_york"]["late"]
        _, slo, shi = rate_ratio(la["deaths"], b["deaths"], la["person_years"], b["person_years"], dispersion=phi[k])
        node["change_swing"] = {"lo_pct": r(100 * (slo - 1), 1), "hi_pct": r(100 * (shi - 1), 1),
                                "direction": "down" if shi < 1 else "up" if slo > 1 else "unclear"}
        node["new_york_base"] = nb
        node["new_york_change"] = count_change(nla["deaths"], nb["deaths"], exposure_now=nla["person_years"] / PER,
                                               exposure_before=nb["person_years"] / PER)
        node["contrast"] = change_contrast(nla["deaths"], nb["deaths"], la["deaths"], b["deaths"],
                                           exposures_a=(nla["person_years"], nb["person_years"]),
                                           exposures_b=(la["person_years"], b["person_years"]),
                                           dispersion=max(phi["new_york"], phi[k]))
        assert node["contrast"]["direction"] == "unclear", f"the page says {k}'s fall is not separated from New York's on consistent counts"
        assert node["change_swing"]["direction"] == "unclear", f"the page says {k}'s own fall since its break could be chance"
    # Singapore on its residents alone (citizens and permanent residents), against the total population the police use
    from nycdata.world_population import SINGSTAT_POP, singstat_rows
    res_pop = singstat_rows(SINGSTAT_POP, "Resident Population")
    sg_res_py = int(sum(res_pop[y] for y in range(LATE[0], LATE[1] + 1)))
    sg = cities["singapore"]["late"]
    sens["singapore_residents_only"] = {"person_years": sg_res_py, "rate": r(sg["deaths"] / sg_res_py * PER, 4),
                                        "total_population_rate": sg["rate"],
                                        "non_resident_share": r(1 - sg_res_py / sg["person_years"], 4)}
    # FARS's 2022 change: crashes involving only e-bikes left the file. The upper bound is every e-bike rider the police
    # recorded killed (most died in crashes with a car or truck, which FARS still collects) and everyone else killed in a
    # crash whose recorded vehicles include an e-bike and no motor vehicle; the closer count keeps only the riders whose
    # crash has no motor vehicle recorded. Both rest on the police's vehicle codes.
    from nycdata import roads
    killed, _ = roads.collision_deaths()
    yr = killed["date"].dt.year
    in_late = killed[(yr >= LATE[0]) & (yr <= LATE[1])]
    no_motor = ~in_late["v1"].isin(MOTOR) & ~in_late["v2"].isin(MOTOR)
    rider = in_late["road_user"].eq("e-bike")
    with_ebike = in_late["v1"].eq("e-bike") | in_late["v2"].eq("e-bike")
    ebike = int(rider.sum())
    others = int((~rider & ~in_late["road_user"].isin(("vehicle occupant", "motorcycle", "moped")) & with_ebike & no_motor).sum())
    riders_no_motor = int((rider & no_motor).sum())
    nl = cities["new_york"]["late"]
    london_late = cities["london"]["late"]["deaths"] / cities["london"]["late"]["person_years"]
    sens["fars_ebike_bound"] = {"ebike_riders_killed": ebike, "others_killed_ebike_only": others,
                                "upper_bound": ebike + others, "years": f"{LATE[0]}-{LATE[1]}",
                                "rate_with": r((nl["deaths"] + ebike + others) / nl["person_years"] * PER, 4),
                                "london_ratio_with": r(((nl["deaths"] + ebike + others) / nl["person_years"]) / london_late, 4),
                                "riders_no_motor_vehicle": riders_no_motor,
                                "no_motor_vehicle": riders_no_motor + others,
                                "rate_with_no_motor_vehicle": r((nl["deaths"] + riders_no_motor + others) / nl["person_years"] * PER, 4)}
    # the e-bike gap carried into New York's change since 2007-2009, when e-bikes were few: the fall on the closer count
    # and at the upper bound
    ne = cities["new_york"]["early"]
    for name, extra in (("change_with_no_motor_vehicle_pct", riders_no_motor + others), ("change_with_upper_bound_pct", ebike + others)):
        sens["fars_ebike_bound"][name] = r(100 * (((nl["deaths"] + extra) / nl["person_years"]) / (ne["deaths"] / ne["person_years"]) - 1), 2)
    # people on foot in the police records of the same years: all killed, and those killed in crashes with an e-bike and
    # no motor vehicle (the claim that e-bikes are what kills New Yorkers is tested on these)
    on_foot = in_late["road_user"].eq("pedestrian")
    sens["fars_ebike_bound"]["pedestrians_killed"] = int(on_foot.sum())
    sens["fars_ebike_bound"]["pedestrians_killed_ebike_only"] = int((on_foot & with_ebike & no_motor).sum())
    assert sens["fars_ebike_bound"]["pedestrians_killed_ebike_only"] == others, "the page calls the others people on foot"
    assert riders_no_motor < ebike / 2, "the page says most of the riders died in crashes with a car or truck"
    # the crash record names up to five vehicles and the library's extract keeps two: on the table's own five fields, does
    # a motor vehicle ever appear only among the third to fifth? (outside review, 15 November 2026)
    fc = pd.read_csv(NYPD_FATAL_VEHICLES, dtype=str, keep_default_na=False)
    fields = ["vehicle_type_code1", "vehicle_type_code2", "vehicle_type_code_3", "vehicle_type_code_4", "vehicle_type_code_5"]
    classes = fc[fields].apply(lambda col: col.map(roads.vclass))
    motor_first_two, motor_any = classes[fields[:2]].isin(MOTOR).any(axis=1), classes.isin(MOTOR).any(axis=1)
    ebike_any = classes.eq("e-bike").any(axis=1)
    sens["fars_ebike_bound"]["all_vehicle_fields"] = {
        "crashes": int(len(fc)), "killed": int(fc["number_of_persons_killed"].astype(int).sum()),
        "pedestrians_killed": int(fc["number_of_pedestrians_killed"].astype(int).sum()),
        "motor_vehicle_only_in_later_fields": int((~motor_first_two & motor_any).sum()),
        "pedestrians_killed_ebike_no_motor": int(fc.loc[ebike_any & ~motor_any, "number_of_pedestrians_killed"].astype(int).sum())}
    check = sens["fars_ebike_bound"]["all_vehicle_fields"]
    assert check["motor_vehicle_only_in_later_fields"] == 0, "the page says the first two vehicle fields decide every fatal crash"
    assert check["pedestrians_killed_ebike_no_motor"] == others and check["pedestrians_killed"] == int(on_foot.sum()), check
    # Singapore's residents-only rate against New York's, with the swing allowance: about level, not above
    sr = sens["singapore_residents_only"]
    ratio_, lo_, hi_ = rate_ratio(nl["deaths"], sg["deaths"], nl["person_years"], sr["person_years"],
                                  dispersion=max(phi["new_york"], phi["singapore"]))
    sr["new_york_ratio"] = {"ratio": r(ratio_, 4), "lo": r(lo_, 4), "hi": r(hi_, 4)}
    assert lo_ < 1 < hi_, "the page says New York's rate would be about level with Singapore's on residents alone"
    # Tokyo's two definitions in 2022-2024: the 30-day count over the 24-hour count
    sens["tokyo_30d_over_24h"] = r(cities["tokyo"]["level"]["deaths"] / cities["tokyo"]["late"]["deaths"], 4)
    A.results["sensitivity"] = sens

    # ---- New York's long view and its stall
    nyr = rate["new_york"].set_index("year")
    first3 = period(rate["new_york"], (LONG_FROM, LONG_FROM + 2))
    low = period(rate["new_york"], LOW)
    low_year = int(nyr["per_100k"].idxmin())
    A.results["new_york"] = {
        "first": {"year": LONG_FROM, "deaths": int(nyr.loc[LONG_FROM, "deaths"]), "rate": r(nyr.loc[LONG_FROM, "per_100k"], 2)},
        "first3": first3, "low": low,
        "lowest_year": {"year": low_year, "deaths": int(nyr.loc[low_year, "deaths"]), "rate": r(nyr.loc[low_year, "per_100k"], 2)},
        "last": {"year": int(nyr.index.max()), "deaths": int(nyr["deaths"].iloc[-1]), "rate": r(nyr["per_100k"].iloc[-1], 2)},
        "fall_to_low": count_change(low["deaths"], first3["deaths"], exposure_now=low["person_years"] / PER,
                                    exposure_before=first3["person_years"] / PER),
        "since_low": count_change(ny["late"]["deaths"], low["deaths"], exposure_now=ny["late"]["person_years"] / PER,
                                  exposure_before=low["person_years"] / PER)}
    wl = period(rate["new_york"], WIDER_LOW)
    A.results["new_york"]["wider_low"] = wl
    A.results["new_york"]["since_wider_low"] = count_change(ny["late"]["deaths"], wl["deaths"], exposure_now=ny["late"]["person_years"] / PER,
                                                            exposure_before=wl["person_years"] / PER)
    A.results["new_york"]["low_pop_mean"] = int(round(low["person_years"] / 3))
    A.results["new_york"]["late_pop_mean"] = int(round(ny["late"]["person_years"] / 3))
    A.results["new_york"]["deaths_change_since_low_pct"] = r(100 * (ny["late"]["deaths"] / low["deaths"] - 1), 2)
    A.results["new_york"]["pop_change_since_low_pct"] = r(100 * (ny["late"]["person_years"] / low["person_years"] - 1), 2)
    # the share of the rate's rise that the smaller population accounts for: of the rise in points, and of its logarithm
    _d, _p = ny["late"]["deaths"] / low["deaths"], ny["late"]["person_years"] / low["person_years"]
    A.results["new_york"]["population_share_of_rise"] = {"of_points": r((_d / _p - _d) / (_d / _p - 1), 4),
                                                         "of_log": r(-math.log(_p) / math.log(_d / _p), 4)}
    assert 0.2 < A.results["new_york"]["population_share_of_rise"]["of_log"] < 0.3, "the page says about a quarter"
    # New York's best single year in the federal file against London's 2022-2024 rate (the close's yardstick)
    A.results["new_york"]["best_year_vs_london"] = r(
        float(nyr.loc[low_year, "per_100k"]) / (cities["london"]["late"]["deaths"] / cities["london"]["late"]["person_years"] * PER), 4)
    assert 1.8 < A.results["new_york"]["best_year_vs_london"] < 2.0, "the page says nearly twice"
    A.recheck("new_york.since_wider_low", span(counts["new_york"], (WIDER_LOW[0], LATE[1])).tolist(),
              exposure_now=ny["late"]["person_years"] / PER, exposure_before=wl["person_years"] / PER)
    A.recheck("new_york.fall_to_low", span(counts["new_york"], (LONG_FROM, LOW[1])).tolist(),
              exposure_now=low["person_years"] / PER, exposure_before=first3["person_years"] / PER)
    A.recheck("new_york.since_low", span(counts["new_york"], (LOW[0], LATE[1])).tolist(),
              exposure_now=ny["late"]["person_years"] / PER, exposure_before=low["person_years"] / PER)
    # the policies against the history: Vision Zero began in 2014. How far the rate had fallen by the three years before
    # it, how much of the whole fall to 2017-2019 that was, and where 2022-2024 stands against the five years before it
    pre, vzb = period(rate["new_york"], PRE_VZ), period(rate["new_york"], VZ_BEFORE)
    NY = A.results["new_york"]
    NY["pre_vision_zero"] = pre
    NY["fall_to_pre_vision_zero"] = count_change(pre["deaths"], first3["deaths"], exposure_now=pre["person_years"] / PER,
                                                 exposure_before=first3["person_years"] / PER)
    per_100k = lambda x: x["deaths"] / x["person_years"] * PER   # noqa: E731
    NY["share_of_fall_before_vision_zero"] = r((per_100k(first3) - per_100k(pre)) / (per_100k(first3) - per_100k(low)), 4)
    assert 0.65 < NY["share_of_fall_before_vision_zero"] < 0.75, "the page says about seven-tenths"
    # the share compares sixteen years with six, so the yearly pace is printed beside it: the rate fell faster after
    span_before = (PRE_VZ[0] + 1) - (LONG_FROM + 1)        # mid-year of 1995-1997 to mid-year of 2011-2013
    span_after = (LOW[0] + 1) - (PRE_VZ[0] + 1)            # mid-year of 2011-2013 to mid-year of 2017-2019
    NY["pace_before_vision_zero_pct"] = r(100 * ((per_100k(pre) / per_100k(first3)) ** (1 / span_before) - 1), 3)
    NY["pace_after_pct"] = r(100 * ((per_100k(low) / per_100k(pre)) ** (1 / span_after) - 1), 3)
    NY["pace_years"] = [span_before, span_after]
    # is the fall after 2011-2013 faster than the fall before it? The difference of the two yearly log changes, with the
    # middle period in both and the series' own swing allowed for (outside review, 15 November 2026)
    swing = max(1.0, dispersion(span(counts["new_york"], (LONG_FROM, LOW[1])).tolist()))
    diff = math.log(per_100k(low) / per_100k(pre)) / span_after - math.log(per_100k(pre) / per_100k(first3)) / span_before
    pace_se = math.sqrt(swing * (1 / (span_after ** 2 * low["deaths"]) + (1 / span_after + 1 / span_before) ** 2 / pre["deaths"]
                            + 1 / (span_before ** 2 * first3["deaths"])))
    NY["pace_difference"] = {"log_per_year": r(diff, 4), "se": r(pace_se, 4), "dispersion": r(swing, 2),
                             "range_90": [r(diff - 1.645 * pace_se, 4), r(diff + 1.645 * pace_se, 4)],
                             "range_95": [r(diff - 1.96 * pace_se, 4), r(diff + 1.96 * pace_se, 4)],
                             # the swing (as a multiple of a Poisson count's) at which the 90% range would reach no difference
                             "holds_up_to": r((abs(diff) / (1.645 * pace_se)) ** 2 * swing, 2),
                             # the later window was chosen as the three lowest years, which favours a faster pace after
                             "later_window_is_the_three_lowest_years":
                                 sorted(int(y) for y in nyr["per_100k"].nsmallest(3).index) == list(range(LOW[0], LOW[1] + 1))}
    assert NY["pace_difference"]["range_90"][1] < 0 < NY["pace_difference"]["range_95"][1], \
        "the page says the difference is at the edge of chance: its 90% range clears no difference narrowly, its 95% range does not"
    assert NY["pace_difference"]["later_window_is_the_three_lowest_years"], "the page says the later window is the three lowest years"
    NY["since_before_vision_zero"] = count_change(ny["late"]["deaths"], vzb["deaths"], exposure_now=ny["late"]["person_years"] / PER,
                                                  exposure_before=vzb["person_years"] / PER)
    A.recheck("new_york.fall_to_pre_vision_zero", span(counts["new_york"], (LONG_FROM, PRE_VZ[1])).tolist(),
              exposure_now=pre["person_years"] / PER, exposure_before=first3["person_years"] / PER)
    A.recheck("new_york.since_before_vision_zero", span(counts["new_york"], (VZ_BEFORE[0], LATE[1])).tolist(),
              exposure_now=ny["late"]["person_years"] / PER, exposure_before=vzb["person_years"] / PER)
    for path in ("new_york.fall_to_low", "new_york.since_low", "new_york.since_wider_low", "new_york.fall_to_pre_vision_zero",
                 "new_york.since_before_vision_zero"):
        node = A.results["new_york"][path.split(".")[1]]
        again = A.results["robustness"]["changes"][path.replace(".", "_")]
        if node["direction"] in ("up", "down") and again["direction"] == node["direction"]:
            A.claim(path, node["direction"])

    # ---- beliefs, tested on the counts alone
    since_low = {}
    for k, _, _ in CITIES:
        lo_, la = period(rate[k], LOW), cities[k]["late"]
        since_low[k] = count_change(la["deaths"], lo_["deaths"], exposure_now=la["person_years"] / PER,
                                    exposure_before=lo_["person_years"] / PER)
        since_low[k]["low_rate"], since_low[k]["late_rate"] = lo_["rate"], la["rate"]
        since_low[k]["low_person_years"] = lo_["person_years"]
    A.results["since_2017_2019"] = since_low
    for k in since_low:
        A.recheck(f"since_2017_2019.{k}", span(counts[k], (LOW[0], LATE[1])).tolist(),
                  exposure_now=cities[k]["late"]["person_years"] / PER,
                  exposure_before=since_low[k]["low_person_years"] / PER)
        again = A.results["robustness"]["changes"][f"since_2017_2019_{k}"]
        if since_low[k]["direction"] in ("up", "down") and again["direction"] == since_low[k]["direction"]:
            A.claim(f"since_2017_2019.{k}", since_low[k]["direction"])
    A.results["beliefs"] = {
        "rose_since_2017_2019": [k for k in since_low if A.results["robustness"]["changes"][f"since_2017_2019_{k}"]["direction"] == "up"],
        "fell_since_2017_2019": [k for k in since_low if A.results["robustness"]["changes"][f"since_2017_2019_{k}"]["direction"] == "down"],
        "level_since_2017_2019": [k for k in since_low if A.results["robustness"]["changes"][f"since_2017_2019_{k}"]["direction"] == "unclear"]}
    vb, va = period(rate["new_york"], VZ_BEFORE), period(rate["new_york"], VZ_AFTER)
    A.results["vision_zero_timing"] = {"before": vb, "after": va,
                                       "change": count_change(va["deaths"], vb["deaths"], exposure_now=va["person_years"] / PER,
                                                              exposure_before=vb["person_years"] / PER)}
    A.recheck("vision_zero_timing.change", span(counts["new_york"], (VZ_BEFORE[0], VZ_AFTER[1])).tolist(),
              exposure_now=va["person_years"] / PER, exposure_before=vb["person_years"] / PER)
    if A.results["robustness"]["changes"]["vision_zero_timing_change"]["direction"] == \
            A.results["vision_zero_timing"]["change"]["direction"] != "unclear":
        A.claim("vision_zero_timing.change", A.results["vision_zero_timing"]["change"]["direction"])
    pops = {k: cities[k]["late"]["person_years"] / 3 for k in cities}
    A.results["size"] = {"largest": max(pops, key=pops.get), "lowest_level": A.results["order"]["level"][-1],
                         "population_late_mean": {k: int(round(v)) for k, v in pops.items()}}

    # ---- New York's current year: the police's count, the same months a year apart
    k26 = pd.read_csv(NYPD, usecols=["crash_date"])
    when = pd.to_datetime(k26["crash_date"])
    monthly = when.groupby([when.dt.year, when.dt.month]).size()
    month = lambda y, m: int(monthly.get((y, m), 0))
    ytd = {str(y): sum(month(y, m) for m in range(1, NOW_MONTHS + 1)) for y in (2024, 2025, NOW_YEAR)}
    series = [month(y, m) for y in (2024, 2025, NOW_YEAR) for m in range(1, 13) if (y, m) <= (NOW_YEAR, NOW_MONTHS)]
    A.results["now"] = {"file_last_date": str(when.max().date()), "months": "January to October", "ytd": ytd,
                        "ytd_change": count_change(ytd[str(NOW_YEAR)], ytd["2025"]),
                        "year_2025": sum(month(2025, m) for m in range(1, 13)), "year_2024": sum(month(2024, m) for m in range(1, 13))}
    A.results["now"]["year_change"] = count_change(A.results["now"]["year_2025"], A.results["now"]["year_2024"])
    A.recheck("now.ytd_change", series)
    A.recheck("now.year_change", [month(y, m) for y in (2024, 2025) for m in range(1, 13)])
    for path in ("now.ytd_change", "now.year_change"):
        node = A.results["now"][path.split(".")[1]]
        again = A.results["robustness"]["changes"][path.replace(".", "_")]
        if node["direction"] in ("up", "down") and again["direction"] == node["direction"]:
            A.claim(path, node["direction"])
    # how much a recent month grows as later deaths are added: May 2026 in the file of 9 June against now
    june = pd.to_datetime(pd.read_csv(NYPD_JUNE, usecols=["crash_date"])["crash_date"])
    A.results["now"]["late_additions"] = {"may_2026_in_june_file": int(((june.dt.year == 2026) & (june.dt.month == 5)).sum()),
                                          "may_2026_now": month(2026, 5), "june_file_last_date": str(june.max().date())}
    june_copy = str(june.max().date()) == "2026-06-09"
    if june_copy:
        assert A.results["now"]["late_additions"]["may_2026_in_june_file"] == MAY_2026_IN_JUNE_FILE
    else:
        print("note: the person file on disk is a later download than the copy of 9 June 2026; May 2026 is printed as recorded then")
    A.results["now"]["late_additions"].update({"may_2026_in_june_file": MAY_2026_IN_JUNE_FILE, "june_file_last_date": "2026-06-09",
                                               "local_copy_is_the_june_file": june_copy})
    A.results["now"]["ytd_to_september"] = {str(y): sum(month(y, m) for m in range(1, 10)) for y in (2025, NOW_YEAR)}
    # the same two comparisons allowing for the season: the swing of each month against the same month a year before,
    # 2013 to 2025, in the longer police file. The verdicts do not change.
    jm = june.groupby([june.dt.year, june.dt.month]).size()
    seasonal = max(1.0, dispersion([int(jm.get((y, m), 0)) for y in range(2013, 2026) for m in range(1, 13)], season=12))
    seasonal_check = {"dispersion": r(seasonal, 2), "months": "2013-2025"}
    for name, a, b in (("year", A.results["now"]["year_2025"], A.results["now"]["year_2024"]), ("ytd", ytd[str(NOW_YEAR)], ytd["2025"])):
        _, lo_, hi_ = rate_ratio(a, b, 1, 1, dispersion=seasonal)
        seasonal_check[name] = {"lo_pct": r(100 * (lo_ - 1), 1), "hi_pct": r(100 * (hi_ - 1), 1)}
        assert lo_ < 1 < hi_, f"the page says the {name} gap could be chance"
    A.results["now"]["seasonal_check"] = seasonal_check
    A.results["now"]["retrieved"] = NYPD_RETRIEVED
    # the crash-level table's own count of people killed, month by month: the two tables must agree, so no month of the
    # person file is short (November 2025, the fewest of any month, among them)
    cm = pd.read_csv(NYPD_CRASH_MONTHS)
    crash_month = {(t.year, t.month): int(v) for t, v in zip(pd.to_datetime(cm["month"]), cm["killed"])}
    checked = [(y, m) for y in (2024, 2025, NOW_YEAR) for m in range(1, 13) if (y, m) <= (NOW_YEAR, NOW_MONTHS)]
    differ = {f"{y}-{m:02d}": [month(y, m), crash_month.get((y, m), 0)] for y, m in checked
              if month(y, m) != crash_month.get((y, m), 0)}
    fewest = min(checked, key=lambda ym: month(*ym))
    A.results["now"]["crash_table_check"] = {"months": len(checked), "differ": differ,
                                             "fewest_month": f"{fewest[0]}-{fewest[1]:02d}", "fewest_month_deaths": month(*fewest),
                                             "fewest_month_crash_table": crash_month.get(fewest, 0)}
    assert not differ, f"the person file and the crash table disagree: {differ}"
    assert fewest == (2025, 11), "the page names November 2025 as the file's lowest month"
    A.latest(f"{NOW_YEAR}-{NOW_MONTHS:02d}", "NYPD Motor Vehicle Collisions - Person, people killed, January to October 2026 "
             f"against the same months of 2025 (the file retrieved {NYPD_RETRIEVED})")
    A.long_view(LONG_FROM, int(nyr.index.max()), "New York City's road deaths per 100,000 residents, NHTSA FARS, 1995-2024")

    # ---- the documents: what each city has set out to do, and New York's own record
    Q = A.quotes()
    A.quote_responses(RESPONSES)
    hist = {"dot_2025": Q.quote("nyc_dot_traffic_deaths_2025_release", "nyc_dot_traffic_deaths_2025_release.html",
                                "There were 205 recorded traffic deaths in 2025"),
            "dot_2025_record": Q.quote("nyc_dot_traffic_deaths_2025_release", "nyc_dot_traffic_deaths_2025_release.html",
                                       "dating back to when record-keeping began in 1910")}
    hist["dot_vz_decline"] = Q.quote("nyc_dot_traffic_deaths_2025_release", "nyc_dot_traffic_deaths_2025_release.html",
                                     "traffic deaths are down 31 percent since the launch of Vision Zero in 2014")
    hist["dot_2024"] = Q.quote("nyc_dot_traffic_deaths_2025_release", "nyc_dot_traffic_deaths_2025_release.html",
                               "a 19 percent decline from 253 fatalities last year")
    hist["dot_2018"] = Q.quote("nyc_dot_traffic_deaths_2025_release", "nyc_dot_traffic_deaths_2025_release.html",
                               "one fewer than the previous safest year on record in 2018, when 206 people were killed")
    import re as _re
    hist["fars_ebikes"] = Q.quote("nhtsa_fars_manual_1975_2024", "nhtsa_fars_analytical_users_manual_1975_2024.pdf",
                                  "crashes involving only motorized bicycles were no longer collected")
    # the City's plan of September 2026: its later count for 2025, how it measures New York, and its reading of the rise
    PLAN = ("nyc_vision_zero_reimagined_2026", "nyc_vision_zero_reimagined_2026.pdf")
    hist["plan_lows"] = Q.quote(*PLAN, "historic low of 206 in 2018 and similar low of 210 in 2025")
    hist["plan_us_cities"] = Q.quote(*PLAN, "has achieved some of the lowest traffic fatality rates among major U.S. cities and the nation as a whole")
    hist["plan_two_wheelers"] = Q.quote(*PLAN, "more than doubled between 2014 and 2023")
    hist["plan_two_wheelers_named"] = Q.quote(*PLAN, "motorcycles, mopeds, e-bikes, stand-up scooters, off-road vehicles")
    hist["plan_two_wheelers_why"] = Q.quote(*PLAN, "likely reflects the growing popularity of motorized micromobility in New")
    hist["plan_risky"] = Q.quote(*PLAN, "increases in risky behavior")
    hist["plan_pedestrians"] = Q.quote(*PLAN, "Pedestrian fatalities dropped by approximately 22%")
    assert hist["plan_two_wheelers_why"]["page"] == hist["plan_risky"]["page"] == hist["plan_two_wheelers"]["page"]
    # what two other offices say of their own falls, each with its scope
    hist["tfl_20mph"] = Q.quote("tfl_press_20mph_2023", "tfl_press_20mph_2023.html",
                                "collisions resulting in death or serious injury have reduced by 25 per cent (from 94 to 71)")
    hist["tfl_20mph_reading"] = Q.quote("tfl_press_20mph_2023", "tfl_press_20mph_2023.html",
                                        "demonstrating the huge impact of lowering speeds across London")
    hist["tfl_20mph_when"] = Q.quote("tfl_press_20mph_2023", "tfl_press_20mph_2023.html",
                                     "In March 2020, TfL introduced a 20mph speed limit on all of its roads within the central London Congestion Charging zone")
    hist["toronto_attribution"] = Q.quote("toronto_vision_zero_annual_report_2025", "toronto_vision_zero_annual_report_2025.pdf",
                                          "These reductions are attributed to sustained efforts through the Road Safety Plan as well as "
                                          "external factors such as changes in transportation patterns and improvements in vehicle safety")
    # what is being said: the City's officials, the Council and a newsroom, each from its saved page
    hist["plan_series"] = Q.quote(*PLAN, "297 321 324 275 292 260 273 250 279 299 259 234 232 224 206 221 243 276 263 267 252 210")
    hist["plan_decade_before"] = Q.quote(*PLAN, "averaged approximately 287 traffic deaths per year")
    hist["plan_decade_after"] = Q.quote(*PLAN, "dropped to around 241 fatalities annually")
    hist["plan_decade_pct"] = Q.quote(*PLAN, "an 16% reduction")
    hist["plan_los_angeles"] = Q.quote(*PLAN, "recorded 329 fatalities, or 8.61 per 100,000")
    hist["plan_two_wheelers_peak"] = Q.quote(*PLAN, "peaking at 101 fatalities in 2023 and remaining elevated at 73 in 2025")
    hist["plan_pedestrians_counts"] = Q.quote(*PLAN, "from an average of 156 deaths per year before Vision Zero")
    hist["plan_pedestrians_after"] = Q.quote(*PLAN, "to 122 per year since its launch")
    hist["mayor_30"] = Q.quote("nyc_mayor_vision_zero_reimagined_release_2026", "nyc_mayor_vision_zero_reimagined_release_2026-09-15.html",
                               "with traffic deaths down 30% since its launch in 2014")
    DOT_OCT = ("nyc_dot_pedestrian_fatalities_record_lows_2026_10", "nyc_dot_pedestrian_fatalities_record_lows_2026-10-02.html")
    hist["dot_28"] = Q.quote(*DOT_OCT, "with overall traffic deaths down nearly 28% since Vision Zero")
    hist["dot_second_fewest"] = Q.quote(*DOT_OCT, "the second fewest traffic deaths since the city started tracking data in 1910")
    hist["advocate_34"] = Q.quote("amsterdam_news_traffic_deaths_34_percent_2026", "amsterdam_news_traffic_deaths_34_percent_2026-04-30.html",
                                  "multiple factors helped stem traffic deaths by 34% over the years since the city committed to Vision Zero")
    COUNCIL = ("nyc_council_vision_zero_interventions_2026", "nyc_council_vision_zero_interventions_release_2026-08-05.html")
    hist["council_turns"] = Q.quote(*COUNCIL, "Turn Traffic Calming, which reduced pedestrian casualties by 27 percent")
    hist["council_slow_zones"] = Q.quote(*COUNCIL, "Neighborhood Slow Zones, which reduced pedestrian casualties by 21 percent")
    hist["council_lpi"] = Q.quote(*COUNCIL, "Leading Pedestrian Intervals, which reduced pedestrian casualties by 13 percent")
    hist["council_limit"] = Q.quote(*COUNCIL, "Citywide Speed Limit Reduction, which reduced pedestrian casualties by 10 percent")
    hist["council_scope"] = Q.quote(*COUNCIL, "analyzed pedestrian casualty data at 9,562 intersections that received Vision Zero interventions between 2015 and 2021")
    hist["council_method"] = Q.quote(*COUNCIL, "compares outcomes before and after the physical and regulatory changes were made")
    FULL = ("nyc_council_vision_zero_analysis_2026", "nyc_council_vision_zero_analysis_2026.html")
    hist["council_design"] = Q.quote(*FULL, "our staggered difference-in-difference design")
    hist["council_comparison"] = Q.quote(*FULL, "compares the change in casualties at a treated intersection to the change in casualties at similar intersections that")
    hist["council_no_effect"] = Q.quote(*FULL, "25 MPH Signal Retiming, Enhanced Crossings, Speed Humps, and SIP Intersections/Corridors had no statistically significant effect")
    hist["council_slow_zone"] = Q.quote(*FULL, "in which the speed limit has been reduced to 20 MPH")
    hist["council_caveat"] = Q.quote(*FULL, "other unmeasured factors could also play a role")
    hist["council_years"] = Q.quote(*FULL, "examining data from 2013 to 2023")
    EBIKES = ("nyc_council_ebike_hearing_2026", "nyc_council_ebike_hearing_release_2026-09-30.html")
    hist["speaker_ebikes"] = Q.quote(*EBIKES, "too many New Yorkers are being killed or injured due to E-bikes and E-scooters "
                                              "without the proper safeguards and enforcement")
    hist["speaker_ebikes_named"] = Q.quote(*EBIKES, "said City Council Speaker")
    hist["mayor_30_whole"] = Q.quote("nyc_mayor_vision_zero_reimagined_release_2026", "nyc_mayor_vision_zero_reimagined_release_2026-09-15.html",
                                     "Vision Zero has been a game changer for street safety in New York City, with traffic deaths down 30% "
                                     "since its launch in 2014")
    hist["mayor_30_named"] = Q.quote("nyc_mayor_vision_zero_reimagined_release_2026", "nyc_mayor_vision_zero_reimagined_release_2026-09-15.html",
                                     "NYC DOT Commissioner")
    hist["comptroller_pedestrian_injuries"] = Q.quote(*EBIKES, "accounted for roughly 4.5% of all pedestrian injuries from 2020-2023")
    num = lambda key, pat, g=1: int(_re.search(pat, hist[key]["quote"]).group(g))   # noqa: E731  (figures read from their quotes)
    A.results["history"] = {"quotes": hist, "dot_2025_deaths": num("dot_2025", r"There were (\d+) recorded traffic deaths in 2025"),
                            "dot_2024_deaths": num("dot_2024", r"decline from (\d+) fatalities"),
                            "dot_2018_deaths": num("dot_2018", r"when (\d+) people were killed"),
                            "dot_decline_since_2014_pct": num("dot_vz_decline", r"down (\d+) percent"),
                            "plan_2018_deaths": num("plan_lows", r"historic low of (\d+) in 2018"),
                            "plan_2025_deaths": num("plan_lows", r"similar low of (\d+) in 2025"),
                            "plan_pedestrian_fall_pct": num("plan_pedestrians", r"approximately (\d+)%"),
                            "tfl_ksi_fall_pct": num("tfl_20mph", r"serious injury have reduced by (\d+) per cent \(from"),
                            "tfl_ksi_before": num("tfl_20mph", r"serious injury have reduced by \d+ per cent \(from (\d+) to (\d+)\)", 1),
                            "tfl_ksi_after": num("tfl_20mph", r"serious injury have reduced by \d+ per cent \(from (\d+) to (\d+)\)", 2)}
    assert (A.results["history"]["tfl_ksi_before"], A.results["history"]["tfl_ksi_after"]) == (94, 71)
    assert A.results["history"]["plan_2018_deaths"] == A.results["history"]["dot_2018_deaths"], "the two documents agree on 2018"
    assert A.results["history"]["plan_2025_deaths"] > A.results["history"]["plan_2018_deaths"], "the page says 2018 is the lowest on the later count"
    H = A.results["history"]
    H.update({"mayor_decline_pct": num("mayor_30", r"down (\d+)% since its launch"),
              "vision_zero_launch_year": num("mayor_30_whole", r"since its launch in (\d{4})"),
              "dot_october_decline_pct": num("dot_28", r"down nearly (\d+)% since"),
              "advocate_decline_pct": num("advocate_34", r"deaths by (\d+)% over"),
              "plan_decade_before": num("plan_decade_before", r"approximately (\d+) traffic deaths"),
              "plan_decade_after": num("plan_decade_after", r"around (\d+) fatalities annually"),
              "plan_decade_decline_pct": num("plan_decade_pct", r"an (\d+)% reduction"),
              "plan_two_wheelers_peak": num("plan_two_wheelers_peak", r"peaking at (\d+) fatalities in 2023"),
              "plan_two_wheelers_2025": num("plan_two_wheelers_peak", r"elevated at (\d+) in 2025"),
              "plan_pedestrians_before": num("plan_pedestrians_counts", r"average of (\d+) deaths per year before"),
              "plan_pedestrians_after": num("plan_pedestrians_after", r"to (\d+) per year since its launch"),
              "council": {"turn_traffic_calming_pct": num("council_turns", r"Turn Traffic Calming, which reduced pedestrian casualties by (\d+) percent"),
                          "slow_zones_pct": num("council_slow_zones", r"Slow Zones, which reduced pedestrian casualties by (\d+) percent"),
                          "leading_pedestrian_intervals_pct": num("council_lpi", r"Intervals, which reduced pedestrian casualties by (\d+) percent"),
                          "citywide_speed_limit_pct": num("council_limit", r"Limit Reduction, which reduced pedestrian casualties by (\d+) percent"),
                          "intersections": int(_re.search(r"data at ([\d,]+) intersections", hist["council_scope"]["quote"]).group(1).replace(",", ""))},
              "comptroller_pedestrian_injury_pct": float(_re.search(r"roughly ([\d.]+)% of all pedestrian injuries", hist["comptroller_pedestrian_injuries"]["quote"]).group(1))})
    # the City's own yearly count, 2004 to 2025, as its plan charts it (the labels of the chart on the plan's page 40)
    series = [int(x) for x in _re.search(r"297 321 324 [\d ]+? 252 210", hist["plan_series"]["quote"]).group(0).split()]
    assert len(series) == 22, series
    city = dict(zip(range(2004, 2026), series))
    assert city[2018] == H["plan_2018_deaths"] and city[2025] == H["plan_2025_deaths"]
    H["city_series"] = {str(y): n for y, n in city.items()}
    # "since the launch" starts from 2013: the City's highest year since 2006. One year against one year, and decade
    # against decade, on the City's own count
    H["base_year"] = {"year": 2013, "deaths": city[2013], "highest_since": max(y for y in range(2004, 2013) if city[y] > city[2013])}
    H["decline_2013_to_2025_january_count_pct"] = r(100 * (H["dot_2025_deaths"] / city[2013] - 1), 2)
    H["decline_2013_to_2025_plan_count_pct"] = r(100 * (city[2025] / city[2013] - 1), 2)
    H["decade_mean_before"] = r(sum(city[y] for y in range(2004, 2014)) / 10, 1)
    H["vision_zero_years_mean"] = r(sum(city[y] for y in range(2014, 2026)) / 12, 1)
    H["decade_decline_pct"] = r(100 * (H["vision_zero_years_mean"] / H["decade_mean_before"] - 1), 2)
    assert H["base_year"]["highest_since"] == 2006, "the page says 2013 was the City's highest year since 2006"
    assert round(-H["decline_2013_to_2025_january_count_pct"]) == H["dot_decline_since_2014_pct"] == 31
    assert round(-H["decline_2013_to_2025_plan_count_pct"]) == H["mayor_decline_pct"] == 30
    assert (round(H["decade_mean_before"]), round(H["vision_zero_years_mean"])) == (H["plan_decade_before"], H["plan_decade_after"])
    assert round(-H["decade_decline_pct"]) == H["plan_decade_decline_pct"] == 16
    # the City's count per resident in its two lowest years (the Census Bureau's 1 July estimates): 2018 against 2025
    from nycdata import popest
    jp = popest.july_population()
    pop = {y: int(jp.loc[jp["year"] == y, "pop"].sum()) for y in (2024, 2025)}
    assert pop[2024] == int(nyr.loc[2024, "pop"]), "the 2025 residents must come from the series the rates use"
    pop18 = int(nyr.loc[2018, "pop"])
    H["city_rate"] = {"2018": r(city[2018] / pop18 * PER, 4), "2025": r(city[2025] / pop[2025] * PER, 4),
                      "2025_january_count": r(H["dot_2025_deaths"] / pop[2025] * PER, 4),
                      "residents_2018": pop18, "residents_2025": pop[2025]}
    assert H["city_rate"]["2025_january_count"] > H["city_rate"]["2018"], "the page says 2018 was lower per resident on either count"
    # Transport for London's two counts, held to the page's own test of two counts
    H["tfl_ksi_change"] = count_change(H["tfl_ksi_after"], H["tfl_ksi_before"])
    assert "205 recorded traffic deaths in 2025" in hist["dot_2025"]["quote"]
    assert "down 31 percent" in hist["dot_vz_decline"]["quote"]
    # the federal count over the span the City's sentence names, as far as FARS reaches (2013, the year before the
    # launch, to 2024): a check on the reading, never set beside the City's own figure as one series
    A.results["news_check"] = {"fars_2013": int(counts["new_york"][2013]), "fars_2024": int(counts["new_york"][2024]),
                               "fars_2013_2024": count_change(int(counts["new_york"][2024]), int(counts["new_york"][2013]))}

    from nycdata.excel import xlsx_rows
    note = next(" ".join(c for c in row if c) for row in xlsx_rows(R.WIEN_MA23) if any("Ab 2012 ge" in c for c in row))
    A.results["vienna_break_note"] = note[:200]
    assert "Ab 2012 geänderte Erhebungsmethode; ein direkter Vergleich mit den Vorjahresergebnissen ist daher nicht zulässig" in note

    # ---- the published figures the counts are held to (the page's "Check our work" box)
    ras = R.ras0402_london()
    A.reproduce("London, people killed on the roads in 2024 (Department for Transport, table RAS0402)",
                published=ras[2024], published_moe90=None, reproduced=int(counts["london"][2024]), kind="count", tolerance=0)
    berlin_published = R.berlin_report_killed(2025)
    berlin_q = Q.quote("afs_berlin_strassenverkehrsunfaelle_2025", "afs_berlin_strassenverkehrsunfaelle_2025.pdf",
                       f"Verunglückte Getötete {berlin_published}")
    A.reproduce("Berlin, people killed on the roads in 2025 (Amt für Statistik Berlin-Brandenburg, annual report, table 1.1)",
                published=berlin_published, published_moe90=None, reproduced=int(counts["berlin"][2025]),
                kind="count", tolerance=0)
    npa = R.npa_tokyo().set_index("year")
    A.reproduce("Tokyo, people killed within 24 hours in 2025 (National Police Agency's prefecture table)",
                published=int(npa.loc[2025, "deaths_24h"]), published_moe90=None, reproduced=int(counts["tokyo"][2025]),
                kind="count", tolerance=0)
    sg_q = Q.quote("spf_annual_road_traffic_situation_2025", "spf_annual_road_traffic_situation_2025.pdf",
                   "per 100,000 population) increased from 2.35 in 2024")
    A.reproduce("Singapore, road deaths per 100,000 population in 2024 (Singapore Police Force, annual road traffic situation)",
                published=2.35, published_moe90=None,
                reproduced=r(float(rate["singapore"].set_index("year").loc[2024, "per_100k"]), 2), kind="rate", tolerance=0.005)
    assert "2.35 in 2024" in sg_q["quote"]
    A.results["reproduction_source"] = ("The Department for Transport's table RAS0402 for London, the Berlin-Brandenburg "
                                        "statistics office's annual report for Berlin, the National Police Agency's prefecture "
                                        "table for Tokyo and the Singapore Police Force's yearly report: each published separately "
                                        "from the file we count from")
    A.results["reproduction_note"] = ("Counts of deaths must match exactly; Singapore's rate, which the police print to two "
                                      "places on the total population, within half a hundredth.")
    A.results["reproduction_quotes"] = {"berlin_2025": berlin_q}

    # ---- the FAQ's tables, signed, and what the prose prints
    table = {}
    pct = lambda x: 100 * (x - 1)   # noqa: E731
    for k in cities:
        c = cities[k]
        e, l = c["early"], c["late"]
        ratio_, lo_, hi_ = rate_ratio(l["deaths"], e["deaths"], l["person_years"], e["person_years"])
        _, slo, shi = rate_ratio(l["deaths"], e["deaths"], l["person_years"], e["person_years"], dispersion=phi[k])
        row = {"change": pct(ratio_), "lo": pct(lo_), "hi": pct(hi_), "lo_swing": pct(slo), "hi_swing": pct(shi),
               "early_deaths": e["deaths"], "late_deaths": l["deaths"]}
        if k != "new_york":
            ct = change_contrast(ny["late"]["deaths"], ny["early"]["deaths"], l["deaths"], e["deaths"],
                                 exposures_a=(ny["late"]["person_years"], ny["early"]["person_years"]),
                                 exposures_b=(l["person_years"], e["person_years"]), nd=6,
                                 dispersion=max(phi["new_york"], phi[k]))
            row.update({"contrast": ct["change_pct"], "contrast_lo": ct["lo_pct"], "contrast_hi": ct["hi_pct"]})
            row.update({"level_ratio": vs[k]["ratio_swing"][0], "level_lo": vs[k]["ratio_swing"][1], "level_hi": vs[k]["ratio_swing"][2]})
        table[k] = row
    A.results["table"] = table
    recent = {}
    for k in cities:
        s, again = since_low[k], A.results["robustness"]["changes"][f"since_2017_2019_{k}"]
        recent[k] = {"low_deaths": period(rate[k], LOW)["deaths"], "late_deaths": cities[k]["late"]["deaths"], "change": s["change_pct"],
                     "lo": s["lo_pct"], "hi": s["hi_pct"], "lo_swing": again["lo_pct"], "hi_swing": again["hi_pct"]}
    A.results["table_recent"] = recent
    def near_zero(x: float) -> str:
        """A range's end within one point of no change keeps a decimal, so a range that clears does not print as 0%."""
        return f"{x:+.1f}%".replace("-", "−") if 0 < abs(x) < 1 else signed(x)
    for k in recent:
        for f in ("change", "lo", "hi", "lo_swing", "hi_swing"):
            A.printed(f"table_recent.{k}.{f}", near_zero(recent[k][f]))
        A.printed(f"table_recent.{k}.low_deaths", f"{recent[k]['low_deaths']:,}")
    windows = {}
    for key, path, before, after in (("before_vision_zero", "new_york.fall_to_pre_vision_zero", first3, pre),
                                     ("vision_zero_five_years", "vision_zero_timing.change", None, None),
                                     ("since_2015_2019", "new_york.since_wider_low", wl, ny["late"]),
                                     ("since_2009_2013", "new_york.since_before_vision_zero", vzb, ny["late"])):
        node = K.get(A.results, path)
        again = A.results["robustness"]["changes"][path.replace(".", "_")]
        if before is None:
            before, after = A.results["vision_zero_timing"]["before"], A.results["vision_zero_timing"]["after"]
        windows[key] = {"before": before["years"], "after": after["years"], "before_deaths": before["deaths"], "after_deaths": after["deaths"],
                        "before_rate": before["rate"], "after_rate": after["rate"], "change": node["change_pct"], "lo": node["lo_pct"],
                        "hi": node["hi_pct"], "lo_swing": again["lo_pct"], "hi_swing": again["hi_pct"]}
    A.results["table_new_york"] = windows
    for key, w in windows.items():
        for f in ("change", "lo", "hi", "lo_swing", "hi_swing"):
            A.printed(f"table_new_york.{key}.{f}", signed(w[f]))
        for f in ("before_deaths", "after_deaths"):
            A.printed(f"table_new_york.{key}.{f}", f"{w[f]:,}")
        for f in ("before_rate", "after_rate"):
            A.printed(f"table_new_york.{key}.{f}", f"{w[f]:.1f}")
    for k in cities:
        c = cities[k]
        for per in ("early", "late", "level"):
            A.printed(f"cities.{k}.{per}.rate", rate_text(c[per]))
        A.printed(f"cities.{k}.change.change_pct", change_size(c["change"], exposure_now=c["late"]["person_years"] / PER,
                                                              exposure_before=c["early"]["person_years"] / PER))
        fields = ("change", "lo", "hi", "lo_swing", "hi_swing") + (("contrast", "contrast_lo", "contrast_hi") if k != "new_york" else ())
        for f in fields:
            A.printed(f"table.{k}.{f}", signed(table[k][f]))
        for f in ("early_deaths", "late_deaths"):
            A.printed(f"table.{k}.{f}", f"{table[k][f]:,}")
        if k != "new_york":
            for f in ("level_ratio", "level_lo", "level_hi"):
                A.printed(f"table.{k}.{f}", f"{table[k][f]:.2f}")
    A.printed("cities.new_york.latest.deaths", f"{cities['new_york']['latest']['deaths']:,}")
    for k in ("london", "madrid", "singapore"):
        A.printed(f"vs_new_york.{k}.ratio", f"{vs[k]['ratio']:.1f}")
    A.printed("vs_new_york.london.ratio_early", f"{vs['london']['ratio_early']:.1f}")
    A.results["rate_base"] = PER
    A.printed("rate_base", f"{PER:,}")
    for k in US:
        A.printed(f"since_2017_2019.{k}.change_pct", change_size(since_low[k], exposure_now=cities[k]["late"]["person_years"] / PER,
                                                                 exposure_before=since_low[k]["low_person_years"] / PER))
    nyl = A.results["new_york"]
    A.printed("new_york.first.deaths", f"{nyl['first']['deaths']:,}")
    A.printed("new_york.first.rate", f"{nyl['first']['rate']:.1f}")
    A.printed("new_york.lowest_year.deaths", f"{nyl['lowest_year']['deaths']:,}")
    A.printed("new_york.lowest_year.rate", f"{nyl['lowest_year']['rate']:.1f}")
    A.printed("new_york.lowest_year.year", str(nyl["lowest_year"]["year"]))
    A.printed("new_york.fall_to_low.change_pct", change_size(nyl["fall_to_low"], exposure_now=nyl["low"]["person_years"] / PER,
                                                             exposure_before=nyl["first3"]["person_years"] / PER))
    vz = A.results["vision_zero_timing"]
    A.printed("vision_zero_timing.before.rate", rate_text(vz["before"]))
    A.printed("vision_zero_timing.after.rate", rate_text(vz["after"]))
    A.printed("vision_zero_timing.change.change_pct", change_size(vz["change"], exposure_now=vz["after"]["person_years"] / PER,
                                                                  exposure_before=vz["before"]["person_years"] / PER))
    nw = A.results["now"]
    for y in (2025, NOW_YEAR):
        A.printed(f"now.ytd.{y}", f"{nw['ytd'][str(y)]:,}")
    A.printed("now.year_2024", f"{nw['year_2024']:,}")
    A.printed("now.year_2025", f"{nw['year_2025']:,}")
    A.printed("now.late_additions.may_2026_in_june_file", str(nw["late_additions"]["may_2026_in_june_file"]))
    A.printed("now.late_additions.may_2026_now", str(nw["late_additions"]["may_2026_now"]))
    h = A.results["history"]
    A.printed("history.dot_2025_deaths", str(h["dot_2025_deaths"]))
    A.printed("history.dot_2024_deaths", str(h["dot_2024_deaths"]))
    A.printed("history.dot_2018_deaths", str(h["dot_2018_deaths"]))
    se = A.results["sensitivity"]
    A.printed("sensitivity.fars_ebike_bound.ebike_riders_killed", str(se["fars_ebike_bound"]["ebike_riders_killed"]))
    A.printed("sensitivity.fars_ebike_bound.rate_with", f"{se['fars_ebike_bound']['rate_with']:.1f}")
    A.printed("sensitivity.fars_ebike_bound.others_killed_ebike_only", str(se["fars_ebike_bound"]["others_killed_ebike_only"]))
    A.printed("sensitivity.fars_ebike_bound.no_motor_vehicle", str(se["fars_ebike_bound"]["no_motor_vehicle"]))
    A.printed("sensitivity.fars_ebike_bound.rate_with_no_motor_vehicle", f"{se['fars_ebike_bound']['rate_with_no_motor_vehicle']:.1f}")
    A.printed("history.plan_2025_deaths", str(h["plan_2025_deaths"]))
    A.printed("history.plan_2018_deaths", str(h["plan_2018_deaths"]))
    A.printed("history.plan_pedestrian_fall_pct", f"{h['plan_pedestrian_fall_pct']}%")
    A.printed("history.tfl_ksi_fall_pct", f"{h['tfl_ksi_fall_pct']}%")
    A.printed("history.tfl_ksi_before", str(h["tfl_ksi_before"]))
    A.printed("history.tfl_ksi_after", str(h["tfl_ksi_after"]))
    A.printed("now.crash_table_check.fewest_month_deaths", str(nw["crash_table_check"]["fewest_month_deaths"]))
    A.printed("new_york.first3.rate", rate_text(nyl["first3"]))
    A.printed("new_york.pre_vision_zero.rate", rate_text(nyl["pre_vision_zero"]))
    A.printed("new_york.fall_to_pre_vision_zero.change_pct",
              change_size(nyl["fall_to_pre_vision_zero"], exposure_now=nyl["pre_vision_zero"]["person_years"] / PER,
                          exposure_before=nyl["first3"]["person_years"] / PER))
    A.printed("new_york.pace_before_vision_zero_pct", f"{abs(nyl['pace_before_vision_zero_pct']):.1f}%")
    A.printed("new_york.pace_after_pct", f"{abs(nyl['pace_after_pct']):.1f}%")
    A.printed("history.vision_zero_launch_year", str(h["vision_zero_launch_year"]))
    A.printed("new_york.since_before_vision_zero.change_pct",
              change_size(nyl["since_before_vision_zero"], exposure_now=ny["late"]["person_years"] / PER,
                          exposure_before=vz["before"]["person_years"] / PER))
    for key in ("mayor_decline_pct", "dot_october_decline_pct", "advocate_decline_pct", "plan_decade_decline_pct"):
        A.printed(f"history.{key}", f"{h[key]}%")
    A.printed("history.base_year.deaths", str(h["base_year"]["deaths"]))
    A.printed("history.city_rate.2018", f"{h['city_rate']['2018']:.1f}")
    A.printed("history.city_rate.2025", f"{h['city_rate']['2025']:.1f}")
    assert f"{h['city_rate']['2025_january_count']:.1f}" == f"{h['city_rate']['2025']:.1f}", "the page says 2.4 on either count"
    for key in ("turn_traffic_calming_pct", "slow_zones_pct", "leading_pedestrian_intervals_pct", "citywide_speed_limit_pct"):
        A.printed(f"history.council.{key}", f"{h['council'][key]}%")
    A.printed("history.council.intersections", f"{h['council']['intersections']:,}")
    A.printed("history.comptroller_pedestrian_injury_pct", f"{h['comptroller_pedestrian_injury_pct']}%")
    A.printed("sensitivity.fars_ebike_bound.pedestrians_killed", str(se["fars_ebike_bound"]["pedestrians_killed"]))
    A.printed("sensitivity.fars_ebike_bound.all_vehicle_fields.crashes", str(se["fars_ebike_bound"]["all_vehicle_fields"]["crashes"]))
    A.printed("sensitivity.fars_ebike_bound.change_with_no_motor_vehicle_pct",
              f"{abs(se['fars_ebike_bound']['change_with_no_motor_vehicle_pct']):.0f}%")
    A.printed("sensitivity.fars_ebike_bound.change_with_upper_bound_pct",
              f"{abs(se['fars_ebike_bound']['change_with_upper_bound_pct']):.0f}%")
    A.results["sensitivity"]["tokyo_30d_over_24h_pct"] = r(100 * (se["tokyo_30d_over_24h"] - 1), 1)
    A.printed("sensitivity.tokyo_30d_over_24h_pct", f"{se['tokyo_30d_over_24h_pct']:.0f}%")
    for name in ("ratio", "lo", "hi"):
        A.printed(f"sensitivity.singapore_residents_only.new_york_ratio.{name}",
                  f"{se['singapore_residents_only']['new_york_ratio'][name]:.2f}")
    for k in POST_BREAK:
        A.printed(f"sensitivity.{k}_post_break.new_york_change.change_pct",
                  f"{abs(se[f'{k}_post_break']['new_york_change']['change_pct']):.0f}%")
    # the chart titles and the headings are typed: hold each to the results it states (the code review, C4)
    four = [k for k in A.results["contrast_summary"]["new_york_fell_less_than"] if k not in POST_BREAK]
    assert four == ["london", "tokyo", "hong_kong", "singapore"], four
    A.results["contrast_summary"]["on_consistent_counts"] = four
    assert not A.results["order"]["outside_us_above_new_york"], "the heading says all nine had fewer"
    assert set(A.results["beliefs"]["rose_since_2017_2019"]) == set(US), "the title says only the three American cities rose"
    assert nyl["lowest_year"]["year"] == 2018 and nyl["fall_to_low"]["change_pct"] < -50, "the title says more than half, to 2018"
    for k in ("london", "tokyo", "hong_kong"):
        assert vs[k]["ratio_swing"][1] > 2 and vs[k]["ratio_late"] > vs[k]["ratio_early"], f"the headline says more than twice {k}'s, and a growing gap"
    A.printed("sensitivity.fars_ebike_bound.london_ratio_with", f"{se['fars_ebike_bound']['london_ratio_with']:.1f}")
    A.printed("sensitivity.singapore_residents_only.rate", f"{se['singapore_residents_only']['rate']:.1f}")
    A.printed("sensitivity.singapore_residents_only.non_resident_share", f"{100 * se['singapore_residents_only']['non_resident_share']:.0f}%")
    for k in POST_BREAK:
        node = se[f"{k}_post_break"]
        A.printed(f"sensitivity.{k}_post_break.change.change_pct",
                  change_size(node["change"], exposure_now=cities[k]["late"]["person_years"] / PER,
                              exposure_before=node["base"]["person_years"] / PER))
        A.printed(f"sensitivity.{k}_post_break.base.rate", rate_text(node["base"]))
    A.printed("new_york.since_wider_low.change_pct", change_size(nyl["since_wider_low"], exposure_now=ny["late"]["person_years"] / PER,
                                                                 exposure_before=nyl["wider_low"]["person_years"] / PER))
    A.printed("new_york.low.deaths", f"{nyl['low']['deaths']:,}")
    A.printed("cities.new_york.late.deaths", f"{ny['late']['deaths']:,}")
    A.printed("new_york.pop_change_since_low_pct", f"{abs(nyl['pop_change_since_low_pct']):.0f}%")
    nc = A.results["news_check"]
    A.printed("news_check.fars_2013", str(nc["fars_2013"]))
    A.printed("news_check.fars_2024", str(nc["fars_2024"]))
    A.printed("news_check.fars_2013_2024.change_pct", change_size(nc["fars_2013_2024"]))
    A.printed("history.dot_decline_since_2014_pct", f"{h['dot_decline_since_2014_pct']} percent")
    A.results["size"]["tokyo_millions"] = r(A.results["size"]["population_late_mean"]["tokyo"] / 1e6, 1)
    A.printed("size.tokyo_millions", f"{A.results['size']['tokyo_millions']:.0f}")
    A.results["responses_figures"] = {"madrid_pedestrian_cut": 50, "seoul_target": 1.8, "seoul_new_york": 2.9,
                                      "seoul_london_berlin": 1.5}
    for key, (city, needle, text) in {"madrid_pedestrian_cut": ("madrid", "Reducir un 50% la media", "50%"),
                                      "seoul_target": ("seoul", "목표치 1.8명은", "1.8"),
                                      "seoul_new_york": ("seoul", "뉴욕 2.9명보다는", "2.9"),
                                      "seoul_london_berlin": ("seoul", "베를린 1.5명과", "1.5")}.items():
        assert any(needle in d["quote"] for d in A.results["responses"][city]), (key, needle)
        A.printed(f"responses_figures.{key}", text)

    # ---- charts
    E, L = f"{EARLY[0]}-{EARLY[1]}", f"{LATE[0]}-{LATE[1]}"
    years_ny = list(range(LONG_FROM, int(nyr.index.max()) + 1))
    A.chart("long_view", lines(
        title="New York's road deaths per resident fell by more than half to 2018, then rose",
        subtitle="People killed on New York City's roads per 100,000 residents, 1995 to 2024",
        x=[[str(t), str(t)] for t in years_ny],
        series=[["new_york", "New York City", "New York"]],
        cells={"": {"new_york": {str(t): r(nyr.loc[t, "per_100k"], 2) for t in years_ny}}},
        format="dec1", axis="Deaths per 100,000 residents",
        x_ticks=[str(t) for t in years_ny if t % 5 == 0 or t == years_ny[-1]],
        note="Deaths within 30 days of a crash involving a motor vehicle on a public road, in the five boroughs (FARS). "
             "From 2022 FARS no longer collects crashes involving only e-bikes, so the last three years are a little low "
             "against the earlier ones. 2024 is FARS's Annual Report File, replaced by a final file about a year later; the "
             "City's and the police's own counts for 2025 and 2026 are different counts and are not drawn here.",
        provenance="NHTSA Fatality Analysis Reporting System; Census Bureau population estimates"))

    A.chart("then_and_now", strip(
        title="All nine cities here outside the United States had fewer road deaths per resident than New York in 2022-2024",
        subtitle=f"People killed on the roads per 100,000 residents a year, {E} against {L}",
        x=[[E, f"{EARLY[0]} to {EARLY[1]}"], [L, f"{LATE[0]} to {LATE[1]}"]],
        series=[[k, label + (" (within 24 hours)" if k == "tokyo" else ""), short + (" (24 hours)" if k == "tokyo" else "")]
                for k, label, short in CITIES] + [["tokyo_30d", "Tokyo (within 30 days)", "Tokyo (30 days)"]],
        cells={"": {**{k: {E: cities[k]["early"]["rate"], L: cities[k]["late"]["rate"]} for k in cities},
                    "tokyo_30d": {L: cities["tokyo"]["level"]["rate"]}}},
        format="dec1", axis="Deaths per 100,000 residents a year",
        note="Each city's official count, mostly deaths within 30 days of the crash. Tokyo's long series counts deaths "
             "within 24 hours; its 30-day count for 2022-2024 is about 30% higher. The Madrid region is the "
             f"Comunidad de Madrid, motorways included, and its {E} counts are estimates; Toronto's records leave "
             "out the provincial highways. Each change carries a 90% range (the FAQ lists them).",
        provenance="NHTSA FARS; UK DfT; ONISR; AfS Berlin-Brandenburg; Statistik Austria; DGT; City of Toronto; "
                   "Tokyo Metropolitan Police; Hong Kong Transport Department; Singapore Police Force; national and city "
                   "population estimates"))

    years_w = list(range(2005, 2026))
    def cell(k, t):
        s = rate[k].set_index("year")["per_100k"]
        return r(s[t], 2) if t in s.index else None
    A.chart("world_lines", lines(
        title="London's, Tokyo's, Hong Kong's and Singapore's road deaths per resident fell by about half; New York's fell by a fifth",
        subtitle="People killed on the roads per 100,000 residents, 2005 to 2025",
        x=[[str(t), str(t)] for t in years_w],
        series=[[k, dict((a, b) for a, b, _ in CITIES)[k] + (" (24 hours)" if k == "tokyo" else ""),
                 dict((a, c) for a, _, c in CITIES)[k]] for k in WORLD_LINES],
        cells={"": {k: {str(t): cell(k, t) for t in years_w} for k in WORLD_LINES}},
        format="dec1", axis="Deaths per 100,000 residents",
        x_ticks=[str(t) for t in years_w if t % 5 == 0],
        note="Each line runs where its city's count reaches: New York's to 2024, FARS's latest year (from 2022 FARS no "
             "longer collects crashes involving only e-bikes), Hong Kong's open file from 2007 to 2024, the Madrid region's to "
             "2024 (its counts before 2011 estimated). Tokyo counts deaths within 24 hours, the others within 30 days; "
             "Vienna's recording changed in 2012. Paris, Berlin, Toronto, Chicago and Los Angeles are in the data file.",
        provenance="NHTSA FARS; UK DfT; Statistik Austria; Tokyo Metropolitan Police; Hong Kong Transport Department; "
                   "Singapore Police Force; national and city population estimates"))

    years_us = list(range(2000, 2025))
    A.chart("us_cities", lines(
        title="All three American cities' rates rose after 2019; New York's stayed far below the other two's",
        subtitle="People killed on the roads per 100,000 residents in three American cities, 2000 to 2024",
        x=[[str(t), str(t)] for t in years_us],
        series=[["new_york", "New York City", "New York"], ["chicago", "City of Chicago", "Chicago"],
                ["los_angeles", "City of Los Angeles", "Los Angeles"]],
        cells={"": {k: {str(t): cell(k, t) for t in years_us} for k in US}},
        format="dec1", axis="Deaths per 100,000 residents",
        x_ticks=[str(t) for t in years_us if t % 5 == 0 or t == years_us[-1]],
        note="All three from FARS, the same federal count: crashes FARS places inside each city's limits (New York's five "
             "boroughs). From 2022 FARS no longer collects crashes involving only e-bikes, in all three cities alike.",
        provenance="NHTSA Fatality Analysis Reporting System; Census Bureau population estimates"))

    month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    cum = {}
    for y in (2024, 2025, NOW_YEAR):
        tot, cum[str(y)] = 0, {}
        for m in range(1, 13):
            if (y, m) > (NOW_YEAR, NOW_MONTHS):
                break
            tot += month(y, m)
            cum[str(y)][month_names[m - 1]] = tot
    A.chart("this_year", lines(
        title="This year is running close to last year on the police's count",
        subtitle="People killed on New York City's roads, running total from January, NYPD crash records",
        x=[[m, m] for m in month_names],
        series=[["2024", "2024", "2024"], ["2025", "2025", "2025"], [str(NOW_YEAR), f"{NOW_YEAR} (to October)", str(NOW_YEAR)]],
        cells={"": cum}, format="num", axis="People killed since 1 January",
        x_axis="Month",
        note="The police's person-level crash records, a different count from FARS and from the City's official count. "
             "Deaths are added when someone dies days after a crash, so the latest months still grow.",
        provenance=f"NYPD Motor Vehicle Collisions - Person (NYC Open Data), retrieved {NYPD_RETRIEVED}"))

    rows = []
    for k, label, _ in CITIES:
        for _, x in rate[k].iterrows():
            rows.append({"city": label + (" (24 hours)" if k == "tokyo" else ""), "area": R.AREAS[k][0], "year": int(x["year"]), "deaths": int(x["deaths"]),
                         "residents": int(x["pop"]), "deaths_per_100k": r(x["per_100k"], 3), "definition": R.AREAS[k][2],
                         "counted_by": R.AREAS[k][1]})
    for _, x in rate["tokyo_30d"].iterrows():
        rows.append({"city": "Tokyo (30 days)", "area": R.AREAS["tokyo_30d"][0], "year": int(x["year"]), "deaths": int(x["deaths"]),
                     "residents": int(x["pop"]), "deaths_per_100k": r(x["per_100k"], 3), "definition": R.AREAS["tokyo_30d"][2],
                     "counted_by": R.AREAS["tokyo_30d"][1]})
    A.write(data=pd.DataFrame(rows))
    print(f"{SLUG}: wrote {A.out}")
    return 0


#: What each city has set out to do about road deaths, from its own documents: city -> [(source id, saved file,
#: needle, what it establishes)]. Every sentence the page prints about a plan or a limit rests on one of these quotes.
RESPONSES = {
    "new_york": [("nyc_vision_zero_action_plan_2014", "nyc_vision_zero_action_plan_2014.pdf",
                  "the power to reduce the citywide speed limit to 25mph", "plan: Vision Zero, 2014, asked Albany for a 25 mph limit"),
                 ("nyc_dot_speed_limit_25_2014", "nyc_dot_25mph_release_2014-10-15.html",
                  "New law lowering the default speed limit across New York City to take effect on November 7",
                  "limit: 25 mph by default from 7 November 2014"),
                 ("nyc_vision_zero_reimagined_2026", "nyc_vision_zero_reimagined_2026.pdf",
                  "to lower speed limits to 15 mph at every eligible school location", "limit: 15 mph at schools, under Sammy's Law"),
                 ("nyc_vision_zero_reimagined_2026", "nyc_vision_zero_reimagined_2026.pdf",
                  "Expand 20 MPH speed limits within entire neighborhoods", "plan: 20 mph zones, 2026"),
                 ("nyc_vision_zero_reimagined_2026", "nyc_vision_zero_reimagined_2026.pdf",
                  "eliminate traffic deaths and serious injuries over the next decade", "plan: the 2026 plan's goal")],
    "london": [("tfl_vision_zero_action_plan_2018", "tfl_vision_zero_action_plan_2018.pdf",
                "by 2041, all deaths and serious injuries will be eliminated from London", "plan: zero by 2041"),
               ("tfl_press_20mph_2023", "tfl_press_20mph_2023.html",
                "Currently over half of London's roads have a 20mph speed limit", "limit: 20 mph on over half the roads")],
    "paris": [("paris_vitesse_30_kmh_page", "paris_vitesse_30_kmh_page.html",
               "La circulation des véhicules est limitée à 30 km/h depuis le 30 août 2021 dans tout Paris",
               "limit: 30 km/h across Paris since 30 August 2021"),
              ("paris_peripherique_50_kmh_press_2024", "paris_peripherique_50_kmh_press_2024.pdf",
               "mettra en application la mesure le 1er octobre", "limit: the ring road at 50 km/h from 1 October 2024")],
    "berlin": [("berlin_mobilitaetsgesetz_2018", "berlin_mobilitaetsgesetz_2018.pdf",
                "ist Leitlinie für alle Planungen, Standards und Maßnahmen", "law: Vision Zero in the mobility law, 2018")],
    "vienna": [("wien_step2025_fachkonzept_mobilitaet", "wien_step2025_fachkonzept_mobilitaet.pdf",
                "soll weiter verfolgt werden", "plan: Vision Zero in the city's mobility plan, 2014"),
               ("bmimi_verkehrssicherheit_jahresbericht_2024", "bmimi_verkehrssicherheit_jahresbericht_2024.pdf",
                "Halbierung der Verkehrstoten und Schwerverletzten bis zum Jahr 2030", "plan: Austria halves deaths by 2030")],
    "madrid": [("madrid_plan_estrategico_seguridad_vial_2021_2030", "madrid_plan_estrategico_seguridad_vial_2021_2030.pdf",
                "Reducir un 50% la media anual de fallecidos por atropello", "plan: halve pedestrian deaths"),
               ("boe_real_decreto_970_2020_velocidad_urbana", "boe_real_decreto_970_2020_velocidad_urbana.pdf",
                "30 km/h en vías de un único carril por sentido de circulación", "limit: 30 km/h on one-lane streets, Spain, 2021")],
    "toronto": [("toronto_vision_zero_annual_report_2025", "toronto_vision_zero_annual_report_2025.pdf",
                 "initiated the Vision Zero Road Safety Plan in 2016", "plan: Vision Zero, 2016"),
                ("toronto_vision_zero_annual_report_2025", "toronto_vision_zero_annual_report_2025.pdf",
                 "reducing the speed limits on all local roads and laneways within an area to 30 km/h",
                 "limit: 30 km/h on local roads, area by area")],
    "tokyo": [("tmg_traffic_safety_plan_12_overview_2026", "tmg_traffic_safety_plan_12_overview_2026.pdf",
               "主要都市（ロンドン・ニューヨーク・パリ）の中で最も少ないロンドンの", "plan: a target below London's level"),
              ("tmg_traffic_safety_plan_12_overview_2026", "tmg_traffic_safety_plan_12_overview_2026.pdf",
               "水準を下回る目標を設定", "plan: a target below London's level (the sentence's end)"),
              ("npa_residential_roads_30kmh_2026", "npa_residential_roads_30kmh_2026.html",
               "法定速度 が60km/hから 30km/h に引き下げ となります", "limit: 30 km/h on residential roads from September 2026")],
    "hong_kong": [("hk_seat_belts_mobile_devices_press_2026", "hk_seat_belts_mobile_devices_press_2026.html",
                   "all public transport and commercial vehicles' seated passengers must wear seat belts",
                   "rule: seat belts in public transport and commercial vehicles from January 2026")],
    "singapore": [("spf_annual_road_traffic_situation_2025", "spf_annual_road_traffic_situation_2025.pdf",
                   "from 142 persons in 2024 to 149 persons in 2025", "count: the police's own 2025 count"),
                  ("spf_annual_road_traffic_situation_2025", "spf_annual_road_traffic_situation_2025.pdf",
                   "Speed compliance is a key strategy to improve road safety", "plan: speed enforcement"),
                  ("spf_annual_road_traffic_situation_2025", "spf_annual_road_traffic_situation_2025.pdf",
                   "the concerning upward trend in road fatalities over the past five years", "warning: the police's own words"),
                  ("mha_enhanced_penalties_speeding_2025", "mha_enhanced_penalties_speeding_2025.html",
                   "will be raising the penalties for speeding offences with effect from 1 January 2026",
                   "rule: higher speeding penalties from January 2026")],
    "seoul": [("seoul_traffic_safety_plan_2017_press", "seoul_traffic_safety_plan_2017_press.html",
               "목표치 1.8명은 뉴욕 2.9명보다는 낮고 런던, 베를린 1.5명과 유사한 수준이다",
               "plan: a 2021 target below New York's rate, near London's and Berlin's"),
              ("seoul_speed_limit_5030_press_2020", "seoul_speed_limit_5030_press_2020.html",
               "간선도로는 시속 50km, 이면도로는 시속 30km를 기본으로", "limit: 50 km/h on arterials, 30 km/h on side streets")],
}



if __name__ == "__main__":
    raise SystemExit(main())
