"""Build the study pages from the results files. Every number on a page comes from results/ or assumptions.json, and
the rounding of each one the prose leans on is asserted here.

Usage: python3 -I -B site/render.py   (writes index.html, fresh.html, results.html, lenders.html, method.html)
"""
import html
import re
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent


def load(name):
    return json.loads((ROOT / name).read_text(encoding="utf-8"))


S = load("results/summary-r1.json")
L = load("results/lenders-r1.json")
PREP = load("results/prepare-r1.json")
AS = load("assumptions.json")
PROTO = load("protocol-r1.json")
RULES = load("rules/conversion-rules.json")
CSS = (ROOT / "site" / "page.css").read_text(encoding="utf-8")

STUDY_TITLE = "Loan data conversion: which reconciliation catches the faults"
DATA_LABEL = ("Real public data: 523,243 SBA loan records, 45,597 Montana mortgage records for 2017 and the FDIC bank "
              "list, all federal public data.")


def e(t):
    return html.escape(str(t), quote=True)


def pc(v, d=0):
    return f"{100 * v:.{d}f}%"


def n0(v):
    return f"{round(v):,}"


def bn(v):
    return f"US${v / 1e9:.2f} billion"


# ---------- the numbers the pages use, with their rounding checked ----------
C = S["checks"]
CO = S["combinations"]
M, F = S["main"], S["fresh"]
MD, FD = {f["id"]: f for f in M}, {f["id"]: f for f in F}
NM, NF = len(M), len(F)
assert (NM, NF) == (19, 40)
N_CODE_M, N_RULE_M = C["totals"]["main_code"]["of"], C["totals"]["main_rule"]["of"]
N_CODE_F, N_RULE_F = C["totals"]["fresh_code"]["of"], C["totals"]["fresh_rule"]["of"]
assert (N_CODE_M, N_RULE_M, N_CODE_F, N_RULE_F) == (13, 6, 33, 7)


def caught(check, which):
    return C[check][which]["caught"]


TOT_M, TOT_F = caught("totals", "main"), caught("totals", "fresh")
QUICK_M, QUICK_F = caught("cheap_set", "main"), caught("cheap_set", "fresh")
RULES_M, RULES_F = caught("target_rules", "main"), caught("target_rules", "fresh")
REB_M, REB_F = caught("record_compare", "main"), caught("record_compare", "fresh")
QR_F = CO["cheap_set_plus_record_compare"]["fresh"]
QR_M = CO["cheap_set_plus_record_compare"]["main"]
QRS_F = QR_F["plus_sample_60_expected"]
assert (TOT_M, TOT_F, QUICK_M, QUICK_F, RULES_M, RULES_F) == (8, 17, 17, 25, 15, 22)
assert (REB_M, REB_F, QR_F["caught"], QR_M["caught"]) == (13, 33, 36, 18)
assert f"{QRS_F:.1f}" == "39.8" and QR_F["missed"] == ["F10", "F16", "F21", "F32"] and QR_M["missed"] == ["M14"]
assert CO["every_automated_check"]["fresh"]["caught"] == QR_F["caught"]
TOT_RULE = C["totals"]["main_rule"]["caught"] + C["totals"]["fresh_rule"]["caught"]
assert TOT_RULE == 0 and C["record_compare"]["fresh_code"]["caught"] == N_CODE_F
assert C["record_compare"]["fresh_rule"]["caught"] == 0 and C["record_compare"]["main_rule"]["caught"] == 0
assert pc(TOT_F / NF, 1) == "42.5%"
STATUS_M, STATUS_F = caught("totals_by_status", "main"), caught("totals_by_status", "fresh")
CENSUS_M, CENSUS_F = caught("code_census", "main"), caught("code_census", "fresh")
assert (STATUS_M, STATUS_F, CENSUS_M, CENSUS_F) == (9, 19, 2, 0)
MISSED_ALL_P = [FD[i]["p_sample_60"] for i in QR_F["missed"]]
assert (pc(min(MISSED_ALL_P)), f"{max(MISSED_ALL_P):.3f}") == ("80%", "1.000")
assert all(FD[i]["layer"] == "rule" and FD[i]["family"] == "remap" for i in QR_F["missed"])

SM60, SM200 = C["sample_60"], C["sample_200"]
assert (f"{SM60['main_expected']:.1f}", f"{SM60['fresh_expected']:.1f}") == ("17.0", "31.5")
assert (f"{SM200['main_expected']:.1f}", f"{SM200['fresh_expected']:.1f}") == ("18.3", "34.8")
assert (len(SM60["main_below_half"]), len(SM60["fresh_below_half"]), len(SM200["fresh_below_half"])) == (2, 9, 5)

# charge-off stakes on the correct conversion and under three faults
CORR = S["correct"]["stakes"]
RATE7, RATE5 = CORR["7A"]["chargeoff_rate_count"], CORR["504"]["chargeoff_rate_count"]
assert (pc(RATE7, 2), pc(RATE5, 2)) == ("2.49%", "0.97%")
CO7, CO5 = CORR["7A"]["chargeoff_reported_usd"], CORR["504"]["chargeoff_reported_usd"]
assert (bn(CO7), bn(CO5), bn(CO7 + CO5)) == ("US$1.10 billion", "US$0.52 billion", "US$1.62 billion")
M03 = MD["M03"]   # charge-off mapped to closed in the rule document
assert M03["layer"] == "rule" and not M03["fired"]["totals"] and M03["fired"]["target_rules"]
assert not M03["fired"]["record_compare"] and not M03["fired"]["code_census"] and not M03["fired"]["totals_by_status"]
assert abs(M03["chargeoff"]["7A"]["chargeoff_reported_usd"] + CO7) < 0.01 and abs(M03["chargeoff"]["504"]["chargeoff_reported_usd"] + CO5) < 0.01
M19 = MD["M19"]   # status map from the dictionary
DICT_ROWS = M19["affected"]
assert M19["dictionary"] and DICT_ROWS == 74600 and M19["fired"]["code_census"] and M19["fired"]["target_rules"]
assert not M19["fired"]["totals"] and not M19["fired"]["record_compare"]
RATE7_DICT = M19["chargeoff"]["7A"]["rate_count"]
assert pc(RATE7_DICT, 2) == "3.22%"
assert S["correct"]["census_with_dictionary_maps"]["unmapped"]["7A.LoanStatus.status_map"]["P I F"] == DICT_ROWS
M14 = MD["M14"]   # purchased loans booked as originations
ORIG, ORIG_M14 = CORR["HMDA"]["hmda_originations"], M14["hmda_originations"]
assert (ORIG, ORIG_M14) == (24577, 32819) and not any(M14["fired"][k] for k in ("totals", "totals_by_status", "target_rules", "code_census", "record_compare"))
M18 = MD["M18"]
assert M18["dictionary"] and M18["fired"]["code_census"] and not M18["fired"]["totals"]

# the declared reversal lines
REV = S["reversal"]
CO_FRESH, CO_MISSED = REV["fresh_chargeoff_faults"], REV["fresh_chargeoff_missed_by_cheap_set"]
assert (len(CO_FRESH), CO_MISSED, REV["totals_alone_enough"], REV["add_record_compare_to_gate"]) == (15, ["F08"], False, False)
assert pc(REV["cheap_set_miss_share_on_chargeoff_faults"], 1) == "6.7%" and (len(CO_MISSED) + 1) / len(CO_FRESH) > 0.10
F08 = FD["F08"]
assert F08["layer"] == "code" and F08["fired"]["record_compare"] and F08["fired"]["totals_by_status"]
assert pc(F08["chargeoff"]["7A"]["rate_count"], 2) == "3.22%"
TOT_LINE = 0.8
assert PROTO["decision"]["reversal"][0].startswith("if totals alone catch at least 80%")
assert "more than 10%" in PROTO["decision"]["reversal"][1]

# predictions as scored by tools/summarize.py
PS = S["predictions_scored"]
assert [PS[f"P{i}"]["held"] for i in range(1, 9)] == [True, True, True, True, True, False, True, False]
GAPS = PS["P8"]["value"]
assert (GAPS["totals"], round(GAPS["target_rules"]), round(GAPS["cheap_set"])) == (0.4, 24, 27)
assert PS["P1"]["value"] == NM - TOT_M == 11 and PS["P4"]["value"] == 5 and PS["P5"]["value"] == 2

# the fresh draw
assert S["fresh_draws"] == 41 and len(S["fresh_redraws"]) == 1 and S["fresh_identical_pairs"] == [["F19", "F25"]]

# money: assumed, chosen after the results (assumptions.json)
DAY = AS["analyst_day_usd"]["base"]
EFF = AS["effort_days"]
COST_FAULT = AS["cost_per_escaped_fault_usd"]["base"]
NFAULTS = AS["faults_per_conversion"]["base"]
QUICK_DAYS = EFF["code_census"] + EFF["target_rules"]
REB_DAYS = EFF["rebuild"]["base"]
READ_DAYS = EFF["sample_read"]["days"]
ESC_TOT = NFAULTS * (NF - TOT_F) / NF
ESC_QUICK = NFAULTS * (NF - QUICK_F) / NF
ESC_QR = NFAULTS * (NF - QR_F["caught"]) / NF
ESC_QRS = NFAULTS * (NF - QRS_F) / NF
assert (f"{ESC_TOT:.2f}", f"{ESC_QUICK:.2f}", f"{ESC_QR:.2f}", f"{ESC_QRS:.3f}") == ("5.75", "3.75", "1.00", "0.055")
assert (QUICK_DAYS * DAY, REB_DAYS * DAY, READ_DAYS * DAY) == (2800, 12000, 1600)
BREAK_REB = REB_DAYS * DAY / (ESC_QUICK - ESC_QR)
assert round(BREAK_REB, -2) == 4400
LOW_N = AS["faults_per_conversion"]["low"]
BREAK_REB_LOW = REB_DAYS * DAY / (LOW_N * (QR_F["caught"] - QUICK_F) / NF)
assert round(BREAK_REB_LOW, -2) == 21800

