"""P05, as preregistered in prereg/P05.md (bundle 836db4f4…f8413d). Run: ~/.venvs/ots/bin/python analysis/P05.py
Writes results/P05.json (aggregates only; no individual is named or profiled)."""
import datetime as dt, glob, json, os, re, warnings
import numpy as np, pandas as pd, statsmodels.api as sm
warnings.filterwarnings("ignore")
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CB = os.path.join(ROOT, "work/batch1/p05_data/casebooks-data-master")
X = "{http://www.w3.org/XML/1998/namespace}id"
O_ROOTS = {"dead_or_absent": ["aliveOrDead", "death", "absentPerson"], "lost_or_stolen": ["lossAndTheft", "treasure"],
"bewitchment": ["witchcraftAndDevil", "witchcraftSufferedNonMedical", "witchcraftSuspect"]}
B_ROOTS = ["illnessGeneral", "illnessesNamed", "symptomsSpecified", "prognosis"]
MIND_ROOT = "diseasesOfTheMind"
def topic_tree():
import xml.etree.ElementTree as ET
src = open(f"{CB}/master-lists/topics.xml", encoding="utf-8").read()
src = re.sub(r"", "", src, flags=re.S); src = re.sub(r"&[a-zA-Z0-9]+;", "", src)
root = ET.fromstring(src.encode())
desc = {}
def walk(e):
ids = set()
for c in e.iter("{http://www.tei-c.org/ns/1.0}item"):
if c.get(X): ids.add(c.get(X))
return ids
for item in root.iter("{http://www.tei-c.org/ns/1.0}item"):
if item.get(X): desc[item.get(X)] = walk(item) # includes itself
return desc
def person_links():
"""CASEnnnn#localid -> PERSONnnnn, from the project's person authority files."""
m = {}
for f in ("names-forman-only.xml", "names-napier-only.xml", "names-both-forman-napier.xml"):
txt = open(f"{CB}/master-lists/{f}", encoding="utf-8").read()
for pid, body in re.findall(r']*>(.*?)', txt, flags=re.S):
for link in re.findall(r'.*? 1).sum())))
idx = e[e.group.isin(["O", "B"])].groupby("client").head(1).copy()
n_idx = len(idx)
idx = idx[idx.apply(lambda r: r.date <= last[r.practice] - pd.Timedelta(days=days), axis=1)]
steps.append((f"index consultations censored ({days} days)", n_idx - len(idx)))
by_client = {c: (g.date.values, g.case.values) for c, g in e.groupby("client")}
def returns(r):
ds, cs = by_client[r.client]; lo = np.datetime64(r.date); hi = np.datetime64(r.date + pd.Timedelta(days=days))
m = (ds >= lo) & (ds <= hi) & (cs != r.case) if same_day else (ds > lo) & (ds <= hi)
return int(m.sum())
idx["returns"] = [returns(r) for r in idx.itertuples()]
idx["prior"] = [int((by_client[r.client][0] < np.datetime64(r.date)).sum()) for r in idx.itertuples()]
idx["later_beyond"] = [int((by_client[r.client][0] > np.datetime64(r.date + pd.Timedelta(days=days))).sum()) for r in idx.itertuples()]
if practice: idx = idx[idx.practice == practice]
if drop_O_mind: idx = idx[~((idx.group == "O") & idx.mind)]
idx["O"] = (idx.group == "O").astype(float)
idx["napier"] = (idx.practice == "napier").astype(float)
yr = (idx.date.dt.year - (idx.date.dt.year.mean() if practice else 1615)) / 10; idx["yr"] = yr; idx["yr2"] = yr ** 2
return idx
def nb_rr(idx, term="O"):
cols = [c for c in [term, "napier", "yr", "yr2", "self"] if idx[c].std() > 0]
Xm = sm.add_constant(idx[cols])
r = sm.NegativeBinomial(idx.returns, Xm).fit(disp=0, maxiter=500)
b, (lo, hi) = r.params[term], r.conf_int().loc[term]
if np.isfinite(lo) and np.isfinite(hi) and r.params["alpha"] > 1e-6:
return {"RR": round(float(np.exp(b)), 3), "L": round(float(np.exp(lo)), 3), "U": round(float(np.exp(hi)), 3), "alpha": round(float(r.params["alpha"]), 3), "n": int(len(idx)), "model": "negative binomial (NB2)"}
# fallback when NB2 does not converge to an interior solution: Poisson with robust (sandwich) errors
g = sm.GLM(idx.returns, Xm, family=sm.families.Poisson()).fit(cov_type="HC0")
b, (lo, hi) = g.params[term], g.conf_int().loc[term]
return {"RR": round(float(np.exp(b)), 3), "L": round(float(np.exp(lo)), 3), "U": round(float(np.exp(hi)), 3), "n": int(len(idx)), "model": "Poisson, robust SE (NB2 did not converge)"}
def logit_or(idx):
Xm = sm.add_constant(idx[["O", "napier", "yr", "yr2", "self"]])
r = sm.Logit((idx.returns > 0).astype(float), Xm).fit(disp=0)
b, (lo, hi) = r.params["O"], r.conf_int().loc["O"]
return {"OR": round(float(np.exp(b)), 3), "L": round(float(np.exp(lo)), 3), "U": round(float(np.exp(hi)), 3)}
def verdict(p):
if p["RR"] >= 1.25 and p["L"] > 1.0: return "confirmed"
if p["U"] < 1.10: return "refuted"
return "inconclusive"
def main():
desc = topic_tree(); links = person_links()
Oset = {k: set().union(*[desc[r] for r in v]) for k, v in O_ROOTS.items()}
Oall = set().union(*Oset.values()); Bset = set().union(*[desc[r] for r in B_ROOTS]); Mind = desc[MIND_ROOT]
df = pd.DataFrame(cases())
df["date"] = pd.to_datetime(df.date, errors="coerce")
def grp(t):
if t & Oall: return "O"
if (t & Bset) and not (t & Mind): return "B"
return "other"
df["group"] = df.topics.map(grp); df["mind"] = df.topics.map(lambda t: bool(t & Mind))
for k, s_ in Oset.items(): df[k] = df.topics.map(lambda t, s_=s_: bool(t & s_))
out = {"n_case_files": int(len(df)), "groups_all_cases": df.group.value_counts().to_dict(),
"cases_with_several_querents": int((df.querents.map(len) > 1).sum())}
steps = []; idx = analyse(df, links, 365, steps)
out["exclusions_primary"] = steps
out["index_by_group"] = idx.group.value_counts().to_dict()
out["mean_returns_by_group"] = idx.groupby("group").returns.mean().round(3).to_dict()
out["share_returning_by_group"] = idx.groupby("group").returns.apply(lambda x: round(float((x > 0).mean()), 3)).to_dict()
out["index_by_group_and_practice"] = {f"{g}|{p}": int(n) for (g, p), n in idx.groupby(["group", "practice"]).size().items()}
out["mean_returns_by_group_and_practice"] = {f"{g}|{p}": round(float(v), 3) for (g, p), v in idx.groupby(["group", "practice"]).returns.mean().items()}
out["primary"] = nb_rr(idx); out["verdict"] = verdict(out["primary"])
out["secondary_a_any_return_logit"] = logit_or(idx)
sub = {}
for k in O_ROOTS:
s_ = idx[(idx.group == "B") | ((idx.group == "O") & idx[k])].copy(); s_["O"] = (s_.group == "O").astype(float)
sub[k] = {**nb_rr(s_), "n_O": int(s_.O.sum())}
out["secondary_b_subtypes"] = sub
st2 = []; out["secondary_c_subject_as_client"] = nb_rr(analyse(df, links, 365, st2, who="subjects")); out["secondary_c_exclusions"] = st2
st3 = []; out["secondary_d_730_days"] = nb_rr(analyse(df, links, 730, st3)); out["secondary_d_exclusions"] = st3
out["D2_same_day_cases_counted"] = nb_rr(analyse(df, links, 365, [], same_day=True))
out["stratified_napier_only"] = nb_rr(analyse(df, links, 365, [], practice="napier"))
out["stratified_forman_only"] = nb_rr(analyse(df, links, 365, [], practice="forman"))
out["O_without_mind_topics"] = nb_rr(analyse(df, links, 365, [], drop_O_mind=True))
out["O_share_with_mind_topics"] = round(float(idx[idx.group == "O"].mind.mean()), 3)
out["linkage_and_history_imbalance"] = {"mean_prior_consultations": idx.groupby("group").prior.mean().round(3).to_dict(),
"share_with_a_consultation_beyond_follow_up": idx.groupby("group").later_beyond.apply(lambda x: round(float((x > 0).mean()), 3)).to_dict(),
"share_Forman": idx.groupby("group").practice.apply(lambda x: round(float((x == "forman").mean()), 3)).to_dict()}
S1 = {}
for label, end in {"1000_cases_a_year": {"forman": "1601-12-31", "napier": "1633-12-31"}, "100_cases_a_year": {"forman": "1603-12-31", "napier": "1640-12-31"}}.items():
st = []; S1[label] = {"end": end, "result": nb_rr(analyse(df, links, 365, st, end=end)), "exclusions": st}
out["S1_not_preregistered_dense_record_censoring"] = {"rule": "follow-up ends at the close of each practice's last year with at least N dated cases; index consultations later than 365 days before that are dropped. Chosen after the stamp, after seeing yearly case counts only.", "cutoffs": S1}
out["deviations"] = [
{"id": "D1", "what": "The preregistered censoring rule (each practice's last dated consultation) was applied as written and censored nothing: Napier's practice has dated records to 1662, continued after his death, but fewer than 500 a year after 1634 and almost none after 1641; Forman's to 1611 but almost none after 1601. Clients indexed late in each record therefore have truncated follow-up. B clients are far more often Forman's than O clients are, so the truncation falls mostly on B and pushes the rate ratio toward the hypothesis. S1 reports two dense-record cut-offs chosen after the stamp.",
"why": "Not foreseen: the thinning of the record after 1601 and 1634 was not known when the rule was written."},
{"id": "D2", "what": "Returns are consultations dated after the index date (the preregistration's 'in the 365 days after the index date'), so other consultations on the index date itself are not counted. Counting them (index case still excluded) is reported as D2_same_day_cases_counted.",
"why": "The preregistration did not say how to treat same-day cases, such as a decumbiture paired with the horary entry."},
{"id": "D3", "what": "Parser corrected before publication: the first run read only the first querent of each case and failed to split refs that list several people ('#a #b'), dropping about 580 cases as unlinked. Every querent token in every cb:querent element now counts.",
"why": "Bug found by the hostile review."},
{"id": "D4", "what": "When a client has both an O and a B case on their earliest date, the lower case number decides the group (count in exclusions_primary).",
"why": "The preregistration did not specify a tie-break."}]
out["notes"] = ["The excess depends on practice composition: within Napier's practice alone the rate ratio is close to 1.10 with an interval including 1; Forman's O group is small.",
"21% or so of O index clients also carry a mind topic, which the B group excludes by design; dropping them is reported (O_without_mind_topics).",
"O is mostly bewitchment (afflictions blamed on witchcraft), so O vs B is largely 'illness blamed on witchcraft' vs 'ordinary illness', not open against bounded questions in general.",
"O clients had more prior consultations and more consultations beyond the follow-up window: the groups differ in linkability and history, contrary to the preregistration's assumption that linkage bias affects both alike.",
"No subtype is estimated precisely; the overall result is essentially the bewitchment result.",
"names-master.xml also references possibly-forman.xml, which is not in the repository."]
json.dump(out, open(os.path.join(ROOT, "results/P05.json"), "w"), indent=1, default=str)
print(json.dumps({k: out[k] for k in ("primary", "verdict", "exclusions_primary", "index_by_group", "D2_same_day_cases_counted", "stratified_napier_only", "stratified_forman_only", "O_without_mind_topics", "linkage_and_history_imbalance")}, indent=1, default=str))
if __name__ == "__main__":
main()