"""Build the study pages from the results files. Every number on a page comes from results/ or assumptions.json.

Usage: python3 -I -B site/render.py   (writes index.html, holdout.html, results.html, method.html)
"""
import html
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"))


TRAIN = load("results/train-r1.json")
HO = load("results/holdout-r1.json")
AT = load("results/assess-train-r1.json")
AH = load("results/assess-holdout-r1.json")
DS = load("results/describe-r1.json")
AFTER = load("results/after-r1.json")
AS = load("assumptions.json")
PRED = load("predictions-r1.json")
PROTO = load("protocol-r1.json")
CSS = (ROOT / "site" / "page.css").read_text(encoding="utf-8")

STUDY_TITLE = "Who will cancel: early signals on real course enrolments"
DATA_LABEL = ("Real public data: the Open University Learning Analytics Dataset, 32,593 course enrolments from Feb 2013 "
              "to Oct 2014, under CC BY 4.0.")
COHORT = PROTO["cohorts"]["names"]


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


def pc(v, d=0):
    """A share (0 to 1) as a percentage string."""
    return f"{100 * v:.{d}f}%"


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


def usd(v):
    s = f"{abs(round(v)):,}"
    return ("minus " if v < 0 else "") + "US$" + s


def x2(v):
    return f"{v:.2f}"


# ---------- the numbers the pages use, with their rounding checked ----------
R14 = TRAIN["rule"]                      # day-14 rule, training
H14 = HO["result"]                    # day-14 rule, holdout
RA = AT["flag"]                       # missed first assignment, training
HA = AH["flag"]                       # missed first assignment, holdout
OFF = AT["offer"]
OFH = AH["offer"]
ALLC = DS["cohorts"]["all"]
MV = AFTER["movement"]
SENS = AFTER["sensitivity_holdout"]
TS = AFTER["test_size"]
V, C, SS = (AS[k] for k in ("value_of_kept_enrolment_usd", "cost_per_offer_usd", "save_share"))

assert R14["k"] == 1 and HO["rule"]["k"] == 1
assert (pc(R14["cancel_rate_flagged"]), pc(R14["cancel_rate_all"]), pc(R14["flag_share"])) == ("25%", "20%", "21%")
assert (pc(H14["cancel_rate_flagged"]), pc(H14["cancel_rate_all"])) == ("26%", "20%")
assert (pc(RA["cancel_rate_flagged"]), pc(RA["cancel_rate_rest"]), pc(RA["capture"])) == ("32%", "14%", "52%")
assert (pc(HA["cancel_rate_flagged"]), pc(HA["cancel_rate_rest"]), pc(HA["capture"])) == ("30%", "13%", "54%")
assert (x2(R14["lift"]), x2(H14["lift"]), x2(RA["lift"]), x2(HA["lift"])) == ("1.23", "1.31", "1.64", "1.60")
assert pc(R14["capture"]) == "25%" and pc(H14["capture"]) == "24%"
assert f'{RA["rate_ratio_flagged_vs_rest"]:.1f}' == "2.3" and f'{HA["rate_ratio_flagged_vs_rest"]:.1f}' == "2.3"
assert HO["holds"] and AH["holds"]
SHARE_BEFORE14 = DS["share_before_day14"]
SHARE_BEFORE0 = DS["share_before_day0"]
assert (pc(SHARE_BEFORE14), pc(SHARE_BEFORE0)) == ("44%", "26%")
BU, BS = TRAIN["signals"][TRAIN["best_usage"]], TRAIN["signals"][TRAIN["best_signup"]]
assert TRAIN["best_usage"] == "clicks_14" and TRAIN["best_signup"] == "studied_credits"
assert (x2(BU["auc"]), x2(BS["auc"])) == ("0.56", "0.58")
# money, per 1,000 enrolled on the first due day, at the base assumptions
EV, FL = OFF["everyone"], OFF["flagged"]
assert (round(EV["kept_at_base"]), round(FL["kept_at_base"]), round(FL["offers"])) == (19, 10, 314)
assert (round(EV["net_base"], -2), round(FL["net_base"], -1)) == (-6800, 2550)
RATIO = OFF["untargeted_over_targeted_cost_per_kept"]
assert f"{RATIO:.1f}" == "1.6" and abs(RATIO - RA["lift"]) < 1e-9
BREAK_EVEN = FL["break_even_save_share_base"]
assert pc(BREAK_EVEN) == "8%"
GRID_WIN, GRID_N = OFF["grid_points_flagged_beats_everyone"], OFF["grid_points"]
assert (GRID_WIN, GRID_N) == (18, 27)
T10 = TS["by_save_share"]["0.1"]
assert T10["per_arm"] == 3523 and TS["flagged_a_year"] == 5639
PASS_LINE = PROTO["holdout_pass"]["lift_ratio_min"] * AT["flag"]["lift"]
assert f"{PASS_LINE:.1f}" == "1.3"

# ---------- checks added after the results (CHANGES-r2.md, and Change 3, whose declaration stays private) ----------
ch2 = load("results/change2-r2.json")
ch3 = load("results/change3-r3.json")
tutor_all = ch2["C-B_tutor_marked_runs"]
tutor_t, tutor_h = tutor_all["training"], tutor_all["holdout"]
assert (x2(tutor_t["lift"]), x2(tutor_h["lift"]), pc(tutor_t["capture"], 1), pc(tutor_h["capture"], 1)) == ("1.88", "1.99", "36.8%", "30.2%")
assert tutor_all["holds"] and (pc(tutor_all["lift_ratio"]), pc(tutor_all["capture_ratio"])) == ("106%", "82%")
N_TUTOR = len(tutor_t["runs"]) + len(tutor_h["runs"])
N_COMPUTER = len(tutor_t["runs_left_out"]) + len(tutor_h["runs_left_out"])
assert (N_TUTOR, N_COMPUTER) == (19, 3)
SD = ch2["C-C_same_day_use"]
SDT, SDH = SD["training"], SD["holdout"]
assert SD["cut"] == 0.1 and (x2(SDT["use_rule"]["lift"]), x2(SDH["use_rule"]["lift"])) == ("1.22", "1.21")
assert (x2(SDT["lift_gap"]), x2(SDH["lift_gap"])) == ("0.66", "0.78")
CA = ch2["C-A_by_course_run"]
CCC_H = CA["holdout"]["CCC 2014J"]
assert (pc(CCC_H["flag_share"]), x2(CCC_H["lift"])) == ("98%", "0.99")
CCC_SHARE_OF_FLAGS = CCC_H["flagged"] / sum(r["flagged"] for r in CA["holdout"].values())
assert sum(r["flagged"] for r in CA["holdout"].values()) == HA["flagged"] and pc(CCC_SHARE_OF_FLAGS) == "65%"
REACH = ch2["C-D_reach"]
assert (pc(REACH["training"]["share_out_of_reach"], 1), pc(REACH["holdout"]["share_out_of_reach"], 1),
        pc(REACH["all_four"]["share_out_of_reach"], 1)) == ("43.2%", "53.6%", "47.0%")
assert REACH["all_four"]["cancellations_registered_by_day0"] == DS["cancellations_registered_by_day0"]
TE = ch2["C-E_test"]
HW, BE_PTS, CLEAR = TE["interval_half_width_points"], TE["break_even_drop_points"], TE["smallest_drop_clearing_break_even_points"]
assert (f"{HW:.1f}", f"{BE_PTS:.1f}", f"{CLEAR:.1f}") == ("2.1", "2.5", "4.6") and TE["per_half"] == T10["per_arm"]
assert abs(BE_PTS / 100 - C["base"] / V["base"]) < 1e-12
READOUT = {k: v["months_to_readout"] for k, v in TE["readout"].items()}
assert sorted(round(v) for v in READOUT.values()) == [20, 21]
EQ = ch2["C-F_equal_effect"]["min_save_share_ratio_flagged_to_rest"]
assert pc(EQ) == "43%" and abs(EQ - RA["cancel_rate_rest"] / RA["cancel_rate_flagged"]) < 1e-12
GRID_EVERYONE = ch2["grid_points_everyone_nets_more"]
assert len(GRID_EVERYONE) == GRID_N - GRID_WIN and all(
    g["cost"] == C["low"] or g["save_share"] == SS["high"] or g["value"] == V["high"] for g in GRID_EVERYONE)
VSTAR, VSTAR_H = ch3["training"]["break_even_value_at_base"], ch3["holdout"]["break_even_value_at_base"]
assert (round(VSTAR, -2), round(VSTAR_H, -2)) == (2200, 2300)
FEE_60 = ch3["fee_page"]["gbp_60_credits"]   # a 60-credit module starting from August 2014, England
assert FEE_60 == 2632
assert all(ch2["predictions"][q]["held"] for q in ("Q1", "Q2", "Q3")) and ch2["predictions"]["Q3"]["at_least_1_3"] == 6
H14_COURSE = sorted(v["lift"] for v in HO["by_course"].values())
assert (x2(H14_COURSE[0]), x2(H14_COURSE[-1])) == ("0.74", "1.64")

