Matthew Ford commited on
Commit
f3ff0be
·
1 Parent(s): 456264c

release: freeze blinded genre challenge v2

Browse files

Former-commit-id: 044d4a26e78b326bb7161bbb515d8643177ef93d
Former-commit-id: e67674ad2b2b4fc2007f7c50424b53679683ce98

.gitignore CHANGED
@@ -46,6 +46,10 @@ data/openpom_curated_4983.csv
46
  *.bak*
47
  src/pino/registry.db*
48
 
 
 
 
 
49
  # WiseMoor authenticated/raw artifacts contain account-specific download data.
50
  data/wisemoor_cookies.txt
51
  data/wisemoor_free_formulas.jsonl
 
46
  *.bak*
47
  src/pino/registry.db*
48
 
49
+ # Restricted answer key for the blinded v2 genre challenge. Keep outside Git;
50
+ # disclose only after evaluator predictions and their hashes are frozen.
51
+ artifacts/genre_challenge_v2_release/label_key.json
52
+
53
  # WiseMoor authenticated/raw artifacts contain account-specific download data.
54
  data/wisemoor_cookies.txt
55
  data/wisemoor_free_formulas.jsonl
artifacts/genre_challenge_v2.json ADDED
The diff for this file is too large to render. See raw diff
 
artifacts/genre_challenge_v2_release/PREREGISTRATION.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Genre Challenge v2: blinded evaluation preregistration
2
+
3
+ Status: frozen before model predictions or challenge-set embeddings are generated or inspected.
4
+
5
+ ## Experimental unit and systems
6
+
7
+ The primary aggregation unit is the matched block: 50 blocks, each containing one formula from each of four genres. The frozen systems are:
8
+
9
+ 1. **Composition baseline:** a classifier using only active-component count, elemental mass vector, concentration HHI, top-weight share, and natural-material weight share.
10
+ 2. **Frozen PIMT representation:** the fixed pretrained PIMT checkpoint, with a linear multinomial probe trained only inside each training fold.
11
+ 3. **Combined model:** the same probe using composition features plus the frozen PIMT representation.
12
+
13
+ No challenge labels may be used to select pooling, layers, features, hyperparameters, thresholds, prompts, or checkpoints. All transformations and hyperparameters must be fitted in the corresponding training data only. The exact checkpoint and evaluation-code hashes must be added to the run manifest before predictions are generated.
14
+
15
+ ## Primary endpoint and estimand
16
+
17
+ The primary endpoint is the block-averaged improvement in four-class balanced accuracy of the combined model over the composition baseline. Accuracy is calculated within each complete matched block and then averaged equally over the 50 blocks. The primary contrast is combined minus composition baseline.
18
+
19
+ The primary uncertainty interval is a two-sided 95% percentile interval from 10,000 paired bootstrap resamples of the 50 blocks, using seed `8675309`. The confirmatory result is positive only if the interval's lower bound is greater than zero. Otherwise it is negative; there is no post-hoc "trend" category.
20
+
21
+ ## Secondary endpoints
22
+
23
+ - Block-averaged macro F1 for each system.
24
+ - PIMT-only minus composition-baseline balanced accuracy.
25
+ - Combined minus composition-baseline log loss.
26
+ - Per-class recall and the full confusion matrix.
27
+ - Same-genre retrieval mean reciprocal rank and enrichment within matched candidates.
28
+ - Real-versus-decoy paired accuracy and ROC AUC when the preregistered decoy tasks are materialized.
29
+
30
+ Secondary intervals use the same paired 10,000-resample block bootstrap and are descriptive; no multiplicity-adjusted confirmatory claims will be made from them.
31
+
32
+ ## Splitting, exclusions, and leakage controls
33
+
34
+ Outer folds must keep exact formulas, active ingredient identities, and all variants of a source formula together. Training and test ingredient identities must be disjoint. Preprocessing, probe fitting, calibration, and hyperparameter selection occur inside the training partition. The blinded evaluator payload contains no genre, source index, or formula ID.
35
+
36
+ All 50 blocks are included. A record may be excluded only for a deterministic execution failure documented before unblinding (for example, an invalid tensor or unavailable frozen checkpoint); its entire four-record block is then excluded from every system and metric. No exclusion based on confidence, error direction, or model output is permitted. If fewer than 45 complete blocks remain, the run is invalid and no confirmatory verdict is issued.
37
+
38
+ ## Ties, missingness, and stopping
39
+
40
+ Class-score ties are resolved by the fixed lexical class order `amber_oriental`, `citrus_cologne`, `floral_woody`, `fougere`. Retrieval-score ties receive average rank. Missing predictions invalidate the whole block. There is one confirmatory run and no optional stopping, repeated-seed selection, or dataset revision after unblinding.
41
+
42
+ Predictions, run configuration, dependency snapshot, checkpoint hashes, and evaluation-code commit must be hashed and made read-only before the restricted label key is opened. Any analysis not specified here is labeled exploratory and cannot change the primary verdict.
artifacts/genre_challenge_v2_release/blinded_challenge.json ADDED
The diff for this file is too large to render. See raw diff
 
