"""Where New York's population change comes from, against ten other big cities': the analysis behind a SparkyData
article.

    py src/build_article.py where-big-cities-grow-from

Each city's population from its own statistical office (card ``world_city_population``) and its change split into
births minus deaths, net moves from the rest of the same country, and net moves from abroad (card
``world_city_components``): New York City from the Census Bureau, with Cook County (Chicago) and Los Angeles County from
the same county files; Greater London from ONS; Paris with its inner ring (and the City of Paris) from INSEE; Tokyo-to
from the Tokyo Metropolitan Government; the Toronto and Montreal metropolitan areas from Statistics Canada; Hong Kong
from its Census and Statistics Department; Singapore from SingStat; the Comunidad de Madrid from INE. Each office
counts on its own year (to 1 July, to 30 June, calendar years) and its own basis, kept and named: Paris's, Madrid's and
Singapore's migration is a residual, both kinds of move together; Tokyo's births, deaths and moves from other
prefectures count Japanese residents, and its moves from abroad sit in "other"; Hong Kong's moves are all from outside.

Each component is a rate per 1,000 residents a year, on the area's population in the same year, averaged over
2002-2011 and over the last ten years, 2016-2025 (Madrid to 2024). These are each office's estimates, published
without margins, so the page compares ten-year averages and the direction of every year, never one year's small
difference. Growth since 2001 comes from the population series. The current reading is 2026 so far where an office
publishes it: Tokyo and Paris to September, New York to March, Hong Kong's year to mid-2026 (provisional).

How each city or its country steers its population comes from its own published document, quoted (``A.quotes``):
a projection, an immigration plan, a measure for births. None is set beside a count as a cause.

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

from __future__ import annotations

import pandas as pd

from article_kit import Article, lines, r, strip
from sparkylib.stats import count_change
from nycdata import world_components as C, world_population as P
from nycdata.paths import REFERENCE

SLUG = "where-big-cities-grow-from"
SEED = 20261104
#: the eleven cities, New York first; the area each stands for is in world_components.AREAS
CITIES = [("new_york", "New York"), ("london", "London"), ("paris_inner", "Paris and inner ring"), ("tokyo", "Tokyo"),
          ("toronto_cma", "Toronto area"), ("montreal_cma", "Montreal area"), ("chicago", "Chicago (Cook County)"),
          ("los_angeles", "Los Angeles County"), ("hong_kong", "Hong Kong"), ("singapore", "Singapore"), ("madrid", "Madrid region")]
OTHERS = tuple(k for k, _ in CITIES if k != "new_york")
SPLIT = ("new_york", "london", "toronto_cma", "montreal_cma", "chicago", "los_angeles")   # moves within the country apart from abroad
RESIDUAL = ("paris_inner", "singapore", "madrid")                                       # migration as change less natural
FIRST = (2002, 2011)
LAST10 = (2016, 2025)
PRE_PANDEMIC = (2016, 2019)
BASE = 2001
LAST = 2025
ENDS = {"madrid": 2024}          # an office whose last year is earlier
DOCS = {"census": ("census_blog_nim_decline_2026", "census_blog_historic_decline_nim_2026-01.html",
                   "Peaked at 2.7 million in 2024. Declined to 1.3 million in 2025"),
        "dcp": ("dcp_population_estimates_july_2026", "dcp_population_estimates_july_2026.pdf",
                "Net international inflows retreated from recent historical highs to more typical levels experienced before the pandemic"),
        "ons": ("ons_bulletin_mye_ew_mid2025", "ons_mye_ew_mid2025_bulletin.pdf",
                "London's population decreased by 0.29% in the year to mid-2025, the first decrease since the year to mid-2021"),
        "statcan": ("statcan_daily_20260114_subprovincial", "statcan_daily_20260114_subprovincial.html",
                    "This is in contrast with a record growth (+269,143; +3.9%) a year earlier"),
        "dcp_revision": ("dcp_population_estimates_july_2026", "dcp_population_estimates_july_2026.pdf", "from 8,478,000 to 8,597,000"),
        "statcan_npr": ("statcan_daily_20260114_subprovincial", "statcan_daily_20260114_subprovincial.html",
                        "particularly among study permit holders"),
        "insee": ("insee_ip2087_bilan_demographique_2025", "insee_ip2087_bilan_demographique_2025.pdf",
                  "le solde naturel en France est négatif pour la première fois depuis la fin de la Seconde Guerre mondiale")}
#: How each city or its country steers its population, from its own documents: city -> [(source id, saved file,
#: needle, what it establishes)]. Filled from the registered documents (see RESPONSES_NOTE); empty cities print
#: "not in the documents we registered".
RESPONSES: dict[str, list[tuple[str, str, str, str]]] = {
    "new_york": [("dcp_population_projections_2030_2055", "dcp_population_projections_2030_2055.pdf",
                  "we project continued population growth through 2055", "projection: growth to 2055"),
                 ("dcp_city_of_yes_housing_final_plan", "dcp_city_of_yes_housing_opportunity_final_plan.pdf",
                  "82,000 new homes over the next 15 years", "plan: homes, 82,000 over fifteen years")],
    "london": [("gla_2024_based_population_projections_blog", "gla_2024_based_population_projections_blog.html",
                "projected to reach between 9.86 million", "projection: 9.86 to 10.25 million by 2046"),
               ("gla_draft_london_plan_2026_press", "gla_draft_london_plan_2026_press.html",
                "as many as 558,000 homes by 2037", "plan: homes, 558,000 by 2037")],
    "paris": [("insee_flash_idf_72_projections_2070", "insee_flash_idf_72_projections_2070.html",
               "la population de l'Île-de-France s'élèverait à 12,53 millions", "projection: Île-de-France 12.53 million in 2070"),
              ("idf_sdrife_adopte_news_2025", "idf_sdrife_adopte_news_2025.html",
               "50 000 nouveaux Franciliens chaque année", "plan: 50,000 new residents and 70,000 homes a year")],
    "tokyo": [("tmg_population_projection_2023_no74", "tmg_population_projection_2023_dy23rf0000.pdf",
               "万人でピークを迎える", "projection: a peak of 14.24 million in 2030"),
              ("tmg_population_projection_2024_no75", "tmg_household_projection_2024_sy24rf0000.pdf",
               "1426.5 万人", "the March 2024 report's restatement of the peak: 14.265 million in 2030"),
              ("cfa_kasokuka_plan_shienkin_page", "cfa_kasokuka_plan_shienkin_page.html",
               "3．6兆円規模の子育て支援", "births: 3.6 trillion yen of child-rearing support")],
    "toronto": [("ontario_mof_population_projections_2025_2051", "ontario_population_projections_2025_2051.html",
                 "almost 3.6 million by 2051", "projection: the city 3.6 million by 2051, after a fall of 200,000"),
                ("ontario_mof_population_projections_2025_2051", "ontario_population_projections_2025_2051.html",
                 "driven primarily by the decline in non-permanent residents", "the fall's stated driver"),
                ("ircc_levels_plan_2026_2028_qp_note", "ircc_levels_plan_2026_2028_qp_note.html",
                 "PR Targets 380,000 380,000 380,000", "immigration: 380,000 permanent residents a year, 2026-2028")],
    "montreal": [("isq_projections_2026_communique", "isq_projections_2026_communique.html",
                  "1,96 million de personnes", "projection: the island back to 1.96 million by 2051, the ring to 2.5 million"),
                 ("ircc_levels_plan_2026_2028_qp_note", "ircc_levels_plan_2026_2028_qp_note.html",
                  "TR Targets 385,000 370,000 370,000", "immigration: temporary arrivals cut to 385,000 then 370,000")],
    "chicago": [("cmap_onto2050_socioeconomic_forecast_appendix", "cmap_onto2050_socioeconomic_forecast_appendix.pdf",
                 "more than 10.6 million residents compared with 8.5 million in 2015", "projection: the seven-county region 10.6 million by 2050")],
    "los_angeles": [("ca_budget_2026_27_demographic_information", "ca_budget_2026_27_demographic_information.pdf",
                     "reach a peak of 40.8 million", "projection: California peaks at 40.8 million in 2050"),
                    ("ca_budget_2026_27_demographic_information", "ca_budget_2026_27_demographic_information.pdf",
                     "largest numeric decline of almost 28,500 persons", "the county's fall of 28,500 in 2024-25")],
    "hong_kong": [("hk_csd_population_projections_2022_2046_press", "hk_csd_population_projections_2022_2046_press.htm",
                   "will reach 8.19 million in mid-2046", "projection: 8.19 million by mid-2046"),
                  ("hk_csd_population_projections_2022_2046_press", "hk_csd_population_projections_2022_2046_press.htm",
                   "890 000 One-way Permit holders", "the projection's assumed inflow: 890,000 permit holders, 510,000 scheme admissions, 240,000 helpers"),
                  ("hk_lcq6_population_policy_2025", "hk_lcq6_population_policy_2025_01_08.htm",
                   "More than 180 000 talents", "arrivals: 180,000 under the talent schemes")],
    "singapore": [("nptd_population_in_brief_2026", "nptd_population_in_brief_2026.pdf",
                   "stood at 6.21 million as at June 2026", "the latest count: 6.21 million, up 1.6% in a year"),
                  ("nptd_population_in_brief_2026", "nptd_population_in_brief_2026.pdf",
                   "25,094 individuals were granted citizenship and 35,352 individuals were granted permanent residency",
                   "immigration: 25,094 citizenships and 35,352 permanent residencies in 2025")],
    "madrid": [("ine_proyecciones_poblacion_2026_2076_press", "ine_proyecciones_poblacion_2026_2076_press.pdf",
                "Comunidad de Madrid (14,4%)", "projection: the region up 14.4% in fifteen years"),
               ("cmadrid_estrategia_natalidad_2022_2026_page", "cmadrid_estrategia_natalidad_2022_2026_page.html",
                "500 euros mensuales a mujeres embarazadas", "births: 500 euros a month to expectant mothers")],
}


def last_of(k: str) -> int:
    return ENDS.get(k, LAST)


def rates(area: str) -> pd.DataFrame:
    """Components per 1,000 residents a year, on the area's population in the same year. ``change`` is the office's own
    population change over the year as its components account for it (for the US areas the vintage's NPOPCHG, which its
    births, deaths, two migration flows and residual add to exactly), and ``migration`` that change less births plus
    deaths: net moves of every kind together with whatever adjustment the office's accounts carry, on the office's own
    period for its births and deaths."""
    c = C.components(area).set_index("year")
    pop = P.population(area).set_index("year")["pop"].reindex(c.index)
    cols = ["natural", "internal", "international", "other", "migration", "change"]
    return c[cols].astype(float).div(pop, axis=0) * 1000


def main(argv: list[str] | None = None) -> int:
    """Run the analysis and write every file (no options)."""
    A = Article(SLUG, __file__, seed=SEED)
    keys = [k for k, _ in CITIES] + ["paris"]
    comp = {k: C.components(k).set_index("year") for k in keys}
    rate = {k: rates(k) for k in keys}
    pops = {k: P.population(k).set_index("year")["pop"] for k in keys}
    labels = dict(CITIES)

    # ---- growth since 2001, from each office's population series (to each office's last year)
    A.results["growth"] = {k: {"pop_2001": int(pops[k][BASE]), "last_year": last_of(k), "pop_last": int(pops[k][last_of(k)]),
                               "pct": r(100 * (pops[k][last_of(k)] / pops[k][BASE] - 1), 1),
                               "pct_a_year": r(100 * ((pops[k][last_of(k)] / pops[k][BASE]) ** (1 / (last_of(k) - BASE)) - 1), 2)} for k in pops}
    order = sorted([k for k, _ in CITIES], key=lambda k: -A.results["growth"][k]["pct_a_year"])
    # the population stock, 2016 to the office's last year (the decade the components' averages cover)
    # the stock over the years the last window's flows cover: July 2015 to July 2025 for a year-to-July office (ten years),
    # 2015 to the last year for the others
    A.results["stock"] = {k: {"pop_2015": int(pops[k][2015]), "pop_last": int(pops[k][last_of(k)]), "years": last_of(k) - 2015,
                              "pct_2015_last": r(100 * (pops[k][last_of(k)] / pops[k][2015] - 1), 1)} for k in pops}
    A.results["growth_order"] = {"by_pct_a_year": order, "rank_of_new_york": order.index("new_york") + 1,
                                 "faster_than_new_york": [k for k in OTHERS if A.results["growth"][k]["pct_a_year"] > A.results["growth"]["new_york"]["pct_a_year"]],
                                 "slower_than_new_york": [k for k in OTHERS if A.results["growth"][k]["pct_a_year"] < A.results["growth"]["new_york"]["pct_a_year"]]}

    # ---- the components, ten-year averages per 1,000 residents
    def avg(k, span, col):
        v = rate[k].loc[span[0]:span[1], col].dropna()
        return r(v.mean(), 1) if len(v) else None
    A.results["decades"] = {}
    for k in rate:
        A.results["decades"][k] = {}
        for name, span in (("first", FIRST), ("last", LAST10)):
            node = {col: avg(k, span, col) for col in ("natural", "internal", "international", "migration", "change")}
            node["years"] = int(len(rate[k].loc[span[0]:span[1]].dropna(subset=["change"])))
            A.results["decades"][k][name] = node
    D = A.results["decades"]
    by = lambda col, name="last": sorted([k for k, _ in CITIES if D[k][name][col] is not None], key=lambda k: -D[k][name][col])
    A.results["order"] = {"natural_last": by("natural"), "migration_last": by("migration"), "change_last": by("change"),
                          "natural_rank_of_new_york": by("natural").index("new_york") + 1,
                          "migration_rank_of_new_york": by("migration").index("new_york") + 1,
                          "change_rank_of_new_york": by("change").index("new_york") + 1,
                          "internal_last": sorted(SPLIT + ("tokyo",), key=lambda k: D[k]["last"]["internal"]),
                          "natural_negative_last": [k for k, _ in CITIES if D[k]["last"]["natural"] < 0],
                          "natural_fell": [k for k, _ in CITIES if D[k]["last"]["natural"] < D[k]["first"]["natural"]]}

    # every year, the direction of the moves within the country
    A.results["internal_every_year"] = {}
    for k in SPLIT + ("tokyo",):
        s = comp[k]["internal"].dropna()
        A.results["internal_every_year"][k] = {"first": int(s.index.min()), "last": int(s.index.max()), "years": int(len(s)),
                                               "years_negative": int((s < 0).sum()), "years_positive": int((s > 0).sum())}
    A.results["lose_to_country_every_year"] = [k for k in SPLIT if A.results["internal_every_year"][k]["years_negative"] == A.results["internal_every_year"][k]["years"]]
    tok_in = comp["tokyo"]["internal"]
    A.results["tokyo"] = {"internal_positive_since": int(tok_in[tok_in <= 0].index.max() + 1),
                          "natural_negative_since": int(comp["tokyo"].index[comp["tokyo"]["natural"] >= 0].max() + 1),
                          "natural_2025": int(comp["tokyo"].loc[LAST, "natural"]), "internal_2025": int(comp["tokyo"].loc[LAST, "internal"]),
                          "change_2025": int(comp["tokyo"].loc[LAST, "change"]), "other_2025": int(comp["tokyo"].loc[LAST, "other"])}
    assert (comp["tokyo"].loc[A.results["tokyo"]["natural_negative_since"]:, "natural"] < 0).all()
    assert (tok_in.loc[A.results["tokyo"]["internal_positive_since"]:] > 0).all()
    hk_nat = comp["hong_kong"]["natural"]
    A.results["hong_kong"] = {"natural_negative_since": int(hk_nat[hk_nat >= 0].index.max() + 1), "natural_2025": int(hk_nat[LAST]),
                              "change_2025": int(comp["hong_kong"].loc[LAST, "change"]), "change_2026": int(comp["hong_kong"].loc[2026, "change"]),
                              "external_2026": int(comp["hong_kong"].loc[2026, "external"]),
                              "one_way_2026": int(comp["hong_kong"].loc[2026, "one_way_permit"]) if "one_way_permit" in comp["hong_kong"] else None}
    A.results["most_lost_to_country"] = min(SPLIT, key=lambda k: D[k]["last"]["internal"])
    A.results["internal_losses_order"] = sorted(SPLIT, key=lambda k: D[k]["last"]["internal"])
    A.results["new_york_internal_rank"] = A.results["internal_losses_order"].index("new_york") + 1

    # ---- 2025: arrivals from abroad against 2024 and against the years before the pandemic
    y25 = {}
    for k in SPLIT:
        intl = comp[k]["international"]
        y25[k] = {"intl_2024": int(intl[2024]), "intl_2025": int(intl[LAST]),
                  "intl_pre_pandemic": int(round(intl.loc[PRE_PANDEMIC[0]:PRE_PANDEMIC[1]].mean(), -3)),
                  "fall_pct": r(100 * (1 - intl[LAST] / intl[2024]), 0),
                  "change_2025": int(pops[k][LAST] - pops[k][LAST - 1]) if k != "london" else int(comp[k].loc[LAST, "change"]),
                  "change_2025_basis": {"london": "ONS's components", "toronto_cma": "Statistics Canada's population estimates, 1 July 2024 to 1 July 2025",
                                        "montreal_cma": "Statistics Canada's population estimates, 1 July 2024 to 1 July 2025"}.get(
                      k, "the Census Bureau's population estimates, 1 July 2024 to 1 July 2025 (its residual included)")}
        if k in ("new_york", "chicago", "los_angeles"):                  # 2016-2019 is Vintage 2020's: no change computed across vintages
            y25[k]["intl_2025_vs_pre_pct"] = None
            y25[k]["intl_pre_pandemic_vintage"] = "Vintage 2020, as published then; not compared with 2025"
        else:
            y25[k]["intl_2025_vs_pre_pct"] = r(100 * (intl[LAST] / intl.loc[PRE_PANDEMIC[0]:PRE_PANDEMIC[1]].mean() - 1), 0)   # on the unrounded mean
    y25["london"]["change_pct"] = r(100 * comp["london"].loc[LAST, "change"] / pops["london"][LAST - 1], 2)
    A.results["y2025"] = y25
    A.results["y2025_fell_from_abroad"] = [k for k in SPLIT if y25[k]["intl_2025"] < y25[k]["intl_2024"]]
    A.results["y2025_shrank"] = [k for k in SPLIT if y25[k]["change_2025"] < 0]
    A.results["y2025_above_pre_pandemic"] = [k for k in SPLIT if y25[k]["intl_2025_vs_pre_pct"] is not None and y25[k]["intl_2025_vs_pre_pct"] > 0]
    A.results["y2025_below_pre_pandemic"] = [k for k in SPLIT if y25[k]["intl_2025_vs_pre_pct"] is not None and y25[k]["intl_2025_vs_pre_pct"] < 0]
    A.results["y2025_not_compared_with_pre_pandemic"] = [k for k in SPLIT if y25[k]["intl_2025_vs_pre_pct"] is None]
    A.results["counts_internal"] = list(SPLIT + ("tokyo",))         # the seven that count moves within the country
    A.results["wider_than_city"] = ["paris_inner", "toronto_cma", "montreal_cma", "chicago", "los_angeles", "madrid"]
    A.results["y2025_others"] = {"paris_inner_change": int(comp["paris_inner"].loc[LAST, "change"]),
                                 "paris_change": int(comp["paris"].loc[LAST, "change"]),
                                 "singapore_change": int(comp["singapore"].loc[LAST, "change"]),
                                 "hong_kong_change": int(comp["hong_kong"].loc[LAST, "change"]),
                                 "madrid_change_2024": int(comp["madrid"].loc[2024, "change"])}
    assert A.results["tokyo"]["change_2025"] > 0

    # ---- the current reading: 2026 so far
    nyc, par, tok = C.now("new_york"), C.now("paris"), C.now("tokyo")
    tok["within"] = int(tok["change"] - tok["internal"] - tok["natural"] - tok["other"])   # moves within Tokyo and the rest
    A.results["now"] = {
        "tokyo": {**tok, "natural_2025_full_year": int(comp["tokyo"].loc[LAST, "natural"])},
        "paris": {"births_2026": par["births"]["2026"], "births_2025": par["births"]["2025"],
                  "deaths_2026": par["deaths"]["2026"], "deaths_2025": par["deaths"]["2025"],
                  "natural_2026": par["births"]["2026"] - par["deaths"]["2026"],
                  "natural_2025": par["births"]["2025"] - par["deaths"]["2025"]},
        "new_york": {"births_2026": nyc["2026"]["births_residents"], "births_2025": nyc["2025"]["births_residents"],
                     "deaths_2026": nyc["2026"]["deaths"], "deaths_2025": nyc["2025"]["deaths"],
                     "births_change_pct": r(100 * (nyc["2026"]["births_residents"] / nyc["2025"]["births_residents"] - 1), 1)},
        "hong_kong": {"change_to_mid_2026": A.results["hong_kong"]["change_2026"], "external_to_mid_2026": A.results["hong_kong"]["external_2026"],
                      "provisional": True}}

    # ---- the documents
    Q = A.quotes()
    A.results["quotes"] = {}
    for key, (src, fname, needle) in DOCS.items():
        q = Q.quote(src, fname, needle)
        A.results["quotes"][key] = {"quote": q["quote"], "source": q["source"], "page": q.get("page")}
    out = {}
    for city, docs in RESPONSES.items():
        out[city] = []
        for src, fname, needle, what in docs:
            q = Q.quote(src, fname, needle)
            out[city].append({"what": what, "source": src, "page": q.get("page"), "quote": q["quote"]})
    A.results["responses"] = out
    A.results["cities_with_response_quote"] = sorted(out)
    # California's county projection is a table (P-2A, 2024 baseline, Vintage 2026 release of 13 March 2026), read as data
    p2a = pd.read_excel(REFERENCE / "reports" / "dof_p2a_county_total_2024_baseline.xlsx", sheet_name="Data", header=1)
    p2a.columns = [str(int(c)) if isinstance(c, float) else str(c) for c in p2a.columns]
    tot = p2a[(p2a["Age"] == "ALL AGES") & (p2a["Sex"] == "ALL SEXES") & (p2a["Race-Ethnicity Recode"] == "ALL RACES")].set_index("Geography")
    la_p2a = {y: int(tot.loc["LOS ANGELES", str(y)]) for y in (2020, 2025, 2030, 2050, 2070)}
    ca_p2a = {y: int(tot.loc["CALIFORNIA", str(y)]) for y in (2020, 2050, 2070)}
    assert la_p2a[2025] == 9_853_435 and la_p2a[2050] == 9_390_823 and ca_p2a[2050] == 41_118_423, (la_p2a, ca_p2a)  # the register's note
    assert max(ca_p2a, key=ca_p2a.get) == 2050
    out["los_angeles"].append({"what": "projection: Los Angeles County 9.85 million in 2025 to 9.39 million in 2050, a table",
                               "source": "dof_p2a_county_projections_2024_baseline", "page": None, "quote": None,
                               "edition": "2024 Baseline, Vintage 2026 Release, updated 13 March 2026", "los_angeles_county": la_p2a, "california": ca_p2a})
    A.results["response_documents"] = sorted({d[0] for docs in RESPONSES.values() for d in docs} | {"dof_p2a_county_projections_2024_baseline"})
    A.results["response_documents_n"] = len(A.results["response_documents"])
    # the documents' own figures the page repeats in the table, each checked against the quote it sits in
    figs = {"la_p2a_2025": f"{la_p2a[2025]:,}", "la_p2a_2050": f"{la_p2a[2050]:,}", "ca_p2a_2050": f"{ca_p2a[2050] / 1e6:.1f}"}
    for k_, v_ in figs.items():
        A.printed(f"responses_figures.{k_}", v_)
    for key, city, token, needle in (("ny_homes", "new_york", "82,000", None), ("london_low", "london", "9.86", None),
                                     ("london_high", "london", "10.25", None), ("london_homes", "london", "558,000", None),
                                     ("paris_residents", "paris", "50,000", "50 000"), ("paris_homes", "paris", "70,000", "70 000"),
                                     ("tokyo_peak", "tokyo", "14.24", "1424"), ("tokyo_peak_2024", "tokyo", "14.265", "1426.5"), ("tokyo_peak_2024_raw", "tokyo", "1426.5", "1426.5"),
                                     ("tokyo_yen", "tokyo", "3.6", "3．6"),
                                     ("toronto_2051", "toronto", "3.6", "3.6 million"), ("toronto_fall", "toronto", "200,000", None),
                                     ("toronto_pr", "toronto", "380,000", None), ("montreal_tr_2026", "montreal", "385,000", None),
                                     ("montreal_tr_2027", "montreal", "370,000", None), ("chicago_2050", "chicago", "10.6", None),
                                     ("chicago_2015", "chicago", "8.5", None), ("la_peak", "los_angeles", "40.8", None),
                                     ("la_fall", "los_angeles", "28,500", None), ("hk_2046", "hong_kong", "8.19", None),
                                     ("sg_pop", "singapore", "6.21", None), ("sg_pct", "singapore", "1.6%", None),
                                     ("sg_citizenships", "singapore", "25,094", None), ("sg_pr", "singapore", "35,352", None),
                                     ("toronto_2025", "toronto", "3.3", "3.3 million"), ("hk_schemes", "hong_kong", "510,000", "510 000"),
                                     ("hk_helpers", "hong_kong", "240,000", "240 000"),
                                     ("madrid_pct", "madrid", "14.4%", "14,4%"), ("madrid_euros", "madrid", "500", "500 euros")):
        assert any((needle or token) in d["quote"] for d in out[city]), (key, token)
        figs[key] = token
        A.printed(f"responses_figures.{key}", token)
    A.results["responses_figures"] = figs
    A.results["cities_with_response_quote_n"] = len(out)

    A.results["method"] = {
        "rates": "each component per 1,000 residents of the same area and year (population: world_city_population)",
        "periods": f"{FIRST[0]}-{FIRST[1]} and {LAST10[0]}-{LAST10[1]} (Madrid to 2024), the years every city's components cover",
        "residual": "Paris, Singapore and Madrid: migration is the change less births plus deaths, moves within the country and from abroad together",
        "tokyo": "births, deaths and moves from other prefectures are Japanese residents'; 'other' holds moves from abroad and all foreign residents' change",
        "hong_kong": "net movement crosses Hong Kong's own boundary (one-way permit holders from the Mainland and everyone else), in thousands to one decimal: neither a country's internal nor its international migration, so it is kept apart (external) and the balance column holds it",
        "singapore": "births and deaths by calendar year, the change June to June, residents and non-residents",
        "counties": "Chicago is Cook County and Los Angeles its county, from the Census Bureau's county files, with the Bureau's residual read into 'other'",
        "toronto": "moves from abroad: immigrants less net emigration plus the change in non-permanent residents (Montreal the same)",
        "estimates": "each office's own estimates, published without margins: ten-year averages and every year's direction are compared, and the order is the observed one",
        "balance": "'change' is each office's own population change over the year as its components account for it, on the period of "
                   "its births and deaths, and 'migration' that change less births plus deaths: net moves of every kind together with "
                   "whatever adjustment the office's accounts carry (the Census Bureau's residual, ONS's unattributable change, Statistics "
                   "Canada's residual deviation, INSEE's and INE's census-quality differences, Hong Kong's movement across its boundary) and, "
                   "for Tokyo, every change among foreign residents and Japanese residents' other register changes; Singapore is the one "
                   "office whose change (June to June) and births and deaths (calendar year) sit on different periods",
        "breaks": "Statistics Canada redefined emigration from July 2016 and converted the early CMA years from census divisions; Tokyo's "
                  "foreign residents entered the registers in 2012; the US components are four vintages while the denominators are the "
                  "spliced intercensal series (sensitivity.us_vintages gives the net loss within each of the last window's two vintages "
                  "on that vintage's own populations and on the spliced ones; sensitivity.halves ranks each half); for the three US areas "
                  "the 2016-2019 net arrivals are Vintage 2020's, as published then, and no change is computed from them to Vintage 2025's "
                  "2025 (the chart shows them as published); London's and the Canadian areas' 2016-2019 and 2025 come from one edition "
                  "each, and y2025.<cma>.intl_2025_vs_pre_2017_2019_pct drops the Canadian year to July 2016, when emigration was redefined",
        "boundaries": "a city or a county counts a move to its suburbs as leaving (New York, Cook County, Los Angeles County); a metropolitan "
                      "area does not (Toronto, Montreal, Paris and the inner ring); the rankings compare the areas as drawn",
        "us_change": "for New York, Chicago and Los Angeles 'change' is each vintage's own population change over the year (NPOPCHG) and "
                     "'other' the Bureau's residual, which the four components and the residual add to exactly; the 2025 change on the first "
                     "screen is the difference of two Vintage 2025 estimates, the same quantity",
        "growth": "growth since 2001 for New York, Cook County and Los Angeles County divides Vintage 2025's 2025 by the 2000s intercensal "
                  "series' 2001, the 2010s intercensal series between (popest.county_july_population); the components are each vintage's own",
        "responses": "each city's own published projection, plan or measure, quoted; none is set beside a count as a cause"}
    A.latest("2026-09", "TMG's monthly population movement and INSEE's monthly births and deaths to September 2026; DOHMH's provisional "
                        "quarters to March 2026; C&SD's year to mid-2026 (provisional)")
    A.long_view(1991, LAST, "Births minus deaths per 1,000 residents, 1991-2025 for New York, Paris, Tokyo, Hong Kong, Singapore and Madrid "
                            "(London, Toronto and Montreal from 2002, Chicago and Los Angeles from 2001); population since 2001 for all eleven")

    A.reproduce("London, change to mid-2025, % (ONS bulletin)", published=-0.29, published_moe90=None,
                reproduced=y25["london"]["change_pct"], kind="pct", tolerance=0.005)
    A.reproduce("Toronto CMA, change 2024/25 (Statistics Canada, The Daily)", published=-992, published_moe90=None,
                reproduced=int(comp["toronto_cma"].loc[LAST, "change"]), kind="count", tolerance=0)
    A.reproduce("Tokyo-to, change in 2025 (TMG)", published=75018, published_moe90=None,
                reproduced=int(comp["tokyo"].loc[LAST, "change"]), kind="count", tolerance=0)
    A.reproduce("City of Paris, change in 2025 (INSEE Flash Île-de-France 111, rounded to hundreds)", published=-18000,
                published_moe90=None, reproduced=int(comp["paris"].loc[LAST, "change"]), kind="count", tolerance=50)
    A.results["reproduction_source"] = "ONS's mid-2025 bulletin; Statistics Canada's Daily of 14 January 2026; TMG's 2025 summary; INSEE Flash Île-de-France 111"
    A.results["reproduction_note"] = "Each office's published figure against the same figure from its files; INSEE rounds to hundreds."

    # ---- what the prose prints
    G = A.results["growth"]
    for k in ("new_york", "singapore", "toronto_cma", "paris", "paris_inner", "chicago", "los_angeles"):
        A.printed(f"growth.{k}.pct", f"{abs(G[k]['pct']):.1f}%")
    A.printed("growth_order.rank_of_new_york", str(A.results["growth_order"]["rank_of_new_york"]))
    for k in D:
        for name in ("first", "last"):
            for col in ("natural", "internal", "international", "migration", "change"):
                if D[k][name][col] is not None:
                    A.printed(f"decades.{k}.{name}.{col}", f"{abs(D[k][name][col]):.1f}")     # unsigned; the table adds the sign
            A.printed(f"decades.{k}.{name}.years", str(D[k][name]["years"]))
    for key in ("natural_rank_of_new_york", "migration_rank_of_new_york", "change_rank_of_new_york"):
        A.printed(f"order.{key}", str(A.results["order"][key]))
    A.printed("new_york_internal_rank", str(A.results["new_york_internal_rank"]))
    for k in A.results["internal_every_year"]:
        for key in ("years", "years_negative", "years_positive", "first", "last"):
            A.printed(f"internal_every_year.{k}.{key}", str(A.results["internal_every_year"][k][key]))
    T = A.results["tokyo"]
    for key in ("natural_2025", "internal_2025", "change_2025", "other_2025"):
        A.printed(f"tokyo.{key}", f"{abs(T[key]):,}")
    H = A.results["hong_kong"]
    for key in ("natural_2025", "change_2025", "change_2026", "external_2026"):
        A.printed(f"hong_kong.{key}", f"{abs(H[key]):,}")
    A.printed("hong_kong.natural_negative_since", str(H["natural_negative_since"]))
    for k in SPLIT:
        for key in ("intl_2024", "intl_2025", "intl_pre_pandemic"):
            A.printed(f"y2025.{k}.{key}", f"{y25[k][key]:,}")
        A.printed(f"y2025.{k}.change_2025", f"{abs(y25[k]['change_2025']):,}")
        if y25[k]["intl_2025_vs_pre_pct"] is not None:
            A.printed(f"y2025.{k}.intl_2025_vs_pre_pct", f"{abs(y25[k]['intl_2025_vs_pre_pct']):.0f}%")
        A.printed(f"y2025.{k}.fall_pct", f"{y25[k]['fall_pct']:.0f}%")
    A.printed("y2025.london.change_pct", f"{abs(y25['london']['change_pct']):.2f}%")
    A.results["dcp_revision_difference"] = 8597000 - 8478000
    assert "from 8,478,000 to 8,597,000" in A.results["quotes"]["dcp_revision"]["quote"]
    A.printed("dcp_revision_difference", f"{A.results['dcp_revision_difference']:,}")
    for k in ("new_york", "singapore"):
        A.printed(f"growth.{k}.pop_2001", f"{G[k]['pop_2001']:,}")
        A.printed(f"growth.{k}.pop_last", f"{G[k]['pop_last']:,}")
    for key in ("paris_change", "paris_inner_change", "singapore_change"):
        A.printed(f"y2025_others.{key}", f"{abs(A.results['y2025_others'][key]):,}")
    N = A.results["now"]
    for key in ("change", "internal", "natural"):
        A.printed(f"now.tokyo.{key}", f"{abs(N['tokyo'][key]):,}")
    for key in ("births_2026", "births_2025"):
        A.printed(f"now.paris.{key}", f"{N['paris'][key]:,}")
    for key in ("births_2026", "births_2025"):
        A.printed(f"now.new_york.{key}", f"{N['new_york'][key]:,}")
    A.printed("now.tokyo.within", f"{abs(N['tokyo']['within']):,}")
    A.printed("stock.new_york.pct_2015_last", f"{abs(A.results['stock']['new_york']['pct_2015_last']):.1f}%")
    A.results["growth"]["new_york"]["index_last"] = r(100 * pops["new_york"][LAST] / pops["new_york"][BASE], 1)
    A.printed("growth.new_york.index_last", f"{A.results['growth']['new_york']['index_last']:.1f}")
    A.results["tokyo"]["pop_2025_millions"] = r(pops["tokyo"][LAST] / 1e6, 2)
    A.printed("tokyo.pop_2025_millions", f"{A.results['tokyo']['pop_2025_millions']:.2f}")
    A.results["tokyo"]["revised_2026_01"] = {"before": 14270748, "after": 14234309, "note": "TMG's revision of 29 October 2026 to the 2025 census, 1 January 2026, from the register's note; not in the file read"}
    A.printed("tokyo.revised_2026_01.after", f"{A.results['tokyo']['revised_2026_01']['after']:,}")
    A.printed("tokyo.revised_2026_01.before", f"{A.results['tokyo']['revised_2026_01']['before']:,}")
    A.results["tokyo"]["pop_2025_millions"] = r(pops["tokyo"][LAST] / 1e6, 2)
    A.printed("tokyo.pop_2025_millions", f"{A.results['tokyo']['pop_2025_millions']:.2f}")
    A.results["tokyo"]["revised_2026_01"] = {"before": 14270748, "after": 14234309, "note": "TMG's revision of 29 October 2026 to the 2025 census, 1 January 2026, from the register's note; not in the file read"}
    A.printed("tokyo.revised_2026_01.after", f"{A.results['tokyo']['revised_2026_01']['after']:,}")
    A.printed("tokyo.revised_2026_01.before", f"{A.results['tokyo']['revised_2026_01']['before']:,}")
    A.printed("tokyo.natural_negative_since", str(T["natural_negative_since"]))
    A.printed("tokyo.internal_positive_since", str(T["internal_positive_since"]))
    A.printed("now.new_york.births_change_pct", f"{abs(N['new_york']['births_change_pct']):.1f}%")
    A.printed("cities_with_response_quote_n", str(A.results["cities_with_response_quote_n"]))
    A.printed("response_documents_n", str(A.results["response_documents_n"]))
    # the quarterly births: a count-change range (births are counts of events), the house rule for a named change
    bc = count_change(N["new_york"]["births_2026"], N["new_york"]["births_2025"])     # now against before: a Poisson range on the counts
    A.results["now"]["new_york"]["births_change"] = bc
    for f in ("lo_pct", "hi_pct"):
        A.printed(f"now.new_york.births_change.{f}", f"{abs(bc[f]):.1f}%")
    # no claim: the provisional file gives quarters, not the finer series A.recheck needs; the range is printed as a sensitivity
    # the US components' last window spans two vintages: the net loss to the rest of the country within each, on that
    # vintage's own 1 July populations (popest.vintage_populations), as a sensitivity to the splice the denominators use
    from nycdata import popest
    # the ranking within each half of the last window (2016-2020, which for the US areas is Vintage 2020, and 2021-2025,
    # Vintage 2025): does New York's place on the two measures hold in both?
    halves = {}
    for name, span in (("2016_2020", (2016, 2020)), ("2021_2025", (2021, 2025))):
        m = {k: float(rate[k].loc[span[0]:span[1], "migration"].dropna().mean()) for k, _ in CITIES if len(rate[k].loc[span[0]:span[1], "migration"].dropna())}
        i = {k: float(rate[k].loc[span[0]:span[1], "internal"].dropna().mean()) for k in SPLIT}
        mo, io = sorted(m, key=lambda k: m[k]), sorted(i, key=lambda k: i[k])    # ranked on the unrounded means
        ties = [k for k in m if k != "new_york" and abs(m[k] - m["new_york"]) < 0.05]   # level at the printed precision
        halves[name] = {"migration": {k: r(v, 1) for k, v in m.items()}, "migration_unrounded": {k: r(v, 4) for k, v in m.items()},
                        "migration_order": mo, "migration_rank_of_new_york": mo.index("new_york") + 1, "migration_level_with_new_york": ties,
                        "internal": {k: r(v, 1) for k, v in i.items()}, "internal_unrounded": {k: r(v, 4) for k, v in i.items()},
                        "internal_order": io, "internal_rank_of_new_york": io.index("new_york") + 1}
    A.results["sensitivity"] = {"us_vintages": {}, "halves": halves,
                                "new_york_largest_loss_in_both_halves": all(halves[h]["migration_rank_of_new_york"] == 1 and not halves[h]["migration_level_with_new_york"] for h in halves),
                                "new_york_largest_internal_loss_in_both_halves": all(halves[h]["internal_rank_of_new_york"] == 1 for h in halves)}
    counties = {"new_york": [(36, 5), (36, 47), (36, 61), (36, 81), (36, 85)], "chicago": [popest.COUNTY_OF_CITY["chicago"]],
                "los_angeles": [popest.COUNTY_OF_CITY["los_angeles"]]}
    for k in counties:
        vp = popest.vintage_populations(counties[k]).set_index("year")["pop"]
        own = (comp[k]["internal"].astype(float) / vp.reindex(comp[k].index)) * 1000
        A.results["sensitivity"]["us_vintages"][k] = {
            "internal_2016_2020_on_vintage_2020": r(own.loc[2016:2020].mean(), 1), "internal_2021_2025_on_vintage_2025": r(own.loc[2021:2025].mean(), 1),
            "internal_2016_2020_on_spliced": r(rate[k].loc[2016:2020, "internal"].mean(), 1), "internal_2021_2025_on_spliced": r(rate[k].loc[2021:2025, "internal"].mean(), 1)}
    for k in ("new_york",):
        for key in ("internal_2016_2020_on_vintage_2020", "internal_2021_2025_on_vintage_2025", "internal_2016_2020_on_spliced", "internal_2021_2025_on_spliced"):
            A.printed(f"sensitivity.us_vintages.{k}.{key}", f"{abs(A.results['sensitivity']['us_vintages'][k][key]):.1f}")
    for h in ("2016_2020", "2021_2025"):
        A.printed(f"sensitivity.halves.{h}.migration.new_york", f"{abs(A.results['sensitivity']['halves'][h]['migration']['new_york']):.1f}")
    A.printed("sensitivity.halves.2021_2025.migration.los_angeles", f"{abs(A.results['sensitivity']['halves']['2021_2025']['migration']['los_angeles']):.1f}")
    assert A.results["sensitivity"]["halves"]["2021_2025"]["migration_level_with_new_york"] == ["los_angeles"], A.results["sensitivity"]["halves"]["2021_2025"]
    assert A.results["sensitivity"]["halves"]["2016_2020"]["migration_rank_of_new_york"] == 1 and not A.results["sensitivity"]["halves"]["2016_2020"]["migration_level_with_new_york"]
    # the Canadian pre-pandemic baseline without the year to July 2016, when Statistics Canada redefined emigration
    for k in ("toronto_cma", "montreal_cma"):
        intl = comp[k]["international"]
        base = intl.loc[2017:PRE_PANDEMIC[1]].mean()
        y25[k]["intl_2025_vs_pre_2017_2019_pct"] = r(100 * (intl[LAST] / base - 1), 0)
        A.printed(f"y2025.{k}.intl_2025_vs_pre_2017_2019_pct", f"{abs(y25[k]['intl_2025_vs_pre_2017_2019_pct']):.0f}%")
    # the documents' own figures the page repeats beside their quotes, read from the quotes
    assert "2.7 million in 2024" in A.results["quotes"]["census"]["quote"] and "1.3 million in 2025" in A.results["quotes"]["census"]["quote"]
    A.results["quotes_figures"] = {"nim_2024_millions": 2.7, "nim_2025_millions": 1.3}
    A.printed("quotes_figures.nim_2024_millions", "2.7")
    A.printed("quotes_figures.nim_2025_millions", "1.3")

    # ---- charts
    years = list(range(1991, LAST + 1))
    A.chart("growth", strip(
        title="Since 2001 Singapore, the Toronto area and Madrid's region have grown fastest; New York, Los Angeles and Chicago least",
        subtitle="Population, each city's 2001 = 100, at 2013 and at the comparison's endpoint, 2025 (Madrid 2024); the City of Paris drawn beside the eleven",
        x=[["2013", "2013"], ["last", "2025 (Madrid 2024)"]],
        series=[[k, labels[k], labels[k]] for k, _ in CITIES] + [["paris", "City of Paris", "City of Paris"]],
        cells={"": {k: {"2013": r(100 * pops[k][2013] / pops[k][BASE], 1), "last": r(100 * pops[k][last_of(k)] / pops[k][BASE], 1)} for k in keys}},
        format="dec1", axis="Population, 2001 = 100",
        note="Each office's own estimates on its own date: 1 July (New York, Chicago, Los Angeles, Toronto, Montreal, Madrid), 30 June "
             "(London, Hong Kong, Singapore), mid-year from 1 January estimates (Paris), 1 October (Tokyo). Chicago is Cook County, "
             "Los Angeles its county, Madrid the Comunidad; Singapore counts residents and non-residents. The order is the observed one.",
        provenance="Census Bureau; ONS; INSEE; TMG; Statistics Canada; C&SD Hong Kong; SingStat; INE"))

    A.chart("rest_of_country", strip(
        title="Of the seven offices that count moves within their country, New York's and London's show the largest losses; Tokyo's a gain",
        subtitle="Net moves from the rest of the same country, per 1,000 residents a year",
        x=[["first", f"{FIRST[0]} to {FIRST[1]}"], ["last", f"{LAST10[0]} to {LAST10[1]}"]],
        series=[[k, labels[k], labels[k]] for k in SPLIT + ("tokyo",)],
        cells={"": {k: {name: D[k][name]["internal"] for name in ("first", "last")} for k in SPLIT + ("tokyo",)}},
        format="dec1", axis="Net moves from the rest of the country, per 1,000 residents a year",
        note="Below zero, more residents moved to the rest of the country than came from it. New York, Chicago and Los Angeles: the "
             "Census Bureau's net domestic migration. London: ONS's net internal migration. Toronto and Montreal areas: net moves from "
             "the rest of the province and the other provinces. Tokyo: Japanese residents' net moves from other prefectures. INSEE, INE "
             "and SingStat do not separate moves within the country from moves from abroad, and Hong Kong counts only moves across its "
             "own boundary. Means of the observed years: nine for the three US areas in 2002-11 (no year to July 2010).",
        provenance="Census Bureau; ONS; Statistics Canada; Tokyo Metropolitan Government"))

    LONG = [("new_york", "New York"), ("london", "London"), ("tokyo", "Tokyo"), ("hong_kong", "Hong Kong"), ("singapore", "Singapore"), ("madrid", "Madrid region")]
    A.chart("births_minus_deaths", lines(
        title=f"Births minus deaths have fallen in every city; deaths have outnumbered births in Hong Kong since {H['natural_negative_since']} and, among Tokyo's Japanese residents, since {T['natural_negative_since']}",
        subtitle="Births minus deaths per 1,000 residents a year, six of the eleven cities",
        x=[[str(t), str(t)] for t in years],
        series=[[k, lab, lab] for k, lab in LONG],
        cells={"": {k: {str(t): r(rate[k].loc[t, "natural"], 2) for t in years if t in rate[k].index and pd.notna(rate[k].loc[t, "natural"])} for k, _ in LONG}},
        format="dec1", axis="Births minus deaths per 1,000 residents",
        x_ticks=[str(t) for t in years if t % 5 == 0 or t in (1991, LAST)],
        note="Each office's year: to 1 July (New York), to 30 June (London, Hong Kong), calendar (Tokyo, Singapore, Madrid). London's "
             "start in 2002, Madrid's end in 2024; New York's years to July 2000 and 2010 are in none of the Census Bureau's files. "
             "Tokyo counts Japanese residents' births and deaths; Singapore counts non-residents' too; Hong Kong's population is on "
             "the resident-population method from 1997, an earlier one before. The other five cities are in the data file.",
        provenance="Census Bureau; ONS; TMG; C&SD Hong Kong; SingStat; INE"))

    A.chart("from_abroad", strip(
        title="Net arrivals from abroad fell in all six cities that count them separately, in 2025",
        subtitle="Net moves from abroad, thousands: 2024 and 2025 for the six cities that count them, and the 2016-2019 average for London, Toronto and Montreal, from the same edition as their 2025",
        x=[["pre", f"{PRE_PANDEMIC[0]} to {PRE_PANDEMIC[1]}, a year"], ["2024", "2024"], ["2025", "2025"]],
        series=[[k, labels[k], labels[k]] for k in SPLIT],
        cells={"": {k: {**({} if k in ("new_york", "chicago", "los_angeles") else {"pre": r(y25[k]["intl_pre_pandemic"] / 1000, 1)}),
                        "2024": r(y25[k]["intl_2024"] / 1000, 1), "2025": r(y25[k]["intl_2025"] / 1000, 1)} for k in SPLIT}},
        format="dec1", axis="Net moves from abroad, thousands",
        note="Each office's year: to 1 July (New York, Chicago, Los Angeles, Toronto and Montreal areas), to 30 June (London). "
             "Toronto and Montreal: immigrants less net emigration plus the change in non-permanent residents (students and "
             "temporary workers). For New York, Cook County and Los Angeles County the 2016-2019 average is Vintage 2020's, a "
             "different edition from their 2024 and 2025 (Vintage 2025), so it is not drawn and no change is computed from it; "
             "the table in the questions gives it as published. London's and the Canadian areas' three dots come from one edition each.",
        provenance="Census Bureau; ONS; Statistics Canada"))

    A.chart("components_last10", strip(
        title="Averaged over 2016-2025, every office but Tokyo's and Hong Kong's counted more births than deaths; the rest of the change reinforced or offset that balance",
        subtitle="Per thousand residents a year, 2016-2025 (Madrid 2016-2024): births minus deaths, and the rest of the office's population change (net moves of every kind and its adjustments; Tokyo's births and deaths are Japanese residents')",
        x=[["natural", "Births minus deaths"], ["migration", "The rest of the change"]],
        series=[[k, labels[k], labels[k]] for k, _ in CITIES],
        cells={"": {k: {"natural": D[k]["last"]["natural"], "migration": D[k]["last"]["migration"]} for k, _ in CITIES}},
        format="dec1", axis="Per 1,000 residents a year",
        note="'The rest of the change' is the change in each office's own population estimates less the births and deaths it "
             "counts: net moves of every kind together with whatever else the estimates carry (the Census Bureau's residual, ONS's "
             "unattributable change, Statistics Canada's residual deviation, INSEE's census-quality differences, Hong Kong's movement "
             "across its own boundary) and, for Tokyo, every change among foreign residents. Tokyo's births and deaths are Japanese "
             "residents'; Singapore's count non-residents against a June-to-June change. The 2016-25 averages hold ten observed years "
             "except Madrid's nine (2016-24).",
        provenance="Census Bureau; ONS; INSEE; TMG; Statistics Canada; C&SD Hong Kong; SingStat; INE"))

    rows_out = []
    for k in keys:
        label = labels.get(k, "City of Paris")
        for t, row in comp[k].iterrows():
            rows_out.append({"area": label, "year": int(t), "period": row["period"],
                             **{c: (int(row[c]) if pd.notna(row[c]) else None) for c in ("births", "deaths", "natural", "internal",
                                                                                         "international", "other", "migration", "change")},
                             "population": int(pops[k][t]) if t in pops[k].index else None})
    A.write(data=pd.DataFrame(rows_out))
    print(f"{SLUG}: wrote {A.out}")
    return 0


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