# version 2 (CHANGES-r2.md, tools/change2.py): rules counted only when failures rise, and three sizing figures
V2 = load("results/change2-r2.json")
V2M, V2F = V2["rules_on_rises"]["main"], V2["rules_on_rises"]["fresh"]
assert (V2M["rules_any_move"], V2F["rules_any_move"], V2M["quick_any_move"], V2F["quick_any_move"]) == (RULES_M, RULES_F, QUICK_M, QUICK_F)
RISE_M, RISE_F = V2M["rules_rise"], V2F["rules_rise"]
assert (RISE_M, RISE_F, V2M["quick_rise"], V2F["quick_rise"]) == (12, 20, QUICK_M, QUICK_F)
assert V2M["only_fell"] == ["M10", "M13", "M16"] and V2F["only_fell"] == ["F19", "F25"]
V2B = V2["sizing"]
BE = V2B["rebuild_break_even_usd_by_days"]
assert abs(BE[str(REB_DAYS)] - BREAK_REB) < 1e-6 and abs(V2B["faults_removed_by_rebuild_per_conversion"] - (ESC_QUICK - ESC_QR)) < 1e-9
BE_LO, BE_HI = BE[str(EFF["rebuild"]["low"])], BE[str(EFF["rebuild"]["high"])]
assert (round(BE_LO, -2), round(BE_HI, -2), EFF["rebuild"]["low"], EFF["rebuild"]["high"]) == (2900, 7300, 10, 25)
CM = V2B["chargeoff_miss"]
assert (CM["missed"], CM["of"]) == (len(CO_MISSED), len(CO_FRESH)) and pc(CM["upper_95"]) == "32%"
ZERO_N = V2B["zero_miss_faults_for_upper_under_10pct"]
assert ZERO_N == 29 and V2B["zero_miss_upper_at_that_n"] < 0.10

# third version (CHANGES-r3.md, tools/change3.py): totals against the source's own units, bounds, test size, rebuild share
V3 = load("results/change3-r3.json")
TSU_M, TSU_F = V3["totals_source_units"]["main"], V3["totals_source_units"]["fresh"]
assert (TSU_M["totals_first"], TSU_F["totals_first"]) == (TOT_M, TOT_F)
TOTSU_M, TOTSU_F = TSU_M["totals_source_units"], TSU_F["totals_source_units"]
assert (TOTSU_M, TOTSU_F, TSU_M["newly_caught"], TSU_F["newly_caught"]) == (9, 19, ["M05"], ["F09", "F36"])
QB_M, QB_F = V3["quick_check_bounds"]["main"], V3["quick_check_bounds"]["fresh"]
assert (QB_M["quick"], QB_F["quick"]) == (QUICK_M, QUICK_F)
ALONE_M, ALONE_F = len(QB_M["rules_alone"]), len(QB_F["rules_alone"])
LOWQ_M, LOWQ_F = QB_M["quick_without_rules"], QB_F["quick_without_rules"]
assert (ALONE_M, ALONE_F, LOWQ_M, LOWQ_F) == (7, 8, 10, 17) and LOWQ_F == TOT_F
T3 = V3["test"]
UP1 = T3["chargeoff_miss"]["upper"]
assert pc(UP1) == "28%" and T3["zero_miss_n"] == ZERO_N
PASS_OBS, PASS_LINE = T3["zero_miss_pass_chance_at_observed"], T3["zero_miss_pass_chance_at_line"]
assert (pc(PASS_OBS, 1), pc(PASS_LINE, 1)) == ("13.5%", "4.7%")
SZ = T3["sized_for_80pct"]
assert (SZ["n"], SZ["max_misses"]) == (436, 33) and SZ["power"] >= 0.8
RSN = V3["rebuild_share_needed"]["by_days"]
assert (pc(RSN[str(REB_DAYS)]), pc(RSN["10"]), pc(RSN["25"])) == ("9%", "6%", "15%")
CODE_PAST_QUICK = [f for f in F if f["layer"] == "code" and not f["fired"]["cheap_set"]]
assert len(CODE_PAST_QUICK) == 11 and all(f["fired"]["record_compare"] for f in CODE_PAST_QUICK)

# fourth version (CHANGES-r4.md, tools/change4.py): the low end at the reversal line, both ends past the quick checks,
# draws the test needs, totals by fault kind
V4 = load("results/change4-r4.json")
RL = V4["reversal_low_end"]
assert RL["missed_high"] == list(CO_MISSED) and RL["chargeoff_faults"] == len(CO_FRESH)
CO_LOW = len(RL["missed_low"])
assert CO_LOW == 4 and pc(RL["share_low"]) == "27%"
CPQ = V4["code_past_quick"]
PAST_HI, PAST_LO = len(CPQ["high"]), len(CPQ["low"])
assert (PAST_HI, PAST_LO, CPQ["code_faults"]) == (11, 16, N_CODE_F)
DRAWS = V4["test_draws"]
DRAWS_MEAN, DRAWS_95 = DRAWS["mean_draws"], DRAWS["draws_for_95pct"]
assert DRAWS["chargeoff_moving_needed"] == SZ["n"] and (round(DRAWS_MEAN), DRAWS_95) == (1163, 1236)
TBK = V4["totals_by_kind"]
TOUCH_CODE = TBK["main"]["table"]["code"]["touch"] + TBK["fresh"]["table"]["code"]["touch"]
OTHER_CODE = N_CODE_M + N_CODE_F - TOUCH_CODE
assert all(TBK[w]["table"][l]["caught_other"] == 0 for w in ("main", "fresh") for l in ("code", "rule"))
assert all(TBK[w]["table"]["code"]["caught_touch"] == TBK[w]["table"]["code"]["touch"] for w in ("main", "fresh"))
assert (TOUCH_CODE, OTHER_CODE) == (25, 21)


BYS = S["correct"]["by_source"]
assert (BYS["7A"], BYS["504"], BYS["HMDA"], BYS["7A"] + BYS["504"]) == (403644, 119599, 45597, 523243)
assert sum(BYS.values()) == PREP["target_rows"] == 568840
assert max(C[k]["fresh"]["caught"] for k in ("totals", "totals_by_status", "target_rules", "code_census")) == RULES_F


def usd(v):
    return f"US${round(v):,}"


# ---------- lenders ----------
LM = L["matchers"]
NLOC = L["sba_locations_with_cert"]
assert NLOC == L["true_pairs"] == 1872
REC = {k: v["recall"] for k, v in LM.items()}
assert (pc(REC["name"]), pc(REC["name_state"]), pc(REC["name_city_state"]), pc(REC["name_state_active_after_results"])) == ("63%", "84%", "93%", "93%")
assert (LM["name"]["wrong"], LM["name_state"]["wrong"], LM["name_city_state"]["wrong"], LM["name_state_active_after_results"].get("wrong", 0)) == (2, 1, 1, 0)
LCF = L["conflicts_sba_fdic"]
LSH = L["conflict_shares_sba_fdic"]
assert pc(LSH["city"], 1) == "3.2%" and LCF["fdic_inactive"] == 11 and L["loans_at_inactive_certs"] == 272
HF = L["hmda_fdic"]
assert (HF["lenders"], HF["linked"], HF["no_fdic_record"]) == (391, 186, 205)

# ---------- the headline ----------
H1_LIMIT = "On public SBA files"
H1 = (f"{H1_LIMIT}, mapping statuses from the SBA's data dictionary left {n0(DICT_ROWS)} loans with no status, and "
      "matching totals missed it. Check each converted loan against rules too.")
_first, _call = H1.split(". ", 1)
assert len(H1.split()) <= 30 and len(_first.split()) <= 28 and len(_call.split()) <= 10 and ";" not in H1
assert len(H1_LIMIT.split()) <= 6 and H1_LIMIT in H1
assert MD["M19"]["rules_moved"] == {"R02": DICT_ROWS}   # the rule that every converted loan has a status
LIMIT = "Every cost and saving figure is assumed and was chosen after the results."   # the qualifiers sentence, once


# ---------- page frame (kit parts: section bar, takeaway, next study) ----------
HEAD_LINKS = ('<link rel="icon" href="data:,">'
              '<link rel="preload" href="vendor/viz-design-system/assets/fonts/newsreader-latin-500-normal.woff2" as="font" type="font/woff2" crossorigin>'
              '<link rel="preload" href="vendor/viz-design-system/assets/fonts/public-sans-latin-400-normal.woff2" as="font" type="font/woff2" crossorigin>'
              '<link rel="preload" href="vendor/viz-design-system/assets/fonts/public-sans-latin-600-normal.woff2" as="font" type="font/woff2" crossorigin>'
              '<link rel="stylesheet" href="vendor/viz-design-system/tokens.css"><link rel="stylesheet" href="vendor/viz-design-system/kit/kit.css">'
              '<link rel="stylesheet" href="vendor/viz-design-system/kit/takeaway.css"><link rel="stylesheet" href="vendor/viz-design-system/kit/wayfinding.css">')
SCRIPTS = ('<script src="vendor/viz-design-system/kit/kit.js"></script>'
           '<script src="vendor/viz-design-system/kit/takeaway.js"></script>'
           '<script src="vendor/viz-design-system/kit/wayfinding.js" defer></script>')
SITE_HEADER = ('<a class="kit-skip" href="#main">Skip to content</a><header class="site"><div class="kit-wrap site-row">'
               '<p class="site-id"><a class="site-name" href="../">Diogo Travassos</a><span class="site-role">Data '
               'leadership · Analytics · Decision-making</span></p><nav aria-label="Site"><a href="../#studies">Studies</a>'
               '<a href="https://www.linkedin.com/in/diogo-travassos/">LinkedIn</a><a href="mailto:hello@diogotravassos.dev">'
               'Email</a><button class="theme-toggle" type="button" data-theme-toggle>Theme: auto</button></nav></div></header>')