artifacts/genre_challenge_v2_release/environment.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Captured: 2026-07-15 UTC
2
+ Platform: Linux x86_64
3
+ uv: 0.11.14
4
+ Python: 3.11.15
5
+ numpy: 2.4.6
6
+ scipy: 1.17.1
7
+ rdkit: 2026.03.3
8
+ torch: 2.13.0+cu130
9
+ Dependency lock: uv.lock (committed repository version)
10
+ Execution: uv run --frozen
artifacts/genre_challenge_v2_release/test_output.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Command: uv run --frozen pytest -q tests/test_genre_challenge_v2.py tests/test_archive_genre_challenge_v2.py
2
+
3
+ ........ [100%]
4
+ 8 passed in 0.35s
scripts/archive_genre_challenge_v2.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Create the immutable, blinded v2 challenge release artifacts.
3
+
4
+ This is a custodial operation only: it copies selected source formulas into an
5
+ anonymous evaluator payload and writes the labels to a separate restricted key.
6
+ It never loads model embeddings or computes evaluation outcomes.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import random
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+
20
+ def sha256(path: Path) -> str:
21
+ digest = hashlib.sha256()
22
+ with path.open("rb") as handle:
23
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
24
+ digest.update(chunk)
25
+ return digest.hexdigest()
26
+
27
+
28
+ def canonical_formula(row: dict[str, Any]) -> list[dict[str, Any]]:
29
+ """Retain formula inputs while stripping labels and source metadata."""
30
+ return [
31
+ {
32
+ key: component[key]
33
+ for key in ("cas", "name", "smiles", "weight_fraction")
34
+ if key in component
35
+ }
36
+ for component in row.get("formula", [])
37
+ ]
38
+
39
+
40
+ def archive(challenge_path: Path, dataset_path: Path, output_dir: Path, seed: int) -> dict[str, Any]:
41
+ challenge = json.loads(challenge_path.read_text(encoding="utf-8"))
42
+ records = challenge["challenge_records"]
43
+ if len(records) % 4:
44
+ raise ValueError("challenge records must contain complete four-record blocks")
45
+
46
+ wanted = {int(record["source_index"]) for record in records}
47
+ sources: dict[int, dict[str, Any]] = {}
48
+ with dataset_path.open(encoding="utf-8") as handle:
49
+ for source_index, line in enumerate(handle):
50
+ if source_index in wanted:
51
+ sources[source_index] = json.loads(line)
52
+ if sources.keys() != wanted:
53
+ raise ValueError(f"missing source rows: {sorted(wanted - sources.keys())}")
54
+
55
+ rng = random.Random(seed)
56
+ block_order = list(range(len(records) // 4))
57
+ rng.shuffle(block_order)
58
+ blinded, key_records = [], []
59
+ for public_block_number, source_block_number in enumerate(block_order, start=1):
60
+ source_block = records[source_block_number * 4:(source_block_number + 1) * 4]
61
+ within_order = list(range(4))
62
+ rng.shuffle(within_order)
63
+ for public_position, source_position in enumerate(within_order, start=1):
64
+ selected = source_block[source_position]
65
+ blind_id = f"V2-B{public_block_number:03d}-R{public_position}"
66
+ source_index = int(selected["source_index"])
67
+ blinded.append({
68
+ "blind_id": blind_id,
69
+ "block_id": f"V2-B{public_block_number:03d}",
70
+ "formula": canonical_formula(sources[source_index]),
71
+ })
72
+ key_records.append({
73
+ "blind_id": blind_id,
74
+ "source_block": source_block_number + 1,
75
+ "source_index": source_index,
76
+ "formula_id": selected.get("formula_id"),
77
+ "genre": selected["genre"],
78
+ })
79
+
80
+ output_dir.mkdir(parents=True, exist_ok=True)
81
+ blinded_path = output_dir / "blinded_challenge.json"
82
+ key_path = output_dir / "label_key.json"
83
+ blinded_doc = {
84
+ "release": "genre-challenge-v2",
85
+ "status": "frozen_blinded_evaluator_payload",
86
+ "records": blinded,
87
+ }
88
+ key_doc = {
89
+ "release": "genre-challenge-v2",
90
+ "status": "restricted; do not disclose until predictions are frozen",
91
+ "blinding_seed": seed,
92
+ "records": key_records,
93
+ }
94
+ blinded_path.write_text(json.dumps(blinded_doc, indent=2) + "\n", encoding="utf-8")
95
+ key_path.write_text(json.dumps(key_doc, indent=2) + "\n", encoding="utf-8")
96
+ os.chmod(blinded_path, 0o444)
97
+ os.chmod(key_path, 0o400)
98
+ return {
99
+ "challenge_sha256": sha256(challenge_path),
100
+ "source_dataset_sha256": sha256(dataset_path),
101
+ "blinded_payload_sha256": sha256(blinded_path),
102
+ "label_key_sha256": sha256(key_path),
103
+ "records": len(blinded),
104
+ "blocks": len(block_order),
105
+ }
106
+
107
+
108
+ def main() -> None:
109
+ parser = argparse.ArgumentParser()
110
+ parser.add_argument("--challenge", required=True, type=Path)
111
+ parser.add_argument("--dataset", required=True, type=Path)
112
+ parser.add_argument("--output-dir", required=True, type=Path)
113
+ parser.add_argument("--seed", type=int, default=20260715)
114
+ args = parser.parse_args()
115
+ print(json.dumps(archive(args.challenge, args.dataset, args.output_dir, args.seed), indent=2))
116
+
117
+
118
+ if __name__ == "__main__":
119
+ main()
scripts/build_genre_challenge_v2.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build and freeze the v2 genre challenge set without inspecting embeddings."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ from collections import Counter, defaultdict
8
+ import hashlib
9
+ import json
10
+ from pathlib import Path
11
+ from typing import Any, Iterable
12
+
13
+ import numpy as np
14
+ from rdkit import Chem, RDLogger
15
+ from rdkit.Chem import Descriptors
16
+
17
+ from pino.genre_benchmark import SOLVENTS
18
+ from pino.registry import AromaRegistry
19
+ from pino.thermo.naturals import NATURAL_PROFILES
20
+
21
+
22
+ SUBSTANTIVE_GENRES = ("amber_oriental", "citrus_cologne", "floral_woody", "fougere")
23
+ ELEMENTS = ("C", "H", "N", "O", "F", "P", "S", "Cl", "Br", "I", "B", "Si")
24
+ RDLogger.DisableLog("rdApp.error")
25
+
26
+
27
+ def sha256(path: Path) -> str:
28
+ digest = hashlib.sha256()
29
+ with path.open("rb") as handle:
30
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
31
+ digest.update(chunk)
32
+ return digest.hexdigest()
33
+
34
+
35
+ def identity(component: dict[str, Any]) -> str:
36
+ return str(component.get("cas") or component.get("smiles") or component.get("name") or "").strip().lower()
37
+
38
+
39
+ def genre(row: dict[str, Any]) -> str:
40
+ return str(row.get("genre") or row.get("metadata", {}).get("generation_strategy") or "wildcard")
41
+
42
+
43
+ def positive_active_components(row: dict[str, Any]) -> list[dict[str, Any]]:
44
+ return [
45
+ component for component in row.get("formula", [])
46
+ if identity(component) not in SOLVENTS and float(component.get("weight_fraction", 0.0)) > 0
47
+ ]
48
+
49
+
50
+ def _natural_profile(identifier: str) -> dict[str, Any] | None:
51
+ key = identifier.strip()
52
+ return NATURAL_PROFILES.get(key) or NATURAL_PROFILES.get(f"NATURAL:{key}")
53
+
54
+
55
+ def _resolve_smiles(component: dict[str, Any], registry: AromaRegistry | None) -> str | None:
56
+ """Resolve the structure carried inline, in a SMILES: key, or by registry id."""
57
+ inline = str(component.get("smiles") or "").strip()
58
+ identifier = str(component.get("cas") or component.get("name") or "").strip()
59
+ candidates = [inline]
60
+ if identifier.upper().startswith("SMILES:"):
61
+ candidates.append(identifier.split(":", 1)[1])
62
+ if registry is not None and identifier:
63
+ record = registry.get(identifier)
64
+ if record:
65
+ candidates.append(str(record.get("smiles") or "").strip())
66
+ for candidate in candidates:
67
+ if not candidate:
68
+ continue
69
+ if candidate.upper().startswith("SMILES:"):
70
+ candidate = candidate.split(":", 1)[1]
71
+ mol = Chem.MolFromSmiles(candidate)
72
+ if mol is not None and len(Chem.GetMolFrags(mol)) == 1:
73
+ return Chem.MolToSmiles(mol, canonical=True)
74
+ return None
75
+
76
+
77
+ def resolved_active_components(
78
+ row: dict[str, Any], registry: AromaRegistry | None = None
79
+ ) -> tuple[list[dict[str, Any]], list[str]]:
80
+ """Expand complex materials and aggregate their resolved pure constituents."""
81
+ aggregated: dict[str, dict[str, Any]] = {}
82
+ unresolved: list[str] = []
83
+
84
+ def add(component: dict[str, Any], weight: float, lineage: tuple[str, ...] = ()) -> None:
85
+ identifier = str(component.get("cas") or component.get("name") or "").strip()
86
+ profile = _natural_profile(identifier)
87
+ if profile:
88
+ profile_key = identifier.removeprefix("NATURAL:")
89
+ if profile_key in lineage:
90
+ unresolved.append(identifier)
91
+ return
92
+ for constituent, fraction in profile["constituents"].items():
93
+ add({"cas": constituent}, weight * float(fraction), lineage + (profile_key,))
94
+ return
95
+ smiles = _resolve_smiles(component, registry)
96
+ if not smiles:
97
+ unresolved.append(identifier or str(component.get("smiles") or "<missing identifier>"))
98
+ return
99
+ entry = aggregated.setdefault(smiles, {"cas": identifier, "smiles": smiles, "weight_fraction": 0.0})
100
+ entry["weight_fraction"] += weight
101
+
102
+ for component in positive_active_components(row):
103
+ add(component, float(component["weight_fraction"]))
104
+ return list(aggregated.values()), unresolved
105
+
106
+
107
+ def characterize(
108
+ row: dict[str, Any], source_index: int, registry: AromaRegistry | None = None
109
+ ) -> dict[str, Any]:
110
+ active, unresolved = resolved_active_components(row, registry)
111
+ weights = np.asarray([float(c["weight_fraction"]) for c in active], dtype=float)
112
+ element_mass = Counter()
113
+ valid = not unresolved
114
+ for component, weight in zip(active, weights):
115
+ smiles = str(component["smiles"])
116
+ mol = Chem.MolFromSmiles(smiles)
117
+ if mol is None or len(Chem.GetMolFrags(mol)) != 1:
118
+ valid = False
119
+ continue
120
+ molecular_weight = Descriptors.MolWt(mol)
121
+ if molecular_weight <= 0:
122
+ valid = False
123
+ continue
124
+ for atom in mol.GetAtoms():
125
+ element_mass[atom.GetSymbol()] += weight * atom.GetMass() / molecular_weight
126
+ total = float(weights.sum())
127
+ proportions = weights / total if total else weights
128
+ hhi = float(np.square(proportions).sum()) if len(proportions) else 0.0
129
+ return {
130
+ "source_index": source_index,
131
+ "genre": genre(row),
132
+ "active_count": len(active),
133
+ "structurally_valid": bool(active) and valid,
134
+ "unresolved_identifiers": sorted(set(unresolved)),
135
+ "element_vector": [float(element_mass[e]) for e in ELEMENTS],
136
+ "element_other": float(sum(v for e, v in element_mass.items() if e not in ELEMENTS)),
137
+ "hhi": hhi,
138
+ "top_weight_share": float(proportions.max()) if len(proportions) else 0.0,
139
+ "ingredients": sorted({str(c["smiles"]) for c in active}),
140
+ "natural_weight_share": natural_weight_share(row),
141
+ }
142
+
143
+
144
+ def natural_weight_share(row: dict[str, Any]) -> float:
145
+ """Fraction of the active formula entered as a natural/complex material."""
146
+ active = positive_active_components(row)
147
+ total = sum(float(c["weight_fraction"]) for c in active)
148
+ if not total:
149
+ return 0.0
150
+ natural = sum(
151
+ float(c["weight_fraction"]) for c in active
152
+ if _natural_profile(str(c.get("cas") or c.get("name") or "")) is not None
153
+ )
154
+ return natural / total
155
+
156
+
157
+ def size_bin(active_count: int) -> str:
158
+ if active_count == 2:
159
+ return "2"
160
+ if active_count <= 5:
161
+ return "3-5"
162
+ if active_count <= 10:
163
+ return "6-10"
164
+ return "11+"
165
+
166
+
167
+ def composition_match(a: dict[str, Any], b: dict[str, Any]) -> bool:
168
+ """Predeclared hard-negative caliper using label-free formula properties."""
169
+ if size_bin(a["active_count"]) != size_bin(b["active_count"]):
170
+ return False
171
+ va, vb = np.asarray(a["element_vector"]), np.asarray(b["element_vector"])
172
+ denom = float(np.linalg.norm(va) * np.linalg.norm(vb))
173
+ cosine = float(np.dot(va, vb) / denom) if denom else 0.0
174
+ return (
175
+ cosine >= 0.98
176
+ and abs(a["hhi"] - b["hhi"]) <= 0.10
177
+ and abs(a["top_weight_share"] - b["top_weight_share"]) <= 0.10
178
+ and not (set(a["ingredients"]) & set(b["ingredients"]))
179
+ )
180
+
181
+
182
+ def exact_formula_key(row: dict[str, Any]) -> tuple[tuple[str, int], ...]:
183
+ """Order-independent resolved formula key, with weights rounded to 1e-6."""
184
+ return tuple(sorted(
185
+ (str(c["smiles"]), round(float(c["weight_fraction"]) * 1_000_000))
186
+ for c in row["resolved_components"]
187
+ ))
188
+
189
+
190
+ def near_duplicate(a: dict[str, Any], b: dict[str, Any]) -> bool:
191
+ """Conservative near-duplicate rule: same ingredients and nearly same weights."""
192
+ aw = {c["smiles"]: float(c["weight_fraction"]) for c in a["resolved_components"]}
193
+ bw = {c["smiles"]: float(c["weight_fraction"]) for c in b["resolved_components"]}
194
+ if aw.keys() != bw.keys():
195
+ return False
196
+ at, bt = sum(aw.values()), sum(bw.values())
197
+ return max(abs(aw[k] / at - bw[k] / bt) for k in aw) <= 0.02
198
+
199
+
200
+ def collapse_duplicates(rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
201
+ """Keep the lowest source index from each exact/near formula family."""
202
+ families: dict[tuple[str, ...], list[dict[str, Any]]] = defaultdict(list)
203
+ for row in rows:
204
+ families[tuple(row["ingredients"])].append(row)
205
+ kept, clusters = [], []
206
+ for ingredient_key in sorted(families):
207
+ representatives: list[dict[str, Any]] = []
208
+ for row in sorted(families[ingredient_key], key=lambda r: r["source_index"]):
209
+ match = next((r for r in representatives if near_duplicate(r, row)), None)
210
+ if match is None:
211
+ representatives.append(row)
212
+ kept.append(row)
213
+ else:
214
+ clusters.append({"representative": match["source_index"], "collapsed": row["source_index"]})
215
+ return sorted(kept, key=lambda r: r["source_index"]), {
216
+ "input_records": len(rows), "representatives": len(kept),
217
+ "collapsed_records": len(clusters), "clusters": clusters,
218
+ "rule": "identical resolved ingredient set and maximum normalized weight difference <= 0.02",
219
+ }
220
+
221
+
222
+ def selection_distance(a: dict[str, Any], b: dict[str, Any]) -> float:
223
+ va, vb = np.asarray(a["element_vector"]), np.asarray(b["element_vector"])
224
+ cosine = float(np.dot(va, vb) / (np.linalg.norm(va) * np.linalg.norm(vb)))
225
+ return ((1 - cosine) / 0.02 + abs(a["hhi"] - b["hhi"]) / .10
226
+ + abs(a["top_weight_share"] - b["top_weight_share"]) / .10
227
+ + abs(a["natural_weight_share"] - b["natural_weight_share"]))
228
+
229
+
230
+ def select_balanced_challenge(
231
+ records: list[dict[str, Any]], registry: AromaRegistry | None, per_genre: int
232
+ ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
233
+ """Deterministically select disjoint, pairwise-calipered four-genre blocks."""
234
+ candidates = []
235
+ for index, source in enumerate(records):
236
+ row = characterize(source, index, registry)
237
+ if row["genre"] not in SUBSTANTIVE_GENRES or row["active_count"] < 2 or not row["structurally_valid"]:
238
+ continue
239
+ row["formula_id"] = source.get("formula_id") or source.get("metadata", {}).get("formula_id")
240
+ row["resolved_components"], _ = resolved_active_components(source, registry)
241
+ candidates.append(row)
242
+ candidates, duplicate_audit = collapse_duplicates(candidates)
243
+ by_genre = {g: [r for r in candidates if r["genre"] == g] for g in SUBSTANTIVE_GENRES}
244
+ used: set[int] = set()
245
+ blocks: list[list[dict[str, Any]]] = []
246
+ anchor_genre = min(SUBSTANTIVE_GENRES, key=lambda g: len(by_genre[g]))
247
+ bins = ("3-5", "6-10", "11+")
248
+ common = {b: min(sum(size_bin(r["active_count"]) == b for r in by_genre[g])
249
+ for g in SUBSTANTIVE_GENRES) for b in bins}
250
+ denominator = sum(common.values())
251
+ raw_quota = {b: per_genre * common[b] / denominator for b in bins}
252
+ bin_quota = {b: int(raw_quota[b]) for b in bins}
253
+ for b in sorted(bins, key=lambda x: (-(raw_quota[x] - bin_quota[x]), x))[:per_genre - sum(bin_quota.values())]:
254
+ bin_quota[b] += 1
255
+ anchors = sorted(by_genre[anchor_genre], key=lambda r: (size_bin(r["active_count"]), r["hhi"], r["source_index"]))
256
+ selected_bins: Counter[str] = Counter()
257
+ for anchor in anchors:
258
+ if anchor["source_index"] in used:
259
+ continue
260
+ anchor_bin = size_bin(anchor["active_count"])
261
+ if anchor_bin not in bin_quota or selected_bins[anchor_bin] >= bin_quota[anchor_bin]:
262
+ continue
263
+ block = [anchor]
264
+ for name in SUBSTANTIVE_GENRES:
265
+ if name == anchor["genre"]:
266
+ continue
267
+ feasible = [r for r in by_genre[name] if r["source_index"] not in used
268
+ and all(composition_match(r, chosen) for chosen in block)]
269
+ if not feasible:
270
+ break
271
+ block.append(min(feasible, key=lambda r: (sum(selection_distance(r, x) for x in block), r["source_index"])))
272
+ if len(block) == len(SUBSTANTIVE_GENRES):
273
+ blocks.append(block)
274
+ used.update(r["source_index"] for r in block)
275
+ selected_bins[anchor_bin] += 1
276
+ if len(blocks) == per_genre:
277
+ break
278
+ # If a scarce bin cannot realize its proportional quota as a complete
279
+ # pairwise clique, fill from any remaining bin without relaxing calipers.
280
+ if len(blocks) < per_genre:
281
+ for anchor in anchors:
282
+ if anchor["source_index"] in used:
283
+ continue
284
+ block = [anchor]
285
+ for name in SUBSTANTIVE_GENRES:
286
+ if name == anchor["genre"]:
287
+ continue
288
+ feasible = [r for r in by_genre[name] if r["source_index"] not in used
289
+ and all(composition_match(r, chosen) for chosen in block)]
290
+ if not feasible:
291
+ break
292
+ block.append(min(feasible, key=lambda r: (
293
+ sum(selection_distance(r, x) for x in block), r["source_index"])))
294
+ if len(block) == len(SUBSTANTIVE_GENRES):
295
+ blocks.append(block)
296
+ used.update(r["source_index"] for r in block)
297
+ selected_bins[size_bin(anchor["active_count"])] += 1
298
+ if len(blocks) == per_genre:
299
+ break
300
+ if len(blocks) < per_genre:
301
+ raise ValueError(f"only {len(blocks)} pairwise-matched blocks available; requested {per_genre}")
302
+ selected = [r for block in blocks for r in sorted(block, key=lambda r: r["genre"])]
303
+ lean = [{k: r[k] for k in ("source_index", "formula_id", "genre", "active_count", "element_vector",
304
+ "element_other", "hhi", "top_weight_share", "natural_weight_share", "ingredients")}
305
+ for r in selected]
306
+ audit = {
307
+ "selection_method": "deterministic greedy pairwise-calipered four-genre blocks",
308
+ "blocks": len(blocks), "records": len(lean), "per_genre": count_by_genre(lean),
309
+ "size_bin_quota": bin_quota,
310
+ "source_indices_unique": len({r["source_index"] for r in lean}) == len(lean),
311
+ "duplicate_collapse": duplicate_audit,
312
+ "size_bins_by_genre": {g: dict(sorted(Counter(size_bin(r["active_count"]) for r in lean if r["genre"] == g).items())) for g in SUBSTANTIVE_GENRES},
313
+ "natural_weight_share_by_genre": {g: {"mean": float(np.mean([r["natural_weight_share"] for r in lean if r["genre"] == g])), "nonzero": sum(r["natural_weight_share"] > 0 for r in lean if r["genre"] == g)} for g in SUBSTANTIVE_GENRES},
314
+ }
315
+ return lean, audit
316
+
317
+
318
+ def count_by_genre(rows: Iterable[dict[str, Any]]) -> dict[str, int]:
319
+ counts = Counter(row["genre"] for row in rows)
320
+ return {name: counts.get(name, 0) for name in (*SUBSTANTIVE_GENRES, "wildcard")}
321
+
322
+
323
+ def census(records: list[dict[str, Any]], registry: AromaRegistry | None = None) -> dict[str, Any]:
324
+ characterized = [characterize(row, i, registry) for i, row in enumerate(records)]
325
+ multi = [r for r in characterized if r["active_count"] >= 2]
326
+ valid = [r for r in multi if r["structurally_valid"]]
327
+ substantive = [r for r in valid if r["genre"] in SUBSTANTIVE_GENRES]
328
+
329
+ partners: dict[int, set[str]] = defaultdict(set)
330
+ pair_counts: Counter[tuple[str, str]] = Counter()
331
+ for i, left in enumerate(substantive):
332
+ for right in substantive[i + 1:]:
333
+ if left["genre"] == right["genre"] or not composition_match(left, right):
334
+ continue
335
+ pair = tuple(sorted((left["genre"], right["genre"])))
336
+ pair_counts[pair] += 1
337
+ partners[left["source_index"]].add(right["genre"])
338
+ partners[right["source_index"]].add(left["genre"])
339
+
340
+ matchable = [r for r in substantive if partners[r["source_index"]]]
341
+ per_genre = {}
342
+ for name in SUBSTANTIVE_GENRES:
343
+ eligible = [r for r in substantive if r["genre"] == name]
344
+ matched = [r for r in eligible if partners[r["source_index"]]]
345
+ per_genre[name] = {
346
+ "eligible": len(eligible),
347
+ "composition_matchable": len(matched),
348
+ "matchable_to_all_three_other_genres": sum(len(partners[r["source_index"]]) == 3 for r in eligible),
349
+ "by_size_bin": dict(sorted(Counter(size_bin(r["active_count"]) for r in eligible).items())),
350
+ }
351
+ return {
352
+ "records": len(records),
353
+ "resolution": {
354
+ "records_with_unresolved_active_identifiers": sum(bool(r["unresolved_identifiers"]) for r in characterized),
355
+ "unresolved_identifier_counts": dict(sorted(Counter(
356
+ identifier for r in characterized for identifier in r["unresolved_identifiers"]
357
+ ).items())),
358
+ },
359
+ "attrition": {
360
+ "all": count_by_genre(characterized),
361
+ "multi_component": count_by_genre(multi),
362
+ "multi_component_structurally_valid": count_by_genre(valid),
363
+ "substantive_composition_matchable": count_by_genre(matchable),
364
+ },
365
+ "per_substantive_genre": per_genre,
366
+ "cross_genre_candidate_pairs": {"__vs__".join(pair): count for pair, count in sorted(pair_counts.items())},
367
+ "maximum_balanced_pool_from_individually_matchable_records": min(
368
+ (per_genre[g]["composition_matchable"] for g in SUBSTANTIVE_GENRES), default=0
369
+ ),
370
+ "wildcard_open_set_pool": {
371
+ "multi_component_structurally_valid": sum(r["genre"] == "wildcard" for r in valid),
372
+ "singleton_sanity_check": sum(r["genre"] == "wildcard" and r["active_count"] == 1 for r in characterized),
373
+ },
374
+ }
375
+
376
+
377
+ def specification(dataset: Path, report: dict[str, Any], selected: bool = False) -> dict[str, Any]:
378
+ return {
379
+ "protocol_version": 2,
380
+ "status": ("frozen_challenge_rows_selected; embeddings_and_outcomes_not_inspected" if selected else
381
+ "frozen_design_and_feasibility_census; challenge_rows_not_selected; embeddings_not_inspected"),
382
+ "dataset": {"path": str(dataset), "sha256": sha256(dataset), "records": report["records"]},
383
+ "primary_population": {
384
+ "genres": list(SUBSTANTIVE_GENRES),
385
+ "requirements": [
386
+ "at least two positive-weight non-solvent resolved constituents",
387
+ "natural/complex materials expanded recursively",
388
+ "CAS and SMILES: identifiers resolve to one-fragment canonical SMILES",
389
+ "duplicate resolved constituents aggregated before characterization",
390
+ ],
391
+ "excluded": "wildcard and singleton records",
392
+ },
393
+ "matching": {
394
+ "size_bins": ["2", "3-5", "6-10", "11+"],
395
+ "element_mass_cosine_minimum": 0.98,
396
+ "concentration_hhi_absolute_tolerance": 0.10,
397
+ "top_weight_share_absolute_tolerance": 0.10,
398
+ "shared_active_ingredient_maximum": 0,
399
+ "selection_rule": "balanced across four genres; optimize match coverage without using embeddings or outcomes",
400
+ },
401
+ "tasks": {
402
+ "primary": [
403
+ "real formula versus non-identity weight permutation",
404
+ "real formula versus ingredient-matched decoy",
405
+ "same-genre versus different-genre composition-matched retrieval",
406
+ ],
407
+ "residual_value": "nested cross-validation: composition alone versus composition plus learned embedding",
408
+ "open_set": "wildcard is rejection-only and never a fifth primary class",
409
+ "sanity_check": "report singleton wildcard classification separately",
410
+ },
411
+ "metrics": {
412
+ "classification": ["macro_f1", "balanced_accuracy", "per_class_recall"],
413
+ "contrastive": ["paired_accuracy", "roc_auc"],
414
+ "retrieval": ["same_genre_enrichment", "mean_reciprocal_rank"],
415
+ "uncertainty": "formula-level paired bootstrap 95% intervals",
416
+ "raw_accuracy_is_primary": False,
417
+ },
418
+ "leakage_controls": [
419
+ "all preprocessing and hyperparameter selection fit inside training folds",
420
+ "exact formula and active ingredient identities disjoint across outer folds",
421
+ "decoys and contrastive variants remain in the source formula's fold",
422
+ "final row selection is frozen before learned embeddings are inspected",
423
+ ],
424
+ "go_no_go": {
425
+ "minimum_individually_matchable_records_per_genre": 20,
426
+ "minimum_candidate_pairs_per_genre_pair": 20,
427
+ "pass": report["maximum_balanced_pool_from_individually_matchable_records"] >= 20
428
+ and all(v >= 20 for v in report["cross_genre_candidate_pairs"].values())
429
+ and len(report["cross_genre_candidate_pairs"]) == 6,
430
+ },
431
+ }
432
+
433
+
434
+ def main() -> None:
435
+ parser = argparse.ArgumentParser()
436
+ parser.add_argument("--dataset", required=True)
437
+ parser.add_argument("--output", required=True)
438
+ parser.add_argument("--registry", default=None, help="Aroma registry SQLite path")
439
+ parser.add_argument("--per-genre", type=int, default=50,
440
+ help="Rows per substantive genre in the frozen challenge set")
441
+ args = parser.parse_args()
442
+ dataset, output = Path(args.dataset), Path(args.output)
443
+ with dataset.open(encoding="utf-8") as handle:
444
+ records = [json.loads(line) for line in handle if line.strip()]
445
+ with AromaRegistry(args.registry) as registry:
446
+ report = census(records, registry)
447
+ selected, audit = select_balanced_challenge(records, registry, args.per_genre)
448
+ result = {"specification": specification(dataset, report, selected=True),
449
+ "feasibility_census": report, "selection_audit": audit,
450
+ "challenge_records": selected}
451
+ output.parent.mkdir(parents=True, exist_ok=True)
452
+ output.write_text(json.dumps(result, indent=2) + "\n")
453
+ print(json.dumps(result, indent=2))
454
+
455
+
456
+ if __name__ == "__main__":
457
+ main()
tests/test_archive_genre_challenge_v2.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import json
3
+ from pathlib import Path
4
+
5
+
6
+ PATH = Path(__file__).parents[1] / "scripts" / "archive_genre_challenge_v2.py"
7
+ SPEC = importlib.util.spec_from_file_location("archive_genre_challenge_v2", PATH)
8
+ MODULE = importlib.util.module_from_spec(SPEC)
9
+ assert SPEC.loader
10
+ SPEC.loader.exec_module(MODULE)
11
+
12
+
13
+ def test_archive_separates_evaluator_payload_from_label_key(tmp_path):
14
+ dataset = tmp_path / "source.jsonl"
15
+ rows = []
16
+ challenge_rows = []
17
+ genres = ["amber_oriental", "citrus_cologne", "floral_woody", "fougere"]
18
+ for index in range(8):
19
+ rows.append({"genre": genres[index % 4], "formula_id": f"F{index}", "formula": [
20
+ {"cas": f"cas-{index}", "smiles": "CCO", "weight_fraction": 1.0}
21
+ ]})
22
+ challenge_rows.append({"source_index": index, "formula_id": f"F{index}", "genre": genres[index % 4]})
23
+ dataset.write_text("".join(json.dumps(row) + "\n" for row in rows))
24
+ challenge = tmp_path / "challenge.json"
25
+ challenge.write_text(json.dumps({"challenge_records": challenge_rows}))
26
+
27
+ output = tmp_path / "release"
28
+ result = MODULE.archive(challenge, dataset, output, seed=7)
29
+ blinded = json.loads((output / "blinded_challenge.json").read_text())
30
+ key = json.loads((output / "label_key.json").read_text())
31
+
32
+ assert result["records"] == 8
33
+ assert result["blocks"] == 2
34
+ assert all("genre" not in row and "source_index" not in row and "formula_id" not in row for row in blinded["records"])
35
+ assert {row["blind_id"] for row in blinded["records"]} == {row["blind_id"] for row in key["records"]}
36
+ assert (output / "blinded_challenge.json").stat().st_mode & 0o777 == 0o444
37
+ assert (output / "label_key.json").stat().st_mode & 0o777 == 0o400
tests/test_genre_challenge_v2.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from importlib.util import module_from_spec, spec_from_file_location
2
+ from pathlib import Path
3
+
4
+ from pino.registry import AromaRegistry
5
+
6
+
7
+ PATH = Path(__file__).parents[1] / "scripts" / "build_genre_challenge_v2.py"
8
+ SPEC = spec_from_file_location("build_genre_challenge_v2", PATH)
9
+ MODULE = module_from_spec(SPEC)
10
+ assert SPEC.loader
11
+ SPEC.loader.exec_module(MODULE)
12
+
13
+
14
+ def record(genre, components):
15
+ return {"genre": genre, "formula": components}
16
+
17
+
18
+ def component(cas, smiles=None, weight=0.5):
19
+ if smiles is None:
20
+ smiles = {"a": "CC", "b": "CCC", "c": "CCCC", "d": "CCCCC", "e": "CCCCCC", "f": "CCCCCCC", "g": "CCCCCCCC"}.get(cas, "CCO")
21
+ return {"cas": cas, "smiles": smiles, "weight_fraction": weight}
22
+
23
+
24
+ def test_characterize_excludes_solvent_and_requires_valid_single_fragment_smiles():
25
+ row = record("fougere", [component("64-17-5", weight=0.2), component("a"), component("b")])
26
+ result = MODULE.characterize(row, 7)
27
+ assert result["active_count"] == 2
28
+ assert result["structurally_valid"] is True
29
+ assert result["source_index"] == 7
30
+
31
+ invalid = MODULE.characterize(record("fougere", [component("a", "not-smiles"), component("b")]), 8)
32
+ assert invalid["structurally_valid"] is False
33
+
34
+
35
+ def test_composition_match_enforces_size_concentration_and_identity_calipers():
36
+ base = MODULE.characterize(record("fougere", [component("a"), component("b")]), 0)
37
+ matched = MODULE.characterize(record("floral_woody", [component("c"), component("d")]), 1)
38
+ overlap = MODULE.characterize(record("floral_woody", [component("a"), component("d")]), 2)
39
+ singleton = MODULE.characterize(record("floral_woody", [component("c", weight=1.0)]), 3)
40
+ assert MODULE.composition_match(base, matched)
41
+ assert not MODULE.composition_match(base, overlap)
42
+ assert not MODULE.composition_match(base, singleton)
43
+
44
+
45
+ def test_census_keeps_wildcard_out_of_primary_pool():
46
+ rows = [
47
+ record("fougere", [component("a"), component("b")]),
48
+ record("floral_woody", [component("c"), component("d")]),
49
+ record("wildcard", [component("e"), component("f")]),
50
+ record("wildcard", [component("g", weight=1.0)]),
51
+ ]
52
+ result = MODULE.census(rows)
53
+ assert result["per_substantive_genre"]["fougere"]["composition_matchable"] == 1
54
+ assert result["wildcard_open_set_pool"] == {
55
+ "multi_component_structurally_valid": 1,
56
+ "singleton_sanity_check": 1,
57
+ }
58
+
59
+
60
+ def test_characterize_resolves_cas_smiles_keys_expands_naturals_and_aggregates(tmp_path):
61
+ registry = AromaRegistry(tmp_path / "registry.db")
62
+ registry.add({"cas": "5989-27-5", "name": "limonene", "smiles": "CC1=CCC(CC1)C(=C)C"})
63
+ registry.add({"cas": "123-35-3", "name": "myrcene", "smiles": "CC(=CCCC(=C)C=C)C"})
64
+ row = record("citrus_cologne", [
65
+ component("NATURAL:8008-57-9", smiles="", weight=0.5),
66
+ component("SMILES:CCO", smiles="", weight=0.25),
67
+ component("5989-27-5", smiles="", weight=0.25),
68
+ ])
69
+ result = MODULE.characterize(row, 0, registry)
70
+ registry.close()
71
+ assert result["structurally_valid"] is True
72
+ assert result["active_count"] == 3
73
+ assert result["unresolved_identifiers"] == []
74
+ assert len(result["ingredients"]) == 3
75
+
76
+
77
+ def test_characterize_reports_unresolved_identifier(tmp_path):
78
+ with AromaRegistry(tmp_path / "registry.db") as registry:
79
+ result = MODULE.characterize(record("fougere", [component("unknown", smiles="")]), 0, registry)
80
+ assert result["structurally_valid"] is False
81
+ assert result["unresolved_identifiers"] == ["unknown"]
82
+
83
+
84
+ def test_duplicate_collapse_is_order_independent_and_conservative():
85
+ rows = []
86
+ for index, weights in enumerate(((.5, .5), (.51, .49), (.8, .2))):
87
+ result = MODULE.characterize(record("fougere", [
88
+ component("a", weight=weights[0]), component("b", weight=weights[1])]), index)
89
+ result["resolved_components"], _ = MODULE.resolved_active_components(record("fougere", [
90
+ component("b", weight=weights[1]), component("a", weight=weights[0])]))
91
+ rows.append(result)
92
+ kept, audit = MODULE.collapse_duplicates(rows)
93
+ assert [row["source_index"] for row in kept] == [0, 2]
94
+ assert audit["collapsed_records"] == 1
95
+
96
+
97
+ def test_natural_weight_share_uses_pre_expansion_formula_weight():
98
+ row = record("citrus_cologne", [
99
+ component("NATURAL:8008-57-9", smiles="", weight=.25),
100
+ component("SMILES:CCO", smiles="", weight=.75),
101
+ ])
102
+ assert MODULE.natural_weight_share(row) == .25