"""Admit reviewed context negatives while preserving per-street class mass.""" import numpy as np def prepare_context(records, weights, additions): names = [r["name"] for r in records] if ( not names or len(set(names)) != len(names) or set(names) != set(weights) or set(names) != set(additions) ): raise ValueError("Matching unique TRAIN records, weights and additions required") out, result = [], {} for r in records: name = r["name"] t, w, a = r["target"], weights[name], additions[name] if ( r["split"] != "train" or t.dtype != np.uint8 or t.ndim != 2 or not np.isin(t, [0, 1, 255]).all() or w.shape != t.shape or w.dtype.kind != "f" or not np.isfinite(w).all() or np.any(w < 0) or np.any(w[t == 255] != 0) or a.dtype != bool or a.shape != t.shape or np.any(a & (t != 255)) ): raise ValueError("Only unknown pixels may become reviewed TRAIN background") target = t.copy() target[a] = 0 out.append(dict(r, target=target, context_added=a.copy())) result[name] = w.copy() for group in sorted({r["group"] for r in records}): before = [r for r in records if r["group"] == group] after = [r for r in out if r["group"] == group] if not any(additions[r["name"]].any() for r in before): continue mass = sum( float(weights[r["name"]][r["target"] == 0].sum(dtype=np.float64)) for r in before ) present = [r for r in after if np.any(r["target"] == 0)] if mass <= 0 or not present: raise ValueError("Existing reviewed street background mass required") for r in present: mask = r["target"] == 0 result[r["name"]][mask] = mass / len(present) / int(mask.sum()) actual = sum( float(result[r["name"]][r["target"] == 0].sum(dtype=np.float64)) for r in after ) if not np.isclose(actual, mass, atol=1e-8, rtol=1e-6): raise ValueError("Street background mass changed") return out, result def context_gate(old, new, control): """Frozen coverage screen; no thresholds or model selection after fitting.""" checks = { "halve_context_fp": new["context_fp"] <= 0.5 * old["context_fp"], "reduce_bce": new["bce"] < old["bce"], "beat_control_bce": new["bce"] < control["bce"], } for key in ["original_fp", "prior_added_fp", "weak_fn", "clear_fn"]: checks["retain_" + key] = new[key] <= old[key] for key in ["background_fp", "weak_fn", "clear_fn"]: checks["control_" + key] = new[key] <= control[key] return {"passed": all(checks.values()), "checks": checks}