Matthew Ford commited on
Commit
083a17a
·
1 Parent(s): e7a7086

pimt v8 run statistical validation

Browse files

Former-commit-id: 7205da7e4ccbaf29b01104c11b6fedf607a3eba4
Former-commit-id: 1ea0c927d1540f8088b4040f0366a5418b7750b8

artifacts/pimt_v8_stats_tests_report.json ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "character": {
3
+ "character_codes": [
4
+ "A",
5
+ "B",
6
+ "C",
7
+ "D",
8
+ "E",
9
+ "F",
10
+ "G",
11
+ "H",
12
+ "I",
13
+ "J",
14
+ "K",
15
+ "L",
16
+ "M",
17
+ "P",
18
+ "Q",
19
+ "R",
20
+ "S",
21
+ "T",
22
+ "U",
23
+ "V",
24
+ "W",
25
+ "X",
26
+ "Y"
27
+ ],
28
+ "genres": [
29
+ "amber_oriental",
30
+ "citrus_cologne",
31
+ "floral_woody",
32
+ "fougere",
33
+ "wildcard"
34
+ ],
35
+ "label_snapshot": "v8_2_clause_guard_dominance",
36
+ "n_character_codes": 23,
37
+ "n_labelled_formulas": 3832
38
+ },
39
+ "character_permutation_null_all_genres": {
40
+ "genuine": true,
41
+ "null_95": 0.0103,
42
+ "null_mean": 0.0079,
43
+ "observed": 0.08,
44
+ "p_value": 0.0001
45
+ },
46
+ "character_permutation_null_drop_wildcard": {
47
+ "genuine": true,
48
+ "null_95": 0.0126,
49
+ "null_mean": 0.0092,
50
+ "observed": 0.026,
51
+ "p_value": 0.0001
52
+ },
53
+ "diagnostic": "statistical_validation_tests",
54
+ "paired_bootstrap": {
55
+ "delta_r2": {
56
+ "ci95": [
57
+ 0.007,
58
+ 0.3115
59
+ ],
60
+ "excludes_zero": true,
61
+ "observed": 0.1584,
62
+ "p_two_sided": 0.041
63
+ },
64
+ "delta_rho": {
65
+ "ci95": [
66
+ -0.1407,
67
+ 0.2463
68
+ ],
69
+ "excludes_zero": false,
70
+ "observed": 0.0503,
71
+ "p_two_sided": 0.6178
72
+ }
73
+ },
74
+ "pimt_version": "v8",
75
+ "random_drop_control": {
76
+ "flagged_percentile": 74.7,
77
+ "flagged_rho": 0.7084524548124993,
78
+ "full_rho": 0.6634,
79
+ "random_drop_ci95": [
80
+ 0.5074,
81
+ 0.7967
82
+ ],
83
+ "random_drop_mean": 0.6579,
84
+ "specific_to_flagged": false
85
+ },
86
+ "substantivity": {
87
+ "baseline_key": "baseline_physical_gbm",
88
+ "flagged_rho": 0.7084524548124993,
89
+ "n_test": 34,
90
+ "structure_key": "structure_full_gbm"
91
+ },
92
+ "verdict": {
93
+ "character": "genuine_with_and_without_wildcard",
94
+ "drop10": "not_specific_to_flagged",
95
+ "rho_cross_check": "not_significant",
96
+ "substantivity": "structure_beats_baseline_on_r2_only"
97
+ },
98
+ "williams_test": {
99
+ "df": 31,
100
+ "p": 0.5504,
101
+ "r_base": 0.6131,
102
+ "r_between_models": 0.803,
103
+ "r_struct": 0.6634,
104
+ "t": 0.604
105
+ }
106
+ }
artifacts/pimt_v8_stats_tests_report.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PIMT v8 statistical validation tests
2
+
3
+ Substantivity split: n=34, structure=`structure_full_gbm`, baseline=`baseline_physical_gbm`.
4
+
5
+ ## Verdict
6
+
7
+ - Structure beats the physicochemical baseline as an R2 claim, not as a Spearman-rho claim.
8
+ - The Williams dependent-correlation cross-check does not support a significant rho difference.
9
+ - The drop-10 rho gain is not specific to the flagged materials under random-drop control.
10
+ - Character separation clears the permutation null both with and without wildcard, but remains small in magnitude.
11
+
12
+ ## Substantivity
13
+
14
+ | Test | Result |
15
+ | --- | --- |
16
+ | Paired bootstrap delta rho | observed=0.0503; 95% CI=(-0.1407, 0.2463); p=0.6178; excludes zero=False |
17
+ | Paired bootstrap delta R2 | observed=0.1584; 95% CI=(0.007, 0.3115); p=0.0410; excludes zero=True |
18
+ | Williams test | r_struct=0.6634; r_base=0.6131; r_between_models=0.8030; t=0.604; df=31; p=0.5504 |
19
+ | Random drop control | full_rho=0.6634; random_drop_mean=0.6579; 95% random-drop CI=(0.5074, 0.7967); flagged_rho=0.7085; flagged_percentile=74.7; specific_to_flagged=False |
20
+
21
+ ## Character
22
+
23
+ Label snapshot: `v8_2_clause_guard_dominance`; labelled formulas=3832; observed non-carrier character codes=23.
24
+
25
+ | Test | Observed | Null mean | Null 95% | p | Genuine |
26
+ | --- | ---: | ---: | ---: | ---: | --- |
27
+ | All 5 genres | 0.0800 | 0.0079 | 0.0103 | 0.0001 | True |
28
+ | Exclude wildcard | 0.0260 | 0.0092 | 0.0126 | 0.0001 | True |
scripts/pimt_v8_stats_tests.py CHANGED
@@ -9,15 +9,26 @@ Four tests that turn v8 point-estimate claims into tested claims:
9
  3. character_permutation_null -> is 26-class genre separation above chance?
