Matthew Ford commited on
Commit
cc86172
·
1 Parent(s): 4947605

feat: low-evidence gating in substitution_v11 + wisemoor description provenance

Browse files

substitution_v11: stop manufacturing neutral 0.5 for unobserved features. Missing
features now yield None (evidence_coverage=0), a row needs >=2 mutually-observed
scoring components to count as a trustworthy retrieval, an answer resolving to the
target is excluded as invalid (not a miss), and unimplemented modes
(cost_match/regulatory_match without supporting data) are reported unsupported.
Wisemoor converters preserve source-observed description text as provenance
(description_provenance), never promoted to an assessor label. Tests cover the
three gating behaviours. .gitignore: add .venv-pom/, aroma.db, *.log, large v11.6
dataset jsonl.


Former-commit-id: ad4230835bac66729ed85e28cb52aafb628979df
Former-commit-id: ba6b13133db06e31e2256e4d2222f8a7795363f8

.gitignore CHANGED
@@ -67,3 +67,14 @@ data/odour_taxonomy_26.json
67
  data/per_material_signal_inspection_v8*.jsonl
68
  data/substantivity_targets_poucher_enriched_v8_phase1.jsonl
69
  data/substantivity_targets_poucher_tiers_v8.jsonl
 
 
 
 
 
 
 
 
 
 
 
 
67
  data/per_material_signal_inspection_v8*.jsonl
68
  data/substantivity_targets_poucher_enriched_v8_phase1.jsonl
69
  data/substantivity_targets_poucher_tiers_v8.jsonl
70
+
71
+ # v11.6 / A/B session additions (2026-07-17)
72
+ .venv-pom/
73
+ data/aroma.db
74
+ *.log
75
+ data/empirical_dataset_v9_plus_wisemoor_clean.jsonl
76
+ data/empirical_dataset_v9_plus_wisemoor_clean.repaired.jsonl
77
+ data/pimt_candidate_20260716_a_train.jsonl
78
+ data/repaired_formulas_v11_6*.jsonl
79
+ data/tgsc_demo_formulas_v2.repaired.jsonl
80
+ data/material_profiles_v11_6.jsonl
scripts/build_wisemoor_training_records.py CHANGED
@@ -111,6 +111,11 @@ def main() -> None:
111
  "source": candidate["source"],
112
  "source_url": candidate.get("source_url"),
113
  "source_name": candidate.get("name"),
 
 
 
 
 
114
  "wisemoor": candidate.get("metadata", {}),
115
  "concentrate_ratio": args.concentrate_ratio,
116
  }
 
111
  "source": candidate["source"],
112
  "source_url": candidate.get("source_url"),
113
  "source_name": candidate.get("name"),
114
+ "source_description": candidate.get("description"),
115
+ "source_notes": candidate.get("notes"),
116
+ "source_description_provenance": (
117
+ (candidate.get("metadata") or {}).get("description_provenance")
118
+ ),
119
  "wisemoor": candidate.get("metadata", {}),
120
  "concentrate_ratio": args.concentrate_ratio,
121
  }
scripts/convert_wisemoor_to_training_candidates.py CHANGED
@@ -787,6 +787,10 @@ def convert_record(
787
  "source": "wisemoor_labtorium_free_sanitized",
788
  "source_url": record.get("source_url"),
789
  "name": record.get("name"),
 
 
 
 
790
  "genre": "wisemoor_formula",
791
  "notes": record.get("notes"),
792
  "formula": formula,
@@ -797,6 +801,10 @@ def convert_record(
797
  "amount_coverage": amount_coverage,
798
  "unresolved_count": len(unresolved),
799
  "sanitized_source": str(Path("data/wisemoor_free_formulas.sanitized.jsonl")),
 
 
 
 
800
  },
801
  }
802
  return candidate, audit
 
787
  "source": "wisemoor_labtorium_free_sanitized",
788
  "source_url": record.get("source_url"),
789
  "name": record.get("name"),
790
+ # Preserve source-observed formula text as provenance. This is useful
791
+ # for retrieval and later human/AI-assisted extraction, but is not an
792
+ # assessor label and must not be promoted to one implicitly.
793
+ "description": record.get("description"),
794
  "genre": "wisemoor_formula",
