Matthew Ford commited on
Commit
848a7a5
·
1 Parent(s): 8553abb

fix(v11): preregister mode-aware retrieval evaluation

Browse files

Former-commit-id: 2235f151e5157b07d00bbc083e50aab0252c1b58
Former-commit-id: 769d2edfb6e0dc2b9bcd56ef01084ef96361b861

artifacts/pimt_v11_evaluation_protocol.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "protocol_id": "pimt-v11-retrieval-eval-1",
3
+ "status": "preregistered-before-v11.1-evaluation",
4
+ "confidence_interval": {
5
+ "confidence_level": 0.95,
6
+ "method": "wilson-score",
7
+ "reporting_rule": "Report numerator, denominator, and interval; do not report a bare point estimate."
8
+ },
9
+ "answer_shapes": {
10
+ "single_material": "A hit requires the one documented material in the top-k results.",
11
+ "any_of": "A hit requires at least one preregistered acceptable material in the top-k results.",
12
+ "accord": "A hit requires every preregistered accord component in the top-k results. Partial component recall is diagnostic only and never counts as a headline hit."
13
+ },
14
+ "mode_rule": "Score each row using its own preregistered mode. A global mode may be used only as an explicitly labelled sensitivity analysis.",
15
+ "accounting_rule": {
16
+ "excluded": "A row is excluded before ranking when its target or any answer material required by its answer shape lacks a profile.",
17
+ "missed": "An evaluable row is missed only when the preregistered answer rule is not satisfied by the top-k results.",
18
+ "identity": "n_total = n_excluded + n_evaluable and n_evaluable = n_hit + n_missed"
19
+ },
20
+ "baselines": {
21
+ "random": {
22
+ "role": "sanity-floor",
23
+ "rule": "Deterministic SHA-256 ordering of eligible candidates, keyed by pair_id."
24
+ },
25
+ "physicochemical_only": {
26
+ "role": "primary-baseline",
27
+ "rule": "Use the same row mode and candidate pool after removing odor descriptor distributions."
28
+ }
29
+ },
30
+ "primary_comparison": "full-profile versus physicochemical-only"
31
+ }
scripts/pimt_v11_build.py CHANGED
@@ -20,6 +20,7 @@ from pino.materials import MATERIALS # noqa: E402
20
  from pino.substitution_v11 import ( # noqa: E402
21
  PIMT_V11,
22
  descriptor_distribution_from_codes,
 
23
  evaluate_formula,
24
  evaluate_material,
25
  evaluate_retriever,
@@ -667,23 +668,60 @@ def build_profiles() -> list[dict[str, Any]]:
667
 
668
 
669
  def report_descriptor_external_delta(eval_rows: list[dict[str, Any]], profiles: list[dict[str, Any]]) -> dict[str, Any]:
670
- full = evaluate_retriever(eval_rows, profiles, mode="function_match", top_k=5)
671
  no_desc_profiles = [{**row, "descriptor_distribution": {}} for row in profiles]
672
- physchem_only = evaluate_retriever(eval_rows, no_desc_profiles, mode="function_match", top_k=5)
673
- delta = full["top_k_hit_rate"] - physchem_only["top_k_hit_rate"]
 
 
 
 
 
 
 
674
  return {
675
  "descriptor_validation_rule": "external eval only; no cosine self-consistency metric reported",
676
- "with_descriptors_top5_hit_rate": full["top_k_hit_rate"],
677
- "physchem_only_top5_hit_rate": physchem_only["top_k_hit_rate"],
678
- "external_hit_rate_delta": delta,
679
- "verdict": "kept" if delta >= 0 else "dropped",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
680
  }
681
 
682
 
 
 
 
 
 
 
 
683
  def write_reports(
684
  eval_rows: list[dict[str, Any]],
685
  profiles: list[dict[str, Any]],
686
  retrieval: dict[str, Any],
 
687
  descriptor_delta: dict[str, Any],
688
  ) -> None:
689
  ARTIFACTS.mkdir(exist_ok=True)
@@ -720,7 +758,7 @@ def write_reports(
720
  },
721
  "milestone_2": {"profile_path": "data/material_profiles_v11.jsonl", **profile_field_counts},
722
  "milestone_3": retrieval,
723
- "milestone_4": descriptor_delta,
724
  "milestone_5": {
725
  "formula_optimisation_layer": "scoped-only-not-built",
726
  "design_path": "artifacts/pimt_v11_formula_layer_design.md",
@@ -738,17 +776,23 @@ def write_reports(
738
  "sample_formula_assessment": sample_formula,
739
  }
740
  (ARTIFACTS / "pimt_v11_assessment.json").write_text(json.dumps(summary, indent=2, sort_keys=True), encoding="utf-8")
741
- md = f"""# PIMT v11 Substitution Retriever Assessment
742
 
743
  - Eval set: `data/substitution_eval_set_v11.jsonl`, n={len(eval_rows)}
744
  - Material profiles: `data/material_profiles_v11.jsonl`, n={len(profiles)}
745
- - Retriever mode: `{retrieval['mode']}`, top-{retrieval['top_k']} hit-rate={retrieval['top_k_hit_rate']:.3f} over n={retrieval['n_evaluable']} evaluable pairs; skipped={retrieval['n_skipped']}
 
 
 
 
 
746
  - Mean absolute substantivity delta on evaluable pairs: `{retrieval['mean_substantivity_delta_abs']}`
747
- - Descriptor external delta: {descriptor_delta['external_hit_rate_delta']:.3f}; verdict=`{descriptor_delta['verdict']}`
748
 
749
  ## Boundaries
750
 
751
  - Substitution pairs remain evaluation data only. No manufactured labels and no trained substitution ranker are created.
 
752
  - Descriptor distributions are validated only by external substitution hit-rate; no cosine self-consistency score is reported.
753
  - v10 substantivity is used as a ranking prior/penalty, not as a generator.
754
  - IFRA/allergen/use-level, cost, and availability fields are marked `enrichment_pending`.
@@ -779,7 +823,14 @@ def main() -> None:
779
  args = parser.parse_args()
780
  DATA.mkdir(exist_ok=True)
781
  ARTIFACTS.mkdir(exist_ok=True)
782
- write_jsonl(DATA / "substitution_eval_set_v11.jsonl", SUBSTITUTION_EVAL_ROWS)
 
 
 
 
 
 
 
783
  profiles = build_profiles()
784
  write_jsonl(DATA / "material_profiles_v11.jsonl", profiles)
785
  descriptor_rows = [
@@ -794,8 +845,9 @@ def main() -> None:
794
  if row.get("descriptor_distribution")
795
  ]
796
  write_jsonl(DATA / "descriptor_distributions_v11.jsonl", descriptor_rows)
797
- retrieval = evaluate_retriever(SUBSTITUTION_EVAL_ROWS, profiles, mode="function_match", top_k=args.top_k)
798
- descriptor_delta = report_descriptor_external_delta(SUBSTITUTION_EVAL_ROWS, profiles)
 
799
  (ARTIFACTS / "pimt_v11_retriever_eval.json").write_text(
800
  json.dumps(retrieval, indent=2, sort_keys=True),
801
  encoding="utf-8",
@@ -804,17 +856,21 @@ def main() -> None:
804
  json.dumps(descriptor_delta, indent=2, sort_keys=True),
805
  encoding="utf-8",
806
  )
807
- write_reports(SUBSTITUTION_EVAL_ROWS, profiles, retrieval, descriptor_delta)
808
  print(
809
  json.dumps(
810
  {
811
  "pimt_version": PIMT_V11,
812
  "eval_pairs": len(SUBSTITUTION_EVAL_ROWS),
813
  "profiles": len(profiles),
814
- "top5_hit_rate": retrieval["top_k_hit_rate"],
815
  "n_evaluable": retrieval["n_evaluable"],
816
- "descriptor_delta": descriptor_delta["external_hit_rate_delta"],
817
- "descriptor_verdict": descriptor_delta["verdict"],
 
 
 
 
818
  },
819
  indent=2,
820
  )
 
20
  from pino.substitution_v11 import ( # noqa: E402
21
  PIMT_V11,
22
  descriptor_distribution_from_codes,
23
+ explicit_eval_row,
24
  evaluate_formula,
25
  evaluate_material,
26
  evaluate_retriever,
 
668
 
669
 
670
  def report_descriptor_external_delta(eval_rows: list[dict[str, Any]], profiles: list[dict[str, Any]]) -> dict[str, Any]:
671
+ full = evaluate_retriever(eval_rows, profiles, top_k=5)
672
  no_desc_profiles = [{**row, "descriptor_distribution": {}} for row in profiles]
673
+ physchem_only = evaluate_retriever(eval_rows, no_desc_profiles, top_k=5)
674
+ full_interval = full["top_k_hit"]["wilson_95"]
675
+ baseline_interval = physchem_only["top_k_hit"]["wilson_95"]
676
+ intervals_overlap = bool(
677
+ full_interval
678
+ and baseline_interval
679
+ and full_interval[0] <= baseline_interval[1]
680
+ and baseline_interval[0] <= full_interval[1]
681
+ )
682
  return {
683
  "descriptor_validation_rule": "external eval only; no cosine self-consistency metric reported",
684
+ "primary_baseline": "physicochemical_only",
685
+ "with_descriptors_top5_hit": full["top_k_hit"],
686
+ "physicochemical_only_top5_hit": physchem_only["top_k_hit"],
687
+ "hit_count_difference": full["n_hit"] - physchem_only["n_hit"],
688
+ "wilson_intervals_overlap": intervals_overlap,
689
+ "comparative_conclusion": (
690
+ "no_demonstrated_advantage_over_physicochemical_only"
691
+ if intervals_overlap
692
+ else "interval_separation_favors_full_profile"
693
+ if full["n_hit"] > physchem_only["n_hit"]
694
+ else "interval_separation_favors_physicochemical_only"
695
+ ),
696
+ }
697
+
698
+
699
+ def evaluate_baselines(eval_rows: list[dict[str, Any]], profiles: list[dict[str, Any]], top_k: int) -> dict[str, Any]:
700
+ no_desc_profiles = [{**row, "descriptor_distribution": {}} for row in profiles]
701
+ return {
702
+ "primary": "physicochemical_only",
703
+ "physicochemical_only": evaluate_retriever(eval_rows, no_desc_profiles, top_k=top_k),
704
+ "random_sanity_floor": evaluate_retriever(
705
+ eval_rows,
706
+ profiles,
707
+ top_k=top_k,
708
+ ranking_strategy="random",
709
+ ),
710
  }
711
 
712
 
713
+ def _wilson_text(result: dict[str, Any]) -> str:
714
+ metric = result["top_k_hit"]
715
+ interval = metric["wilson_95"]
716
+ interval_text = "undefined" if interval is None else f"[{interval[0]:.3f}, {interval[1]:.3f}]"
717
+ return f"{metric['successes']}/{metric['total']}; 95% Wilson {interval_text}"
718
+
719
+
720
  def write_reports(
721
  eval_rows: list[dict[str, Any]],
722
  profiles: list[dict[str, Any]],
723
  retrieval: dict[str, Any],
724
+ baselines: dict[str, Any],
725
  descriptor_delta: dict[str, Any],
726
  ) -> None:
727
  ARTIFACTS.mkdir(exist_ok=True)
 
758
  },
759
  "milestone_2": {"profile_path": "data/material_profiles_v11.jsonl", **profile_field_counts},
760
  "milestone_3": retrieval,
761
+ "milestone_4": {"baselines": baselines, "descriptor_external_validation": descriptor_delta},
762
  "milestone_5": {
763
  "formula_optimisation_layer": "scoped-only-not-built",
764
  "design_path": "artifacts/pimt_v11_formula_layer_design.md",
 
776
  "sample_formula_assessment": sample_formula,
777
  }
778
  (ARTIFACTS / "pimt_v11_assessment.json").write_text(json.dumps(summary, indent=2, sort_keys=True), encoding="utf-8")
779
+ md = f"""# PIMT v11.1 Substitution Retriever Assessment
780
 
781
  - Eval set: `data/substitution_eval_set_v11.jsonl`, n={len(eval_rows)}
782
  - Material profiles: `data/material_profiles_v11.jsonl`, n={len(profiles)}
783
+ - Retriever modes: row-specific `{retrieval['mode_counts']}`
784
+ - Full-profile top-{retrieval['top_k']} hit: {_wilson_text(retrieval)}
785
+ - Full-profile by-mode hit: `{retrieval['by_mode_top_k_hit']}`
786
+ - Physicochemical-only primary baseline: {_wilson_text(baselines['physicochemical_only'])}
787
+ - Deterministic-random sanity floor: {_wilson_text(baselines['random_sanity_floor'])}
788
+ - Accounting: n-total={retrieval['n_eval_rows']}, n-evaluable={retrieval['n_evaluable']}, n-excluded={retrieval['n_excluded']}, n-hit={retrieval['n_hit']}, n-missed={retrieval['n_missed']}
789
  - Mean absolute substantivity delta on evaluable pairs: `{retrieval['mean_substantivity_delta_abs']}`
790
+ - Full minus physicochemical-only hit-count difference: {descriptor_delta['hit_count_difference']}; conclusion=`{descriptor_delta['comparative_conclusion']}`
791
 
792
  ## Boundaries
793
 
794
  - Substitution pairs remain evaluation data only. No manufactured labels and no trained substitution ranker are created.
795
+ - The accord scoring rule was preregistered in `artifacts/pimt_v11_evaluation_protocol.json`: every documented component is required; partial component recall is diagnostic only.
796
  - Descriptor distributions are validated only by external substitution hit-rate; no cosine self-consistency score is reported.
797
  - v10 substantivity is used as a ranking prior/penalty, not as a generator.
798
  - IFRA/allergen/use-level, cost, and availability fields are marked `enrichment_pending`.
 
823
  args = parser.parse_args()
824
  DATA.mkdir(exist_ok=True)
825
  ARTIFACTS.mkdir(exist_ok=True)
826
+ protocol_path = ARTIFACTS / "pimt_v11_evaluation_protocol.json"
827
+ if not protocol_path.exists():
828
+ raise RuntimeError("evaluation protocol must be preregistered before running v11.1")
829
+ protocol = json.loads(protocol_path.read_text(encoding="utf-8"))
830
+ if protocol.get("status") != "preregistered-before-v11.1-evaluation":
831
+ raise RuntimeError("evaluation protocol is not marked preregistered")
832
+ eval_rows = [explicit_eval_row(row) for row in SUBSTITUTION_EVAL_ROWS]
833
+ write_jsonl(DATA / "substitution_eval_set_v11.jsonl", eval_rows)
834
  profiles = build_profiles()
835
  write_jsonl(DATA / "material_profiles_v11.jsonl", profiles)
836
  descriptor_rows = [
 
845
  if row.get("descriptor_distribution")
846
  ]
847
  write_jsonl(DATA / "descriptor_distributions_v11.jsonl", descriptor_rows)
848
+ retrieval = evaluate_retriever(eval_rows, profiles, top_k=args.top_k)
849
+ baselines = evaluate_baselines(eval_rows, profiles, top_k=args.top_k)
850
+ descriptor_delta = report_descriptor_external_delta(eval_rows, profiles)
851
  (ARTIFACTS / "pimt_v11_retriever_eval.json").write_text(
852
  json.dumps(retrieval, indent=2, sort_keys=True),
853
  encoding="utf-8",
 
856
  json.dumps(descriptor_delta, indent=2, sort_keys=True),
857
  encoding="utf-8",
858
  )
859
+ write_reports(eval_rows, profiles, retrieval, baselines, descriptor_delta)
860
  print(
861
  json.dumps(
862
  {
863
  "pimt_version": PIMT_V11,
864
  "eval_pairs": len(SUBSTITUTION_EVAL_ROWS),
865
  "profiles": len(profiles),
866
+ "top5_hit": retrieval["top_k_hit"],
867
  "n_evaluable": retrieval["n_evaluable"],
868
+ "n_excluded": retrieval["n_excluded"],
869
+ "n_missed": retrieval["n_missed"],
870
+ "physicochemical_only_top5_hit": baselines["physicochemical_only"]["top_k_hit"],
871
+ "random_sanity_floor_top5_hit": baselines["random_sanity_floor"]["top_k_hit"],
872
+ "descriptor_hit_count_difference": descriptor_delta["hit_count_difference"],
873
+ "descriptor_comparative_conclusion": descriptor_delta["comparative_conclusion"],
874
  },
875
  indent=2,
876
  )
src/pino/substitution_v11.py CHANGED
@@ -1,5 +1,6 @@
1
  from __future__ import annotations
2
 
 
3
  import json
4
  import math
5
  from collections import Counter
@@ -9,6 +10,7 @@ from typing import Any, Iterable
9
  import numpy as np
10
 
11
  PIMT_V11 = "v11"
 
12
 
13
 
14
  def load_jsonl(path: str | Path) -> list[dict[str, Any]]:
@@ -24,6 +26,52 @@ def write_jsonl(path: str | Path, rows: Iterable[dict[str, Any]]) -> None:
24
  )
25
 
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def normalize_name(value: str | None) -> str:
28
  if not value:
29
  return ""
@@ -233,41 +281,89 @@ def evaluate_formula(formula: list[dict[str, Any]], profiles: list[dict[str, Any
233
  def evaluate_retriever(
234
  eval_rows: list[dict[str, Any]],
235
  profiles: list[dict[str, Any]],
236
- mode: str = "function_match",
237
  top_k: int = 5,
 
238
  ) -> dict[str, Any]:
 
 
239
  lookup = profile_lookup(profiles)
240
  evaluated = []
241
- skipped = []
242
- for row in eval_rows:
 
 
 
243
  target_key = row.get("target_cas") or row.get("target")
244
- expected_keys = [row.get("substitute_cas"), row.get("substitute")]
245
  if not (lookup.get(str(target_key)) or lookup.get(normalize_name(str(target_key)))):
246
- skipped.append({"pair_id": row["pair_id"], "reason": "target_missing_profile"})
247
  continue
248
- if not any(lookup.get(str(key)) or lookup.get(normalize_name(str(key))) for key in expected_keys if key):
249
- skipped.append({"pair_id": row["pair_id"], "reason": "documented_substitute_missing_profile"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  continue
251
- ranked = substitute(str(target_key), profiles, mode=mode, top_k=top_k)
252
- rank_names = {normalize_name(r["candidate"]) for r in ranked}
253
- rank_cas = {str(r.get("candidate_cas")) for r in ranked if r.get("candidate_cas")}
254
- hit = any(
255
- str(key) in rank_cas or normalize_name(str(key)) in rank_names
256
- for key in expected_keys
257
- if key
258
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259
  target_profile = lookup.get(str(target_key)) or lookup.get(normalize_name(str(target_key)))
260
- substitute_profile = next(
261
- (lookup.get(str(key)) or lookup.get(normalize_name(str(key))) for key in expected_keys if key),
262
- None,
263
- )
264
  evaluated.append(
265
  {
266
  "pair_id": row["pair_id"],
267
  "grade": row["grade"],
 
 
268
  "hit_top_k": bool(hit),
269
  "top_k": ranked,
270
- "documented_substitute": row.get("substitute"),
 
 
 
271
  "substantivity_delta_abs": (
272
  abs(
273
  float(target_profile.get("substantivity_log10_predicted"))
@@ -282,17 +378,30 @@ def evaluate_retriever(
282
  }
283
  )
284
  n = len(evaluated)
285
- hit_rate = sum(1 for row in evaluated if row["hit_top_k"]) / n if n else 0.0
 
 
 
 
 
 
 
 
286
  subst_deltas = [row["substantivity_delta_abs"] for row in evaluated if row["substantivity_delta_abs"] is not None]
287
  return {
288
  "pimt_version": PIMT_V11,
289
- "mode": mode,
 
 
290
  "top_k": top_k,
291
  "n_eval_rows": len(eval_rows),
292
  "n_evaluable": n,
293
- "n_skipped": len(skipped),
294
- "top_k_hit_rate": hit_rate,
 
 
 
295
  "mean_substantivity_delta_abs": float(np.mean(subst_deltas)) if subst_deltas else None,
296
  "evaluated": evaluated,
297
- "skipped": skipped,
298
  }
 
1
  from __future__ import annotations
2
 
3
+ import hashlib
4
  import json
5
  import math
6
  from collections import Counter
 
10
  import numpy as np
11
 
12
  PIMT_V11 = "v11"
13
+ ANSWER_SHAPES = {"single_material", "any_of", "accord"}
14
 
15
 
16
  def load_jsonl(path: str | Path) -> list[dict[str, Any]]:
 
26
  )
27
 
28
 
29
+ def wilson_interval(successes: int, total: int, z: float = 1.959963984540054) -> dict[str, Any]:
30
+ """Return count-first 95% Wilson score reporting for a binomial proportion."""
31
+ if total < 0 or successes < 0 or successes > total:
32
+ raise ValueError("Wilson counts must satisfy 0 <= successes <= total")
33
+ if total == 0:
34
+ return {"successes": successes, "total": total, "wilson_95": None}
35
+ proportion = successes / total
36
+ z2 = z * z
37
+ denominator = 1.0 + z2 / total
38
+ center = (proportion + z2 / (2.0 * total)) / denominator
39
+ half_width = z * math.sqrt(
40
+ (proportion * (1.0 - proportion) + z2 / (4.0 * total)) / total
41
+ ) / denominator
42
+ return {
43
+ "successes": successes,
44
+ "total": total,
45
+ "wilson_95": [max(0.0, center - half_width), min(1.0, center + half_width)],
46
+ }
47
+
48
+
49
+ def explicit_eval_row(row: dict[str, Any]) -> dict[str, Any]:
50
+ """Upgrade a legacy one-substitute row to the explicit v11.1 answer schema."""
51
+ if "answer" in row:
52
+ return row
53
+ return {
54
+ **row,
55
+ "answer": {
56
+ "shape": "single_material",
57
+ "materials": [{"name": row.get("substitute"), "cas": row.get("substitute_cas")}],
58
+ },
59
+ }
60
+
61
+
62
+ def _answer(row: dict[str, Any]) -> tuple[str, list[dict[str, Any]]]:
63
+ answer = explicit_eval_row(row)["answer"]
64
+ shape = answer.get("shape")
65
+ materials = answer.get("materials") or []
66
+ if shape not in ANSWER_SHAPES:
67
+ raise ValueError(f"unsupported answer shape for {row.get('pair_id')}: {shape!r}")
68
+ if not materials or any(not (item.get("cas") or item.get("name")) for item in materials):
69
+ raise ValueError(f"answer materials missing for {row.get('pair_id')}")
70
+ if shape == "single_material" and len(materials) != 1:
71
+ raise ValueError(f"single_material answer must contain exactly one material: {row.get('pair_id')}")
72
+ return str(shape), materials
73
+
74
+
75
  def normalize_name(value: str | None) -> str:
76
  if not value:
77
  return ""
 
281
  def evaluate_retriever(
282
  eval_rows: list[dict[str, Any]],
283
  profiles: list[dict[str, Any]],
284
+ mode: str | None = None,
285
  top_k: int = 5,
286
+ ranking_strategy: str = "model",
287
  ) -> dict[str, Any]:
288
+ if ranking_strategy not in {"model", "random"}:
289
+ raise ValueError(f"unknown ranking strategy: {ranking_strategy}")
290
  lookup = profile_lookup(profiles)
291
  evaluated = []
292
+ excluded = []
293
+ mode_counts = Counter()
294
+ for legacy_row in eval_rows:
295
+ row = explicit_eval_row(legacy_row)
296
+ shape, answer_materials = _answer(row)
297
  target_key = row.get("target_cas") or row.get("target")
 
298
  if not (lookup.get(str(target_key)) or lookup.get(normalize_name(str(target_key)))):
299
+ excluded.append({"pair_id": row["pair_id"], "reason": "target_missing_profile"})
300
  continue
301
+ resolved_answers = []
302
+ missing_answers = []
303
+ for item in answer_materials:
304
+ keys = [item.get("cas"), item.get("name")]
305
+ profile = next(
306
+ (lookup.get(str(key)) or lookup.get(normalize_name(str(key))) for key in keys if key),
307
+ None,
308
+ )
309
+ if profile is None:
310
+ missing_answers.append(item)
311
+ else:
312
+ resolved_answers.append(profile)
313
+ insufficient = not resolved_answers if shape == "any_of" else bool(missing_answers)
314
+ if insufficient:
315
+ excluded.append(
316
+ {
317
+ "pair_id": row["pair_id"],
318
+ "reason": "answer_material_missing_profile",
319
+ "missing_answer_materials": missing_answers,
320
+ }
321
+ )
322
  continue
323
+ row_mode = mode or row.get("mode")
324
+ if row_mode not in MODE_WEIGHTS:
325
+ raise ValueError(f"unsupported retrieval mode for {row['pair_id']}: {row_mode!r}")
326
+ mode_counts[row_mode] += 1
327
+ if ranking_strategy == "model":
328
+ ranked = substitute(str(target_key), profiles, mode=row_mode, top_k=top_k)
329
+ else:
330
+ target_profile_key = profile_key(lookup.get(str(target_key)) or lookup[normalize_name(str(target_key))])
331
+ candidates = [profile for profile in profiles if profile_key(profile) != target_profile_key]
332
+ candidates.sort(
333
+ key=lambda profile: hashlib.sha256(
334
+ f"{row['pair_id']}|{profile_key(profile)}".encode("utf-8")
335
+ ).digest()
336
+ )
337
+ ranked = [
338
+ {"candidate": profile.get("name"), "candidate_cas": profile.get("cas")}
339
+ for profile in candidates[:top_k]
340
+ ]
341
+ ranked_keys = {
342
+ profile_key(profile)
343
+ for result in ranked
344
+ for profile in [
345
+ lookup.get(str(result.get("candidate_cas")))
346
+ or lookup.get(normalize_name(result.get("candidate")))
347
+ ]
348
+ if profile
349
+ }
350
+ answer_keys = {profile_key(profile) for profile in resolved_answers}
351
+ matched_keys = ranked_keys & answer_keys
352
+ hit = answer_keys <= ranked_keys if shape == "accord" else bool(matched_keys)
353
  target_profile = lookup.get(str(target_key)) or lookup.get(normalize_name(str(target_key)))
354
+ substitute_profile = resolved_answers[0]
 
 
 
355
  evaluated.append(
356
  {
357
  "pair_id": row["pair_id"],
358
  "grade": row["grade"],
359
+ "mode": row_mode,
360
+ "answer_shape": shape,
361
  "hit_top_k": bool(hit),
362
  "top_k": ranked,
363
+ "documented_answer": row["answer"],
364
+ "answer_components_retrieved": len(matched_keys),
365
+ "answer_components_total": len(answer_keys),
366
+ "unavailable_optional_answers": missing_answers if shape == "any_of" else [],
367
  "substantivity_delta_abs": (
368
  abs(
369
  float(target_profile.get("substantivity_log10_predicted"))
 
378
  }
379
  )
380
  n = len(evaluated)
381
+ n_hit = sum(1 for row in evaluated if row["hit_top_k"])
382
+ n_missed = n - n_hit
383
+ by_mode_top_k_hit = {}
384
+ for row_mode in sorted(mode_counts):
385
+ mode_rows = [row for row in evaluated if row["mode"] == row_mode]
386
+ by_mode_top_k_hit[row_mode] = wilson_interval(
387
+ sum(1 for row in mode_rows if row["hit_top_k"]),
388
+ len(mode_rows),
389
+ )
390
  subst_deltas = [row["substantivity_delta_abs"] for row in evaluated if row["substantivity_delta_abs"] is not None]
391
  return {
392
  "pimt_version": PIMT_V11,
393
+ "mode": mode or "per-row",
394
+ "mode_counts": dict(sorted(mode_counts.items())),
395
+ "ranking_strategy": ranking_strategy,
396
  "top_k": top_k,
397
  "n_eval_rows": len(eval_rows),
398
  "n_evaluable": n,
399
+ "n_excluded": len(excluded),
400
+ "n_hit": n_hit,
401
+ "n_missed": n_missed,
402
+ "top_k_hit": wilson_interval(n_hit, n),
403
+ "by_mode_top_k_hit": by_mode_top_k_hit,
404
  "mean_substantivity_delta_abs": float(np.mean(subst_deltas)) if subst_deltas else None,
405
  "evaluated": evaluated,
406
+ "excluded": excluded,
407
  }
tests/test_substitution_v11.py CHANGED
@@ -1,6 +1,6 @@
1
  from __future__ import annotations
2
 
3
- from pino.substitution_v11 import evaluate_formula, evaluate_material, evaluate_retriever, substitute
4
 
5
 
6
  def tiny_profiles():
@@ -57,16 +57,117 @@ def test_evaluate_retriever_uses_eval_rows_without_training():
57
  "substitute": "Documented Floral Substitute",
58
  "substitute_cas": "2",
59
  "grade": "acceptable",
 
60
  }
61
  ]
62
 
63
  result = evaluate_retriever(rows, tiny_profiles(), top_k=1)
64
 
65
  assert result["n_evaluable"] == 1
66
- assert result["top_k_hit_rate"] == 1.0
 
 
 
 
 
 
67
  assert "trained" not in result
68
 
69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  def test_assessment_interfaces_do_not_emit_safety_authority():
71
  material = evaluate_material("1", tiny_profiles())
72
  formula = evaluate_formula([{"cas": "1", "weight_fraction": 0.4}], tiny_profiles())
 
1
  from __future__ import annotations
2
 
3
+ from pino.substitution_v11 import evaluate_formula, evaluate_material, evaluate_retriever, substitute, wilson_interval
4
 
5
 
6
  def tiny_profiles():
 
57
  "substitute": "Documented Floral Substitute",
58
  "substitute_cas": "2",
59
  "grade": "acceptable",
60
+ "mode": "odor_match",
61
  }
62
  ]
63
 
64
  result = evaluate_retriever(rows, tiny_profiles(), top_k=1)
65
 
66
  assert result["n_evaluable"] == 1
67
+ assert result["n_hit"] == 1
68
+ assert result["n_missed"] == 0
69
+ assert result["n_excluded"] == 0
70
+ assert result["top_k_hit"] == wilson_interval(1, 1)
71
+ assert result["mode"] == "per-row"
72
+ assert result["mode_counts"] == {"odor_match": 1}
73
+ assert result["by_mode_top_k_hit"] == {"odor_match": wilson_interval(1, 1)}
74
  assert "trained" not in result
75
 
76
 
77
+ def test_evaluate_retriever_uses_each_rows_mode():
78
+ rows = [
79
+ {
80
+ "pair_id": "odor-row",
81
+ "target_cas": "1",
82
+ "substitute_cas": "2",
83
+ "grade": "acceptable",
84
+ "mode": "odor_match",
85
+ },
86
+ {
87
+ "pair_id": "function-row",
88
+ "target_cas": "1",
89
+ "substitute_cas": "2",
90
+ "grade": "acceptable",
91
+ "mode": "function_match",
92
+ },
93
+ ]
94
+
95
+ result = evaluate_retriever(rows, tiny_profiles(), top_k=1)
96
+
97
+ assert result["mode_counts"] == {"function_match": 1, "odor_match": 1}
98
+ assert [item["mode"] for item in result["evaluated"]] == ["odor_match", "function_match"]
99
+
100
+
101
+ def test_accord_requires_every_component_and_reports_component_recall():
102
+ rows = [
103
+ {
104
+ "pair_id": "accord-row",
105
+ "target_cas": "1",
106
+ "grade": "acceptable",
107
+ "mode": "accord_rebuild",
108
+ "answer": {
109
+ "shape": "accord",
110
+ "materials": [{"cas": "2"}, {"cas": "3"}],
111
+ },
112
+ }
113
+ ]
114
+
115
+ missed = evaluate_retriever(rows, tiny_profiles(), top_k=1)
116
+ hit = evaluate_retriever(rows, tiny_profiles(), top_k=2)
117
+
118
+ assert missed["n_missed"] == 1
119
+ assert missed["evaluated"][0]["answer_components_retrieved"] == 1
120
+ assert missed["evaluated"][0]["answer_components_total"] == 2
121
+ assert hit["n_hit"] == 1
122
+
123
+
124
+ def test_any_of_accepts_one_preregistered_alternative():
125
+ rows = [
126
+ {
127
+ "pair_id": "any-of-row",
128
+ "target_cas": "1",
129
+ "grade": "acceptable",
130
+ "mode": "function_match",
131
+ "answer": {
132
+ "shape": "any_of",
133
+ "materials": [{"cas": "2"}, {"cas": "3"}],
134
+ },
135
+ }
136
+ ]
137
+
138
+ result = evaluate_retriever(rows, tiny_profiles(), top_k=1)
139
+
140
+ assert result["n_hit"] == 1
141
+ assert result["evaluated"][0]["answer_components_retrieved"] == 1
142
+
143
+
144
+ def test_excluded_and_missed_are_separate_first_class_counts():
145
+ rows = [
146
+ {
147
+ "pair_id": "excluded",
148
+ "target_cas": "missing-target",
149
+ "substitute_cas": "2",
150
+ "grade": "acceptable",
151
+ "mode": "function_match",
152
+ },
153
+ {
154
+ "pair_id": "missed",
155
+ "target_cas": "1",
156
+ "substitute_cas": "3",
157
+ "grade": "acceptable",
158
+ "mode": "function_match",
159
+ },
160
+ ]
161
+
162
+ result = evaluate_retriever(rows, tiny_profiles(), top_k=1)
163
+
164
+ assert result["n_eval_rows"] == 2
165
+ assert result["n_excluded"] == 1
166
+ assert result["n_evaluable"] == 1
167
+ assert result["n_missed"] == 1
168
+ assert result["n_hit"] == 0
169
+
170
+
171
  def test_assessment_interfaces_do_not_emit_safety_authority():
172
  material = evaluate_material("1", tiny_profiles())
173
  formula = evaluate_formula([{"cas": "1", "weight_fraction": 0.4}], tiny_profiles())