FOOTER = ('<footer class="site"><div class="kit-wrap"><p><span>Real public data</span><a href="../#studies">Back to all '
          'studies</a></p></div></footer>')
NEXT_STUDY = ('<nav class="next-study kit-wrap" data-next-study aria-label="Next study"><a href="../#studies">All '
              'studies</a></nav>')


def page(fname, title, desc, body, sections):
    nav = "".join(f'<a href="#{i}">{e(t)}</a>' for i, t in sections)
    head = ('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,'
            'initial-scale=1"><meta name="color-scheme" content="light dark"><meta name="robots" content="noindex">'
            f'<meta name="description" content="{e(desc)}"><title>{e(title)}</title>{HEAD_LINKS}<style>{CSS}</style>'
            f'{SCRIPTS}</head><body>')
    bar = (f'<div class="kit-section-bar"><nav class="page-nav" aria-label="Page sections">{nav}</nav>'
           '<span class="kit-progress" aria-hidden="true"></span></div>')
    out = head + SITE_HEADER + '<main id="main">' + body.replace("{SECTION_BAR}", bar) + "</main>" + FOOTER + "</body></html>\n"
    visible = out.split("<style>")[0] + out.split("</style>")[1]
    # the one brace token allowed is the column placeholder copied verbatim from sql/convert.sql
    visible = visible.replace("{ALL_COLS_7A}", "")
    assert "{" not in visible and "}" not in visible, fname
    for ch in (chr(0x2014), chr(0x2013)):
        assert ch not in out, (fname, ch)
    for sid, _ in sections:
        assert f'id="{sid}"' in out, (fname, sid)
    (ROOT / fname).write_text(out, encoding="utf-8")
    print(f"wrote {fname} ({len(out):,} bytes)")


def hero(h1, piece, extra=""):
    return (f'<section class="hero kit-wrap" aria-labelledby="hero-title"><p class="hero-tags"><span class="tag tag-data">'
            f'Real public data</span></p><p class="hero-piece">{e(piece)}</p><h1 id="hero-title">{e(h1)}</h1>{extra}'
            '</section>')


def dek(text, label="The question"):
    return f'<section class="kit-wrap hero-more" aria-label="{e(label)}"><p class="hero-dek">{text}</p></section>'


def block(sid, title, inner):
    return (f'<section id="{sid}" class="block kit-wrap" aria-labelledby="{sid}-title"><h2 id="{sid}-title">{e(title)}'
            f'</h2>{inner}</section>')


def bars(fig_id, rows, scale, animated, default, fmt):
    out = []
    for i, (label, sub, v, kind, text) in enumerate(rows):
        mark = "bar" + ((" tk-mark" + (" tk-key" if kind == "key" else "")) if animated else "")
        style = f"width:{v / scale * 100:.1f}%" + (f";--tk-i:{i}" if animated else "")
        cls = "bar-row pt" + {"key": " is-key", "ref": " is-ref", "after": " is-after", "": ""}[kind]
        val_cls = "bar-value num" + (" tk-key-value" if (animated and kind == "key") else "")
        note = f' <span class="bar-note">({e(sub)})</span>' if sub else ""
        out.append(f'<li class="{cls}" tabindex="0" data-readout="{e(text)}" title="{e(text)}"><span class="bar-label">'
                   f'{e(label)}{note}</span><span class="bar-track" aria-hidden="true">'
                   f'<span class="{mark}" style="{style}"></span></span><span class="{val_cls}">{fmt(v)}</span></li>')
    return (f'<ol class="bars" id="{fig_id}-bars" data-hover-chart data-readout-default="{e(default)}">'
            + "".join(out) + "</ol>")


def tr(cells, head=False, key=False):
    tag = "th" if head else "td"
    first = f'<th scope="{"col" if head else "row"}">{cells[0]}</th>'
    rest = "".join(f'<{tag}{" scope=\"col\"" if head else ""} class="num">{c}</{tag}>' for c in cells[1:])
    return f'<tr{" class=\"row-key\"" if key else ""}>{first}{rest}</tr>'


def table(label, header, rows):
    return (f'<div class="table-scroll" role="region" aria-label="{e(label)}" tabindex="0"><table class="data">'
            f'<caption class="visually-hidden">{e(label)}</caption><thead>{tr(header, head=True)}</thead><tbody>'
            + "".join(rows) + "</tbody></table></div>")


def links_row():
    return ('<p class="links"><a href="index.html">The summary</a><a href="fresh.html">The follow-up: 40 random faults</a>'
            '<a href="results.html">All results</a><a href="lenders.html">Linking lenders</a>'
            '<a href="method.html">Method and checks</a></p>')


def of40(v):
    return f"{v:.1f}" if abs(v - round(v)) > 1e-9 else f"{round(v)}"


# =====================================================================================================================
# Entry page
# =====================================================================================================================
TOUCH_F = TBK["fresh"]["table"]["code"]["touch"]
assert TOUCH_F == TOT_F == 17 and TBK["fresh"]["table"]["code"]["caught"] == TOT_F
assert C["code_census"]["fresh"]["caught"] == 0 and C["code_census"]["main"]["caught"] == 2
assert pc(RATE7, 2) == "2.49%" and LOWQ_F == TOT_F   # untraced, the rules add nothing to totals
assert TOT_F / NF < 0.5 and all(FD[i]["layer"] == "rule" for i in QR_F["missed"]) and len(QR_F["missed"]) == 4
assert TBK["main"]["table"]["rule"]["caught"] == 0 and TBK["fresh"]["table"]["rule"]["caught"] == 0
TK_ROWS = [
    ("Mapped from the codes in the 7(a) file", "", RATE7 * 100, "",
     f"Mapping the codes the 7(a) file actually writes: {pc(RATE7, 2)} of disbursed 7(a) loans were charged off."),
    ("Mapped from the SBA data dictionary", "", RATE7_DICT * 100, "key",
     f"Mapping from the dictionary: {n0(DICT_ROWS)} paid-in-full loans get no status and drop out of the count, so "
     f"the rate reads {pc(RATE7_DICT, 2)}. Record counts and amount totals still matched."),
]
TK_CAPTION = f"Totals still matched, but the 7(a) charge-off rate read {pc(RATE7_DICT, 2)}, not {pc(RATE7, 2)}."
TK_UNIT = ("Loans charged off (written off as lost) per 7(a) loan paid out. Loans with no status drop out of the "
           "count.")
takeaway = (f'<div class="kit-wrap"><figure class="chart takeaway tk-bars" id="takeaway"><figcaption>{e(TK_CAPTION)}'
            f'</figcaption><p class="chart-unit">{e(TK_UNIT)}</p><div class="chart-plot">'
            + bars("takeaway", TK_ROWS, 4, True, "Point at a bar to read it.", lambda v: f"{v:.2f}%")
            + f'</div><p class="takeaway-source">{e(DATA_LABEL)}</p></figure></div>')

DEK = ("Lenders moving loans onto a new system often sign off once record counts and amount totals match the old "
       "system's. This study converted 568,840 records into one loan table. They are "
       "loans from two Small Business Administration (SBA) programs, 7(a) and 504, and Montana mortgages. The SBA data dictionary spells paid in full PIF, but the 7(a) file writes P I F. A "
       f"status map (source code to loan status) built from the dictionary left {n0(DICT_ROWS)} loans with no status. A missing status changes "
       "neither a record count nor a dollar total, so the totals still matched. A rule check caught it: every "
       "converted loan must have a status.")

what_to_do = block("do", "What to do", (
    '<p><strong>Do not sign off a conversion on totals alone.</strong> They see only faults that change a count or '
    'a sum.</p>'
    '<p><strong>Before go-live, run three quick checks.</strong> These are the totals, 19 rules on the converted '
    'loans, and a check that every source code has a mapping.</p>'
    '<p><strong>Trace each rule failure on the first run to its source record before accepting it.</strong> '
    'A failure accepted unchecked catches nothing.</p>'
    '<p><strong>Make a rebuild part of the gate.</strong> A second engineer converts the data again from the rule '
    'document alone, and the two are compared loan by loan.</p>'
    '<p><strong>Have someone who did not write the code maps read 60 loans per source against the '
    'source.</strong> Even fully traced, five faults got past every automated check. Each mapped a code wrong in the rule document both builds read.</p>'))

worth = block("worth", "What it is worth", (
    '<ul class="notes">'
    f'<li>SBA charge-offs on these files total {bn(CO7 + CO5)}. A planted wrong line in the rule document, mapping '
    'charged off to closed, dropped all of them from reports while totals matched.</li></ul>'
    '<p>For illustration, assume a conversion carries '
    f'{NFAULTS} faults, and each one that reaches go-live costs {usd(COST_FAULT)}.</p>'
    '<ul class="notes">'
    f'<li>Totals alone would let about {usd(ESC_TOT * COST_FAULT)} of faults through.</li>'
    f'<li>The quick checks cost about {usd(QUICK_DAYS * DAY)} of analyst time. Traced, they would cut the escaped '
    f'cost to about {usd(ESC_QUICK * COST_FAULT)}. Untraced, they would save nothing over totals.</li>'
    f'<li>The rebuild costs about {usd(REB_DAYS * DAY)}. With it and traced checks, the escaped cost would fall to about '
    f'{usd(ESC_QR * COST_FAULT)}.</li>'
    '</ul>'))

team = block("team", "How I would put this to work with a team", (
    '<ol class="notes">'
    '<li><strong>The conversion analyst writes the rule document first.</strong> A data engineer writes the SQL from '
    'it.</li>'
    '<li><strong>A second engineer writes the rebuild</strong> from the same document, without reading the SQL.</li>'
    '<li><strong>Loan operations owns the code maps</strong> and signs each mapping line and accepted rule '
    'failure. A credit risk analyst reads the 60 loans per source.</li>'
    '<li><strong>The conversion lead holds the go-live gate.</strong> It opens when the quick checks show no '
    'unexplained break and the two versions match loan by loan.</li></ol>'))