795
  "notes": record.get("notes"),
796
  "formula": formula,
 
801
  "amount_coverage": amount_coverage,
802
  "unresolved_count": len(unresolved),
803
  "sanitized_source": str(Path("data/wisemoor_free_formulas.sanitized.jsonl")),
804
+ "description_provenance": (
805
+ "source_observed_wisemoor_product_text"
806
+ if record.get("description") else None
807
+ ),
808
  },
809
  }
810
  return candidate, audit
src/pino/substitution_v11.py CHANGED
@@ -11,6 +11,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]]:
@@ -105,14 +109,14 @@ def cosine_similarity(left: dict[str, float], right: dict[str, float]) -> float:
105
  return float(np.dot(a, b) / denom)
106
 
107
 
108
- def numeric_proximity(a: Any, b: Any, scale: float) -> float:
109
  try:
110
  fa = float(a)
111
  fb = float(b)
112
  except (TypeError, ValueError):
113
- return 0.5
114
  if not (math.isfinite(fa) and math.isfinite(fb)):
115
- return 0.5
116
  return float(math.exp(-abs(fa - fb) / scale))
117
 
118
 
@@ -134,11 +138,11 @@ def note_role(profile: dict[str, Any]) -> str:
134
  return "heart"
135
 
136
 
137
- def role_score(left: dict[str, Any], right: dict[str, Any]) -> float:
138
  l_role = note_role(left)
139
  r_role = note_role(right)
140
  if "unknown" in {l_role, r_role}:
141
- return 0.5
142
  return 1.0 if l_role == r_role else 0.25
143
 
144
 
@@ -166,6 +170,43 @@ MODE_WEIGHTS: dict[str, dict[str, float]] = {
166
  "accord_rebuild": {"odor": 0.35, "substantivity": 0.20, "volatility": 0.20, "role": 0.25},
167
  }