# ---------- the rule as recommended, on the 19 tutor-marked runs (CHANGES-r4.md) ----------
ch4 = load("results/change4-r4.json")
M4T, M4H = ch4["C4-A_B_money"]["training"], ch4["C4-A_B_money"]["holdout"]
EV4, FL4 = M4T["everyone"], M4T["flagged"]
assert (round(EV4["kept_at_base"]), round(FL4["kept_at_base"]), round(FL4["offers"])) == (17, 6, 196)
assert (round(EV4["net_base"], -2), round(FL4["net_base"], -2)) == (-9200, 1800)
assert (round(M4H["flagged"]["offers"]), round(M4H["flagged"]["kept_at_base"]), round(M4H["everyone"]["kept_at_base"])) == (152, 5, 16)
assert (round(M4H["flagged"]["net_base"], -2), round(M4H["everyone"]["net_base"], -2)) == (1100, -11200)
assert all((m["grid_points_flagged_beats_everyone"], m["grid_points"]) == (GRID_WIN, GRID_N) for m in (M4T, M4H))
assert all(len(m["grid_points_everyone_nets_more"]) == GRID_N - GRID_WIN and all(
    g["cost"] == C["low"] or g["save_share"] == SS["high"] or g["value"] == V["high"]
    for g in m["grid_points_everyone_nets_more"]) for m in (M4T, M4H))
assert abs(M4T["untargeted_over_targeted_cost_per_kept"] - tutor_t["lift"]) < 1e-9 and pc(tutor_t["flag_share"]) == "20%"
assert (pc(tutor_t["capture"]), pc(tutor_h["flag_share"]), pc(tutor_h["capture"])) == ("37%", "15%", "30%")
assert abs(FL4["offers"] - 1000 * tutor_t["flag_share"]) < 1e-9
VSTAR4, VSTAR4_H = M4T["break_even_value_at_base"], M4H["break_even_value_at_base"]
assert (round(VSTAR4, -2), round(VSTAR4_H, -2)) == (2200, 2300)
EQ4 = M4T["equal_effect_min_save_share_ratio"]
assert (pc(EQ4), pc(M4H["equal_effect_min_save_share_ratio"])) == ("42%", "41%")
T4 = ch4["C4-C_test"]
HW4, CLEAR4 = T4["interval_half_width_points"], T4["smallest_observed_drop_clearing_break_even_points"]
assert T4["per_half"] == 3361 and (f"{HW4:.1f}", f"{CLEAR4:.1f}", f"{T4['break_even_drop_points']:.1f}") == ("2.2", "4.7", "2.5")
assert f"{T4['sized_drop_points']:.1f}" == "3.1" and pc(T4["chance_interval_clears_break_even_at_sized_drop"]) == "8%"
READ4 = sorted(round(v["months_to_readout"]) for v in T4["readout"].values())
assert READ4 == [44, 45] and round(T4["flagged_a_year"], -1) == 2060
assert (T4["flagged_feb_2014"], T4["flagged_oct_2014"]) == (990, 1074) and T4["flagged_oct_2014"] == tutor_h["flagged"]
LINE4 = ch4["C4-D_reversal_lift"]["line"]
assert f"{LINE4:.1f}" == "1.5" and abs(LINE4 - PROTO["holdout_pass"]["lift_ratio_min"] * tutor_t["lift"]) < 1e-12
FX = ch4["C4-F_fee_usd"]
assert (round(FX["usd_30_credits"], -1), round(FX["usd_60_credits"], -1)) == (2170, 4340) and FX["usd_per_gbp_2014"] == 1.6484
assert FX["usd_60_credits"] > max(VSTAR4, VSTAR4_H) and FX["usd_30_credits"] < VSTAR4
CR = ch4["C4-E_by_course_run"]
assert CR["course_runs"] == 15 and CR["best_usage"] == TRAIN["best_usage"] and CR["best_signup"] == TRAIN["best_signup"]
CR_DIFF = CR["usage_minus_signup_ci_by_course_run"]
assert (x2(CR_DIFF[0]), x2(CR_DIFF[1])) == ("-0.11", "0.06")
CR_LOO = sorted(CR["usage_minus_signup_one_course_left_out"].values())
assert (x2(CR_LOO[0]), x2(CR_LOO[-1])) == ("-0.03", "0.04")

H1 = ("The least active fifth after two weeks cancelled at 25%, barely above the 20% average. I would send save offers "
      "at the first missed assignment.")
assert "university" not in H1   # no caveat in the headline; the scope sits in Limits
assert len(H1.split()) <= 30 and len(H1.split(". ")[0].split()) <= 28 and ";" not in H1 and ":" not in H1
assert len(H1.split(". ")[1].split()) <= 10

LIMIT = "Course enrolments stand in for subscriptions, and every money figure is assumed."  # card qualifier, 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]
    assert "{" not in visible and "}" not in visible, fname
    for ch in (chr(0x2014), chr(0x2013)):
        assert ch not in out, (fname, ch)
    (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 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):
    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", "": ""}[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}">{pc(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="holdout.html">The latest cohort, held out</a>'
            '<a href="results.html">All results</a><a href="method.html">Method and checks</a></p>')


# =====================================================================================================================
# Entry page
# =====================================================================================================================
TK_ROWS = [
    ("Everyone still enrolled on day 14", "", R14["cancel_rate_all"], "ref",
     f"Everyone still enrolled on day 14, three earlier cohorts: {pc(R14['cancel_rate_all'], 1)} cancelled later "
     f"({n0(R14['cancellers'])} of {n0(R14['n'])})."),
    ("Least active fifth after two weeks", "used the course site on 0 or 1 of the first 14 days",
     R14["cancel_rate_flagged"], "key",
     f"Used the course site on 0 or 1 of the first 14 days: {pc(R14['cancel_rate_flagged'], 1)} cancelled later "
     f"({n0(R14['cancellers_flagged'])} of {n0(R14['flagged'])})."),
    ("Missed the first assignment", "among those still enrolled on its due day", RA["cancel_rate_flagged"], "",
     f"Missed the first marked assignment, among those still enrolled on its due day: "
     f"{pc(RA['cancel_rate_flagged'], 1)} cancelled later ({n0(RA['cancellers_flagged'])} of {n0(RA['flagged'])})."),
]
TK_CAPTION = ("Two weeks of low use barely raised the share who went on to cancel. A missed first assignment raised it "
              "more.")
TK_UNIT = "Share who cancelled later in the course, students who started from Feb 2013 to Feb 2014"
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, 0.40, True, "Each bar is the share who cancelled later: point at one to read it.")
            + f'</div><p class="takeaway-source">{e(DATA_LABEL)}</p></figure></div>')

DEK = ("A subscription team often reads a customer's first weeks of use to pick who gets a save offer. I tested that "
       "habit on 32,593 enrolments in 7 courses at the Open University. A student can cancel any day and every click "
       "is logged, so an enrolment works like a subscription. Two weeks of use told little. Of students who missed the "
       f"first marked assignment, {pc(RA['cancel_rate_flagged'])} cancelled later, against {pc(RA['cancel_rate_rest'])} "
       "of those who handed it in. The gap held on the latest cohort of students, kept unseen until the end: "
       f"{pc(HA['cancel_rate_flagged'])} against {pc(HA['cancel_rate_rest'])}. Where most hand it in on time, calling "
       f"only them would gain about US${round(FL4['net_base'], -2):,.0f} per 1,000 students at the costs below. Calling "
       f"everyone would lose about US${abs(round(EV4['net_base'], -2)):,.0f}.")

what_to_do = block("do", "What to do", (
    '<p><strong>Do not trigger the save offer on low use in the first two weeks.</strong> The least active fifth held '
    f'{pc(R14["capture"])} of later cancellations, against about {pc(R14["flag_share"])} for a fifth picked at '
    'random.</p>'
    '<p><strong>Send it to students who miss the first marked assignment, in courses where most hand it in on time, '
    'and test it before you scale it.</strong> '
    f'In those courses they were {pc(tutor_t["flag_share"])} of students enrolled on the due day, and held '
    f'{pc(tutor_t["capture"])} of later cancellations. In a '
    'software subscription, the same signal is the first commitment a customer skips, such as a booked onboarding '
    'call.</p>'))

worth = block("worth", "What it is worth", (
    f'<p>Take 1,000 students still enrolled on the first due day in those courses. Say a save call costs '
    f'US${C["base"]}, a kept enrolment is worth US${V["base"]:,}, and the call keeps {pc(SS["base"])} of those who '
    'would have cancelled.</p>'
    f'<ul class="notes"><li>Calling all 1,000 costs US${C["base"] * 1000:,}, keeps about {round(EV4["kept_at_base"])} '
    f'and loses about US${abs(round(EV4["net_base"], -2)):,.0f}.</li>'
    f'<li>Calling the {round(FL4["offers"])} who missed the assignment costs US${round(FL4["offers"]) * C["base"]:,}, '
    f'keeps about {round(FL4["kept_at_base"])} and gains about US${round(FL4["net_base"], -2):,.0f}.</li></ul>'))

team = block("team", "How I would put this to work with a team", (
    '<ol class="notes">'
    '<li><strong>The analyst, first.</strong> Build the daily list of students who missed the first assignment on its '
    'due day.</li>'
    '<li><strong>Course leads, next.</strong> Choose the call, a pause option and who calls within three days.</li>'
    '<li><strong>Half the list gets the call, chosen at random.</strong> The gap in later cancellations between the '
    'halves is what the call does.</li>'
    '<li><strong>Finance, before the test.</strong> Set the value of a kept enrolment. The decision turns on it.</li>'
    f'<li><strong>The size of the test.</strong> A 3-point drop needs {T4["per_half"]:,} flagged students in each '
    f'half, which pins it to within {HW4:.1f} points. At 2014\'s {round(T4["flagged_a_year"], -1):,} flagged students a '
    f'year, enrolling them and following each to the course end takes {READ4[0]} to {READ4[1]} months. One '
    'readout at the end goes to the head of student services.</li></ol>'))