10
  4. random_drop_control -> is the drop-10 gain specific to the flagged points?
11
 
12
- Dependencies: numpy, scipy. No sklearn needed.
13
- Plug your v8 arrays into the __main__ block (currently synthetic) and run.
 
14
  """
15
 
 
 
 
 
 
 
16
  import numpy as np
17
  from scipy.stats import spearmanr, rankdata, t as tdist
18
  from itertools import combinations
19
 
20
 
 
 
 
 
21
  # --------------------------------------------------------------------------- #
22
  # helpers
23
  # --------------------------------------------------------------------------- #
@@ -196,10 +207,13 @@ def random_drop_control(y_true, pred, k=10, n_iter=10000, seed=0, flagged_rho=No
196
  return out
197
 
198
 
199
- # --------------------------------------------------------------------------- #
200
- # demo / smoke test — replace synthetic data with your v8 arrays
201
- # --------------------------------------------------------------------------- #
202
- if __name__ == "__main__":
 
 
 
203
  rng = np.random.default_rng(20260710)
204
 
205
  # --- Tracks B: 34 held-out molecules -----------------------------------
@@ -208,22 +222,229 @@ if __name__ == "__main__":
208
  pred_struct = y * 0.66 + rng.normal(scale=0.75, size=n_test) # ~structure
209
  pred_base = y * 0.55 + rng.normal(scale=0.9, size=n_test) # ~baseline
210
 
211
- print("1. paired_bootstrap:")
212
- print(" ", paired_bootstrap(y, pred_struct, pred_base, n_boot=2000))
213
- print("2. williams_test:")
214
- print(" ", williams_test(y, pred_struct, pred_base))
215
 
216
  # drop-10: flagged result was rho=0.708 vs full 0.663 in v8
217
- print("4. random_drop_control:")
218
- print(" ", random_drop_control(y, pred_struct, k=10, n_iter=2000, flagged_rho=0.708))
219
 
220
  # --- Track A: character permutation null -------------------------------
221
  genres = ["amber_oriental", "citrus_cologne", "floral_woody", "fougere", "wildcard"]
222
  M, K = 300, 26
223
  formula_genre = rng.choice(genres, size=M)
224
  formula_class_vec = rng.random((M, K)) # near-null by construction
225
- print("3a. character_permutation_null (all 5 genres):")
226
- print(" ", character_permutation_null(formula_genre, formula_class_vec, genres, n_perm=1000))
227
- print("3b. character_permutation_null (drop wildcard):")
228
- print(" ", character_permutation_null(formula_genre, formula_class_vec, genres,
229
- n_perm=1000, exclude=("wildcard",)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  3. character_permutation_null -> is 26-class genre separation above chance?
10
  4. random_drop_control -> is the drop-10 gain specific to the flagged points?
11
 
12
+ Dependencies for the test procedures: numpy, scipy. No sklearn needed.
13
+ The default __main__ block is synthetic. Pass --v8-artifacts to build the real
14
+ v8 arrays from the existing repo diagnostics.
15
  """
16
 
17
+ import argparse
18
+ import json
19
+ import sys
20
+ from pathlib import Path
21
+ from typing import Any
22
+
23
  import numpy as np