168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
  def score_candidate(
171
  target: dict[str, Any],
@@ -182,8 +223,10 @@ def score_candidate(
182
  if c_key in banned or normalize_name(candidate.get("name")) in banned:
183
  return {"score": -1.0, "reasons": {"banned": True}}
184
 
185
- components = {
186
- "odor": cosine_similarity(target.get("descriptor_distribution") or {}, candidate.get("descriptor_distribution") or {}),
 
 
187
  "substantivity": numeric_proximity(
188
  target.get("substantivity_log10_predicted"),
189
  candidate.get("substantivity_log10_predicted"),
@@ -191,11 +234,18 @@ def score_candidate(
191
  ),
192
  "volatility": numeric_proximity(target.get("log10_vapor_pressure_pa"), candidate.get("log10_vapor_pressure_pa"), 1.0),
193
  "role": role_score(target, candidate),
194
- "constraints": 1.0,
195
  }
196
  weights = MODE_WEIGHTS.get(mode, MODE_WEIGHTS["function_match"])
197
- score = sum(components[name] * weight for name, weight in weights.items())
198
- return {"score": float(score), "reasons": components}
 
 
 
 
 
 
 
199
 
200
 
201
  def substitute(
@@ -220,10 +270,19 @@ def substitute(
220
  "candidate_cas": candidate.get("cas"),
221
  "score": scored["score"],
222
  "components": scored["reasons"],
 
 
223
  "note_role": note_role(candidate),
224
  }
225
  )
226
- ranked.sort(key=lambda row: row["score"], reverse=True)
 
 
 
 
 
 
 
227
  return ranked[:top_k]
228
 
229
 
@@ -323,11 +382,19 @@ def evaluate_retriever(
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(
@@ -347,11 +414,15 @@ def evaluate_retriever(
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"],
@@ -363,6 +434,9 @@ def evaluate_retriever(
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(
@@ -388,6 +462,12 @@ def evaluate_retriever(
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",
@@ -399,7 +479,11 @@ def evaluate_retriever(
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,
 
11
 
12
  PIMT_V11 = "v11"
13
  ANSWER_SHAPES = {"single_material", "any_of", "accord"}
14
+ # Minimum mutually-observed scoring components for a row to count as a
15
+ # trustworthy retrieval. Below this the rank is driven mostly by priors /
16
+ # file order, so it is reported as low-evidence, not a model miss or hit.
17
+ MIN_OBSERVED_COMPONENTS = 2
18
 
19
 
20
  def load_jsonl(path: str | Path) -> list[dict[str, Any]]:
 
109
  return float(np.dot(a, b) / denom)
110
 
111
 
112
+ def numeric_proximity(a: Any, b: Any, scale: float) -> float | None:
113
  try:
114
  fa = float(a)
115
  fb = float(b)
116
  except (TypeError, ValueError):
117
+ return None
118
  if not (math.isfinite(fa) and math.isfinite(fb)):
119
+ return None
120
  return float(math.exp(-abs(fa - fb) / scale))
121
 
122
 
 
138
  return "heart"
139
 
140
 
141
+ def role_score(left: dict[str, Any], right: dict[str, Any]) -> float | None:
142
  l_role = note_role(left)
143
  r_role = note_role(right)
144
  if "unknown" in {l_role, r_role}:
145
+ return None
146
  return 1.0 if l_role == r_role else 0.25
147
 
148
 
 
170
  "accord_rebuild": {"odor": 0.35, "substantivity": 0.20, "volatility": 0.20, "role": 0.25},
171
  }
172
 
173
+ MODE_REQUIRED_FIELDS = {
174
+ "regulatory_match": ("regulatory_status", "ifra_restrictions", "allergens"),
175
+ "cost_match": ("cost_tier", "price", "availability_tier"),
176
+ }
177
+
178
+
179
+ def mode_supported(mode: str, target: dict[str, Any], profiles: Iterable[dict[str, Any]]) -> bool:
180
+ """Whether a mode has at least target and catalogue evidence for its advertised axis."""
181
+ fields = MODE_REQUIRED_FIELDS.get(mode)
182
+ if not fields:
183
+ return True
184
+ return any(target.get(field) is not None for field in fields) and any(
185
+ any(profile.get(field) is not None for field in fields) for profile in profiles
186
+ )
187
+
188
+
189
+ def mode_axis_similarity(mode: str, target: dict[str, Any], candidate: dict[str, Any]) -> float | None:
190
+ """Compare observed mode-specific fields; never manufacture a neutral value."""
191
+ if mode == "cost_match":
192
+ numeric = numeric_proximity(target.get("price"), candidate.get("price"), 1.0)
193
+ if numeric is not None:
194
+ return numeric
195
+ for field in ("cost_tier", "availability_tier"):
196
+ if target.get(field) is not None and candidate.get(field) is not None:
197
+ return 1.0 if target[field] == candidate[field] else 0.0
198
+ if mode == "regulatory_match":
199
+ scores = []
200
+ if target.get("regulatory_status") is not None and candidate.get("regulatory_status") is not None:
201
+ scores.append(1.0 if target["regulatory_status"] == candidate["regulatory_status"] else 0.0)
202
+ for field in ("ifra_restrictions", "allergens"):
203
+ left, right = set(target.get(field) or []), set(candidate.get(field) or [])
204
+ if left or right:
205
+ scores.append(len(left & right) / len(left | right))
206
+ if scores:
207
+ return sum(scores) / len(scores)
208
+ return None
209
+
210
 
211
  def score_candidate(
212
  target: dict[str, Any],
 
223
  if c_key in banned or normalize_name(candidate.get("name")) in banned:
224
  return {"score": -1.0, "reasons": {"banned": True}}
225
 
226
+ target_odor = target.get("descriptor_distribution") or {}
227
+ candidate_odor = candidate.get("descriptor_distribution") or {}
228
+ components: dict[str, float | None] = {
229
+ "odor": cosine_similarity(target_odor, candidate_odor) if target_odor and candidate_odor else None,
230
  "substantivity": numeric_proximity(
231
  target.get("substantivity_log10_predicted"),
232
  candidate.get("substantivity_log10_predicted"),
 
234
  ),
235
  "volatility": numeric_proximity(target.get("log10_vapor_pressure_pa"), candidate.get("log10_vapor_pressure_pa"), 1.0),
236
  "role": role_score(target, candidate),
237
+ "constraints": mode_axis_similarity(mode, target, candidate),
238
  }
239
  weights = MODE_WEIGHTS.get(mode, MODE_WEIGHTS["function_match"])
240
+ observed = {name: value for name, value in components.items() if value is not None and name in weights}
241
+ observed_weight = sum(weights[name] for name in observed)
242
+ score = sum(float(value) * weights[name] for name, value in observed.items()) / observed_weight if observed_weight else 0.0
243
+ return {
244
+ "score": float(score),
245
+ "reasons": components,
246
+ "evidence_coverage": observed_weight / sum(weights.values()),
247
+ "observed_components": sorted(observed),
248
+ }
249
 
250
 
251
  def substitute(
 
270
  "candidate_cas": candidate.get("cas"),
271
  "score": scored["score"],
272
  "components": scored["reasons"],
273
+ "evidence_coverage": scored["evidence_coverage"],
274
+ "observed_components": scored["observed_components"],
275
  "note_role": note_role(candidate),
276
  }
277
  )
278
+ ranked.sort(
279
+ key=lambda row: (
280
+ -row["score"],
281
+ -row["evidence_coverage"],
282
+ str(row.get("candidate_cas") or ""),
283
+ normalize_name(row.get("candidate")),
284
+ )
285
+ )
286
  return ranked[:top_k]
287
 
288
 
 
382
  row_mode = mode or row.get("mode")
383
  if row_mode not in MODE_WEIGHTS:
384
  raise ValueError(f"unsupported retrieval mode for {row['pair_id']}: {row_mode!r}")
385
+ target_profile = lookup.get(str(target_key)) or lookup.get(normalize_name(str(target_key)))
386
+ target_profile_key = profile_key(target_profile)
387
+ answer_keys = {profile_key(profile) for profile in resolved_answers}
388
+ if target_profile_key in answer_keys:
389
+ excluded.append({"pair_id": row["pair_id"], "reason": "answer_resolves_to_target"})
390
+ continue
391
+ if not mode_supported(row_mode, target_profile, profiles):
392
+ excluded.append({"pair_id": row["pair_id"], "reason": "mode_features_unsupported", "mode": row_mode})
393
+ continue
394
  mode_counts[row_mode] += 1
395
  if ranking_strategy == "model":
396
  ranked = substitute(str(target_key), profiles, mode=row_mode, top_k=top_k)
397
  else:
 
398
  candidates = [profile for profile in profiles if profile_key(profile) != target_profile_key]
399
  candidates.sort(
400
  key=lambda profile: hashlib.sha256(
 
414
  ]
415
  if profile
416
  }
 
417
  matched_keys = ranked_keys & answer_keys
418
  hit = answer_keys <= ranked_keys if shape == "accord" else bool(matched_keys)
 
419
  substitute_profile = resolved_answers[0]
420
+ # Evidence floor: count mutually-observed scoring components between the
421
+ # target and the documented answer. Rows under the floor are reported as
422
+ # low-evidence so their rank is not read as a trustworthy model outcome.
423
+ answer_scored = score_candidate(target_profile, substitute_profile, mode=row_mode) if target_profile is not None else {}
424
+ answer_observed_components = len(answer_scored.get("observed_components") or [])
425
+ low_evidence = answer_observed_components < MIN_OBSERVED_COMPONENTS
426
  evaluated.append(
427
  {
428
  "pair_id": row["pair_id"],
 
434
  "documented_answer": row["answer"],
435
  "answer_components_retrieved": len(matched_keys),
436
  "answer_components_total": len(answer_keys),
437
+ "answer_observed_components": answer_observed_components,
438
+ "answer_evidence_coverage": answer_scored.get("evidence_coverage"),
439
+ "low_evidence": low_evidence,
440
  "unavailable_optional_answers": missing_answers if shape == "any_of" else [],
441
  "substantivity_delta_abs": (
442
  abs(
 
462
  len(mode_rows),
463
  )
464
  subst_deltas = [row["substantivity_delta_abs"] for row in evaluated if row["substantivity_delta_abs"] is not None]
465
+ n_low_evidence = sum(1 for row in evaluated if row.get("low_evidence"))
466
+ # Trustworthy subset: rows meeting the evidence floor. Hits are also reported
467
+ # restricted to this subset so the headline is not carried by prior-only ranks.
468
+ trustworthy = [row for row in evaluated if not row.get("low_evidence")]
469
+ n_trustworthy = len(trustworthy)
470
+ n_trustworthy_hit = sum(1 for row in trustworthy if row["hit_top_k"])
471
  return {
472
  "pimt_version": PIMT_V11,
473
  "mode": mode or "per-row",
 
479
  "n_excluded": len(excluded),
480
  "n_hit": n_hit,
481
  "n_missed": n_missed,
482
+ "n_low_evidence": n_low_evidence,
483
+ "n_trustworthy": n_trustworthy,
484
+ "n_trustworthy_hit": n_trustworthy_hit,
485
  "top_k_hit": wilson_interval(n_hit, n),
486
+ "top_k_hit_trustworthy_only": wilson_interval(n_trustworthy_hit, n_trustworthy) if n_trustworthy else None,
487
  "by_mode_top_k_hit": by_mode_top_k_hit,
488
  "mean_substantivity_delta_abs": float(np.mean(subst_deltas)) if subst_deltas else None,
489
  "evaluated": evaluated,
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, wilson_interval
4
 
5
 
6
  def tiny_profiles():
@@ -175,3 +175,44 @@ def test_assessment_interfaces_do_not_emit_safety_authority():
175
  assert material["pimt_version"] == "v11"
176
  assert "IFRA/allergen/use-level" in material["enrichment_pending"]
177
  assert formula["substitution_risks"] == ["safety/use-level flags enrichment-pending; no safety claims emitted"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
+ from pino.substitution_v11 import evaluate_formula, evaluate_material, evaluate_retriever, score_candidate, substitute, wilson_interval
4
 
5
 
6
  def tiny_profiles():
 
175
  assert material["pimt_version"] == "v11"
176
  assert "IFRA/allergen/use-level" in material["enrichment_pending"]
177
  assert formula["substitution_risks"] == ["safety/use-level flags enrichment-pending; no safety claims emitted"]
178
+
179
+
180
+ def test_missing_features_are_unobserved_not_neutral_positive_evidence():
181
+ scored = score_candidate(tiny_profiles()[0], {"cas": "4", "name": "Empty"})
182
+
183
+ assert scored["score"] == 0.0
184
+ assert scored["evidence_coverage"] == 0.0
185
+ assert all(value is None for value in scored["reasons"].values())
186
+
187
+
188
+ def test_answer_resolving_to_target_is_invalid_not_a_miss():
189
+ rows = [{
190
+ "pair_id": "self-answer", "target_cas": "1", "substitute_cas": "1",
191
+ "grade": "acceptable", "mode": "function_match",
192
+ }]
193
+
194
+ result = evaluate_retriever(rows, tiny_profiles())
195
+
196
+ assert result["n_evaluable"] == 0
197
+ assert result["excluded"] == [{"pair_id": "self-answer", "reason": "answer_resolves_to_target"}]
198
+
199
+
200
+ def test_unimplemented_mode_is_reported_unsupported_not_as_a_miss():
201
+ rows = [{
202
+ "pair_id": "cost-without-cost-data", "target_cas": "1", "substitute_cas": "2",
203
+ "grade": "acceptable", "mode": "cost_match",
204
+ }]
205
+
206
+ result = evaluate_retriever(rows, tiny_profiles())
207
+
208
+ assert result["n_evaluable"] == 0
209
+ assert result["excluded"][0]["reason"] == "mode_features_unsupported"
210
+
211
+
212
+ def test_cost_mode_uses_observed_cost_axis_when_available():
213
+ target = tiny_profiles()[0] | {"cost_tier": "low"}
214
+ same = tiny_profiles()[1] | {"cost_tier": "low"}
215
+ different = tiny_profiles()[2] | {"cost_tier": "high"}
216
+
217
+ assert score_candidate(target, same, mode="cost_match")["reasons"]["constraints"] == 1.0
218
+ assert score_candidate(target, different, mode="cost_match")["reasons"]["constraints"] == 0.0