SQL_SRC = (ROOT / "sql" / "convert.sql").read_text(encoding="utf-8").splitlines()


def _tidy(lines):
    # alignment padding between tokens is collapsed to one space so the excerpt fits a phone; no token changes
    out = [re.sub(r"(?<=\S) {2,}", " ", ln.rstrip()) for ln in lines]
    assert [x.split() for x in out] == [ln.split() for ln in lines]
    return "\n".join(out)


def _sql_pieces():
    # piece 1: the 7(a) de-duplication step, whole; no cut (its two comment lines above it are said in the prose)
    d0 = SQL_SRC.index("dup_7a AS (")
    d1 = SQL_SRC.index("dup_504 AS (")
    dup = SQL_SRC[d0:d1]
    assert dup[-1] == ")," and "row_number() OVER (PARTITION BY" in dup[1] and len(dup) == 4
    assert "no source carries a loan number" in SQL_SRC[d0 - 1]
    # piece 2: the 7(a) select down to its status column, one marked cut, then the FROM and joins, whole
    i0 = SQL_SRC.index("c7a AS (")
    i_end = SQL_SRC.index("c504 AS (")
    block7 = list(range(i0, i_end))
    i_status = [i for i in block7 if SQL_SRC[i].strip().startswith("ms.status")]
    i_from = [i for i in block7 if SQL_SRC[i].strip() == "FROM raw_7a r"]
    assert len(i_status) == len(i_from) == 1
    i_status, i_from = i_status[0], i_from[0]
    tail = SQL_SRC[i_from:i_end - 1]
    assert tail[-1] == ")," and SQL_SRC[i_end - 1] == "" and any("LEFT JOIN map_status ms" in x for x in tail)
    cut = f"  /* {i_from - i_status - 1} lines cut */"
    st = SQL_SRC[i0:i_status + 1] + [cut] + tail
    for ln in dup + st:
        assert ln == cut or ln in SQL_SRC
    return _tidy(dup), _tidy(st)


SQL_DUP, SQL_STATUS = _sql_pieces()
assert '("{ALL_COLS_7A}", "raw_7a")' in (ROOT / "tools" / "lib.py").read_text(encoding="utf-8")
DUP7 = S["correct"]["exact_duplicates"]["7A"]
assert DUP7 == 396

_CHECKS = (ROOT / "tools" / "checks.py").read_text(encoding="utf-8")
R02_SQL = re.search(r'"R02": "([^"]+)"', _CHECKS).group(1).format(t="loan")
assert R02_SQL == "SELECT count(*) FROM loan WHERE status IS NULL"
assert S["correct"]["rule_failures"]["R02"] == 0
sql_block = block("sql", "The SQL", (
    '<p>The conversion is one SQL script, <a href="sql/convert.sql">sql/convert.sql</a>, run in DuckDB. The totals, '
    'rules and code census are SQL queries too (<a href="tools/checks.py">tools/checks.py</a>). Two pieces of the '
    'script follow, copied from the file.</p>'
    '<p><strong>De-duplication.</strong> A window function numbers rows that match in every source column. Python '
    'fills <code>{ALL_COLS_7A}</code> with the file\'s columns.</p>'
    f'<pre class="sql" tabindex="0"><code>{e(SQL_DUP)}</code></pre>'
    f'<p>On the 7(a) file it flagged {n0(DUP7)} rows as repeats. They stay in the table, flagged.</p>'
    '<p><strong>The status join.</strong></p>'
    f'<pre class="sql" tabindex="0"><code>{e(SQL_STATUS)}</code></pre>'
    '<p>With the dictionary\'s map, P I F finds no match, so the left join leaves the status empty. The rule check '
    f'<code>{e(R02_SQL)}</code> returned {n0(DICT_ROWS)} on that build and 0 on the correct one.</p>'))

change = block("change", "What would change the conclusion", (
    '<ul class="notes">'
    f'<li>Totals alone would be enough only if at least {TOT_LINE:.0%} of real conversion defects '
    'changed a count or a sum. Fewer than half of the study\'s faults did.</li>'
    f'<li>The rebuild stops paying if a fault that reaches go-live costs less than about '
    f'US${round(BREAK_REB, -2):,.0f} at {NFAULTS} faults a conversion, or US${round(BREAK_REB_LOW, -2):,.0f} at '
    f'{LOW_N}.</li>'
    '<li>The rebuild could run on code changes only if quick checks, traced as on a real first run, missed at most '
    '1 in 10 charge-off faults.</li>'
    '</ul>'
    '<p>The tests: after each go-live, log every defect found, its fix cost, and whether it changed a count or a '
    'sum. The last line stays open: its test could cost more than the rebuild.</p>'))

limits = block("limit", "Limits", (
    f'<p><strong>{e(LIMIT)}</strong> The checks\' author wrote the fault list, and '
    'no source gives how often each kind occurs. Faults written blind by someone else are the next step.</p>'
    '<p><strong>The rebuild caught every code fault by construction:</strong> faults sat only in the main SQL. '
    'The cost figures assume it always would.</p>'
    '<p><strong>The code census was built for this mismatch</strong> and caught none of the random faults.</p>'
    '<p><strong>Faults ran one at a time.</strong> The cost figures assume two never hide each other in totals.</p>'
    '<p><strong>The P I F mismatch was seen in a code count before the design,</strong> then run as a planted fault. '
    'How each check treated it follows from how the check works.</p>'
    '<p><strong>The plan written before the runs kept the rebuild out of the gate</strong> unless traced quick checks '
    f'missed over 1 in 10 charge-off faults. They missed {len(CO_MISSED)} of {len(CO_FRESH)}, too few to settle '
    'that line, so the rebuild joined the gate after the results.</p>'
    '<p><strong>No tracing was tested,</strong> so traced figures are an upper bound. The '
    'split by fault kind, the untraced figures and reading the 80% line on real defects were added after the '
    'results.</p>'
    '<p><strong>The 60-loan read assumes a reader who knows the correct rules.</strong> Putting it in the gate was '
    'added after the results.</p>'
    '<p><strong>The source files carry no balances, payments or days past due,</strong> and the mortgage records are '
    'one state in one year.</p>'
    '<p><strong>No source carries a loan number,</strong> so two identical rows may be two loans.</p>'
    '<p><strong>Two of eight conversion predictions and both lender-matching predictions missed.</strong></p>'
    '<p>More limits are on the <a href="method.html#limits">method page</a>.</p>'))

details = block("details", "Detail pages", (
    '<ul class="pages">'
    '<li><a href="fresh.html">The follow-up</a>.</li>'
    '<li><a href="results.html">All results</a>.</li>'
    '<li><a href="lenders.html">Linking lenders</a>.</li>'
    '<li><a href="method.html">Method and checks</a>.</li>'
    '<li><a href="../data-quality-scorecard/">Data quality scorecard</a>.</li>'
    '<li><a href="../three-way-reconciliation/">Three-way reconciliation</a>.</li>'
    '<li><a href="../arr-reconciliation/">ARR reconciliation</a>.</li></ul>'))

entry_body = (hero(H1, STUDY_TITLE) + takeaway + dek(e(DEK)) + "{SECTION_BAR}" + what_to_do + worth + team
              + sql_block + change + limits + details + NEXT_STUDY)
page("index.html", STUDY_TITLE,
     "Which reconciliation catches the faults a loan conversion makes? Totals, rules, a code census, a line-by-line "
     "rebuild and a sample, tested on 568,840 real public loan records.",
     entry_body, [("do", "What to do"), ("worth", "Worth"), ("team", "With a team"),
                  ("sql", "The SQL"),
                  ("change", "What would change it"), ("limit", "Limits"), ("details", "Detail pages")])


# =====================================================================================================================
# Follow-up: 40 faults drawn at random after the checks were frozen
# =====================================================================================================================
FR_H1 = (f"On {NF} faults drawn at random after the checks froze, the quick checks would catch {LOWQ_F} to {QUICK_F}, "
         "from the study's own fault kinds.")
assert len(FR_H1.split()) <= 28 and ";" not in FR_H1
FR_ROWS = []
for label, key in (("Record counts and amount totals", "totals"), ("Rules on the target table, fully traced", "target_rules"),
                   ("The quick checks, fully traced", "cheap_set")):
    for which, wl, kind in (("main", f"{NM} chosen", "ref"), ("fresh", f"{NF} random", "key" if key == "cheap_set" else "")):
        v = C[key][which]["share"]
        bound = key != "totals"
        FR_ROWS.append((f"{label}, {wl}", "upper bound" if bound else "", v, kind,
                        f"{label}, {wl} faults: {C[key][which]['caught']} "
                        + ("would be caught if fully traced" if bound else "caught") + f", {pc(v, 1)}."))
fr_fig = ('<figure class="chart" id="fresh-fig"><figcaption>Totals held steady. Fully traced, the rules and the quick '
          'checks would catch a smaller share of the random faults than of the chosen ones.</figcaption><p class="chart-unit">Share of '
          'faults caught, chosen set against random set</p><div class="chart-plot">'
          + bars("fresh", FR_ROWS, 1.0, False, "Point at a bar to read it.", lambda v: pc(v, 1)) + '</div></figure>')
