from __future__ import annotations import hashlib import numpy as np import pandas as pd import pytest import yaml from volve_dia import m5_synthetic as ms from volve_dia.paths import REPO_ROOT PHRASES = [("equipment", "Top drive failure."), ("weather", "Waiting on weather.")] def toy_acts(n=60, wells=4): rng = np.random.default_rng(0) words = np.array(["drilled", "circulated", "tripped", "reamed", "logged", "cased"]) return pd.DataFrame({ "act_id": [f"A{i:03d}" for i in range(n)], "report_id": [f"R{i // 5:02d}" for i in range(n)], "well": [f"W{i % wells}" for i in range(n)], "seq": [i % 5 for i in range(n)], "comments": [" ".join(rng.choice(words, 4)) if i % 7 else None for i in range(n)], "sum24Hr": ["day summary"] * n, "forecast24Hr": ["forecast"] * n}) @pytest.mark.parametrize("s", [0.0, 0.25, 1.0, 2.0, 5.0]) def test_bisection_hits_target_mean(s): z = ms.zscore(np.random.default_rng(1).gamma(2.0, 1000.0, size=4000)) a = ms.solve_intercept(z, s, 0.114) assert abs((1 / (1 + np.exp(-(a + s * z)))).mean() - 0.114) < 1e-9 if s == 0: assert a == pytest.approx(np.log(0.114 / 0.886), abs=1e-9) def test_zscore_is_standard(): z = ms.zscore([1.0, 2.0, 3.0, 10.0]) assert z.mean() == pytest.approx(0) and z.std() == pytest.approx(1) def test_t2_planting_rates_within_tolerance(): n, pi, c, f = 200_000, 0.183, 0.5, 0.02 y, cue = ms.plant_t2(n, pi, c, f, 21, ms.planting_rng(20261117, c, f)) assert abs(y.mean() - pi) < 0.004 assert abs((cue[y] >= 0).mean() - c) < 0.01 assert abs((cue[~y] >= 0).mean() - f) < 0.003 counts = np.bincount(cue[cue >= 0], minlength=21) / (cue >= 0).sum() assert np.abs(counts - 1 / 21).max() < 0.01 assert cue.min() >= -1 and cue.max() < 21 def test_t2_planting_extremes(): y, cue = ms.plant_t2(10_000, 0.183, 1.0, 0.0, 3, ms.planting_rng(1, 1.0, 0.0)) assert (cue[y] >= 0).all() and (cue[~y] == -1).all() y, cue = ms.plant_t2(10_000, 0.183, 0.0, 0.0, 3, ms.planting_rng(1, 0.0, 0.0)) assert (cue == -1).all() def test_t3_planting_prevalence(): z = ms.zscore(np.linspace(0, 5000, 50_000)) a, p, y = ms.plant_t3(z, 1.0, 0.114, ms.planting_rng(20261117, 1.0)) assert p.mean() == pytest.approx(0.114, abs=1e-9) assert abs(y.mean() - 0.114) < 0.006 assert np.corrcoef(z, p)[0, 1] > 0.8 def test_seeds_are_deterministic_and_distinct(): first = ms.plant_t2(1000, 0.183, 0.5, 0.02, 21, ms.planting_rng(20261117, 0.5, 0.02)) again = ms.plant_t2(1000, 0.183, 0.5, 0.02, 21, ms.planting_rng(20261117, 0.5, 0.02)) other_seed = ms.plant_t2(1000, 0.183, 0.5, 0.02, 21, ms.planting_rng(20261118, 0.5, 0.02)) other_setting = ms.plant_t2(1000, 0.183, 0.5, 0.10, 21, ms.planting_rng(20261117, 0.5, 0.10)) assert all(np.array_equal(u, v) for u, v in zip(first, again)) assert not np.array_equal(first[0], other_seed[0]) assert not np.array_equal(first[0], other_setting[0]) def test_cue_appended_after_comment_only_where_specified(): acts = toy_acts() cue = np.full(len(acts), -1) cue[[1, 7, 12]] = [0, 1, 0] # row 7 has no comment out = ms.apply_cues(acts, cue, PHRASES) assert out.loc[1, "comments"] == acts.loc[1, "comments"] + " Top drive failure." assert out.loc[7, "comments"] == "Waiting on weather." assert out.loc[12, "comments"] == acts.loc[12, "comments"] + " Top drive failure." untouched = np.setdiff1d(np.arange(len(acts)), [1, 7, 12]) pd.testing.assert_frame_equal(out.iloc[untouched], acts.iloc[untouched]) pd.testing.assert_frame_equal(out.drop(columns="comments"), acts.drop(columns="comments")) assert acts.loc[1, "comments"] != out.loc[1, "comments"] # the input frame is not modified def test_text_matches_the_real_construction(): acts = toy_acts() cue = np.full(len(acts), -1) cue[1] = 0 text = ms.t2_text(ms.apply_cues(acts, cue, PHRASES)) # Fields: comments, previous, next, sum24Hr, forecast24Hr of the same report. assert text[1].split(" [SEP] ")[0].endswith("Top drive failure.") assert text[2].split(" [SEP] ")[1].endswith("Top drive failure.") assert text[0].split(" [SEP] ")[2].endswith("Top drive failure.") assert "Top drive" not in text[5] # another report x = ms.t2_inputs(acts, text) assert list(x.columns) == ["well", "text"] def test_null_calibration_on_toy_case(): rng = np.random.default_rng(3) n, pi = 20_000, 0.2 y = rng.random(n) < pi wells = np.repeat(np.arange(10), n // 10) aps = [ms.ap_row(y, rng.random(n), wells, 200, 1) for _ in range(5)] mean = np.mean([a["ap"] for a in aps]) check = ms.null_check(mean, [aps[0]["ci_low"], aps[0]["ci_high"]], y.mean()) assert check["null_check_passed"] assert not ms.null_check(pi + 0.05, [pi + 0.02, pi + 0.08], pi)["null_check_passed"] assert not ms.null_check(pi + 0.005, [pi + 0.001, pi + 0.01], pi)["null_check_passed"] def test_null_calibration_of_the_t2_pipeline_on_toy_text(): acts = toy_acts(n=400, wells=4) settings = {"tfidf_min_df": 2, "logistic_c": [1.0]} y, cue = ms.plant_t2(len(acts), 0.25, 0.0, 0.2, len(PHRASES), ms.planting_rng(5, 0.0, 0.2)) x = ms.t2_inputs(acts, ms.t2_text(ms.apply_cues(acts, cue, PHRASES))) scores, chosen = ms.t2_oof(x, y, settings, n_splits=3) assert np.isfinite(scores).all() and set(chosen) == {"W0", "W1", "W2", "W3"} y1, cue1 = ms.plant_t2(len(acts), 0.25, 1.0, 0.0, len(PHRASES), ms.planting_rng(5, 1.0, 0.0)) x1 = ms.t2_inputs(acts, ms.t2_text(ms.apply_cues(acts, cue1, PHRASES))) strong, _ = ms.t2_oof(x1, y1, settings, n_splits=3) from sklearn.metrics import average_precision_score assert average_precision_score(y1, strong) > average_precision_score(y, scores) + 0.2 def test_t3_knn_scores_use_other_wells(): cells = pd.DataFrame({"well": ["A"] * 20 + ["B"] * 20, "md_top": np.tile(np.arange(20.0), 2)}) y = np.r_[np.ones(20), np.zeros(20)] scores = ms.t3_scores(cells, y) assert (scores[:20] == 0).all() and (scores[20:] == 1).all() def test_interpolation_within_and_out_of_range(): grid = [0.0, 0.1, 0.25, 0.5, 0.75, 1.0] values = [0.18, 0.2, 0.3, 0.4, 0.6, 0.8] r = ms.interpolate(grid, values, 0.35) assert r["value"] == pytest.approx(0.375) and r["out_of_range"] is None assert ms.interpolate(grid, values, 0.18)["value"] == pytest.approx(0.0) assert ms.interpolate(grid, values, 0.8)["value"] == pytest.approx(1.0) assert ms.interpolate(grid, values, 0.9) == {"value": None, "out_of_range": "above_last_grid_point", "target": 0.9} assert ms.interpolate(grid, values, 0.1)["out_of_range"] == "below_first_grid_point" # A non-monotone curve uses the first bracketing segment. r = ms.interpolate([0, 1, 2, 3], [0.1, 0.5, 0.3, 0.6], 0.4) assert r["value"] == pytest.approx(0.75) and r["monotone"] is False def test_interpolation_with_seed_range(): rows = pd.DataFrame({"seed": np.repeat([0, 1], 3), "c": np.tile([0.0, 0.5, 1.0], 2), "ap": [0.2, 0.4, 0.6, 0.2, 0.3, 0.4]}) r = ms.interpolate_with_seeds(rows, "c", 0.45) assert r["value"] == pytest.approx(0.5 + 0.1 / 0.15 * 0.5) assert r["per_seed"][0]["value"] == pytest.approx(0.625) assert r["per_seed"][1]["out_of_range"] == "above_last_grid_point" assert r["seed_range"] == [pytest.approx(0.625), pytest.approx(0.625)] and r["seeds_out_of_range"] == 1 mean = ms.interpolate([0.0, 0.5, 1.0], [0.2, 0.35, 0.5], 0.45) assert r["value"] == pytest.approx(mean["value"]) def test_summarise_reports_mean_range_and_seed0(): rows = pd.DataFrame({"s": [0.0] * 3, "seed": [3, 1, 2], "ap": [0.12, 0.10, 0.11], "ci_low": [0.0, 0.09, 0.0], "ci_high": [1.0, 0.13, 1.0], "prevalence": [0.11, 0.115, 0.112]}) table = ms.summarise(rows, ["s"], 0.114) row = table.iloc[0] assert row["ap_mean"] == pytest.approx(0.11) and row["ap_min"] == 0.10 and row["ap_max"] == 0.12 assert row["seed0_ap"] == 0.10 and row["seed0_ci_low"] == 0.09 assert row["lift_mean"] == pytest.approx(0.11 / 0.114) def _locked_pair(tmp_path, cue_text="cues: {a: [x]}\n"): (tmp_path / "configs").mkdir() cues = tmp_path / "configs/synth_cues.yaml" cues.write_text(cue_text) parent = tmp_path / "configs/parent.yaml" parent.write_text("version: 5\n") protocol = tmp_path / "configs/protocol_test.yaml" protocol.write_text(yaml.safe_dump({ "status": "locked", "version": 6, "extends": {"file": "configs/parent.yaml", "sha256": hashlib.sha256(parent.read_bytes()).hexdigest()}, "inputs_hashed": {"configs/synth_cues.yaml": hashlib.sha256(cues.read_bytes()).hexdigest()}})) protocol.with_suffix(".yaml.sha256").write_text( hashlib.sha256(protocol.read_bytes()).hexdigest() + " configs/protocol_test.yaml\n") return protocol, cues def test_verify_protocol_accepts_and_refuses(tmp_path): protocol, cues = _locked_pair(tmp_path) parsed, digest = ms.verify_protocol(protocol, tmp_path) assert parsed["version"] == 6 and len(digest) == 64 cues.write_text("cues: {a: [y]}\n") with pytest.raises(ValueError, match="synth_cues.yaml"): ms.verify_protocol(protocol, tmp_path) def test_verify_protocol_refuses_edited_protocol(tmp_path): protocol, _ = _locked_pair(tmp_path) protocol.write_text(protocol.read_text() + "# edited\n") with pytest.raises(ValueError, match="checksum"): ms.verify_protocol(protocol, tmp_path) def test_locked_v6_and_cues_verify(): protocol, _ = ms.verify_protocol(REPO_ROOT / "configs/protocol_v6.yaml", REPO_ROOT) assert protocol["t2_cues"]["settings"]["c"] == [0.0, 0.1, 0.25, 0.5, 0.75, 1.0] assert protocol["t3_hazard"]["settings"]["s"] == [0.0, 0.25, 0.5, 1.0, 2.0] phrases = ms.load_cues(REPO_ROOT / "configs/synth_cues.yaml") assert len(phrases) == 21 and len({p for _, p in phrases}) == 21 def test_absence_of_a_cue_is_signal_when_f_exceeds_c(): rng = np.random.default_rng(5) n, pi, f = 200_000, 0.183, 0.10 y, cue = ms.plant_t2(n, pi, 0.0, f, 20, rng) assert ms.no_cue_indicator_ap(y, cue) == pytest.approx(ms.expected_no_cue_ap(pi, f), abs=0.004) assert ms.expected_no_cue_ap(pi, f) > pi + 0.01 y, cue = ms.plant_t2(n, pi, f, f, 20, rng) # c = f is the true null: the cue is independent of the label assert ms.no_cue_indicator_ap(y, cue) == pytest.approx(pi, abs=0.004)