"""Build independent, masked activity and report-day samples for M2.""" from __future__ import annotations import hashlib import json from pathlib import Path import pandas as pd import yaml from volve_dia import audit, paths CONFIG = paths.REPO_ROOT / "configs" ROOT = paths.outputs_dir() / "audit" / "m2_300" def stratified(frame: pd.DataFrame, counts: dict, group: str, spec: dict) -> pd.DataFrame: """Draw by simple random sampling within each disjoint stratum with known inclusion probability.""" pieces = [] for category, n in counts.items(): pool = frame.loc[frame[group].eq(category)] sizes = pool["stratum"].value_counts(sort=False).sort_index().to_dict() allocation = audit.allocate(sizes, n, spec["min_per_stratum"]) for stratum, k in allocation.items(): f = pool.loc[pool["stratum"].eq(stratum)].sample(n=k, random_state=spec["seed"]) pieces.append(f.assign(n_stratum=sizes[stratum], k_stratum=k, weight=sizes[stratum] / k)) result = pd.concat(pieces).sample(frac=1, random_state=spec["seed"]).reset_index(drop=True) if len(result) != sum(counts.values()): raise ValueError("Sample quotas could not be filled.") return result def activity_sample(spec: dict) -> tuple[pd.DataFrame, pd.DataFrame, int]: rows = audit.load_activity_labels().sort_values("act_id") if spec["exclude_pilot"]: pilot = pd.read_csv(ROOT.parent / "trial_100" / "key.csv", usecols=["act_id"]) rows = rows.loc[~rows["act_id"].isin(pilot["act_id"])].copy() rows["zone"] = audit.zone(rows["npt_a"], rows["npt_b"]) category = rows["cause_a"].where(rows["zone"].eq("a"), rows["cause_b"]) category = category.where(rows["zone"].ne("none"), rows["op_class"]) rows["stratum"] = rows["zone"] + "/" + category + "/" + rows["well"] s = stratified(rows, spec["zones"], "zone", spec) s.insert(0, "item", [f"A{i:03d}" for i in range(1, len(s) + 1)]) s = s.rename(columns={"file_date": "report_date", "comments": "target_comment"}) for col in ("start_utc", "end_utc"): s[col] = pd.to_datetime(s[col], utc=True).dt.strftime("%Y-%m-%dT%H:%MZ") s["report_date"] = s["report_date"].astype(str) sheet = s[["item", "wellbore", "report_date", "start_utc", "end_utc", "duration_h", "md", "rig_phase", "prev_comment", "target_comment", "next_comment", "sum24Hr"]] key = s[["item", "act_id", "well", "zone", "stratum", "n_stratum", "k_stratum", "weight", "npt_a", "npt_b", "cause_a", "cause_b", "op_class"]] return sheet, key, len(rows) def section_sample(spec: dict) -> tuple[pd.DataFrame, pd.DataFrame, int]: labels = paths.outputs_dir() / "labels" ddr = paths.outputs_dir() / "ddr" rows = pd.read_parquet(labels / "t1_reports.parquet") rows = rows.loc[rows["scope"].eq("drilling_day"), ["report_id", "well", "section", "filled_by"]].copy() rows["source"] = rows["filled_by"].eq("diaHole").map({True: "published", False: "filled"}) rows["stratum"] = rows["source"] + "/" + rows["section"] s = stratified(rows.sort_values("report_id"), spec["source"], "source", spec) s.insert(0, "item", [f"S{i:03d}" for i in range(1, len(s) + 1)]) reports = pd.read_parquet(ddr / "reports.parquet", columns=["report_id", "sum24Hr"]) act = pd.read_parquet(ddr / "activities.parquet", columns=["report_id", "seq", "comments"]) comments = act.sort_values("seq").groupby("report_id")["comments"].agg(list).rename("activity_comments") view = s[["item", "report_id"]].merge(reports, on="report_id", validate="one_to_one") view = view.join(comments, on="report_id", validate="one_to_one") key = s[["item", "report_id", "well", "source", "section", "filled_by", "stratum", "n_stratum", "k_stratum", "weight"]] return view.drop(columns="report_id"), key, len(rows) def encode(frame: pd.DataFrame) -> str: return frame.to_json(orient="records", lines=True, force_ascii=False) def write_frozen(path: Path, content: str) -> str: raw = content.encode() if path.exists() and path.read_bytes() != raw: raise ValueError(f"Frozen M2 artifact differs: {path}") if not path.exists(): path.write_bytes(raw) return hashlib.sha256(raw).hexdigest() def main() -> None: spec = yaml.safe_load((CONFIG / "m2_validation.yaml").read_text()) ROOT.mkdir(parents=True, exist_ok=True) blind = ROOT / "blind" blind.mkdir(exist_ok=True) manifest = {} for kind, sample in (("activity", activity_sample), ("section", section_sample)): sheet, key, population = sample(spec[f"{kind}_sample"]) manifest[kind] = { "items": len(key), "population": population, "strata": int(key["stratum"].nunique()), "wells": key["well"].value_counts().to_dict(), "blind_sha256": write_frozen(blind / f"{kind}.jsonl", encode(sheet)), "key_sha256": write_frozen(ROOT / f"key_{kind}.csv", key.to_csv(index=False)), "prompt_sha256": write_frozen(blind / f"{kind}_prompt.txt", (CONFIG / f"m2_{kind}_prompt.txt").read_text()), } write_frozen(ROOT / "sample.json", json.dumps(manifest, indent=2) + "\n") print(json.dumps(manifest, indent=2)) if __name__ == "__main__": main()