"""Blind audit of the activity labels: stratified sample, masked rating sheet, agreement. The rater sees what a model sees (the masked input view `t2_inputs`, plus the comments of the activities before and after in the same report) and never the codes or the labels. The key (item -> act_id, stratum, weight, labels) is written to a separate file. Agreement is Cohen's kappa, unweighted and weighted back to the population by the inverse inclusion probability of each stratum. """ from __future__ import annotations import math import numpy as np import pandas as pd #: Values the rater may choose (labels.yaml t2.cause_groups without hse, t1.op_classes without interruption). CAUSES = ("equipment", "weather", "waiting", "stuck_fishing", "lost_circulation", "well_control", "sidetrack", "operation_failed", "unspecified") OP_CLASSES = ("drill_ream", "trip", "casing_cement", "circulate", "bop_wellhead", "formation_evaluation", "completion", "perforate", "wireline", "plug_abandon", "rig_move", "rig_up_down", "wait", "other") def allocate(sizes: dict[str, int], k: int, minimum: int) -> dict[str, int]: """Split k items over strata: `minimum` each (or the whole stratum if smaller), the rest proportional to the square root of the stratum size, by largest remainder, never more than a stratum holds.""" sizes = {s: int(n) for s, n in sizes.items() if n > 0} out = {s: min(minimum, n) for s, n in sizes.items()} if sum(out.values()) > k: raise ValueError(f"{len(sizes)} strata x minimum {minimum} > {k} items") while sum(out.values()) < k: room = {s: n - out[s] for s, n in sizes.items() if n > out[s]} if not room: break left = k - sum(out.values()) w = {s: math.sqrt(sizes[s]) for s in room} share = {s: left * w[s] / sum(w.values()) for s in room} add = {s: min(room[s], int(share[s])) for s in room} if sum(add.values()) == 0: # hand out single items by largest remainder for s in sorted(room, key=lambda s: (-(share[s] - int(share[s])), s))[:left]: add[s] = 1 for s, a in add.items(): out[s] += a return out def spread_sample(frame: pd.DataFrame, k: int, by: str, rng: np.random.Generator) -> pd.DataFrame: """k rows of `frame`, spread over the values of `by` (round robin over a random order of the groups).""" if k >= len(frame): return frame f = frame.sample(frac=1.0, random_state=rng.integers(2**31)) order = {g: i for i, g in enumerate(rng.permutation(f[by].unique()))} f = f.assign(_rank=f.groupby(by).cumcount(), _g=f[by].map(order)) return f.sort_values(["_rank", "_g"]).head(k).drop(columns=["_rank", "_g"]) def zone(npt_a: pd.Series, npt_b: pd.Series) -> pd.Series: """a = NPT under both definitions, b_only = only under the union, none = neither.""" return pd.Series(np.where(npt_a, "a", np.where(npt_b, "b_only", "none")), index=npt_a.index) def draw(frame: pd.DataFrame, plan: dict[str, int], minimum: int, seed: int) -> pd.DataFrame: """Stratified sample. `frame` has act_id, well, zone, stratum (zone/class). `plan` gives the items per zone. Returns the sampled rows with n_stratum, k_stratum and weight = n_stratum / k_stratum.""" rng = np.random.default_rng(seed) parts = [] for z, k in plan.items(): fz = frame[frame["zone"] == z] alloc = allocate(fz["stratum"].value_counts().to_dict(), k, minimum) for s, ks in sorted(alloc.items()): fs = fz[fz["stratum"] == s] parts.append(spread_sample(fs, ks, "well", rng).assign(n_stratum=len(fs), k_stratum=ks)) out = pd.concat(parts, ignore_index=True) out["weight"] = out["n_stratum"] / out["k_stratum"] return out.sample(frac=1.0, random_state=seed).reset_index(drop=True) def cohen_kappa(a: pd.Series, b: pd.Series, weight: pd.Series | None = None) -> float | None: """Cohen's kappa of two label series (optionally with item weights). None if undefined.""" m = a.notna() & b.notna() a, b = a[m].astype(str), b[m].astype(str) w = pd.Series(1.0, index=a.index) if weight is None else weight[m].astype(float) if w.sum() == 0: return None po = float(w[a == b].sum() / w.sum()) pa = w.groupby(a).sum() / w.sum() pb = w.groupby(b).sum() / w.sum() pe = float(sum(pa.get(c, 0.0) * pb.get(c, 0.0) for c in set(pa.index) | set(pb.index))) return None if pe >= 1.0 else (po - pe) / (1.0 - pe) def agreement(a: pd.Series, b: pd.Series, weight: pd.Series | None = None) -> dict: m = a.notna() & b.notna() w = pd.Series(1.0, index=a.index) if weight is None else weight.astype(float) k = cohen_kappa(a, b, weight) return {"n": int(m.sum()), "agreement": (round(float(w[m & (a.astype(str) == b.astype(str))].sum() / w[m].sum()), 4) if m.any() else None), "kappa": None if k is None else round(k, 4)}