#!/usr/bin/env python3
"""What do brain-training meta-analyses agree on? Reproducible calculations.

Altamens Research, published 2026-12-04.
Canonical page: https://www.altamens.com/research/brain-training-meta-analyses/

Standard library only (Python 3.10 or later). No network access, no third-party data files:
every input below is a summary statistic copied from a published, openly licensed table, with
its source. Run:

    python3 calculate.py out

and compare the SHA-256 of the files in `out/` with those listed in methods.md.

What the script does
1. Transfer gradient: Melby-Lervag, Redick & Hulme (2016), Tables 2 and 3. Converts each
   pooled Hedges' g into the probability of superiority, Phi(g / sqrt 2): the chance that a
   randomly chosen trained person gains more than a randomly chosen control person, assuming
   normal distributions with equal variance.
2. Second-order meta-analysis: recomputes the grand mean, the second-order sampling-error
   variance, the observed between-meta-analysis variance and the true variance from the ten
   first-order far-transfer meta-analyses in Gobet & Sala (2023), Tables 1 and 2 (data from
   Sala et al. 2019), and checks them against the published summary values.
3. Sample size: people per group for 80% power (two-sided alpha .05) in a simple two-group
   comparison, normal approximation, for effect sizes taken from steps 1 and 2.
4. Simulation: 20,000 two-group studies with 20 people per group, true effect 0 and 0.12,
   seed 20261204, to show how widely single small studies scatter around the true effect.
"""

import csv
import hashlib
import json
import math
import random
import statistics
import sys
from pathlib import Path

SEED = 20261204
N_SIM = 20_000
N_PER_GROUP = 20
NORMAL = statistics.NormalDist()

# --------------------------------------------------------------------------------------------
# 1. Melby-Lervag, Redick & Hulme (2016), Perspectives on Psychological Science 11(4):512-534,
#    doi:10.1177/1745691616635612, PMC4968033 (CC BY-NC 3.0). Table 2 (immediate posttest) and
#    Table 3 (delayed posttest). Columns: construct, transfer level, control type, g, CI low,
#    CI high, number of studies. Transfer levels follow the paper: near = measures similar or
#    identical to the trained tasks ("criterion measure"), intermediate = other working-memory
#    tests, far = everything else.
# --------------------------------------------------------------------------------------------
MLRH_2016 = [
    # immediate posttest (Table 2)
    ("immediate", "Criterion measure (like the trained task)", "near", "treated", 0.80, 0.62, 0.97, 22),
    ("immediate", "Criterion measure (like the trained task)", "near", "untreated", 1.88, 1.33, 2.42, 16),
    ("immediate", "Verbal working memory", "intermediate", "treated", 0.31, 0.19, 0.42, 60),
    ("immediate", "Verbal working memory", "intermediate", "untreated", 0.42, 0.24, 0.61, 38),
    ("immediate", "Visuospatial working memory", "intermediate", "treated", 0.28, 0.16, 0.40, 40),
    ("immediate", "Visuospatial working memory", "intermediate", "untreated", 0.51, 0.34, 0.69, 25),
    ("immediate", "Nonverbal abilities", "far", "treated", 0.05, -0.02, 0.13, 67),
    ("immediate", "Nonverbal abilities", "far", "untreated", 0.20, 0.11, 0.28, 53),
    ("immediate", "Verbal abilities", "far", "treated", 0.05, -0.07, 0.17, 22),
    ("immediate", "Verbal abilities", "far", "untreated", 0.03, -0.09, 0.14, 16),
    ("immediate", "Word decoding", "far", "treated", 0.08, -0.09, 0.24, 10),
    ("immediate", "Word decoding", "far", "untreated", 0.01, -0.16, 0.17, 7),
    ("immediate", "Reading comprehension", "far", "treated", 0.15, 0.03, 0.27, 19),
    ("immediate", "Reading comprehension", "far", "untreated", 0.12, -0.07, 0.31, 7),
    ("immediate", "Arithmetic", "far", "treated", 0.06, -0.08, 0.19, 15),
    ("immediate", "Arithmetic", "far", "untreated", 0.12, 0.01, 0.23, 14),
    # delayed posttest (Table 3)
    ("delayed", "Criterion measure (like the trained task)", "near", "treated", 0.99, 0.57, 1.41, 2),
    ("delayed", "Criterion measure (like the trained task)", "near", "untreated", 1.16, 0.83, 1.49, 5),
    ("delayed", "Verbal working memory", "intermediate", "treated", 0.28, -0.004, 0.56, 10),
    ("delayed", "Verbal working memory", "intermediate", "untreated", 0.55, 0.27, 0.83, 13),
    ("delayed", "Visuospatial working memory", "intermediate", "treated", 0.40, 0.07, 0.73, 9),
    ("delayed", "Visuospatial working memory", "intermediate", "untreated", 0.39, 0.02, 0.77, 9),
    ("delayed", "Nonverbal abilities", "far", "treated", -0.05, -0.21, 0.11, 12),
    ("delayed", "Nonverbal abilities", "far", "untreated", 0.03, -0.22, 0.28, 7),
    ("delayed", "Verbal abilities", "far", "treated", 0.24, -0.12, 0.60, 3),
    ("delayed", "Verbal abilities", "far", "untreated", 0.61, -0.84, 2.06, 2),
    ("delayed", "Word decoding", "far", "treated", 0.02, -0.29, 0.33, 3),
    ("delayed", "Word decoding", "far", "untreated", -0.07, -0.72, 0.58, 2),
    ("delayed", "Reading comprehension", "far", "treated", -0.09, -0.78, 0.60, 1),
    ("delayed", "Reading comprehension", "far", "untreated", -0.15, -0.48, 0.18, 2),
    ("delayed", "Arithmetic", "far", "treated", 0.22, 0.04, 0.40, 10),
    ("delayed", "Arithmetic", "far", "untreated", 0.08, -0.15, 0.31, 6),
]

