"""Regression checks for M2 sampling and agreement with abstentions.""" import runpy import pandas as pd import pytest from volve_dia.paths import REPO_ROOT def script(name): return runpy.run_path(str(REPO_ROOT / "scripts" / f"10_m2_{name}.py")) def test_stratified_sample_weights_sum_to_the_full_frame(): source = pd.DataFrame({"item": range(9), "zone": ["a"] * 9, "stratum": ["large"] * 8 + ["rare"]}) draw = script("sample")["stratified"](source, {"a": 4}, "zone", {"seed": 23, "min_per_stratum": 1}) assert len(draw) == draw["item"].nunique() == 4 assert draw.groupby("stratum")["weight"].sum().to_dict() == {"large": 8.0, "rare": 1.0} def test_abstention_is_removed_from_kappa_and_counted_in_class_support(): methods = script("agreement") labels = pd.DataFrame({"a": ["yes", "no", None], "b": ["yes", None, "yes"], "c": ["yes", "no", None]}) truth = pd.Series(["yes", "no", "yes"]) stats = methods["score_target"](truth, pd.DataFrame({"well": ["A", "B", "B"], "weight": [1, 1, 8]}), labels) assert stats["vs_code"]["a"]["weighted"]["kappa"] == 1 assert stats["vs_code"]["a"]["weighted_abstention_share"] == pytest.approx(0.8) assert stats["by_class"]["yes"]["rated_items"] == 1 assert stats["fleiss"] == {"n": 1, "kappa": None} def test_regex_negation_excludes_only_its_own_clause(): rules = {"strong_patterns": ["loss of"], "weak_patterns": ["losses"], "exclude_patterns": ["no losses"]} comments = pd.Series(["no losses, loss of 2 m3", "no losses", "losses"]) actual = script("cross_checks")["text_strength"](comments, rules) assert actual.tolist() == ["strong", "none", "weak"] def test_g1_keeps_supported_children_only_if_they_pass_their_own_threshold(): draft = {"class_merging": {"min_kappa": 0.6, "min_audit_items": 20}, "class_evaluability": {"preview": { "t1_section": {"merges": {}}, "t2_cause": {"merges": {"downhole": ["stuck", "loss"]}}, }}} good = {"median_weighted_kappa": 0.7, "rated_items": 25} low_support = {"median_weighted_kappa": 0.7, "rated_items": 19} first = {"targets": { "section": {"by_class": {}}, "operation": {"by_class": {}}, "npt_a": {"by_class": {}}, "cause_a": {"by_class": {"stuck": good, "loss": low_support}, "pooled_classes": {"downhole": good}}, }} pre = {"class_coverage": { **{name: {} for name in ("section", "operation", "npt_a")}, "cause_a": {"stuck": {"evaluable": True}, "loss": {"evaluable": False}}, "cause_a_pooled": {"downhole": {"evaluable": True}}, }} decide = script("protocol")["class_decisions"] decisions = decide(draft, first, pre, "a")["cause_a"] assert decisions["downhole"]["status"] == "keep" assert decisions["stuck"]["within_parent_reportable"] and not decisions["loss"]["within_parent_reportable"] first["targets"]["cause_a"]["pooled_classes"]["downhole"] = low_support decisions = decide(draft, first, pre, "a")["cause_a"] assert {k: v["status"] for k, v in decisions.items()} == {"downhole": "drop", "stuck": "keep", "loss": "drop"}