24
  from scipy.stats import spearmanr, rankdata, t as tdist
25
  from itertools import combinations
26
 
27
 
28
+ ROOT = Path(__file__).resolve().parents[1]
29
+ ARTIFACTS = ROOT / "artifacts"
30
+
31
+
32
  # --------------------------------------------------------------------------- #
33
  # helpers
34
  # --------------------------------------------------------------------------- #
 
207
  return out
208
 
209
 
210
+ def _print_result(title, result):
211
+ print(title)
212
+ print(" ", result)
213
+
214
+
215
+ def _run_synthetic_demo():
216
+ """Demo / smoke test using synthetic arrays."""
217
  rng = np.random.default_rng(20260710)
218
 
219
  # --- Tracks B: 34 held-out molecules -----------------------------------
 
222
  pred_struct = y * 0.66 + rng.normal(scale=0.75, size=n_test) # ~structure
223
  pred_base = y * 0.55 + rng.normal(scale=0.9, size=n_test) # ~baseline
224
 
225
+ _print_result("1. paired_bootstrap:", paired_bootstrap(y, pred_struct, pred_base, n_boot=2000))
226
+ _print_result("2. williams_test:", williams_test(y, pred_struct, pred_base))
 
 
227
 
228
  # drop-10: flagged result was rho=0.708 vs full 0.663 in v8
229
+ _print_result("4. random_drop_control:", random_drop_control(y, pred_struct, k=10, n_iter=2000, flagged_rho=0.708))
 
230
 
231
  # --- Track A: character permutation null -------------------------------
232
  genres = ["amber_oriental", "citrus_cologne", "floral_woody", "fougere", "wildcard"]
233
  M, K = 300, 26
234
  formula_genre = rng.choice(genres, size=M)
235
  formula_class_vec = rng.random((M, K)) # near-null by construction