fr_body = (hero(FR_H1, STUDY_TITLE + ": the follow-up")
           + dek(f"On the {NM} faults chosen first, fully traced quick checks would catch {QUICK_M}. "
                 f"To test the checks on faults nobody chose, a generator drew {NF} more with a fixed seed, after "
                 "every check was frozen. Each draw is a fault kind, a field and a "
                 "scope. The scope is a whole source, one code value, or a random share of records.")
           + "{SECTION_BAR}"
           + block("what", "What it shows", (
               f'<div class="kit-wrap">{fr_fig}</div>'
               f'<p>Totals barely moved: {TOT_M} of {NM}, then {TOT_F} of {NF}. Fully traced, the target rules would fall from '
               f'{RULES_M} of {NM} to {RULES_F} of {NF}. Among the random faults the rules missed were lender names cut to 20 '
               'characters and 504 third-party amounts scaled.</p>'
               f'<p>The rebuild caught all {N_CODE_F} faults in code. With fully traced quick '
               f'checks, the two would catch {QR_F["caught"]} of {NF}.</p>'
               '<p>Even fully traced, four faults slipped past every automated check. All four map a status code wrong in the rule '
               'document: three mortgage action codes and the 504 not-funded code. A read of 60 loans per source would '
               f'catch each with a chance from {pc(min(MISSED_ALL_P))} to nearly 100%.</p>'
               '<p>The prediction was that each share would sit within 15 points across the two sets. Totals did, at '
               f'{GAPS["totals"]} points. The target rules and the quick checks did not, at {round(GAPS["target_rules"])} '
               f'and {round(GAPS["cheap_set"])} points.</p>'))
           + block("limits", "Limits", (
               '<p><strong>No tracing was tested.</strong> Every fully traced figure on this page is an upper bound, '
               'not a measured result.</p>'
               f'<p>The two sets hold only {NM} and {NF} faults.</p>'
               '<p>Chosen faults could flatter the checks, which is why the random set exists.</p>'
               '<p>The generator draws from fault kinds written for this study, with weights set for it. The faults '
               'and the checks share an author. One draw changed no record and was drawn again. Two draws were the '
               'same fault, every 504 record dropped, and both count.</p>'
               '<p>The sample chances assume a reader who knows the correct rules and spots every affected loan. A '
               'reader working from the faulted rule document would miss all four.</p>'
               '<p>The rebuild catches every fault in code by construction: both builds agreed on the correct '
               'conversion.</p>'
               '<p>A target rule caught a fault when its failure count moved off the correct conversion\'s, either '
               'way. Both dropped draws only lowered rule counts. Counted only on rises, as declared before it ran, '
               f'fully traced target rules would catch {RISE_F} of {NF}, and the quick checks would stay at {QUICK_F}. Both '
               'counts use the correct conversion\'s failures, which a real first run does not have. With every '
               f'rule failure on the first run accepted, the quick checks would catch {LOWQ_F}, a figure added after '
               'the results.</p>'))
           + f'<section class="block kit-wrap">{links_row()}</section>' + NEXT_STUDY)
page("fresh.html", "The follow-up: " + STUDY_TITLE,
     "Forty conversion faults drawn at random after the checks were frozen, against the 19 chosen first.",
     fr_body, [("what", "What it shows"), ("limits", "Limits")])


# =====================================================================================================================
# All results
# =====================================================================================================================
CHECK_NAME = [("totals", "Record counts and amount totals"), ("totals_by_status", "Totals by status"),
              ("target_rules", "Rules on the target table"), ("code_census", "Code census (chosen after seeing the data)"),
              ("record_compare", "Line-by-line rebuild"), ("cheap_set", "Quick checks: totals, rules and census")]


def frac(d):
    return f'{d["caught"]} of {d["of"]}'


check_rows = [tr([e(name), frac(C[k]["main"]), frac(C[k]["main_code"]), frac(C[k]["main_rule"]), frac(C[k]["fresh"]),
                  frac(C[k]["fresh_code"]), frac(C[k]["fresh_rule"])], key=k == "cheap_set") for k, name in CHECK_NAME]
check_rows.append(tr(["Quick checks and the rebuild", f'{QR_M["caught"]} of {NM}', "", "", f'{QR_F["caught"]} of {NF}', "",
                      ""], key=True))
check_tab = table("Faults caught by each check", ["Check", f"Chosen ({NM})", "In code", "In rules", f"Random ({NF})",
                                                  "In code", "In rules"], check_rows)
samp_rows = [tr([f"{n} loans per source", f'{C[f"sample_{n}"]["main_expected"]:.1f} of {NM}',
                 str(len(C[f"sample_{n}"]["main_below_half"])), f'{C[f"sample_{n}"]["fresh_expected"]:.1f} of {NF}',
                 str(len(C[f"sample_{n}"]["fresh_below_half"]))]) for n in (60, 200)]
samp_tab = table("Sample read: expected faults caught", ["Sample", "Chosen: expected", "Under even odds",
                                                          "Random: expected", "Under even odds"], samp_rows)
MARK = {True: "yes", False: ""}

RES_H1 = (f"Even fully traced, {len(QR_F['missed'])} of {NF} random faults passed every automated check, all status codes "
          "mapped wrong in the rule document both builds read, in a self-test.")
assert len(RES_H1.split()) <= 28 and ";" not in RES_H1 and len(QR_F["missed"]) == 4


def v2_frac(rows, key, layer=None):
    sel = [r for r in rows if layer is None or r["layer"] == layer]
    return f'{sum(r[key] for r in sel)} of {len(sel)}'


v2_rows = [tr([e(name)] + [v2_frac(V2["rules_on_rises"][w]["rows"], key, lay) for w in ("main", "fresh") for lay in (None, "code", "rule")],
              key=k2 == "q")
           for k2, name, key in (("r", "Rules on the target table, rises only", "rules_rise"),
                                 ("q", "Quick checks, rules on rises only", "quick_rise"))]
assert v2_frac(V2M["rows"], "rules_rise") == f"{RISE_M} of {NM}" and v2_frac(V2F["rows"], "quick_rise") == f"{QUICK_F} of {NF}"
v2_tab = table("Faults caught with rules counted on rises only",
               ["Check", f"Chosen ({NM})", "In code", "In rules", f"Random ({NF})", "In code", "In rules"], v2_rows)
V2_INNER = (
    '<p>A real go-live gate cannot read a fall in a rule\'s failures as a signal. It has a list of failures accepted '
    'on the first full run, and flags only counts above it. Counted that way, in a version declared before it ran, the '
    'list is the correct conversion\'s failures. A real first run already holds its faults, so its list would match '
    'only if every failure on it were traced to its cause. Approved exceptions were not tested.</p>' + v2_tab
    + f'<p>The rules fall from {RULES_F} to {RISE_F} random faults: the two draws that drop every 504 record only '
    f'lowered rule counts. On the chosen faults they fall from {RULES_M} to {RISE_M}, below the {RULES_M} '
    'predicted before it ran. The three they lose also only lowered rule counts, and totals caught all three. The '
    'quick checks do not change.</p>')

PLAIN = [("- INTERVAL 1 DAY", "1 day earlier"), ("+ INTERVAL 1 DAY", "1 day later"), ("+ INTERVAL 1 MONTH", "1 month later"),
         ("FixedorVariableInterestInd = F", "a fixed rate"), ("RevolverStatus = Y", "a revolving line"),
         ("LoanStatus = ", "status "), ("action_taken = ", "action code "), ("chargeoff_date", "charge-off date"),
         ("chargeoff_usd", "charge-off amount"), ("principal_usd", "principal"), ("applicant_income_usd", "applicant income"),
         ("third_party_usd", "third-party amount"), ("origination_date", "approval date"),
         ("paid_in_full_date", "paid-in-full date"), ("lender_name", "lender name"), ("record_kind", "record kind"),
         ("closed_other", "closed (other)"), ("paid_in_full", "paid in full"), ("HMDA code", "mortgage action code"),
         ("HMDA rows", "mortgage records"), ("HMDA row", "mortgage record"), ("7A rows", "7(a) loans"),
         ("7A row", "7(a) loan"), ("504 rows", "504 loans"), ("504 row", "504 loan"), ("7A code", "7(a) code"),
         ("unit of 504.GrossApproval", "unit of the 504 approved amount"),
         ("unit of HMDA.loan_amount_000s", "unit of the mortgage loan amount"), ("status left empty", "status left empty"),
         ("for every 7A", "for every 7(a)"), (" a CASE", " a CASE statement"), ("HMDA ", "mortgage ")]


def plain(name):
    for a, b in PLAIN:
        name = name.replace(a, b)
    assert " - " not in name and "_" not in name and "INTERVAL" not in name, name
    return name


def fault_rows(fs):
    out = []
    for i, f in enumerate(fs, start=1):
        fr = f["fired"]
        out.append(tr([f"{i}. {e(plain(f['name']))}", "rule" if f["layer"] == "rule" else "code", n0(f["affected"]),
                       MARK[fr["totals"]], MARK[fr["totals_by_status"]], MARK[fr["target_rules"]], MARK[fr["code_census"]],
                       MARK[fr["record_compare"]], pc(f["p_sample_60"])]))
    return out


FH = ["Fault", "Where", "Records hit", "Totals", "By status", "Rules", "Census", "Rebuild", "Sample of 60"]
STATUS_NAME = {"7A": "7(a)", "504": "504", "HMDA": "Mortgages"}
status_rows = [tr([f"{STATUS_NAME[s]}: {e(st.replace('_', ' '))}", n0(c), f"US${p / 1e6:,.0f} million"])
               for s, st, c, p in PREP["status"]]
RF = S["correct"]["rule_failures"]
rule_text = {r.split(" ", 1)[0]: r.split(" ", 1)[1] for r in PROTO["checks"]["target_rules"]}
base_rows = [tr([e(rule_text[k]), n0(v)]) for k, v in RF.items() if v]
assert sum(1 for v in RF.values() if v) == 6

FNUM = {f["id"]: i for i, f in enumerate(F, start=1)}
MNUM = {f["id"]: i for i, f in enumerate(M, start=1)}


def nums(ids, table):
    out = [str(table[i]) for i in ids]
    return ", ".join(out[:-1]) + " and " + out[-1]


