"""Planted-signal studies with known ground truth under protocol v6 (T2 text cues, T3 depth hazard). The planted label is drawn by a fixed random rule, so the truth is known exactly. The real activity codes and the real T2/T3 labels are never read. The T2 model is the M3-M4 TF-IDF + logistic baseline unchanged; the T3 forecast is the v5 depth neighbour forecast. """ from __future__ import annotations import numpy as np import pandas as pd import yaml from scipy.special import expit from sklearn.model_selection import LeaveOneGroupOut from .m34_classify import fold_prediction, model_inputs from .m34_features import TEXT, activity_text, strings from .m5_judge import sha256_file from .m5_t5 import ap_ci, knn_scores T2_COLUMNS = ["act_id", "report_id", "well", "seq", "comments", "sum24Hr", "forecast24Hr"] T3_COLUMNS = ["item", "well", "wellbore", "md_top"] def verify_protocol(protocol_path, repo_root): """Return the parsed protocol, or raise if it or any hashed input differs from its locked checksum.""" expected = protocol_path.with_suffix(".yaml.sha256").read_text().split()[0] actual = sha256_file(protocol_path) if actual != expected: raise ValueError(f"{protocol_path.name} does not match its checksum") protocol = yaml.safe_load(protocol_path.read_text()) if protocol.get("status") != "locked": raise ValueError(f"{protocol_path.name} is not locked") parent = protocol.get("extends") if parent and sha256_file(repo_root / parent["file"]) != parent["sha256"]: raise ValueError(f"{parent['file']} does not match the checksum recorded in {protocol_path.name}") for name, digest in protocol.get("inputs_hashed", {}).items(): if sha256_file(repo_root / name) != digest: raise ValueError(f"{name} does not match the checksum recorded in {protocol_path.name}") return protocol, actual def load_cues(path): """Flat list of (class, phrase) in file order.""" cues = yaml.safe_load(path.read_text())["cues"] return [(cls, phrase) for cls, phrases in cues.items() for phrase in phrases] def planting_rng(seed, *settings): """Deterministic generator for one planting: the seed plus each setting in thousandths.""" return np.random.default_rng([int(seed), *(int(round(float(v) * 1000)) for v in settings)]) # T2 text cues --------------------------------------------------------------------------------------------------- def plant_t2(n, pi, c, f, n_phrases, rng): """y ~ Bernoulli(pi); a cue with probability c (planted) or f (unplanted); phrase uniform. -1 means no cue.""" y = rng.random(n) < pi u = rng.random(n) cued = np.where(y, u < c, u < f) phrase = rng.integers(0, n_phrases, size=n) return y, np.where(cued, phrase, -1) def apply_cues(acts, cue, phrases): """Append the chosen phrase after the comment with one space. Rows without a cue are unchanged.""" out = acts.copy() cue = np.asarray(cue) rows = np.flatnonzero(cue >= 0) text = np.array([p for _, p in phrases], dtype=object)[cue[rows]] base = out["comments"].iloc[rows] out.iloc[rows, out.columns.get_loc("comments")] = np.where( base.isna(), text, base.fillna("").astype(str).to_numpy(dtype=object) + " " + text) return out def t2_text(acts): """The masked XML text of the real T2 frame (m34_features.t2_frame), in the row order of acts.""" view = activity_text(acts) return acts["act_id"].map(strings(view.set_index("act_id"), TEXT)).to_numpy() def t2_inputs(acts, text): """Model inputs as m34_classify.model_inputs(frame, 'masked', 'xml'); the T2 frame has no numeric column.""" frame = pd.DataFrame({"well": acts["well"].to_numpy(), "text_xml": text}) return model_inputs(frame, "masked", "xml") def t2_oof(x, y, settings, n_splits, group="well"): """Leave-one-well-out out-of-fold scores with the M3-M4 fold fit (inner GroupKFold over C).""" scores = np.full(len(x), np.nan) chosen = {} groups = x[group].to_numpy() for train_idx, test_idx in LeaveOneGroupOut().split(x, y, groups=groups): train_wells = x["well"].iloc[train_idx] tune = np.flatnonzero(~train_wells.isin(x["well"].iloc[test_idx]).to_numpy()) out, c, _ = fold_prediction(x.iloc[train_idx], y[train_idx], tune, {"xml": x.iloc[test_idx]}, "t2", settings, n_splits, None) scores[test_idx] = out["xml"][1] chosen[str(groups[test_idx[0]])] = c return scores, chosen def cue_exposure(text, y, phrases): """Share of planted and unplanted rows whose model text contains any phrase (own comment or neighbour field).""" contains = np.zeros(len(text), dtype=bool) for _, phrase in phrases: contains |= pd.Series(text).str.contains(phrase, regex=False).to_numpy() return {"planted": float(contains[y].mean()) if y.any() else None, "unplanted": float(contains[~y].mean()) if (~y).any() else None} # T3 depth hazard ------------------------------------------------------------------------------------------------ def zscore(values): values = np.asarray(values, dtype=float) return (values - values.mean()) / values.std() def solve_intercept(z, s, target, lo=-50.0, hi=50.0, tol=1e-12, iterations=200): """Bisection for a such that mean(sigmoid(a + s z)) = target (monotone increasing in a).""" z = np.asarray(z, dtype=float) for _ in range(iterations): mid = (lo + hi) / 2 gap = expit(mid + s * z).mean() - target if abs(gap) < tol: break lo, hi = (mid, hi) if gap < 0 else (lo, mid) return mid def plant_t3(z, s, pi, rng): a = solve_intercept(z, s, pi) p = expit(a + s * np.asarray(z, dtype=float)) return a, p, rng.random(len(p)) < p def t3_scores(cells, y): """v5 depth neighbour forecast (k = 10 nearest md_top cells of the other wells, mean planted label).""" frame = cells[["well", "md_top"]].reset_index(drop=True).assign(planted=np.asarray(y, dtype=int)) return knn_scores(frame, "planted", ["md_top"]).to_numpy() # Summaries ------------------------------------------------------------------------------------------------------ def summarise(rows, key, pi): """Mean and range over seeds per setting; the seed-0 interval; the null check at the null setting.""" out = [] for setting, g in rows.groupby(key, sort=True): g = g.sort_values("seed") first = g.iloc[0] ap = g["ap"] row = dict(zip(key, setting if isinstance(setting, tuple) else (setting,))) row |= {"seeds": int(len(g)), "ap_mean": float(ap.mean()), "ap_min": float(ap.min()), "ap_max": float(ap.max()), "lift_mean": float(ap.mean() / pi), "lift_min": float(ap.min() / pi), "lift_max": float(ap.max() / pi), "ap_minus_pi_mean": float(ap.mean() - pi), "seed0_ap": float(first["ap"]), "seed0_ci_low": float(first["ci_low"]), "seed0_ci_high": float(first["ci_high"]), "prevalence_mean": float(g["prevalence"].mean()), "prevalence_min": float(g["prevalence"].min()), "prevalence_max": float(g["prevalence"].max())} for extra in ("oracle_ap", "cue_rate_planted", "cue_rate_unplanted", "exposure_planted", "exposure_unplanted"): if extra in g: row[f"{extra}_mean"] = float(g[extra].mean()) row[f"{extra}_min"] = float(g[extra].min()) row[f"{extra}_max"] = float(g[extra].max()) out.append(row) return pd.DataFrame(out) def null_check(mean_ap, ci, pi, tolerance=0.01): within = abs(mean_ap - pi) <= tolerance contains = ci is not None and ci[0] <= pi <= ci[1] return {"mean_ap": float(mean_ap), "pi": float(pi), "tolerance": tolerance, "mean_within_tolerance": bool(within), "seed0_ci": list(ci) if ci is not None else None, "seed0_ci_contains_pi": bool(contains), "null_check_passed": bool(within and contains)} def interpolate(grid, values, target): """Grid value at which the AP curve reaches target, by linear interpolation between grid points. Out of range when target lies above the AP at the last grid point or below the AP at the first one. Within range, the first segment that brackets target is used; a curve that never brackets it is also out of range. """ grid, values = np.asarray(grid, dtype=float), np.asarray(values, dtype=float) if target > values[-1]: return {"value": None, "out_of_range": "above_last_grid_point", "target": float(target)} if target < values[0]: return {"value": None, "out_of_range": "below_first_grid_point", "target": float(target)} for i in range(len(grid) - 1): lo, hi = values[i], values[i + 1] if min(lo, hi) <= target <= max(lo, hi): value = grid[i] if hi == lo else grid[i] + (target - lo) / (hi - lo) * (grid[i + 1] - grid[i]) return {"value": float(value), "out_of_range": None, "target": float(target), "segment": [ float(grid[i]), float(grid[i + 1])], "monotone": bool(np.all(np.diff(values) >= 0))} return {"value": None, "out_of_range": "not_bracketed", "target": float(target)} def interpolate_with_seeds(rows, axis, target, fixed=None): """Interpolation on the mean curve, plus per-seed interpolations and their range.""" if fixed: for k, v in fixed.items(): rows = rows[np.isclose(rows[k], v)] mean = rows.groupby(axis)["ap"].mean().sort_index() result = interpolate(mean.index, mean.to_numpy(), target) per_seed = {} for seed, g in rows.groupby("seed"): curve = g.set_index(axis)["ap"].sort_index() per_seed[int(seed)] = interpolate(curve.index, curve.to_numpy(), target) values = [r["value"] for r in per_seed.values() if r["value"] is not None] result["per_seed"] = per_seed result["seed_range"] = [float(min(values)), float(max(values))] if values else None result["seeds_out_of_range"] = int(sum(r["value"] is None for r in per_seed.values())) result["grid"] = [float(v) for v in mean.index] result["mean_ap_curve"] = [float(v) for v in mean.to_numpy()] return result def no_cue_indicator_ap(planted, cue): """AP of the score "the row has no own cue" (1 without, 0 with); the structural signal of f > c. Planted rows receive a cue with probability c and unplanted rows with probability f, so when f > c the absence of a cue already points to a planted row and the setting is not a null even though the cue is independent of the real text. At c = 0 every planted row has no cue and the expected AP is pi / (pi + (1 - pi)(1 - f)). """ from sklearn.metrics import average_precision_score return float(average_precision_score(np.asarray(planted, dtype=bool), (np.asarray(cue) < 0).astype(float))) def expected_no_cue_ap(pi, f): """Expected AP of the no-cue indicator at c = 0 (a two-tier ranking with all positives in the first tier).""" return pi / (pi + (1 - pi) * (1 - f)) def ap_row(y, scores, wells, resamples, seed): block = ap_ci(y, scores, wells, resamples, seed) ci = block["ci95"] or [np.nan, np.nan] return {"ap": block["ap"], "ci_low": ci[0], "ci_high": ci[1], "prevalence": block["prevalence"], "positives": block["positives"], "n": block["n"]}