236
+ _print_result(
237
+ "3a. character_permutation_null (all 5 genres):",
238
+ character_permutation_null(formula_genre, formula_class_vec, genres, n_perm=1000),
239
+ )
240
+ _print_result(
241
+ "3b. character_permutation_null (drop wildcard):",
242
+ character_permutation_null(formula_genre, formula_class_vec, genres, n_perm=1000, exclude=("wildcard",)),
243
+ )
244
+
245
+
246
+ def _load_v8_substantivity_arrays(seed: int, test_fraction: float) -> dict[str, Any]:
247
+ """Build y/test prediction arrays for the saved v8 scaffold split."""
248
+ sys.path.insert(0, str(ROOT / "scripts"))
249
+ import phase1_recompute_v8 as phase1 # noqa: PLC0415
250
+
251
+ report = json.loads((ARTIFACTS / "phase1_recompute_v8.json").read_text())
252
+ payload = phase1.compute_predictions(seed, test_fraction, fetch_pubchem=False)
253
+ structure_key = report["prefer_measured"]["best_structure_model"]
254
+ baseline_key = report["prefer_measured"]["best_baseline"]
255
+ y_true = payload["y"][payload["test_idx"]]
256
+ pred_struct = payload["predictions"][structure_key]
257
+ pred_base = payload["predictions"][baseline_key]
258
+ flagged_rho = report["drop_10"]["results"][report["drop_10"]["best_structure_model"]]["spearman_rho"]
259
+ return {
260
+ "y_true": y_true,
261
+ "pred_struct": pred_struct,
262
+ "pred_base": pred_base,
263
+ "structure_key": structure_key,
264
+ "baseline_key": baseline_key,
265
+ "n_test": int(len(y_true)),
266
+ "flagged_rho": float(flagged_rho),
267
+ }
268
+
269
+
270
+ def _load_v8_character_arrays() -> dict[str, Any]:
271
+ """Build formula-level 26-class character indicator vectors."""
272
+ sys.path.insert(0, str(ROOT / "scripts"))
273
+ import build_odour_taxonomy_census_v8 as census # noqa: PLC0415
274
+ import character_grouping_diagnostic_v8 as character # noqa: PLC0415
275
+
276
+ report = json.loads((ARTIFACTS / "character_grouping_diagnostic_v8.json").read_text())
277
+ primary = report["primary_snapshot_result"]
278
+ labels_path = ROOT / primary["label_path"]
279
+ records = census.load_formula_records()
280
+ labels = {row["cas"]: row for row in character.load_jsonl(labels_path)}
281
+ rows = character.formula_character_rows(records, labels)
282
+ codes = sorted({
283
+ code
284
+ for label in labels.values()
285
+ for code in character.label_codes(label)
286
+ if code not in {"Z", "carrier"}
287
+ })
288
+ code_index = {code: idx for idx, code in enumerate(codes)}
289
+ formula_genre = []
290
+ formula_class_vec = np.zeros((len(rows), len(codes)), dtype=float)
291
+ for row_idx, row in enumerate(rows):
292
+ formula_genre.append(row["genre"])
293
+ for code in row["classes"]:
294
+ if code in code_index:
295
+ formula_class_vec[row_idx, code_index[code]] = 1.0
296
+ genres = sorted(set(formula_genre))
297
+ return {
298
+ "formula_genre": np.asarray(formula_genre),
299
+ "formula_class_vec": formula_class_vec,
300
+ "genres": genres,
301
+ "codes": codes,
302
+ "label_snapshot": report["primary_snapshot"],
303
+ "n_labelled_formulas": int(len(rows)),
304
+ }
305
+
306
+
307
+ def _write_v8_markdown(report: dict[str, Any]) -> None:
308
+ paired = report["paired_bootstrap"]
309
+ williams = report["williams_test"]
310
+ drop = report["random_drop_control"]
311
+ char_all = report["character_permutation_null_all_genres"]
312
+ char_drop = report["character_permutation_null_drop_wildcard"]
313
+ md = [
314
+ "# PIMT v8 statistical validation tests",
315
+ "",
316
+ f"Substantivity split: n={report['substantivity']['n_test']}, "
317
+ f"structure=`{report['substantivity']['structure_key']}`, "
318
+ f"baseline=`{report['substantivity']['baseline_key']}`.",
319
+ "",
320
+ "## Verdict",
321
+ "",
322
+ "- Structure beats the physicochemical baseline as an R2 claim, not as a Spearman-rho claim.",
323
+ "- The Williams dependent-correlation cross-check does not support a significant rho difference.",
324
+ "- The drop-10 rho gain is not specific to the flagged materials under random-drop control.",
325
+ "- Character separation clears the permutation null both with and without wildcard, but remains small in magnitude.",
326
+ "",
327
+ "## Substantivity",
328
+ "",
329
+ "| Test | Result |",
330
+ "| --- | --- |",
331
+ f"| Paired bootstrap delta rho | observed={paired['delta_rho']['observed']:.4f}; "
332
+ f"95% CI={tuple(paired['delta_rho']['ci95'])}; p={paired['delta_rho']['p_two_sided']:.4f}; "
333
+ f"excludes zero={paired['delta_rho']['excludes_zero']} |",
334
+ f"| Paired bootstrap delta R2 | observed={paired['delta_r2']['observed']:.4f}; "
335
+ f"95% CI={tuple(paired['delta_r2']['ci95'])}; p={paired['delta_r2']['p_two_sided']:.4f}; "
336
+ f"excludes zero={paired['delta_r2']['excludes_zero']} |",
337
+ f"| Williams test | r_struct={williams['r_struct']:.4f}; r_base={williams['r_base']:.4f}; "
338
+ f"r_between_models={williams['r_between_models']:.4f}; t={williams['t']:.3f}; "
339
+ f"df={williams['df']}; p={williams['p']:.4f} |",
340
+ f"| Random drop control | full_rho={drop['full_rho']:.4f}; random_drop_mean={drop['random_drop_mean']:.4f}; "
341
+ f"95% random-drop CI={tuple(drop['random_drop_ci95'])}; flagged_rho={drop['flagged_rho']:.4f}; "
342
+ f"flagged_percentile={drop['flagged_percentile']:.1f}; specific_to_flagged={drop['specific_to_flagged']} |",
343
+ "",
344
+ "## Character",
345
+ "",
346
+ f"Label snapshot: `{report['character']['label_snapshot']}`; "
347
+ f"labelled formulas={report['character']['n_labelled_formulas']}; "
348
+ f"observed non-carrier character codes={report['character']['n_character_codes']}.",
349
+ "",
350
+ "| Test | Observed | Null mean | Null 95% | p | Genuine |",
351
+ "| --- | ---: | ---: | ---: | ---: | --- |",
352
+ f"| All 5 genres | {char_all['observed']:.4f} | {char_all['null_mean']:.4f} | "
353
+ f"{char_all['null_95']:.4f} | {char_all['p_value']:.4f} | {char_all['genuine']} |",
354
+ f"| Exclude wildcard | {char_drop['observed']:.4f} | {char_drop['null_mean']:.4f} | "
355
+ f"{char_drop['null_95']:.4f} | {char_drop['p_value']:.4f} | {char_drop['genuine']} |",
356
+ "",
357
+ ]
358
+ (ARTIFACTS / "pimt_v8_stats_tests_report.md").write_text("\n".join(md), encoding="utf-8")
359
+
360
+
361
+ def _run_v8_artifacts(args):
362
+ sub = _load_v8_substantivity_arrays(args.seed, args.test_fraction)
363
+ char = _load_v8_character_arrays()
364
+ report = {
365
+ "pimt_version": "v8",
366
+ "diagnostic": "statistical_validation_tests",
367
+ "substantivity": {
368
+ "n_test": sub["n_test"],
369
+ "structure_key": sub["structure_key"],
370
+ "baseline_key": sub["baseline_key"],
371
+ "flagged_rho": sub["flagged_rho"],
372
+ },
373
+ "character": {
374
+ "label_snapshot": char["label_snapshot"],
375
+ "n_labelled_formulas": char["n_labelled_formulas"],
376
+ "genres": char["genres"],
377
+ "n_character_codes": len(char["codes"]),
378
+ "character_codes": char["codes"],
379
+ },
380
+ "paired_bootstrap": paired_bootstrap(
381
+ sub["y_true"], sub["pred_struct"], sub["pred_base"], n_boot=args.n_boot, seed=args.seed
382
+ ),
383
+ "williams_test": williams_test(sub["y_true"], sub["pred_struct"], sub["pred_base"]),
384
+ "random_drop_control": random_drop_control(
385
+ sub["y_true"], sub["pred_struct"], k=10, n_iter=args.n_iter, seed=args.seed, flagged_rho=sub["flagged_rho"]
386
+ ),
387
+ "character_permutation_null_all_genres": character_permutation_null(
388
+ char["formula_genre"], char["formula_class_vec"], char["genres"], n_perm=args.n_perm, seed=args.seed
389
+ ),
390
+ "character_permutation_null_drop_wildcard": character_permutation_null(
391
+ char["formula_genre"],
392
+ char["formula_class_vec"],
393
+ char["genres"],
394
+ n_perm=args.n_perm,
395
+ seed=args.seed,
396
+ exclude=("wildcard",),
397
+ ),
398
+ }
399
+ report["verdict"] = {
400
+ "substantivity": (
401
+ "structure_beats_baseline_on_r2_only"
402
+ if report["paired_bootstrap"]["delta_r2"]["excludes_zero"]
403
+ and not report["paired_bootstrap"]["delta_rho"]["excludes_zero"]
404
+ else "see_paired_bootstrap"
405
+ ),
406
+ "rho_cross_check": (
407
+ "not_significant"
408
+ if report["williams_test"]["p"] >= 0.05
409
+ else "significant"
410
+ ),
411
+ "drop10": (
412
+ "not_specific_to_flagged"
413
+ if not report["random_drop_control"]["specific_to_flagged"]
414
+ else "specific_to_flagged"
415
+ ),
416
+ "character": (
417
+ "genuine_with_and_without_wildcard"
418
+ if report["character_permutation_null_all_genres"]["genuine"]
419
+ and report["character_permutation_null_drop_wildcard"]["genuine"]
420
+ else "see_permutation_tests"
421
+ ),
422
+ }
423
+ print(json.dumps(report, indent=2, sort_keys=True))
424
+ if args.write_artifacts:
425
+ ARTIFACTS.mkdir(exist_ok=True)
426
+ (ARTIFACTS / "pimt_v8_stats_tests_report.json").write_text(
427
+ json.dumps(report, indent=2, sort_keys=True) + "\n",
428
+ encoding="utf-8",
429
+ )
430
+ _write_v8_markdown(report)
431
+
432
+
433
+ def main():
434
+ parser = argparse.ArgumentParser()
435
+ parser.add_argument("--v8-artifacts", action="store_true", help="run against current v8 repo artifacts")
436
+ parser.add_argument("--write-artifacts", action="store_true", help="write JSON/MD reports under artifacts/")
437
+ parser.add_argument("--seed", type=int, default=20260710)
438
+ parser.add_argument("--test-fraction", type=float, default=0.2)
439
+ parser.add_argument("--n-boot", type=int, default=10000)
440
+ parser.add_argument("--n-perm", type=int, default=10000)
441
+ parser.add_argument("--n-iter", type=int, default=10000)
442
+ args = parser.parse_args()
443
+ if args.v8_artifacts:
444
+ _run_v8_artifacts(args)
445
+ else:
446
+ _run_synthetic_demo()
447
+
448
+
449
+ if __name__ == "__main__":
450
+ main()