numbers = block("numbers", "The three numbers that matter", (
    '<ol class="notes">'
    f'<li><strong>{x2(R14["lift"])}.</strong> The least active fifth cancelled later at {x2(R14["lift"])} times the '
    f'average rate on the earlier cohorts, and {x2(H14["lift"])} times on the latest.</li>'
    f'<li><strong>{RA["rate_ratio_flagged_vs_rest"]:.1f} times.</strong> Students who missed the first assignment '
    f'cancelled later at {RA["rate_ratio_flagged_vs_rest"]:.1f} times the rate of those who handed it in.</li>'
    f'<li><strong>{pc(SHARE_BEFORE14)}.</strong> Of students registered by the start who cancelled, that share left '
    f'before day 14, beyond any two-week signal. Waiting for the first due day leaves '
    f'{pc(REACH["all_four"]["share_out_of_reach"])} out. {pc(SHARE_BEFORE0)} cancelled before the start.</li></ol>'))

change = block("change", "What would change the conclusion", (
    '<ul class="notes">'
    f'<li>If the assignment flag\'s lift in those courses falls below {LINE4:.1f} on the next cohort, it no longer '
    f'travels. Stop targeting on it. It was {x2(tutor_t["lift"])} earlier and {x2(tutor_h["lift"])} on the latest '
    'cohort.</li>'
    f'<li>If the random test\'s whole 95% interval for the drop sits below {BE_PTS:.1f} points, the call loses money at '
    f'US${C["base"]} a call and US${V["base"]:,} a kept enrolment. Drop it and keep the pause option. The interval clears '
    f'{BE_PTS:.1f} only if the observed drop tops {CLEAR4:.1f} points. If it straddles {BE_PTS:.1f}, keep the call only '
    f'if the observed drop is above {BE_PTS:.1f}.</li>'
    f'<li>If Finance values a kept enrolment above about US${round(VSTAR4, -2):,.0f}, call everyone instead, at '
    f'US${C["base"]} a call that keeps {pc(SS["base"])}.</li>'
    '<li>If two weeks of use ranked cancellers at least 0.10 better than sign-up facts, a day-14 offer would be worth a '
    f'test. On a score where 0.5 is a coin flip, they ranked about the same, {x2(BU["auc"])} against '
    f'{x2(BS["auc"])}, both barely above it.</li></ul>'))

limits = block("limit", "Limits", (
    f'<p><strong>{e(LIMIT)}</strong> Students are not software customers, and a course has a fixed end. Over the '
    f'declared money ranges, calling the flagged nets more than calling everyone in {GRID_WIN} of {GRID_N} combinations. '
    f'In the other {GRID_N - GRID_WIN}, a cheap call, a very effective one or a very valuable enrolment tips it. The '
    f'university listed a 60-credit module at \u00a3{FEE_60:,} from August 2014, about '
    f'US${round(FX["usd_60_credits"], -1):,.0f} at that year\'s average rate, where calling everyone nets more. What a '
    'student who cancels still owes is not known.</p>'
    f'<p><strong>One two-week cut served all seven courses.</strong> By course, its lift on the latest cohort ran from '
    f'{x2(H14_COURSE[0])} to {x2(H14_COURSE[-1])}.</p>'
    '<p><strong>The assignment signal was chosen after the results.</strong> The two-week rule, declared first, missed '
    'all three of its predictions. The signal was then fixed on the earlier cohorts and tested once on the unseen one. '
    f'The checks below, the {pc(REACH["all_four"]["share_out_of_reach"])}, and every '
    'figure above for courses where most hand it in on time came after every result.</p>'
    f'<p><strong>In {N_COMPUTER} course runs the flag marked the run, not the student.</strong> Their first test is '
    'marked by computer, and almost no one\'s work is recorded by its due day. The call leaves those runs out, and '
    f'the money, test and lift figures above are for the other {N_TUTOR}.</p>'
    '<p><strong>The flag is read later,</strong> on the first due day, from day 12 to day 61. Use read on that day had '
    f'a lift of only {x2(SDT["use_rule"]["lift"])} ({x2(SDH["use_rule"]["lift"])} on the latest cohort), so the wait '
    'explains little.</p>'
    '<p><strong>Likely to cancel is not the same as possible to keep.</strong> The flagged may be the hardest to win '
    f'back. Calling only them stays cheaper per kept student while the call works at least {pc(EQ4)} as well on them as '
    'on the rest. Only the random test can tell.</p>'))

details = block("details", "Detail pages", (
    '<ul class="pages">'
    '<li><a href="holdout.html">The latest cohort, held out</a>: both rules on the unseen Oct 2014.</li>'
    '<li><a href="results.html">All results</a>: every table and every later check.</li>'
    '<li><a href="method.html">Method and checks</a>: data, definitions, predictions with their scores, and '
    'downloads.</li>'
    '<li>A related study: <a href="../retail-win-back/">which lapsed customers are worth a win-back '
    'contact</a>.</li></ul>'))

entry_body = (hero(H1, STUDY_TITLE) + takeaway
              + f'<section class="kit-wrap hero-more" aria-label="The question"><p class="hero-dek">{e(DEK)}</p></section>'
              + "{SECTION_BAR}" + what_to_do + worth + team + numbers + change + limits + details + NEXT_STUDY)
page("index.html", STUDY_TITLE,
     "Which early signal tells that a new customer will cancel? Two weeks of use against a missed first assignment, on "
     "32,593 real course enrolments, with the latest cohort held out.",
     entry_body, [("do", "What to do"), ("worth", "Worth"), ("team", "With a team"), ("numbers", "Three numbers"),
                  ("change", "What would change it"), ("limit", "Limits"), ("details", "Detail pages")])


# =====================================================================================================================
# Follow-up: the latest cohort, held out
# =====================================================================================================================
HO_H1 = (f"On the unseen Oct 2014 cohort, students who missed the first assignment cancelled later at "
         f"{pc(HA['cancel_rate_flagged'])}, against {pc(HA['cancel_rate_rest'])} of those who handed it in.")
assert len(HO_H1.split()) <= 28 and ";" not in HO_H1
HO_ROWS = [
    ("Two-week rule, earlier cohorts", "", R14["lift"], "ref",
     f"Two-week rule on the three earlier cohorts: lift {x2(R14['lift'])}, holding {pc(R14['capture'])} of later "
     "cancellations."),
    ("Two-week rule, Oct 2014", "", H14["lift"], "",
     f"Two-week rule on Oct 2014: lift {x2(H14['lift'])}, holding {pc(H14['capture'])} of later cancellations."),
    ("Missed first assignment, earlier cohorts", "", RA["lift"], "ref",
     f"Missed first assignment on the three earlier cohorts: lift {x2(RA['lift'])}, holding {pc(RA['capture'])} of later "
     "cancellations."),
    ("Missed first assignment, Oct 2014", "", HA["lift"], "key",
     f"Missed first assignment on Oct 2014: lift {x2(HA['lift'])}, holding {pc(HA['capture'])} of later cancellations."),
]


LIFT_FLOOR, LIFT_TOP = 1.0, 2.0   # bars start at 1.00, no better than random, so their length is the lift above it
assert all(LIFT_FLOOR <= r[2] <= LIFT_TOP for r in HO_ROWS)


def lift_bars():
    out = []
    for label, sub, v, kind, text in HO_ROWS:
        cls = "bar-row pt" + {"key": " is-key", "ref": " is-ref", "": ""}[kind]
        w = (v - LIFT_FLOOR) / (LIFT_TOP - LIFT_FLOOR) * 100
        out.append(f'<li class="{cls}" tabindex="0" data-readout="{e(text)}" title="{e(text)}"><span class="bar-label">'
                   f'{e(label)}</span><span class="bar-track" aria-hidden="true"><span class="bar" style="width:'
                   f'{w:.1f}%"></span></span><span class="bar-value num">{x2(v)}</span></li>')
    return ('<ol class="bars" id="lift-bars" data-hover-chart data-readout-default="Each bar is a lift: the flagged '
            'group\'s later cancellation rate over everyone\'s. Point at one to read it.">' + "".join(out) + "</ol>")


ho_fig = ('<figure class="chart" id="lift-fig"><figcaption>Both rules kept their lift on the cohort they never saw. Only '
          'the assignment flag had much lift to keep.</figcaption><p class="chart-unit">Lift: the flagged group\'s later '
          'cancellation rate divided by everyone\'s. Bars start at 1.00, no better than random.</p><div class="chart-plot">'
          + lift_bars() + '</div></figure>')