FAMILY_NAME = [("drop", "Records dropped"), ("duplicate", "Records loaded twice"),
               ("scale", "An amount or unit scaled"), ("swap", "Two fields, or day and month, swapped"),
               ("round", "An amount rounded"), ("null", "A field left empty"), ("remap", "A code mapped wrong"),
               ("shift_date", "A date shifted"), ("truncate", "A lender name cut short")]
KT = TBK["fresh"]["table"]
kind_rows = [tr([e(name), str(KT[f"code.{k}"]["faults"]), str(KT[f"code.{k}"]["touch"]), str(KT[f"code.{k}"]["caught"])])
             for k, name in FAMILY_NAME if f"code.{k}" in KT]
kind_rows.append(tr(["In the rule document, every kind", str(KT["rule"]["faults"]), "0", str(KT["rule"]["caught"])]))
assert sum(KT[f"code.{k}"]["faults"] for k, _ in FAMILY_NAME if f"code.{k}" in KT) == N_CODE_F
kind_tab = table("Random faults by kind: how many touch a count or a summed amount, and how many totals caught",
                 ["Kind of fault", "Faults", "Touch a count or summed amount", "Caught by totals"], kind_rows)
KINDS_INNER = (
    '<p>A fault touches a count or a summed amount when it leaves records missing or doubled, or changes an approved, '
    'guaranteed or charged-off amount on the converted table. That is read from its effect, not from the totals. '
    f'In code, totals caught every fault that does, {TOUCH_CODE} of {TOUCH_CODE} over both sets, and none of the other '
    f'{OTHER_CODE}. This split was added after the results, in a version declared before it ran.</p>' + kind_tab)

UNITS_INNER = (
    '<p>Here the source side reads each amount in the unit the source system reports, not the rule document\'s. '
    f'Totals then catch {TOTSU_M} of {NM} chosen and {TOTSU_F} of {NF} random faults, against {TOT_M} and {TOT_F}. The '
    'three new catches are units documented wrong: the mortgage loan amount twice and the 504 approved amount once. '
    'Income is not summed, so its unit fault still passes. This check was added after the results, in a version '
    'declared before it ran.</p>')

RANGE_INNER = (
    f'<p>The target rules alone caught {ALONE_M} of the {QUICK_M} chosen and {ALONE_F} of the {QUICK_F} random faults '
    f'the quick checks caught. The {ALONE_F} are random faults {nums(QB_F["rules_alone"], FNUM)} in the table below. If '
    'every rule failure on the first run were accepted, a fault present from that run would raise no rule. The range '
    'below runs from that case to the one where every failure is traced to its cause. These figures were added after '
    'the results, in versions declared before they ran.</p>'
    '<ul class="notes">'
    f'<li><strong>Faults caught by the quick checks:</strong> {LOWQ_M} to {QUICK_M} of {NM} chosen, {LOWQ_F} to '
    f'{QUICK_F} of {NF} random.</li>'
    f'<li><strong>Random faults that move a charge-off figure, missed:</strong> {len(CO_MISSED)} to {CO_LOW} of '
    f'{len(CO_FRESH)}, {pc(RL["share_high"], 1)} to {pc(RL["share_low"], 1)}. The low end is past the 10% line.</li>'
    f'<li><strong>Random faults in code past the quick checks:</strong> {PAST_HI} to {PAST_LO} of {N_CODE_F}. The '
    'rebuild caught all of them.</li></ul>')

TEST_INNER = (
    f'<p>One-sided 95% throughout. For {CM["missed"]} miss in {CM["of"]}, the upper bound is {pc(UP1, 1)}; the '
    f'two-sided interval runs up to {pc(CM["upper_95"], 1)}.</p>'
    '<ul class="notes">'
    f'<li><strong>A test of {ZERO_N} faults with no miss</strong> puts the bound at '
    f'{pc(V2B["zero_miss_upper_at_that_n"], 1)}. But it would pass only {pc(PASS_OBS, 1)} of the time at 1 in 15, and '
    f'{pc(PASS_LINE, 1)} at 10%, so it would rarely settle anything.</li>'
    f'<li><strong>{SZ["n"]} charge-off-moving faults with {SZ["max_misses"]} misses or fewer</strong> put the bound '
    f'under 10%. At 1 in 15 that happens {pc(SZ["power"])} of the time.</li>'
    f'<li><strong>Draws.</strong> At {len(CO_FRESH)} charge-off-moving faults in {NF}, reaching {SZ["n"]} takes '
    f'{n0(round(DRAWS_MEAN))} draws on average, and {n0(DRAWS_95)} for a 95% chance.</li></ul>'
    '<p>The rules in that test are judged against failures accepted on a faulted first run, by someone who does not '
    'know the fault. Judged against a correct conversion, as here, it would measure only the high end. The sizing was '
    'added after the results.</p>'
    '<p>Each draw needs a fresh first run and someone blind to the fault to judge each rule failure. So this test '
    'could cost more than the rebuild it would decide on. A log of real defects after each go-live, noting whether '
    'each moved a count or a sum, costs far less.</p>')

REBUILD_INNER = (
    f'<p>At {NFAULTS} faults a conversion and {usd(DAY)} a day, the rebuild removes '
    f'{V2B["faults_removed_by_rebuild_per_conversion"]:.2f} faults. It pays once an escaped fault costs over '
    f'{usd(BE_LO)} at {EFF["rebuild"]["low"]} days, {usd(BREAK_REB)} at {REB_DAYS} and {usd(BE_HI)} at '
    f'{EFF["rebuild"]["high"]}. At {usd(COST_FAULT)} per escaped fault, it pays if it catches {pc(RSN["10"], 1)}, '
    f'{pc(RSN[str(REB_DAYS)], 1)} or {pc(RSN["25"], 1)} of the code faults it caught here, for those days.</p>'
    f'<p>Faults that would escape a conversion of {NFAULTS}: about {ESC_TOT:.1f} with totals alone. With the quick checks, '
    f'about {ESC_QUICK:.1f} fully traced and {ESC_TOT:.1f} with every failure accepted. With '
    f'the rebuild as well, about {ESC_QR:.0f}. At {LOW_N} faults a conversion, the rebuild pays above about '
    f'US${round(BREAK_REB_LOW, -2):,.0f}. Against the declared {TOT_LINE:.0%} line, totals alone caught '
    f'{pc(TOT_F / NF, 1)} of the random faults. These figures were chosen after the results.</p>')

res_body = (hero(RES_H1, STUDY_TITLE + ": all results")
            + dek("Here is every fault and every check, with a sample's chance of drawing an affected loan. "
                  "A check catches a fault when its result differs from its result on the correct conversion. Counts "
                  "of target rules on rises only sit beside the first counts.",
                  "What this page holds")
            + "{SECTION_BAR}"
            + block("checks", "Faults caught by each check", (
                check_tab +
                '<p>A fault in code changes the conversion SQL. A fault in rules changes the rule document, which the '
                'SQL and the rebuild both read. Totals read no status, flag or income, and their source side uses the '
                f'document\'s units. So they caught none of the {N_RULE_M + N_RULE_F} faults in rules.</p>'
                '<p>Among the chosen faults, nothing automated caught purchased mortgages booked as originations. That '
                f'raised Montana originations from {n0(ORIG)} to {n0(ORIG_M14)}.</p>'))
            + block("rises", "Rules counted on rises only", V2_INNER)
            + block("kinds", "Totals by kind of fault", KINDS_INNER)
            + block("units", "Totals on the source system's own units", UNITS_INNER)
            + block("range", "The quick checks' range", RANGE_INNER)
            + block("test", "How big a test must be", TEST_INNER)
            + block("rebuild", "What the rebuild must catch to pay", REBUILD_INNER)
            + block("sample", "The sample read", (
                samp_tab +
                '<p>The figures are exact chances that a simple random sample per source draws at least one affected '
                'loan, summed over faults. One fixed draw per size, '
                'the same for every fault, happened to catch all 19 chosen faults, so the chances are the measure.</p>'))
            + block("chosen", f"The {NM} chosen faults", table(f"The {NM} chosen faults", FH, fault_rows(M)))
            + block("random", f"The {NF} random faults", table(f"The {NF} random faults", FH, fault_rows(F)))
            + block("correct", "The correct conversion", (
                f'<p>{n0(PREP["target_rows"])} records: {n0(S["correct"]["by_source"]["7A"])} 7(a), '
                f'{n0(S["correct"]["by_source"]["504"])} 504 and {n0(S["correct"]["by_source"]["HMDA"])} mortgage '
                'records. Rows identical in every field to an earlier row are flagged, never dropped: '
                f'{S["correct"]["exact_duplicates"]["7A"]} in 7(a), {S["correct"]["exact_duplicates"]["504"]} in 504 '
                f'and {S["correct"]["exact_duplicates"]["HMDA"]} in mortgages.</p>'
                + table("Records and approved amounts by status", ["Status", "Records", "Approved amount"], status_rows)
                + '<p>Six target rules fail on the correct conversion too, because the source data breaks them. In the '
                'first count a rule fires on a fault when its count moves off these, up or down. The count on rises only '
                'flags moves up.</p>'
                + table("Target rules that fail on the correct conversion", ["Rule", "Records"], base_rows)))
            + block("limits", "Limits", (
                '<p>Faults were run one at a time. Two faults together could mask each other in totals. The faults '
                'and the checks share an author. No source carries a loan number, so ids come from file row '
                'numbers.</p>'
                '<p>No tracing was tested, so every fully traced figure is an upper bound. The rebuild catches every '
                'code fault here by construction. The sample chances assume the reader spots every affected '
                'loan.</p>'))
            + f'<section class="block kit-wrap">{links_row()}</section>' + NEXT_STUDY)