# --------------------------------------------------------------------------------------------
# 2. Gobet & Sala (2023), Perspectives on Psychological Science 18(1):125-141,
#    doi:10.1177/17456916221091830, PMC9903001 (CC BY 4.0). Far transfer only; data from
#    Sala, Aksayli, Tatlidil, Tatsumi, Gondo & Gobet (2019), Collabra: Psychology 5(1):18.
#    Columns: first-order meta-analysis, k_i (samples), mean g_i, S2_gi (variance of the
#    observed g's), tau2_i. Table 1: uncorrected, active and passive controls.
#    Table 2: corrected for publication bias, active controls only.
# --------------------------------------------------------------------------------------------
SECOND_ORDER = {
    "naive": {
        "label": "Uncorrected, active and passive controls (Table 1)",
        "published": {"grand_mean": 0.12, "sampling_error_var": 0.00235, "observed_var": 0.00129, "true_var": 0.0},
        "rows": [
            ("Working memory, typically developing children", 25, 0.13, 0.060, 0.006),
            ("Working memory, children with learning disabilities", 18, 0.12, 0.032, 0.002),
            ("Working memory, adults", 44, 0.12, 0.041, 0.003),
            ("Working memory, older adults", 32, 0.13, 0.085, 0.035),
            ("Action video games, adults", 32, 0.08, 0.073, 0.000),
            ("Non-action video games, adults", 16, 0.15, 0.047, 0.012),
            ("Video games, older adults", 10, 0.04, 0.033, 0.000),
            ("Music, typically developing children", 36, 0.19, 0.087, 0.042),
            ("Chess, typically developing children", 9, 0.13, 0.049, 0.031),
            ("Exergames, older adults", 11, 0.15, 0.079, 0.021),
        ],
    },
    "corrected": {
        "label": "Corrected for publication bias, active controls only (Table 2)",
        "published": {"grand_mean": 0.00, "sampling_error_var": 0.00302, "observed_var": 0.00014, "true_var": 0.0},
        "rows": [
            ("Working memory, typically developing children", 15, 0.01, 0.064, 0.000),
            ("Working memory, children with learning disabilities", 12, 0.02, 0.111, 0.000),
            ("Working memory, adults", 27, 0.00, 0.213, 0.000),
            ("Working memory, older adults", 16, 0.01, 0.009, 0.000),
            ("Action video games, adults", 34, -0.01, 0.107, 0.011),
            ("Non-action video games, adults", 6, 0.00, 0.033, 0.000),
            ("Video games, older adults", 4, -0.03, 0.033, 0.000),
            ("Music, typically developing children", 17, -0.02, 0.055, 0.012),
            ("Chess, typically developing children", 3, 0.01, 0.032, 0.000),
            ("Exergames, older adults", 8, -0.02, 0.072, 0.000),
        ],
    },
}


def prob_superiority(g: float) -> float:
    """P(trained > control) for two normal distributions, equal variance, d = g."""
    return NORMAL.cdf(g / math.sqrt(2))