ho_body = (hero(HO_H1, STUDY_TITLE + ": the latest cohort, held out")
           + '<section class="kit-wrap hero-more" aria-label="The question"><p class="hero-dek">A rule fitted on past '
           'customers can fail on the next ones. So the latest cohort, Oct 2014, was kept out of every step until both '
           'rules were fixed and saved. Then each rule was applied to it once, unchanged.</p></section>'
           + "{SECTION_BAR}"
           + block("what", "What it shows", (
               f'<div class="kit-wrap">{ho_fig}</div>'
               f'<p>Oct 2014 had {n0(HO["enrolments"])} enrolments in 7 courses. On it, the two-week rule flagged '
               f'{pc(H14["flag_share"])} of those still enrolled on day 14. They cancelled later at '
               f'{pc(H14["cancel_rate_flagged"])}, against {pc(H14["cancel_rate_all"])} for everyone. That is a lift of '
               f'{x2(H14["lift"])}, against {x2(R14["lift"])} before. The rule held, but it held little.</p>'
               f'<p>The assignment flag picked out {pc(HA["flag_share"])} of those still enrolled on the due day. They '
               f'held {pc(HA["capture"])} of later cancellations. Its lift was {x2(HA["lift"])}, against '
               f'{x2(RA["lift"])} before. The pass line, set before the holdout was read, was 80% of the earlier lift '
               'and capture. Both rules passed.</p>'
               f'<p>The money moved with it. At the same assumed costs, calling the {round(OFH["flagged"]["offers"])} '
               f'flagged per 1,000 gains about US${round(OFH["flagged"]["net_base"], -2):,.0f}. Calling everyone loses '
               f'about US${abs(round(OFH["everyone"]["net_base"], -2)):,.0f}.</p>'
               f'<p>One course, which first ran in Feb 2014, cancelled the most: {pc(MV["new_courses"]["CCC"]["rate"])} '
               f'of its students cancelled later. The two-week rule\'s lift on it was {x2(HO["by_course"]["CCC"]["lift"])}. '
               'The <a href="results.html#holdout-courses">course table</a> has each course.</p>'
               '<p>That course\'s first test is marked by computer, and almost no one\'s work is recorded by its listed due '
               f'day. So the assignment flag caught {pc(CCC_H["flag_share"])} of its students, {pc(CCC_SHARE_OF_FLAGS)} of '
               f'everyone it flagged on Oct 2014, and told nothing there: its lift in that course was {x2(CCC_H["lift"])}. '
               f'On the other six courses the flag\'s lift was {x2(tutor_h["lift"])}, against {x2(tutor_t["lift"])} on '
               f'runs of the same kind before. Its capture was {pc(tutor_all["capture_ratio"])} of the earlier value, just '
               f'over the pass line. There, calling the {round(M4H["flagged"]["offers"])} flagged per 1,000 gains about '
               f'US${round(M4H["flagged"]["net_base"], -2):,.0f}, and calling everyone loses about '
               f'US${abs(round(M4H["everyone"]["net_base"], -2)):,.0f}. The <a href="results.html#after">run table</a> has '
               'every course run.</p>'))
           + block("limits", "Limits", (
               '<p>The holdout is one cohort from the same university, only eight months after the last earlier one. A '
               'new kind of customer could behave differently. The assignment signal was chosen after the earlier '
               'cohorts\' results, though before this cohort was read.</p>'
               '<p>The figures for the other six courses, the money there and the run table come from checks added after '
               'every result, Oct 2014 included.</p>'
               f'<p>The results table marks {SENS["withdrawn_without_cancel_day"]} Oct 2014 enrolments as withdrawn with '
               'no cancellation day. Counting them as cancellations, a check added after the results, moves the '
               f'assignment flag\'s lift to {x2(SENS["missed_first_assessment"]["lift"])} and the two-week rule\'s to '
               f'{x2(SENS["day14_rule"]["lift"])}.</p>'))
           + f'<section class="block kit-wrap">{links_row()}</section>' + NEXT_STUDY)
page("holdout.html", "The latest cohort, held out: " + STUDY_TITLE,
     "Both early-signal rules, fixed on three earlier cohorts, applied once to the unseen Oct 2014 cohort of real course "
     "enrolments.", ho_body, [("what", "What it shows"), ("limits", "Limits")])


# =====================================================================================================================
# All results
# =====================================================================================================================
SIG_NAME = {"days_active_14": "Days with any use, days 0 to 13", "clicks_14": "Clicks, days 0 to 13",
            "days_since_active_14": "Days since last use, on day 13", "days_active_pre": "Days with use before the start",
            "lead_days": "Days registered before the start", "studied_credits": "Total study load (credits)",
            "prev_attempts": "Earlier attempts at the course"}
GROUP_NAME = {"usage": "First two weeks", "trial": "Before the start", "signup": "At sign-up"}
CRS = CR["signals"]
assert all(abs(CRS[n]["auc"] - s["auc"]) < 1e-12 and CRS[n]["ci_by_enrolment_frozen"] == s["ci"] for n, s in TRAIN["signals"].items())
assert all(CRS[n]["ci_by_course_run"][0] <= s["ci"][0] and CRS[n]["ci_by_course_run"][1] >= s["ci"][1]
           for n, s in TRAIN["signals"].items())   # resampling whole course runs widens every interval
sig_rows = [tr([e(SIG_NAME[n]), e(GROUP_NAME[s["group"]]), x2(s["auc"]), f'{x2(s["ci"][0])} to {x2(s["ci"][1])}',
                f'{x2(CRS[n]["ci_by_course_run"][0])} to {x2(CRS[n]["ci_by_course_run"][1])}'],
               key=n in (TRAIN["best_usage"], TRAIN["best_signup"])) for n, s in TRAIN["signals"].items()]
CR_TOP = max(s["ci_by_course_run"][1] for s in CRS.values())
assert x2(CR_TOP) == "0.63" and x2(max(s["auc"] for s in TRAIN["signals"].values())) == "0.58"
assert (x2(TRAIN["usage_minus_signup_ci"][0]), x2(TRAIN["usage_minus_signup_ci"][1])) == ("-0.03", "0.00")
assert x2(CR["usage_minus_signup_auc"]) == "-0.01"
by_days = [tr([str(d), n0(TRAIN["cancel_rate_by_days_active"][str(d)]["n"]), pc(TRAIN["cancel_rate_by_days_active"][str(d)]["cancel_rate"], 1),
               n0(HO["cancel_rate_by_days_active"][str(d)]["n"]), pc(HO["cancel_rate_by_days_active"][str(d)]["cancel_rate"], 1)],
              key=d <= 1) for d in range(15)]


def rule_row(name, s):
    return tr([e(name), pc(s["flag_share"], 1), pc(s["cancel_rate_flagged"], 1), pc(s["cancel_rate_rest"], 1),
               pc(s["cancel_rate_all"], 1), x2(s["lift"]), pc(s["capture"], 1)])


rule_rows = [rule_row("Two-week rule, earlier cohorts", R14), rule_row("Two-week rule, Oct 2014", H14),
             rule_row("Two-week rule, earlier cohorts, read on the due day", AT["day14_rule_same_population"]),
             rule_row("Missed first assignment, earlier cohorts", RA), rule_row("Missed first assignment, Oct 2014", HA)]
order = PROTO["cohorts"]["order"]
fun_rows = []
for p in order + ["all"]:
    f = DS["cohorts"][p]["funnel"]
    fun_rows.append(tr([e(COHORT.get(p, "All four")), n0(f["signed_up"]), n0(f["registered_by_day0"]), n0(f["day0"]),
                        n0(f["day14"]), n0(f["first_due"]), n0(f["end"]), pc(f["end"] / f["registered_by_day0"], 1)],
                       key=p == "all"))
per = ALLC["periods"]
period_keys = ["before_day0", "0-29", "30-59", "60-89", "90-119", "120-149", "150-179", "180-209", "210-239", "240-269"]
period_name = {"before_day0": "Before the start"}
per_rows = [tr([e(period_name.get(k, "Days " + k.replace("-", " to "))), n0(per[k]),
                pc(per[k] / DS["cancellations_registered_by_day0"], 1)], key=k in ("before_day0", "0-29"))
            for k in period_keys]
assert per["before_day0"] == 2643 and per["0-29"] == 2376 and max(per[k] for k in period_keys[2:]) < per["0-29"] / 2
rec_rows = []
for p in order + ["all"]:
    r = DS["cohorts"][p]["reconciliation"]
    b = DS["cohorts"][p]["bridge"]
    rec_rows.append(tr([e(COHORT.get(p, "All four")), n0(r["cancel_day_and_withdrawn"]), n0(r["cancel_day_not_withdrawn"]),
                        n0(r["no_cancel_day_but_withdrawn"]), n0(b["stayed"]),
                        n0(b["stayed"] - b["stayed_vs_pass_fail_distinction"]), pc(r["disagree_share"], 2)], key=p == "all"))
assert ALLC["reconciliation"]["disagree"] == 102 and DS["cohorts"]["2014J"]["reconciliation"]["disagree"] == 87
assert all(DS["cohorts"][p]["bridge"]["sum_check"] == DS["cohorts"][p]["bridge"]["signed_up"] for p in order + ["all"])
mv_rows = [tr([e(m), pc(DS["movement"]["by_course"][m]["rate_from"], 1), pc(DS["movement"]["by_course"][m]["rate_to"], 1),
               pc(DS["movement"]["by_course"][m]["weight_from"], 1)]) for m in MV["shared_courses"]]
mv_rows.append(tr(["CCC (not run in Oct 2013)", "none", pc(MV["new_courses"]["CCC"]["rate"], 1), "0.0%"]))
MVC = DS["movement"]["by_course"]
MV_MOVE = {m: MVC[m]["rate_to"] - MVC[m]["rate_from"] for m in MV["shared_courses"]}
MV_UP, MV_DOWN = max(MV_MOVE, key=MV_MOVE.get), min(MV_MOVE, key=MV_MOVE.get)
assert (MV_UP, MV_DOWN) == ("GGG", "DDD") and MV_MOVE[MV_UP] > 0 > MV_MOVE[MV_DOWN]
assert (pc(MVC["GGG"]["rate_from"], 1), pc(MVC["GGG"]["rate_to"], 1), pc(MVC["DDD"]["rate_from"], 1),
        pc(MVC["DDD"]["rate_to"], 1)) == ("4.2%", "12.5%", "25.3%", "20.9%")
assert (pc(MV["rate_from"], 1), pc(MV["rate_to"], 1), pc(MV["rate_to_shared_courses_only"], 1)) == ("16.7%", "19.7%", "16.6%")
course_rows = [tr([e(m), n0(v["n"]), pc(v["cancel_rate_all"], 1), pc(v["flag_share"], 1), x2(v["lift"]), pc(v["capture"], 1)])
               for m, v in HO["by_course"].items()]
grid_rows = []
for gf, ge in zip(OFF["flagged"]["net_grid"], OFF["everyone"]["net_grid"]):
    grid_rows.append(tr([pc(gf["save_share"]), f'US${gf["cost"]}', f'US${gf["value"]:,}', usd(gf["net"]), usd(ge["net"])],
                        key=(gf["save_share"], gf["cost"], gf["value"]) == (SS["base"], C["base"], V["base"])))