page("results.html", "All results: " + STUDY_TITLE,
     "Every planted conversion fault and which reconciliation check caught it, with sample odds.", res_body,
     [("checks", "By check"), ("rises", "Rises only"), ("kinds", "By kind"), ("units", "Source units"),
      ("range", "Range"), ("test", "Test size"), ("rebuild", "Rebuild"), ("sample", "Sample"), ("chosen", "Chosen faults"), ("random", "Random faults"),
      ("correct", "Correct conversion"), ("limits", "Limits")])



# =====================================================================================================================
# Second part: lenders
# =====================================================================================================================
LN_H1 = (f"Matching SBA lenders to FDIC banks on name and state found the right bank for {pc(REC['name_state'])}, "
         "short of the 90% predicted before the match ran.")
assert len(LN_H1.split()) <= 28
MATCH_NAME = [("name", "Name only"), ("name_state", "Name and state"), ("name_city_state", "Name, city and state"),
              ("name_state_active_after_results", "Name and state, active banks only (added after the results)")]
match_rows = [tr([e(lab), n0(LM[k]["right"]), n0(LM[k].get("wrong", 0)), n0(LM[k].get("ambiguous", 0)),
                  n0(LM[k].get("none", 0)), pc(LM[k]["recall"], 1), pc(LM[k]["precision"], 2)],
                 key=k == "name_state") for k, lab in MATCH_NAME]
CF_NAME = [("name_as_written", "Name as written"), ("name", "Name after cleaning"), ("city", "City"), ("zip5", "ZIP code"),
           ("state", "State"), ("fdic_inactive", "Bank no longer active")]
WINS = {"name_as_written": "FDIC", "name": "FDIC", "city": "FDIC", "zip5": "FDIC", "state": "FDIC", "fdic_inactive": "FDIC"}
cf_rows = [tr([e(lab), n0(LCF[k]), pc(LSH[k], 1), WINS[k]]) for k, lab in CF_NAME]
SW = L["rule"]
assert SW["legal name"] == "FDIC" and SW["lender the loan is assigned to and its SBA location id"] == "SBA"
sw_rows = [tr([e(k[0].upper() + k[1:]), e(v)]) for k, v in SW.items()]
ln_fig_rows = [(lab.split(" (")[0], "added after the results" if "after" in k else "", LM[k]["recall"],
                "after" if "after" in k else ("key" if k == "name_state" else ""),
                f"{lab}: right bank for {n0(LM[k]['right'])} of {n0(NLOC)} lender locations, {pc(LM[k]['recall'], 1)}.")
               for k, lab in MATCH_NAME]
ln_fig = ('<figure class="chart" id="match-fig"><figcaption>Each field added to the key found the right bank more often, '
          'with almost no wrong links.</figcaption><p class="chart-unit">Share of 1,872 lender locations linked to the '
          'right FDIC bank</p><div class="chart-plot">'
          + bars("match", ln_fig_rows, 1.0, False, "Point at a bar to read it.", pc) + '</div></figure>')
ln_body = (hero(LN_H1, STUDY_TITLE + ": linking lenders")
           + dek("A conversion often has to tie each loan's lender to one legal identity, so exposure can be summed by "
                 f"institution. The 7(a) file carries each lender's FDIC certificate for {n0(NLOC)} lender locations. "
                 "That gives a true answer to test name matching against.")
           + "{SECTION_BAR}"
           + block("match", "Match rates", (
               f'<div class="kit-wrap">{ln_fig}</div>'
               + table("Name matching against the FDIC list", ["Key", "Right", "Wrong", "Several candidates", "No match",
                                                                "Right share", "Precision"], match_rows)
               + f'<p>Name alone found the right bank for {pc(REC["name"])}. Many names belong to several FDIC records, '
               f'so {n0(LM["name"]["ambiguous"])} locations had more than one candidate. Adding the state found '
               f'{pc(REC["name_state"])}, with {LM["name_state"]["wrong"]} wrong link. Adding the city found '
               f'{pc(REC["name_city_state"])}.</p>'))
           + block("conflicts", "Fields that conflict", (
               table("SBA and FDIC fields that differ on true pairs", ["Field", "Lender locations", "Share", "Wins"],
                     cf_rows)
               + f'<p>On the {n0(NLOC)} true pairs, the city differed for {pc(LSH["city"], 1)}, not the 15% predicted. '
               f'{LCF["fdic_inactive"]} locations, with {L["loans_at_inactive_certs"]} loans, point to banks the FDIC '
               'lists as no longer active.</p>'
               f'<p>Of {HF["lenders"]} Montana mortgage lenders, {HF["linked"]} link to the FDIC list by their Federal '
               f'Reserve id. The other {HF["no_fdic_record"]} have no FDIC record; the FDIC lists only the banks and '
               f'savings institutions it insures. Of the {HF["linked"]}, {HF["name"]} names, {HF["city"]} cities and '
               f'{HF["state"]} states differ, and {HF["fdic_inactive"]} are no longer active.</p>'))
           + block("wins", "Which source wins", (
               '<p>Declared before the match ran:</p>'
               + table("Source that wins each field", ["Field", "Source"], sw_rows)))
           + block("limits", "Limits", (
               '<p>Only 7(a) lenders carry a certificate, so 504 lenders were not tested. The legal entity identifier '
               'register was not used. The FDIC list is today\'s, so banks merged since a loan was made show as '
               'inactive.</p>'))
           + f'<section class="block kit-wrap">{links_row()}</section>' + NEXT_STUDY)
page("lenders.html", "Linking lenders: " + STUDY_TITLE,
     "SBA 7(a) lenders matched to their FDIC identity: match rates, conflicting fields and the source that wins.",
     ln_body, [("match", "Match rates"), ("conflicts", "Conflicts"), ("wins", "Source wins"), ("limits", "Limits")])


# =====================================================================================================================
# Method and checks
# =====================================================================================================================
PLAIN_PRED = {
    "P1": f"Totals miss at least 9 of the {NM} chosen faults.",
    "P2": "Totals miss both faults written from the data dictionary.",
    "P3": f"The rebuild catches all {N_CODE_M} chosen faults in code and none of the {N_RULE_M} in rules (true by "
          "construction).",
    "P4": f"The target rules catch at least 4 of the {N_RULE_M} chosen faults in rules.",
    "P5": "Totals by status catch at most 2 faults that plain totals miss.",
    "P6": "A 60-loan sample has under even odds on at least 3 chosen faults.",
    "P7": f"The quick checks catch at least 15 of the {NM} chosen faults.",
    "P8": "On the random faults, totals, rules and the quick checks each land within 15 points of their chosen-set share.",
    "P9": "Name and state link at least 90% of lender locations to the right bank, at 98% precision or better.",
    "P10": "The city differs for at least 15% of true lender pairs.",
}
MEASURED = {
    "P1": f"missed {PS['P1']['value']}", "P2": "missed both", "P3": f"{PS['P3']['value'][0]} and {PS['P3']['value'][1]}",
    "P4": f"{PS['P4']['value']}", "P5": f"{PS['P5']['value']}", "P6": f"{PS['P6']['value']}", "P7": f"{PS['P7']['value']}",
    "P8": f"{GAPS['totals']}, {round(GAPS['target_rules'])} and {round(GAPS['cheap_set'])} points",
    "P9": f"{pc(REC['name_state'], 1)} at {pc(LM['name_state']['precision'], 2)}", "P10": pc(LSH["city"], 1)}
HELD = {**{k: v["held"] for k, v in PS.items()},
        "P9": REC["name_state"] >= 0.9 and LM["name_state"]["precision"] >= 0.98, "P10": LSH["city"] >= 0.15}
assert [HELD[f"P{i}"] for i in range(1, 11)] == [True] * 5 + [False, True, False, False, False]
pred_rows = [tr([e(PLAIN_PRED[k]), ("held, by construction" if k == "P3" else "held") if HELD[k] else "missed",
                  e(MEASURED[k])]) for k in PLAIN_PRED]

glossary = ('<dl class="glossary">'
            '<dt>Conversion</dt><dd>Moving records from source systems into one target table with one set of codes and '
            'units.</dd>'
            '<dt>Rule document</dt><dd>The written mapping: each source field, code and unit, and its target.</dd>'
            '<dt>Tie out</dt><dd>Counts and sums on the target match the same counts and sums on the source.</dd>'
            '<dt>Target rules</dt><dd>Checks on the converted table alone, such as a charged-off loan having a '
            'charge-off date.</dd>'
            '<dt>Code census</dt><dd>A count of code values in the source files that have no entry in the rule document.</dd>'
            '<dt>Rebuild</dt><dd>A second conversion, written from the same rule document without reading the SQL, and '
            'compared with the first record by record.</dd>'
            '<dt>Quick checks</dt><dd>Totals, target rules and the code census together.</dd>'
            '<dt>Charge-off</dt><dd>A loan the lender has written off as lost.</dd>'
            '<dt>Charge-off rate</dt><dd>Charged-off loans over disbursed loans: active, paid in full or charged '
            'off.</dd>'
            '<dt>7(a) and 504</dt><dd>The two main SBA loan programs: general business loans, and loans for real estate '
            'and equipment.</dd>'
            '<dt>HMDA</dt><dd>The public record of mortgage applications that lenders must report.</dd>'
            '<dt>FDIC certificate</dt><dd>The id the FDIC gives each bank it insures.</dd>'
            '<dt>Source wins</dt><dd>The declared rule for which source\'s value to keep when two disagree.</dd>'
            '</dl>')