def second_order(rows):
    """Second-order meta-analysis in the style of Schmidt & Oh (2013).

    Each first-order mean g_i has sampling-error variance S2_gi / k_i. Weights are the inverse
    of that variance. True between-meta-analysis variance = max(0, observed - sampling error).
    Adjusted first-order means shrink towards the grand mean by sigma2 / (sigma2 + e_i).
    """
    e = [s2 / k for _, k, _, s2, _ in rows]
    w = [1 / x for x in e]
    g = [gi for _, _, gi, _, _ in rows]
    sw = sum(w)
    grand = sum(wi * gi for wi, gi in zip(w, g)) / sw
    observed = sum(wi * (gi - grand) ** 2 for wi, gi in zip(w, g)) / sw
    sampling = sum(wi * ei for wi, ei in zip(w, e)) / sw
    true_var = max(0.0, observed - sampling)
    adjusted = [grand + (true_var / (true_var + ei)) * (gi - grand) for gi, ei in zip(g, e)]
    return {
        "grand_mean": grand,
        "sampling_error_var": sampling,
        "observed_var": observed,
        "true_var": true_var,
        "share_of_observed_variance_explained_by_sampling_error": min(1.0, sampling / observed) if observed else 1.0,
        "adjusted": adjusted,
    }


def n_per_group(d: float, alpha: float = 0.05, power: float = 0.80) -> int:
    """People per group for a two-sided two-sample comparison, normal approximation."""
    za = NORMAL.inv_cdf(1 - alpha / 2)
    zb = NORMAL.inv_cdf(power)
    return math.ceil(2 * (za + zb) ** 2 / d**2)


def t_two_sided_critical(df: int, alpha: float = 0.05) -> float:
    """Critical t for a two-sided test, by bisection on a Simpson-integrated t density."""

    def pdf(x):
        c = math.gamma((df + 1) / 2) / (math.sqrt(df * math.pi) * math.gamma(df / 2))
        return c * (1 + x * x / df) ** (-(df + 1) / 2)

    def upper_tail(t, steps=4000):
        # P(T > t) = 0.5 - integral_0^t pdf
        h = t / steps
        s = pdf(0) + pdf(t) + sum((4 if i % 2 else 2) * pdf(i * h) for i in range(1, steps))
        return 0.5 - s * h / 3

    lo, hi = 0.0, 10.0
    for _ in range(80):
        mid = (lo + hi) / 2
        if upper_tail(mid) > alpha / 2:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2


def simulate(true_d: float, rng: random.Random, t_crit: float):
    n = N_PER_GROUP
    df = 2 * n - 2
    j = 1 - 3 / (4 * df - 1)  # Hedges' small-sample correction
    gs, pos_sig, neg_sig = [], 0, 0
    for _ in range(N_SIM):
        a = [rng.gauss(true_d, 1) for _ in range(n)]
        b = [rng.gauss(0, 1) for _ in range(n)]
        ma, mb = statistics.fmean(a), statistics.fmean(b)
        sp = math.sqrt((statistics.variance(a) + statistics.variance(b)) / 2)
        d = (ma - mb) / sp
        t = d / math.sqrt(2 / n)
        gs.append(j * d)
        if t > t_crit:
            pos_sig += 1
        elif t < -t_crit:
            neg_sig += 1
    gs.sort()
    q = lambda p: gs[int(p * (len(gs) - 1))]
    return {
        "true_effect": true_d,
        "people_per_group": n,
        "studies": N_SIM,
        "median_g": round(q(0.5), 3),
        "central_95pct_low": round(q(0.025), 3),
        "central_95pct_high": round(q(0.975), 3),
        "share_g_at_least_0.30": round(sum(1 for g in gs if g >= 0.30) / N_SIM, 4),
        "share_significant_positive": round(pos_sig / N_SIM, 4),
        "share_significant_negative": round(neg_sig / N_SIM, 4),
    }


def write_csv(path: Path, header, rows):
    with path.open("w", newline="", encoding="utf-8") as f:
        w = csv.writer(f, lineterminator="\n")
        w.writerow(header)
        w.writerows(rows)