assert sum(1 for gf in OFF["flagged"]["net_grid"] if (gf["save_share"], gf["cost"], gf["value"]) == (SS["base"], C["base"], V["base"])) == 1


def run_name(run):
    m, p = run.split()
    return f"{m} {COHORT[p]}"


def maybe_pc(v):
    return "none" if v is None else pc(v, 1)


after_run_rows = []
for split in ("training", "holdout"):
    for run, r in CA[split].items():
        after_run_rows.append(tr([e(run_name(run)), "Tutor" if r["first_test_tutor_marked"] else "Computer", n0(r["n"]),
                                  pc(r["flag_share"], 1), maybe_pc(r["cancel_rate_flagged"]),
                                  maybe_pc(r["cancel_rate_rest"]), x2(r["lift"])],
                                 key=not r["first_test_tutor_marked"]))
assert len(after_run_rows) == 22


def same_day_row(name, st, score):
    return tr([e(name), pc(st["flag_share"], 1), pc(st["cancel_rate_flagged"], 1), pc(st["cancel_rate_rest"], 1),
               pc(st["cancel_rate_all"], 1), x2(st["lift"]), pc(st["capture"], 1), x2(score)])


same_day_rows = [same_day_row("Missed first assignment, earlier cohorts", tutor_t, SDT["assignment_flag_auc"]),
                 same_day_row("Low use to the due day, earlier cohorts", SDT["use_rule"], SDT["use_rule"]["auc_use_share"]),
                 same_day_row("Missed first assignment, Oct 2014", tutor_h, SDH["assignment_flag_auc"]),
                 same_day_row("Low use to the due day, Oct 2014", SDH["use_rule"], SDH["use_rule"]["auc_use_share"])]
assert abs(SDT["assignment_flag_lift"] - tutor_t["lift"]) < 1e-12 and abs(SDH["assignment_flag_lift"] - tutor_h["lift"]) < 1e-12
rec4_rows = [tr([e(name), n0(round(m["flagged"]["offers"])), n0(round(m["flagged"]["kept_at_base"])),
                 usd(m["flagged"]["net_base"]), n0(round(m["everyone"]["kept_at_base"])), usd(m["everyone"]["net_base"]),
                 usd(m["break_even_value_at_base"])])
             for name, m in (("Earlier cohorts", M4T), ("Oct 2014", M4H))]
LO, HI = TE["sized_drop_points"] - HW, TE["sized_drop_points"] + HW
assert (f'{TE["sized_drop_points"]:.1f}', f"{LO:.1f}", f"{HI:.1f}") == ("3.0", "0.9", "5.1")


CURVE_STYLE = {"2013B": "fixed", "2013J": "learned", "2014B": "tis", "2014J": "tisc"}   # line class and key swatch


def curves_key():
    """A key matching each line's colour and dash, since two cohorts share a colour and end at the same point."""
    return ('<p class="key">' + "".join(
        f'<span><span class="sw sw-{CURVE_STYLE[p]}"></span>{e(COHORT[p])}</span>' for p in order) + '</p>')


def curves_svg():
    W, H, L, B, T, Rm = 640, 316, 48, 52, 14, 128
    days = list(range(-60, 271, 10))
    ymin, ymax = 0.55, 1.0

    def x(d):
        return L + (d + 60) / 330 * (W - L - Rm)

    def y(v):
        return T + (ymax - v) / (ymax - ymin) * (H - T - B)
    parts = [f'<svg class="lines" viewBox="0 0 {W} {H}" role="img" aria-labelledby="curves-t"><title id="curves-t">'
             'Share of enrolments not yet cancelled, by day, for each cohort</title>']
    for v in (0.6, 0.7, 0.8, 0.9, 1.0):
        parts.append(f'<line class="grid" x1="{L}" x2="{W - Rm}" y1="{y(v):.1f}" y2="{y(v):.1f}"/>'
                     f'<text class="tick" x="{L - 6}" y="{y(v) + 4:.1f}" text-anchor="end">{round(v * 100)}%</text>')
    for d in (-60, 0, 60, 120, 180, 240):
        parts.append(f'<text class="tick" x="{x(d):.1f}" y="{H - B + 18}" text-anchor="middle">{d}</text>')
    parts.append(f'<line class="zero" x1="{x(0):.1f}" x2="{x(0):.1f}" y1="{T}" y2="{H - B}"/>')
    parts.append(f'<text class="lab" x="{(L + W - Rm) / 2:.0f}" y="{H - 4}" text-anchor="middle">Day of the course '
                 '(0 is the start)</text>')
    styles = {p: "s-" + s for p, s in CURVE_STYLE.items()}
    ends = {}
    for p in order:
        cv = DS["curves"][p]
        pts = " ".join(f"{x(d):.1f},{y(cv[str(d)]):.1f}" for d in days)
        parts.append(f'<polyline class="ser {styles[p]}" points="{pts}"/>')
        ends[p] = cv[str(days[-1])]
    # end labels in line order from the top, pushed apart so no two overlap
    placed = []
    for p in sorted(order, key=lambda q: -ends[q]):
        ly = y(ends[p]) + 4
        if placed and ly < placed[-1] + 20:
            ly = placed[-1] + 20
        placed.append(ly)
        parts.append(f'<text class="lab" x="{W - Rm + 6}" y="{ly:.1f}">{e(COHORT[p])} {pc(ends[p])}</text>')
    parts.append("</svg>")
    return "".join(parts)


RES_H1 = (f"Of {n0(ALLC['funnel']['registered_by_day0'])} enrolments registered by the start, "
          f"{pc(DS['cancellations_registered_by_day0'] / ALLC['funnel']['registered_by_day0'])} cancelled, half of them "
          "before day 30.")