RESULT_FILES = ["prepare-r1.json", "main-r1.json", "fresh-r1.json", "summary-r1.json", "lenders-r1.json"]
downloads = ('<ul class="notes">'
             '<li>Results: ' + ", ".join(f'<a href="results/{f}">{f}</a>' for f in RESULT_FILES) + '.</li>'
             '<li>Rules and design: <a href="rules/conversion-rules.json">rules/conversion-rules.json</a>, '
             '<a href="protocol-r1.json">protocol-r1.json</a>, <a href="predictions-r1.json">predictions-r1.json</a>, '
             '<a href="amendments-r1.json">amendments-r1.json</a>, <a href="assumptions.json">assumptions.json</a>.</li>'
             '<li>Rules on rises only, declared: <a href="CHANGES-r2.md">CHANGES-r2.md</a> and '
             '<a href="results/change2-r2.json">results/change2-r2.json</a>.</li>'
             '<li>Source units, the range and test size, declared: <a href="CHANGES-r3.md">CHANGES-r3.md</a> and '
             '<a href="results/change3-r3.json">results/change3-r3.json</a>.</li>'
             '<li>The low end, draws and totals by kind, declared: <a href="CHANGES-r4.md">CHANGES-r4.md</a> and '
             '<a href="results/change4-r4.json">results/change4-r4.json</a>.</li>'
             '<li>Data: <a href="data/sources.json">data/sources.json</a> lists each public file, its URL, licence and '
             'sha256. The raw files are not copied here.</li>'
             '<li>Code: <a href="sql/convert.sql">sql/convert.sql</a>, <a href="tools/reference.py">tools/reference.py</a>, '
             '<a href="tools/checks.py">tools/checks.py</a>, <a href="tools/fresh_faults.py">tools/fresh_faults.py</a>, '
             '<a href="tools/run_study.py">tools/run_study.py</a>, <a href="tools/summarize.py">tools/summarize.py</a>, '
             '<a href="tools/lenders.py">tools/lenders.py</a>, <a href="tools/get_data.py">tools/get_data.py</a>, '
             '<a href="tools/change2.py">tools/change2.py</a>, <a href="tools/change3.py">tools/change3.py</a>, '
             '<a href="tools/change4.py">tools/change4.py</a>, '
             '<a href="tests/test_study.py">tests/test_study.py</a>, <a href="site/render.py">site/render.py</a>, and '
             'the <a href="README.md">README</a> with the commands.</li></ul>')


URL = "https://diogotravassos.dev/loan-data-conversion/"
PROMPT = (
    f"This method comes from Diogo Travassos's study \"{STUDY_TITLE}\" ({URL}). If you can open links, read it first: "
    "it plants faults in a real conversion of public loan records and measures which checks catch them. The steps below "
    "stand on their own if you can't.\n\n"
    "Help me test the reconciliation for a loan data conversion, using the rule document, source extracts and target "
    "table I describe below.\n\n"
    "Method:\n"
    "1. Check the rule document against the data first. Count each value of every coded source field. Flag any value "
    "with no mapping, and any mapping whose code never appears.\n"
    "2. Build four checks: record counts and amount totals per source; the same by status; rules on the target table "
    "alone (status present and in its domain, charged-off loans have a charge-off date, amounts in range, dates in "
    "order); and the code census from step 1.\n"
    "3. On the first full run, trace every rule failure to a source record. Accept only traced failures as exceptions, "
    "and count a rule as firing only when its failures rise above that accepted list.\n"
    "4. Write a second conversion from the rule document alone, without reading the first, and compare the two record "
    "by record.\n"
    "5. Plant at least 20 faults, some in the conversion code and some in the rule document: dropped codes, unit "
    "mix-ups, duplicated loans, joins that drop or fan out rows, swapped fields, shifted dates. Plant each before the "
    "first run, so whoever accepts the exceptions does not know it. Run every check on every fault and record which "
    "ones fired.\n"
    "6. For a sample of 60 records per source, work out the chance of drawing at least one affected record for each "
    "fault.\n\n"
    "Report back: a table of faults by check, the share each check caught among code faults and among rule faults, the "
    "faults no automated check caught, and which checks you would put in the go-live gate and why. If the exception "
    "step was not tested, report the rule catches as a range, from accepting every first-run failure to tracing every "
    "one. Do not trust a check until it has fired on a planted fault.\n\n"
    f"In your report, say which study you followed and link it: {URL}")
use_block = block("use", "Use this at your company", (
    "<p>To test the checks on your own conversion, paste this into your AI assistant with a description of your rule "
    f'document and tables.</p><pre class="prompt">{e(PROMPT)}</pre>'))

TOT_TOL = PROTO["checks"]["totals"]["tolerance_usd"]
METH_H1 = (f"The SBA data dictionary writes paid in full as PIF and the 7(a) file as P I F, so a dictionary-built "
           f"status map leaves {n0(DICT_ROWS)} loans unmapped.")
assert len(METH_H1.split()) <= 28 and ";" not in METH_H1
meth_body = (hero(METH_H1, STUDY_TITLE + ": method and checks")
             + dek("The data, the conversion, the faults, the checks, and the predictions with their outcomes.",
                   "What this page holds")
             + "{SECTION_BAR}"
             + block("data", "Data", (
                 '<ul class="notes">'
                 '<li><strong>SBA 7(a) loans</strong> approved from fiscal year 2020 to September 2026: 403,644 '
                 'records.</li>'
                 '<li><strong>SBA 504 loans</strong> approved from fiscal year 2010 to September 2026: 119,599 '
                 'records.</li>'
                 '<li><strong>HMDA mortgage records</strong> for Montana in 2017, with the lender panel: 45,597 '
                 'records.</li>'
                 '<li><strong>The FDIC list</strong> of insured institutions, active and inactive.</li></ul>'
                 '<p>All are public federal data. Borrower names in the SBA files were not carried into the target '
                 'table.</p>'))
             + block("conversion", "The conversion", (
                 f'<p>The rule document came first. It maps {len(RULES["fields"])} target fields, each source status '
                 'code and each unit. The SQL reads its code maps from that document, so a wrong rule reaches the SQL '
                 'the way a wrong specification reaches real conversion code. A second build in plain Python reads the '
                 'raw files and the same document and shares no code with the SQL.</p>'
                 '<p>Amounts round half away from zero to the cent. Without that rule the two builds differ on 1 '
                 'record, a guaranteed amount of US$3,749,992.425; it was added to the rule document before any fault '
                 'ran.</p>'
                 f'<p>The rebuild caught none of the {N_RULE_M + N_RULE_F} faults in the rule document and every fault in '
                 'code.</p>'))
             + block("faults", "The faults", (
                 f'<p>The {NM} chosen faults were picked to cover several kinds of conversion error. They include a dropped status '
                 'code, a unit mix-up, duplicated loans, and a join that drops or fans out rows. '
                 f'{N_CODE_M} sit in the SQL and {N_RULE_M} in the rule document. Two copy the SBA data dictionary, '
                 'which disagrees with its own files.</p>'
                 f'<p>The {NF} random faults were drawn by a generator with a fixed seed, after the checks were '
                 'frozen. Each picks a kind, a field and a scope. A draw that changed no record was drawn '
                 'again.</p>'))
             + block("checks", "The checks", (
                 '<ul class="notes">'
                 f'<li><strong>Totals:</strong> record counts and sums of approved, guaranteed and charged-off amounts '
                 f'per source, within US${TOT_TOL:.0f}. The source side reads the rule document\'s units. Read in '
                 'the source system\'s own units instead, a check added after the results, it catches '
                 f'{TOTSU_F} of {NF} random faults.</li>'
                 '<li><strong>Totals by status:</strong> the same, by source and status.</li>'
                 '<li><strong>Target rules:</strong> 19 rules on the converted table. A rule fired when its failure '
                 'count moved off the correct conversion\'s, either way. Counted on rises only, in a version '
                 'declared before it ran, it flags moves up.</li>'
                 '<li><strong>Code census:</strong> code values in the source files with no entry in the rule document. It was chosen '
                 'after seeing the data.</li>'
                 '<li><strong>Rebuild:</strong> the second build compared with the SQL record by record.</li>'
                 '<li><strong>Sample read:</strong> 60 or 200 loans per source, traced to the target. The calculation gives '
                 'the exact chance of drawing an affected loan.</li></ul>'))
             + block("preds", "Predictions and outcomes", (
                 '<p>Written before any fault ran. The expected finding was that totals would miss many faults and the quick checks would catch most. '
                 'The opposite was that totals would catch most faults.</p>'
                 + table("Predictions and outcomes", ["Prediction", "Outcome", "Measured"], pred_rows)))
             + use_block
             + block("glossary", "Glossary", glossary)
             + block("downloads", "Downloads and how to rebuild", (
                 '<p>The README lists the commands. They fetch the public files, check each sha256, then rebuild every '
                 'result and page.</p>' + downloads))
             + block("limits", "Limits", (
                 '<p>Faults ran one at a time. The sample reader is assumed perfect and to know the correct rules. The '
                 'cost and saving figures are assumed and were chosen after the results. The faults and the checks share an '
                 'author. One prediction that held, the rebuild\'s, could not have missed. No source gives how often each '
                 'kind of fault occurs. Approved exceptions from a real first run were not tested.</p>'
                 '<p>Two faults together could hide each other in totals, and the cost figures assume they do not.</p>'
                 '<p>Totals were bound to catch any fault in the code that changed a count or a sum, since that is all '
                 'they add up. Unit faults in the rule document moved both sides, so totals missed them.</p>'
                 '<p>The code census was built for the P I F mismatch and caught none of the random faults.</p>'
                 '<p>Both builds read the same rule document, so the rebuild cannot catch a fault in it. It catches every '
                 'fault in code by construction, and its cost figures assume it always would.</p>'
                 '<p>A defect log after go-live counts only defects someone found, so it is a floor. The study did not '
                 'size or cost it.</p>'))
             + f'<section class="block kit-wrap">{links_row()}</section>' + NEXT_STUDY)
page("method.html", "Method and checks: " + STUDY_TITLE,
     "Data, rule document, planted faults, checks, predictions and downloads for the loan conversion study.",
     meth_body,
     [("data", "Data"), ("conversion", "Conversion"), ("faults", "Faults"), ("checks", "Checks"),
      ("preds", "Predictions"), ("use", "Use it"), ("glossary", "Glossary"), ("downloads", "Downloads"), ("limits", "Limits")])