def main(out_dir: str) -> None:
    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    summary = {"seed": SEED, "python": sys.version.split()[0]}

    # 1. Transfer gradient
    rows = []
    for timing, construct, level, control, g, lo, hi, k in MLRH_2016:
        rows.append([
            timing, construct, level, control, f"{g:.2f}", f"{lo:.3f}".rstrip("0").rstrip("."), f"{hi:.2f}", k,
            "yes" if lo > 0 else "no", f"{prob_superiority(g) * 100:.1f}",
        ])
    write_csv(
        out / "transfer_gradient.csv",
        ["posttest", "outcome", "transfer_level", "control_group", "hedges_g", "ci95_low", "ci95_high",
         "studies", "ci_excludes_zero", "prob_superiority_pct"],
        rows,
    )
    imm = [r for r in MLRH_2016 if r[0] == "immediate"]
    gap = {}
    for construct in dict.fromkeys(r[1] for r in imm):
        t = next(r[4] for r in imm if r[1] == construct and r[3] == "treated")
        u = next(r[4] for r in imm if r[1] == construct and r[3] == "untreated")
        gap[construct] = {"treated": t, "untreated": u, "untreated_minus_treated": round(u - t, 2)}
    far_treated = [r for r in imm if r[2] == "far" and r[3] == "treated"]
    summary["transfer_gradient"] = {
        "source": "Melby-Lervag, Redick & Hulme 2016, Tables 2-3",
        "prob_superiority_pct_treated_controls_immediate": {
            r[1]: round(prob_superiority(r[4]) * 100, 1) for r in imm if r[3] == "treated"
        },
        "far_transfer_treated_range": [min(r[4] for r in far_treated), max(r[4] for r in far_treated)],
        "far_transfer_treated_significant": [r[1] for r in far_treated if r[5] > 0],
        "untreated_vs_treated_immediate": gap,
    }

    # 2. Second-order meta-analysis
    so_rows = []
    summary["second_order"] = {}
    for key, spec in SECOND_ORDER.items():
        res = second_order(spec["rows"])
        for (name, k, gi, s2, tau2), adj in zip(spec["rows"], res["adjusted"]):
            so_rows.append([key, name, k, f"{gi:.2f}", f"{s2:.3f}", f"{tau2:.3f}", f"{s2 / k:.5f}", f"{adj:.3f}"])
        pub = spec["published"]
        summary["second_order"][key] = {
            "label": spec["label"],
            "meta_analyses": len(spec["rows"]),
            "samples": sum(r[1] for r in spec["rows"]),
            "first_order_range": [min(r[2] for r in spec["rows"]), max(r[2] for r in spec["rows"])],
            "recomputed": {k: round(v, 5) for k, v in res.items() if k != "adjusted"},
            "published": pub,
            "samples_match_collabra_model3_k233": (sum(r[1] for r in spec["rows"]) == 233) if key == "naive" else None,
            "grand_mean_matches_to_2dp": round(res["grand_mean"], 2) == pub["grand_mean"],
            "true_var_matches": res["true_var"] == pub["true_var"],
            "prob_superiority_pct_at_grand_mean": round(prob_superiority(res["grand_mean"]) * 100, 1),
        }
    write_csv(
        out / "second_order.csv",
        ["analysis", "first_order_meta_analysis", "samples_k", "mean_g", "var_observed_g", "tau2",
         "sampling_error_var_of_mean", "adjusted_mean_g"],
        so_rows,
    )

    # 3. Sample size for 80% power
    targets = [
        ("Criterion measure, treated controls (MLRH 2016)", 0.80),
        ("Verbal working memory, treated controls (MLRH 2016)", 0.31),
        ("Uncorrected far transfer, second-order mean (Sala 2019)", 0.12),
        ("Nonverbal abilities, treated controls (MLRH 2016)", 0.05),
    ]
    power_rows = [[label, f"{d:.2f}", n_per_group(d), 2 * n_per_group(d)] for label, d in targets]
    write_csv(out / "sample_size.csv", ["effect", "d", "people_per_group", "people_total"], power_rows)
    summary["sample_size_80pct_power"] = {r[0]: r[2] for r in power_rows}

    # 4. Simulation of small studies
    rng = random.Random(SEED)
    t_crit = t_two_sided_critical(2 * N_PER_GROUP - 2)
    sims = [simulate(d, rng, t_crit) for d in (0.0, 0.12)]
    write_csv(out / "small_study_simulation.csv", list(sims[0].keys()), [list(s.values()) for s in sims])
    summary["t_critical_df38"] = round(t_crit, 4)
    summary["simulation"] = sims

    (out / "summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    for p in sorted(out.iterdir()):
        print(hashlib.sha256(p.read_bytes()).hexdigest(), p.name)


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "out")