assert RES_H1 == "Of 32,314 enrolments registered by the start, 31% cancelled, half of them before day 30."
assert 0.5 <= (per["before_day0"] + per["0-29"]) / DS["cancellations_registered_by_day0"] < 0.51
res_body = (hero(RES_H1,
                 STUDY_TITLE + ": all results")
            + '<section class="kit-wrap hero-more" aria-label="What this page holds"><p class="hero-dek">Most cancellations come early. More cancel before the start than in any later 30 days, and the first 30 days come next.</p></section>'
            + "{SECTION_BAR}"
            + block("signals", "Which signal ranks who will cancel", (
                '<p>Each signal was scored by how well it ranks later cancellers above stayers, among students still '
                'enrolled on day 14, on the three earlier cohorts. A score of 0.5 is a coin flip, and 1.0 is perfect. '
                'Each 95% interval comes from 1,000 resamples: of single enrolments, and of whole course runs, which '
                'keeps the students of one run together.</p>'
                + table("Ranking score of each signal", ["Signal", "Known", "Score", "Interval, enrolments",
                                                         "Interval, course runs"], sig_rows)
                + f'<p>No signal scored above {x2(max(s["auc"] for s in TRAIN["signals"].values()))}, and no interval '
                f'by course run reaches past {x2(CR_TOP)}. The best use signal scored {x2(-CR["usage_minus_signup_auc"])} '
                f'below the best sign-up one, with an interval by course run from {x2(CR_DIFF[0])} to {x2(CR_DIFF[1])}. '
                f'Leaving out one course at a time, the gap ran from {x2(CR_LOO[0])} to {x2(CR_LOO[-1])}. Either way the '
                'two rank about the same. Days registered before the start ranked the wrong way round: students who '
                'signed up early cancelled later slightly more often.</p>'))
            + block("days", "Later cancellations by days of use in the first two weeks", (
                '<p>The rate falls with use, but slowly. Students active on all 14 days still cancelled later at '
                f'{pc(TRAIN["cancel_rate_by_days_active"]["14"]["cancel_rate"])}.</p>'
                + table("Later cancellation rate by days with any use, days 0 to 13",
                        ["Days with use", "Earlier cohorts", "Cancelled later", "Oct 2014", "Cancelled later"], by_days)))
            + block("rules", "The two rules", (
                '<p>Lift is the flagged group\'s later cancellation rate over everyone\'s. Capture is the share of later '
                'cancellations the flag holds. The third row scores the two-week rule on the due-day group, the same '
                'students as the assignment flag. It still reads only days 0 to 13, earlier than the due day in all but '
                'one course run, so it does not compare the two read on the same day. The '
                '<a href="#same-day">same-day check</a> does.</p>'
                + table("The two rules on each group", ["Rule and group", "Flagged", "Flagged cancel", "Rest cancel",
                                                        "Everyone", "Lift", "Capture"], rule_rows)))
            + block("funnel", "The funnel and the cohort curves", (
                '<p>From sign-up to the end of the course, for students registered by the start.</p>'
                + table("Students still enrolled at each point, by cohort",
                        ["Cohort", "Signed up", "By the start", "Day 0", "Day 14", "First due day", "End", "Kept"],
                        fun_rows)
                + f'<figure class="chart" id="curves"><figcaption>Every cohort loses most before day 60, then declines '
                'slowly.</figcaption><p class="chart-unit">Share of enrolments not yet cancelled, by day</p>'
                f'{curves_key()}<div class="chart-plot">{curves_svg()}</div></figure>'
                '<p>Cancellations by 30-day period, all four cohorts. The block before the start is the largest. The '
                'first 30 days come next, more than twice any later period.</p>'
                + table("Cancellations by period", ["Period", "Cancellations", "Share"], per_rows)))
            + block("recon", "Two tables that should agree", (
                '<p>The data records a cancellation twice: as a day in the registration table, and as the result '
                '"Withdrawn" in the results table. Its documentation says they are the same set. They are not quite.</p>'
                + table("Cancellations in the two tables", ["Cohort", "Both", "Day, not withdrawn", "Withdrawn, no day",
                                                            "Stayed", "Pass, fail or distinction", "Disagree"], rec_rows)
                + f'<p>{ALLC["reconciliation"]["disagree"]} enrolments disagree, {DS["cohorts"]["2014J"]["reconciliation"]["disagree"]} '
                'of them in Oct 2014, all withdrawn with no day. The study counts the dated table.</p>'))
            + block("movement", "Why Oct 2014 cancelled more than Oct 2013", (
                f'<p>Among students still enrolled on day 14, later cancellations rose from {pc(MV["rate_from"], 1)} '
                f'in Oct 2013 to {pc(MV["rate_to"], 1)} in Oct 2014. In the six courses both cohorts ran, the rate was '
                f'{pc(MV["rate_to_shared_courses_only"], 1)}. Inside them, rises and falls cancelled out: '
                f'{MV_UP} went from {pc(MVC[MV_UP]["rate_from"], 1)} to {pc(MVC[MV_UP]["rate_to"], 1)}, and {MV_DOWN} '
                f'from {pc(MVC[MV_DOWN]["rate_from"], 1)} to {pc(MVC[MV_DOWN]["rate_to"], 1)}. The blend\'s whole rise '
                f'came from a course that first ran in Feb 2014, where {pc(MV["new_courses"]["CCC"]["rate"])} cancelled '
                'later.</p>'
                '<p>The call: read retention course by course. The blended rise points at all seven courses. Read by '
                f'course, it points at the new one and at {MV_UP}, whose rise the flat six-course rate hides.</p>'
                + table("Later cancellation rate by course, Oct 2013 and Oct 2014",
                        ["Course", "Oct 2013", "Oct 2014", "Weight in Oct 2013"], mv_rows)))
            + block("holdout-courses", "The two-week rule by course, Oct 2014", (
                table("Two-week rule by course on Oct 2014", ["Course", "Students", "Cancelled later", "Flagged", "Lift",
                                                              "Capture"], course_rows)))
            + block("money", "The save call over the assumed ranges", (
                '<p>Net gain per 1,000 students enrolled on the first due day, earlier cohorts, all 22 course runs, for a '
                'call to the students who missed the first assignment and for a call to everyone. The bold row is the '
                'base case. The entry page uses the same base case on the 19 tutor-marked runs, in '
                '<a href="#recommended">the call as recommended</a>.</p>'
                + table("Net gain of the save call over the assumed ranges",
                        ["Save share", "Cost a call", "Value kept", "Flagged", "Everyone"], grid_rows)))
            + block("after", "The flag by course run", (
                f'<p>In {N_COMPUTER} course runs the first test is marked by computer, and nearly every '
                'student\'s work is recorded after its listed due day. There the flag marks the run, not the student. '
                'The bold rows are those runs.</p>'
                + table("The assignment flag by course run", ["Course run", "First test", "Students", "Flagged",
                                                              "Flagged cancel", "Rest cancel", "Lift"], after_run_rows)
                + f'<p>On the {N_TUTOR} runs whose first test is marked by a tutor, the flag\'s lift was '
                f'{x2(tutor_t["lift"])} on the earlier cohorts and {x2(tutor_h["lift"])} on Oct 2014, with capture '
                f'{pc(tutor_t["capture"], 1)} and {pc(tutor_h["capture"], 1)}. Oct 2014 kept {pc(tutor_all["lift_ratio"])} of the earlier '
                f'lift and {pc(tutor_all["capture_ratio"])} of the capture, so the flag passes the holdout line there too. The '
                'prediction, a lift of at least 1.5 that passes on Oct 2014, held. Within courses on Oct 2014, the lift '
                f'was at least 1.3 in {ch2["predictions"]["Q3"]["at_least_1_3"]} of the '
                f'{ch2["predictions"]["Q3"]["courses"]} tutor-marked courses, against a prediction of at least 5.</p>'))
            + block("same-day", "The flag against use read on the same day", (
                '<p>The two-week rule reads days 0 to 13, but the flag is read on the first due day, between day 12 and '
                'day 61. This check reads use on the same day as the flag: the share of days from day 0 to the due day '
                f'with any use, on the {N_TUTOR} tutor-marked runs. It flags students active on {pc(SD["cut"])} of those '
                'days or fewer, a cut chosen on the earlier cohorts to flag about as many students as the assignment '
                'flag.</p>'
                + table("The assignment flag and use read on the same day", ["Rule and group", "Flagged", "Flagged cancel",
                                                                             "Rest cancel", "Everyone", "Lift", "Capture",
                                                                             "Ranking score"], same_day_rows)
                + f'<p>The flag\'s lift beat same-day use by {x2(SDT["lift_gap"])} on the earlier cohorts and '
                f'{x2(SDH["lift_gap"])} on Oct 2014, against a declared bar of 0.20. The wait explains little of the '
                'flag\'s edge.</p>'))
            + block("test", "Reach, the test and the money on all 22 runs", (
                '<ul class="notes">'
                '<li><strong>Out of reach.</strong> Of students registered by the start who cancelled, '
                f'{pc(REACH["training"]["share_out_of_reach"], 1)} in the earlier cohorts and '
                f'{pc(REACH["holdout"]["share_out_of_reach"], 1)} in Oct 2014 did so on or before the first due day, '
                f'{pc(REACH["all_four"]["share_out_of_reach"], 1)} over all four.</li>'
                f'<li><strong>Precision.</strong> With {TE["per_half"]:,} a half, the 95% interval on the drop in later '
                f'cancellations is about {HW:.1f} points either way. A true {TE["sized_drop_points"]:.1f}-point drop would '
                f'read as about {LO:.1f} to {HI:.1f}, across the break-even of {BE_PTS:.1f} points (US${C["base"]} over '
                f'US${V["base"]:,}, the same as keeping {pc(BREAK_EVEN)} of the flagged would-be cancellers). Only an '
                f'observed drop above {CLEAR:.1f} points clears it. Telling a {TE["sized_drop_points"]:.1f}-point drop from break-even '
                f'would need about {TE["per_half_to_clear_break_even_at_sized_drop"]:,} a half.</li>'
                f'<li><strong>Readout.</strong> Enrolling {TE["total"]:,} flagged students and following the last of them '
                f'to the end of the course takes {READOUT["Feb start"]:.1f} months from a Feb start or '
                f'{READOUT["Oct start"]:.1f} from an Oct start, with one readout at the end.</li>'
                '<li><strong>Equal effect.</strong> Calling only the flagged costs less per kept student than calling '
                f'everyone while the call keeps at least {pc(EQ)} as large a share of would-be cancellers among the '
                f'flagged as among the rest ({pc(RA["cancel_rate_rest"], 1)} over {pc(RA["cancel_rate_flagged"], 1)}).</li>'
                f'<li><strong>Value.</strong> At US${C["base"]} a call that keeps {pc(SS["base"])}, calling everyone nets '
                f'more once a kept enrolment is worth over US${VSTAR:,.0f} on the earlier cohorts, or US${VSTAR_H:,.0f} '
                f'on Oct 2014. The university listed a 60-credit module at \u00a3{FEE_60:,} from August 2014. In the '
                f'money table, all {len(GRID_EVERYONE)} combinations where calling everyone nets more have a '
                f'US${C["low"]} call, a {pc(SS["high"])} save share or a US${V["high"]:,} enrolment.</li></ul>'))
            + block("recommended", "The call as recommended: the 19 tutor-marked runs", (
                '<p>The entry page prices the call it recommends: to students who miss the first marked assignment, in '
                f'the {N_TUTOR} course runs whose first test a tutor marks. The base case is the same: US${C["base"]} a '
                f'call, US${V["base"]:,} a kept enrolment, and {pc(SS["base"])} of would-be cancellers kept.</p>'
                + table("The save call on the tutor-marked runs, per 1,000 enrolled on the first due day",
                        ["Cohorts", "Calls to the flagged", "Kept", "Net", "Everyone kept", "Everyone net",
                         "Value where everyone wins"], rec4_rows)
                + '<ul class="notes">'
                f'<li><strong>Over the ranges.</strong> Calling the flagged nets more than calling everyone in '
                f'{M4T["grid_points_flagged_beats_everyone"]} of {GRID_N} combinations on the earlier cohorts and '
                f'{M4H["grid_points_flagged_beats_everyone"]} on Oct 2014, as on all 22 runs.</li>'
                f'<li><strong>Precision.</strong> The control rate is {pc(T4["cancel_rate_control"], 1)}, the flagged\'s '
                f'later cancellation rate on Oct 2014, so keeping {pc(SS["base"])} is a {T4["sized_drop_points"]:.1f}-point '
                f'drop, which needs {T4["per_half"]:,} a half. The 95% interval is then about {HW4:.1f} points either '
                f'way. Only an observed drop above {CLEAR4:.1f} points clears the {BE_PTS:.1f}-point break-even. At a '
                f'true {T4["sized_drop_points"]:.1f}-point drop the interval clears it '
                f'{pc(T4["chance_interval_clears_break_even_at_sized_drop"])} of the time, and clearing it 80% of the '
                f'time would take about {T4["per_half_for_80pct_chance_to_clear_break_even"]:,} a half.</li>'
                f'<li><strong>If it straddles the break-even.</strong> Go by the observed drop: keep the call only if it '
                f'is above {BE_PTS:.1f} points. At the assumed costs that is the choice with the higher expected '
                'net.</li>'
                f'<li><strong>Readout.</strong> These runs flagged {n0(T4["flagged_feb_2014"])} students in Feb 2014 and '
                f'{n0(T4["flagged_oct_2014"])} in Oct 2014, {n0(T4["flagged_a_year"])} in the year. Enrolling '
                f'{n0(T4["total"])} takes {T4["readout"]["Feb start"]["cohorts_needed"]} cohorts: '
                f'{T4["readout"]["Feb start"]["months_to_readout"]:.1f} months from a Feb start or '
                f'{T4["readout"]["Oct start"]["months_to_readout"]:.1f} from an Oct start to one readout.</li>'
                '<li><strong>Equal effect.</strong> Calling only the flagged costs less per kept student while the call '
                f'keeps at least {pc(EQ4)} as large a share among them as among the rest '
                f'({pc(M4H["equal_effect_min_save_share_ratio"])} on Oct 2014).</li>'
                f'<li><strong>Reversal line.</strong> A new cohort fails the holdout bar set before the holdout if the '
                f'flag\'s lift on these runs falls below 80% of {x2(tutor_t["lift"])}, which is {x2(LINE4)}.</li>'
                f'<li><strong>The fee in dollars.</strong> At the 2014 average of US${FX["usd_per_gbp_2014"]} to the '
                'pound, from the Federal Reserve\'s table of that year\'s average exchange rates, the fee page\'s '
                f'£{ch3["fee_page"]["gbp_30_credits"]:,} for 30 credits is about US${FX["usd_30_credits"]:,.0f} and '
                f'£{FEE_60:,} for 60 credits about US${FX["usd_60_credits"]:,.0f}. Calling everyone nets more above '
                f'US${VSTAR4:,.0f} on the earlier cohorts and US${VSTAR4_H:,.0f} on Oct 2014.</li></ul>'))
            + block("wrong", "What went wrong or was missed", (
                '<ul class="notes">'
                '<li>The expected finding failed. The prediction, declared before any result, was that two weeks of use '
                'would rank cancellers far better than sign-up facts. It ranked them about the same as the student\'s '
                f'study load ({x2(BU["auc"])} against {x2(BS["auc"])}).</li>'
                f'<li>A two-week signal cannot reach {pc(SHARE_BEFORE14)} of the cancellations, and the first due day '
                f'cannot reach {pc(REACH["all_four"]["share_out_of_reach"])}, because they happen first.</li>'
                f'<li>In {N_COMPUTER} course runs the assignment flag marked the whole run. That was found only after '
                'the results.</li>'
                f'<li>Priced on all 22 runs, the call looked better than the call as recommended: about '
                f'US${round(FL["net_base"], -1):,.0f} per 1,000 against US${round(FL4["net_base"], -2):,.0f}, with a test '
                f'of {round(min(READOUT.values()))} to {round(max(READOUT.values()))} months against {READ4[0]} to '
                f'{READ4[1]}.</li>'
                '<li>The data has no record of any contact, so nothing here measures what a save call does.</li>'
                '<li>Demographic fields were left out of every rule by design, so their power was not measured.</li>'
                '</ul>'))
            + block("limits", "Limits", (
                '<p><strong>Several parts came after every result.</strong> The split of the Oct 2014 rise was added '
                'after the results. The intervals by course run and every section from the flag by course run on come '
                'from checks declared in three later change files after every result had been read, each saved before '
                'its code ran. Each was built for a doubt the results raised, so none counts toward a hit rate.</p>'
                '<p><strong>Every money input is assumed,</strong> and so is the repeat of 2014\'s flagged counts in '
                'every readout month above. What a student who cancels still owes is not known.</p>'
                '<p><strong>Both kinds of interval are rough.</strong> The intervals by enrolment treat enrolments as '
                'independent, though they sit in 15 course runs and a student can enrol more than once, so they are '
                'too narrow. The intervals by course run rest on only 15 runs, and still count a student enrolled in two '
                'runs twice.</p>'))
            + f'<section class="block kit-wrap">{links_row()}</section>' + NEXT_STUDY)
page("results.html", "All results: " + STUDY_TITLE,
     "Every signal, rule, funnel, reconciliation and money table of the early-signal study on 32,593 real course "
     "enrolments.", res_body,
     [("signals", "Signals"), ("rules", "Rules"), ("funnel", "Funnel"), ("recon", "Two tables"),
      ("movement", "Oct 2014"), ("money", "Money"), ("after", "By course run"), ("recommended", "As recommended"),
      ("wrong", "What went wrong"), ("limits", "Limits")])


# =====================================================================================================================
# Method and checks
# =====================================================================================================================
def held(pid):
    t, h, at, ah = TRAIN, HO, AT, AH
    vals = {"P1": (t["usage_minus_signup_auc"] >= 0.10, f'difference {t["usage_minus_signup_auc"]:+.3f}'.replace("-", "minus ")),
            "P2": (t["rule"]["lift"] >= 2.0, f'lift {x2(t["rule"]["lift"])}'),
            "P3": (t["rule"]["capture"] >= 0.40, f'capture {pc(t["rule"]["capture"], 1)}'),
            "P4": (DS["share_before_day14"] >= 0.30, f'{pc(DS["share_before_day14"], 1)} before day 14'),
            "P5": (h["holds"], f'lift {x2(h["lift_ratio"])} and capture {x2(h["capture_ratio"])} of the earlier values'),
            "P6": (DS["cohorts"]["all"]["reconciliation"]["disagree_share"] < 0.01,
                   f'{pc(DS["cohorts"]["all"]["reconciliation"]["disagree_share"], 2)} disagree'),
            "A1": (at["flag"]["lift"] >= 2.0, f'lift {x2(at["flag"]["lift"])}'),
            "A2": (at["flag"]["capture"] >= 0.40, f'capture {pc(at["flag"]["capture"], 1)}, but '
                   f'{pc(tutor_t["capture"], 1)} on the {N_TUTOR} tutor-marked runs'),
            "A3": (ah["holds"], f'lift {x2(ah["lift_ratio"])} and capture {x2(ah["capture_ratio"])} of the earlier values'),
            "A4": (at["day14_rule_same_population"]["lift"] < 1.5, f'lift {x2(at["day14_rule_same_population"]["lift"])}')}
    return vals[pid]


CHANGE_PREDS = [("A1", "The missed-assignment flag has a lift of at least 2.0 on the earlier cohorts."),
                ("A2", "It holds at least 40% of later cancellations on the earlier cohorts."),
                ("A3", "It holds on Oct 2014: lift and capture each at least 80% of the earlier values."),
                ("A4", "On the same students, the two-week rule's lift stays below 1.5.")]
PLAIN_PRED = {"P1": "Two weeks of use ranks cancellers at least 0.10 better than the best sign-up fact.",
              "P2": "The two-week rule's lift is at least 2.0 on the earlier cohorts.",
              "P3": "It holds at least 40% of later cancellations on the earlier cohorts.",
              "P4": "At least 30% of all cancellations happen before day 14.",
              "P5": "The two-week rule holds on Oct 2014: lift and capture each at least 80% of the earlier values.",
              "P6": "The two tables disagree on fewer than 1% of enrolments."}
assert [p["id"] for p in PRED["predictions"]] == list(PLAIN_PRED)
Q = ch2["predictions"]
LATER_PREDS = [
    (f"On the {N_TUTOR} course runs whose first test is marked by a tutor, the flag's lift is at least 1.5 on the "
     "earlier cohorts, and it holds on Oct 2014.", Q["Q1"]["held"],
     f'lift {x2(Q["Q1"]["training_lift"])}; on Oct 2014, lift {x2(tutor_all["lift_ratio"])} and capture '
     f'{x2(tutor_all["capture_ratio"])} of the earlier values'),
    ("On the same students, the flag's lift beats use read on the due day by at least 0.20, on both.",
     Q["Q2"]["held"], f'by {x2(Q["Q2"]["gap_training"])} and {x2(Q["Q2"]["gap_holdout"])}'),
    (f'Within courses on Oct 2014, the flag\'s lift is at least 1.3 in at least 5 of the {Q["Q3"]["courses"]} '
     "tutor-marked courses.", Q["Q3"]["held"], f'{Q["Q3"]["at_least_1_3"]} of {Q["Q3"]["courses"]}')]
WHEN = {"P": "With the design", "A": "After the training results"}
pred_rows = ([tr([e(text), WHEN[pid[0]], "held" if held(pid)[0] else "missed", e(held(pid)[1])])
              for pid, text in list(PLAIN_PRED.items()) + CHANGE_PREDS]
             + [tr([e(text), "After all results", "held" if ok else "missed", e(m)]) for text, ok, m in LATER_PREDS])
assert [held(p)[0] for p in PLAIN_PRED] == [False, False, False, True, True, True]
assert [held(p)[0] for p, _ in CHANGE_PREDS] == [False, True, True, True]

glossary = ('<dl class="glossary">'
            '<dt>Cohort</dt><dd>All enrolments in courses that start in the same month.</dd>'
            '<dt>Holdout</dt><dd>A cohort kept out of every step until the rules were fixed, then used once to test '
            'them.</dd>'
            '<dt>Later cancellation</dt><dd>A cancellation after the day a rule is read: day 14, or the first due '
            'day.</dd>'
            '<dt>Lift</dt><dd>The flagged group\'s later cancellation rate divided by everyone\'s. 1.00 is no better '
            'than random.</dd>'
            '<dt>Capture</dt><dd>The share of later cancellations that fall in the flagged group.</dd>'
            '<dt>Ranking score</dt><dd>The chance that a random canceller ranks riskier than a random stayer. 0.5 is a '
            'coin flip. Often called AUC.</dd>'
            '<dt>Save offer</dt><dd>A contact meant to keep a customer who would otherwise cancel: here, a call with a '
            'pause option.</dd>'
            '<dt>Break-even save share</dt><dd>The share of would-be cancellers a call must keep to pay for itself.</dd>'
            '</dl>')

downloads = ('<ul class="notes">'
             '<li><a href="data/enrolments.csv.gz">data/enrolments.csv.gz</a>: one row per enrolment, with the '
             'registration and cancellation days, the result and the first-two-weeks use. Demographic fields are not '
             'in it.</li>'
             '<li><a href="data/first-assessment.csv.gz">data/first-assessment.csv.gz</a>: each enrolment\'s first '
             'assignment, its due day and the day it was handed in.</li>'
             '<li><a href="data/due-usage.csv.gz">data/due-usage.csv.gz</a>: each enrolment\'s first due day and its '
             'days with any use from day 0 to that day.</li>'
             '<li><a href="data/sources.json">data/sources.json</a>: the source, licence, URL and sha256.</li>'
             '<li>Results: <a href="results/train-r1.json">train-r1.json</a>, <a href="results/rule-r1.json">'
             'rule-r1.json</a>, <a href="results/holdout-r1.json">holdout-r1.json</a>, '
             '<a href="results/assess-train-r1.json">assess-train-r1.json</a>, <a href="results/assess-rule-r1.json">'
             'assess-rule-r1.json</a>, <a href="results/assess-holdout-r1.json">assess-holdout-r1.json</a>, '
             '<a href="results/describe-r1.json">describe-r1.json</a>, <a href="results/after-r1.json">'
             'after-r1.json</a>, <a href="results/change2-r2.json">change2-r2.json</a>, '
             '<a href="results/change3-r3.json">change3-r3.json</a>, <a href="results/change4-r4.json">'
             'change4-r4.json</a>.</li>'
             '<li>Design: <a href="CHANGES-r1.md">CHANGES-r1.md</a>, <a href="CHANGES-r2.md">CHANGES-r2.md</a>, '
             '<a href="CHANGES-r4.md">CHANGES-r4.md</a>, '
             '<a href="protocol-r1.json">protocol-r1.json</a>, <a href="predictions-r1.json">predictions-r1.json</a>, '
             '<a href="assumptions.json">assumptions.json</a>.</li>'
             '<li>Code: <a href="tools/get_data.py">tools/get_data.py</a>, <a href="tools/get_first_assessment.py">'
             'tools/get_first_assessment.py</a>, <a href="tools/run_study.py">tools/run_study.py</a>, '
             '<a href="tools/run_assessment_signal.py">tools/run_assessment_signal.py</a>, '
             '<a href="tools/after_results.py">tools/after_results.py</a>, <a href="tools/get_due_usage.py">'
             'tools/get_due_usage.py</a>, <a href="tools/run_change2.py">tools/run_change2.py</a>, '
             '<a href="tools/run_change3.py">tools/run_change3.py</a>, <a href="tools/run_change4.py">'
             'tools/run_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>')

meth_body = (hero("Each rule was fixed on three cohorts and tested once on a fourth that no step had read.",
                  STUDY_TITLE + ": method and checks")
             + '<section class="kit-wrap hero-more" aria-label="What this page holds"><p class="hero-dek">Each rule was chosen on Feb 2013, Oct 2013 and Feb 2014. Oct 2014 stayed unread until both rules were saved. Three later changes added checks after every result had been read.</p></section>'
             + "{SECTION_BAR}"
             + block("data", "Data", (
                 '<p>The Open University Learning Analytics Dataset is a public release of 32,593 enrolments in 22 runs '
                 'of 7 courses, from Feb 2013 to Oct 2014, under CC BY 4.0. It records when each student registered and '
                 'cancelled, their result, and their daily clicks on the course site. It was anonymised before release. '
                 'Kuzilek, Hlosta and Zdrahal describe it in the journal Scientific Data. Demographic fields were dropped '
                 'on loading.</p>'
                 '<p>How it maps to a subscription: registration is sign-up, day 0 is the start of the course, the days '
                 'before it are the trial, clicks are product use, and unregistering is cancelling. Days are counted '
                 'from each course\'s start.</p>'))
             + block("defs", "Definitions", (
                 '<ul class="notes">'
                 '<li><strong>Cancels:</strong> the enrolment has a cancellation day. Otherwise it stays.</li>'
                 '<li><strong>Two-week group:</strong> registered by day 0 and not cancelled before day 14. Outcome: '
                 'cancels on day 14 or later.</li>'
                 '<li><strong>Due-day group:</strong> registered by day 0 and not cancelled by the first assignment\'s due '
                 'day, which falls between day 12 and day 61. Outcome: cancels after that day.</li>'
                 f'<li><strong>Two-week rule:</strong> flag a student active on at most {R14["k"]} of days 0 to 13. The '
                 'threshold was the one whose flagged share on the earlier cohorts came closest to 20%.</li>'
                 '<li><strong>Assignment flag:</strong> the first marked assignment was not handed in by its due day. A '
                 'mark carried over from an earlier attempt counts as handed in.</li>'
                 '<li><strong>Use to the due day:</strong> the share of days from day 0 to the first due day, both '
                 'included, with any use of the course site.</li>'
                 '<li><strong>Tutor-marked runs:</strong> the 19 course runs whose first marked assignment is marked by '
                 'a tutor. The call is recommended only there.</li></ul>'))
             + block("order", "In what order", (
                 '<ol class="notes">'
                 '<li>The design, the signals, the retention definition, the predictions and the money assumptions were '
                 'written down and saved before any outcome was computed. Only the tables\' shape had been read.</li>'
                 '<li>The training step dropped Oct 2014 before computing anything. It fixed the two-week rule.</li>'
                 '<li>The rule missed its first three predictions. The assignment signal was then declared, with its own '
                 'predictions, after those results and before Oct 2014 was read. It was fixed on the earlier cohorts.'
                 '</li>'
                 '<li>Only then were both rules applied to Oct 2014, unchanged.</li>'
                 '<li>The cohort curves, the funnel, the two-table check and the course split came last. The course '
                 'split of the Oct 2014 rise, the check counting undated withdrawals and the test size were added '
                 'after the results.</li>'
                 '<li>After every result had been read, more checks were declared and saved before their code ran: the '
                 'flag by course run, the tutor-marked runs alone, use read on the due day, the share out of reach, the '
                 'test\'s precision and readout, and the equal-effect condition, with three predictions.</li>'
                 '<li>The next change added the value of a kept enrolment at which calling everyone nets more. It was '
                 'declared after the university\'s fee page had been read and after a first estimate of that value from '
                 'the published money figures, and its code computes the value exactly. Its declaration is not '
                 'published, so this step gives what it says.</li>'
                 f'<li>A last change priced the call, sized its test and set its reversal line on the {N_TUTOR} '
                 'tutor-marked runs alone, since the call is recommended only there. It also resampled whole course runs '
                 'for the ranking scores\' intervals and turned the fee into dollars at the 2014 average rate. No change '
                 'rewrites a frozen result.</li></ol>'))
             + block("preds", "The predictions and how they scored", (
                 '<p>The expected finding was that two weeks of use would rank cancellers far better than sign-up facts '
                 'and that a rule on it would hold on the latest cohort. The opposite was that sign-up facts would do '
                 'as well, or the rule would fall apart on the latest cohort.</p>'
                 + table("Predictions and outcomes", ["Prediction", "Declared", "Outcome", "Measured"], pred_rows)
                 + '<p>The first six were declared with the design, and the next four after the training results, before '
                 'the holdout. The last three test checks built for doubts the results raised, so they stay out of any '
                 'hit rate.</p>'))
             + block("checks", "Checks", (
                 '<ul class="notes">'
                 '<li>The download is checked against its sha256 before any table is built.</li>'
                 '<li>The ranking score is checked against a direct count of every canceller and stayer pair.</li>'
                 '<li>The training step stops if any Oct 2014 row is loaded. The two holdout steps and the later checks '
                 'record the sha256 of the frozen files they read.</li>'
                 '<li>The same-day cut was chosen on the earlier cohorts before Oct 2014 was scored.</li>'
                 '<li>The resample by course run first reproduces every frozen ranking score exactly.</li></ul>'))
             + block("tools", "Tools, and what they stand in for", (
                 '<p>Python with NumPy reads the 10.6 million activity rows as a stream, keeping only what a rule could '
                 'know by day 14. In a company, that step is a warehouse model over the product event table, and the '
                 'daily flag is a scheduled job that writes to the customer team\'s queue. One pass over the whole '
                 'dataset gives each result. The intervals come from resampling enrolments, and again whole course '
                 'runs.</p>'))
             + block("glossary", "Glossary", glossary)
             + block("downloads", "Downloads and how to rebuild", (
                 '<p>The README lists the commands. They rebuild the data from the public download, then every result '
                 'and page.</p>' + downloads))
             + block("limits", "Limits", (
                 '<p><strong>The later checks came after every result.</strong> Each was declared before its code ran '
                 'and built for a doubt the results raised, so none counts toward a hit rate.</p>'
                 '<p><strong>Both kinds of interval are rough.</strong> Resampling enrolments treats them as independent, '
                 'so those intervals are too narrow. Resampling whole course runs rests on only 15 runs, and still counts '
                 'a student enrolled in two runs twice.</p>'))
             + f'<section class="block kit-wrap">{links_row()}</section>' + NEXT_STUDY)
page("method.html", "Method and checks: " + STUDY_TITLE,
     "Data, definitions, order of steps, predictions and their outcomes, checks and downloads for the early-signal "
     "study on real course enrolments.", meth_body,
     [("data", "Data"), ("defs", "Definitions"), ("order", "Order"), ("preds", "Predictions"), ("checks", "Checks"),
      ("glossary", "Glossary"), ("downloads", "Downloads"), ("limits", "Limits")])
