Jainamshahhh commited on
Commit
fe85344
·
verified ·
1 Parent(s): 67f05a9

Upload fields.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. fields.py +346 -0
fields.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The MolPerceive field contract. Written BEFORE any corpus row exists, on purpose.
2
+
3
+ This module is the single place that answers "what is scored, what is only reported, and
4
+ what may never be asked at all". Nothing downstream is allowed to invent a field: the
5
+ generator draws from HEADLINE, the scorer scores HEADLINE, and EXCLUDED is a hard refusal
6
+ list that the gate re-asserts against every shipped row.
7
+
8
+ WHY EXCLUDED EXISTS AND WHY IT IS FROZEN FIRST. The chart entry learned that a scorer
9
+ silently decides what is winnable (HANDOFF 5.4: a perfect pie chart scores 0). The
10
+ inverse failure is worse and is what this file prevents: shipping a field that is either
11
+ unscoreable in principle, or so easy that the number flatters us. Deciding the field set
12
+ after seeing which fields score well is how a benchmark gets built backwards.
13
+
14
+ THE CALL CHAIN IS PINNED, NOT MERELY THE VERSION. RDKit exposes several mutually
15
+ inconsistent answers for the same chemical question inside ONE release: CalcNumHBD versus
16
+ CalcNumLipinskiHBD, Lipinski.NumHAcceptors delegating to the general CalcNumHBA (RDKit
17
+ issue 6206), symmetrized SSSR ring counts (cubane gives 6, true SSSR gives 5). Stating
18
+ "rdkit 2026.03.4" is therefore not enough to make a label reproducible. RDKIT_CALL_CHAIN
19
+ below names the exact expression for every field we score or report, and the scorer prints
20
+ it, so a reviewer can reproduce a label without reading our source.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ # The rdkit build every label in this entry was computed with. The scorer WARNS on a
25
+ # mismatch rather than failing, so a reviewer with a different pip still gets a usable
26
+ # run and can see for themselves which fields moved.
27
+ RDKIT_PINNED = "2026.03.4"
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # 1. HEADLINE. Every one carries a verified near-zero external floor.
31
+ # ---------------------------------------------------------------------------
32
+ # floor evidence, all fetched from the primary source rather than a summary:
33
+ # ChemIQ (arXiv 2505.07735, body text not abstract): GPT-4o carbon counting from
34
+ # SMILES 4.0% (n=50), shortest path canonical 11.1% (n=54), shortest path random
35
+ # 5.6% (n=54), atom mapping semi-canonical 0.0% (n=92), atom mapping random 0.0%
36
+ # (n=92).
37
+ # MolBasic (arXiv 2607.03007, Table 1): Qwen3-8B heavy atom counting 6.09%, total
38
+ # bond counting 3.07%; graph-to-SMILES near zero across every model tested.
39
+ HEADLINE: dict[str, str] = {
40
+ "element_counts": "symbol to int map, includes hydrogen",
41
+ "formula": "Hill notation string",
42
+ "heavy_atom_count": "int",
43
+ "bond_count": "int, bonds between heavy atoms only",
44
+ "atom_at_index": "element symbol at a given rdkit atom index",
45
+ "path_len": "shortest bond path between two atom indices",
46
+ "smiles_from_graph": "SMILES string, scored by InChIKey identity",
47
+ }
48
+
49
+ # Fields that take an argument from the request, and the argument names they carry.
50
+ FIELD_PARAMS: dict[str, tuple[str, ...]] = {
51
+ "atom_at_index": ("k",),
52
+ "path_len": ("i", "j"),
53
+ }
54
+
55
+ # Fields whose value is determined by the molecular GRAPH rather than by a bulk tally.
56
+ # Gate 7 requires at least one of these per scored row, so a model cannot pass by
57
+ # learning composition statistics without ever traversing the structure.
58
+ GRAPH_DETERMINED = ("element_counts", "atom_at_index", "path_len", "smiles_from_graph")
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # 2. SEPARATELY REPORTED. Computed and published, never pooled into the headline.
62
+ # ---------------------------------------------------------------------------
63
+ SEPARATE_REPORTED: dict[str, str] = {
64
+ "ring_count":
65
+ "GPT-4o already scores 45.8% on ChemIQ ring counting (n=48), which the ChemIQ "
66
+ "authors attribute to their sampled molecules having at most six rings. Not a "
67
+ "near-zero floor, so it is not a headline.",
68
+ "aromatic_ring_count":
69
+ "same compressed denominator as ring_count.",
70
+ "bond_count_by_type":
71
+ "Qwen3-8B already scores 45.81% on MolBasic specific bond type counting.",
72
+ "rotatable_bonds":
73
+ "definition drift: CalcNumRotatableBonds default versus "
74
+ "NumRotatableBondsOptions.Strict give different answers in one rdkit build.",
75
+ "hbd":
76
+ "CalcNumHBD versus CalcNumLipinskiHBD disagree inside a single rdkit version.",
77
+ "hba":
78
+ "Lipinski.NumHAcceptors delegates to the general CalcNumHBA (rdkit issue 6206).",
79
+ "stereocenters":
80
+ "FindPotentialStereo versus the removed legacy implementation disagree.",
81
+ "formal_charge":
82
+ "near constant on this corpus, so it would be free points. See gate 7, the "
83
+ "label entropy check, which is what caught it.",
84
+ "degree_unsaturation":
85
+ "near constant on this corpus for the same reason.",
86
+ "mw":
87
+ "decimal arithmetic on a base whose card reports GSM8K 38.4. Any tolerance we "
88
+ "pick would be arbitrary and would decide the score.",
89
+ }
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # 3. EXCLUDED BY CONSTRUCTION. Never a model output, in any slice, ever.
93
+ # ---------------------------------------------------------------------------
94
+ # Note the deliberate asymmetry on InChIKey: it is excluded as an OUTPUT and is
95
+ # simultaneously our dedup key, our train-to-eval leak key, and the scoring key for
96
+ # smiles_from_graph. Those are the correct uses of a hash. Emitting one is not.
97
+ EXCLUDED: dict[str, str] = {
98
+ "inchikey":
99
+ "a SHA-derived hash of the structure. A chemist who understands the molecule "
100
+ "perfectly scores 0, so the field measures hash recall, not chemistry. It is "
101
+ "the internal dedup key, the leak key and the scoring key for smiles_from_graph "
102
+ "instead.",
103
+ "canonical_smiles":
104
+ "scored by string equality it measures agreement with one implementation's "
105
+ "atom-ranking algorithm. A chemically correct answer can differ from rdkit's "
106
+ "string. smiles_from_graph is scored by InChIKey identity for exactly this "
107
+ "reason.",
108
+ "monoisotopic_mass":
109
+ "four-decimal arithmetic. See mw: any tolerance decides the score.",
110
+ "logp":
111
+ "a fitted parameter sum (Crippen). There is no ground truth to recompute, only "
112
+ "agreement with one parameterisation.",
113
+ "tpsa":
114
+ "a fitted parameter sum (Ertl). Same objection as logp.",
115
+ "iupac_name":
116
+ "no deterministic permissively licensed reference implementation exists, so we "
117
+ "could not recompute the label at scoring time, which is the whole claim.",
118
+ }
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # 4. Reason codes, split by what they actually require.
122
+ # ---------------------------------------------------------------------------
123
+ # CHEMISTRY is the headline abstention number. Establishing these needs rdkit's
124
+ # sanitisation to run and report a typed problem; no string inspection can do it.
125
+ CHEMISTRY_REASONS = ("valence_error", "kekulization_failure")
126
+
127
+ # SYNTAX codes are pure string checks and require no chemistry at all. They stay in the
128
+ # corpus because a chemist typo is a chemist typo, and they are reported on their own
129
+ # line, never pooled into the abstention headline. Pooling them would inflate the one
130
+ # number the entry is built around.
131
+ SYNTAX_REASONS = ("unbalanced_parenthesis", "unclosed_ring_bond", "unknown_element")
132
+
133
+ OUT_OF_SCOPE_REASONS = ("element_not_supported", "size_out_of_range")
134
+
135
+ ALL_REASONS = CHEMISTRY_REASONS + SYNTAX_REASONS + OUT_OF_SCOPE_REASONS
136
+ STATUSES = ("ok", "invalid_structure", "out_of_scope")
137
+
138
+ # Deleted on purpose, recorded so nobody re-adds them:
139
+ # atom_label_absent unreachable, no generator mutation can produce it
140
+ # multiple_components a substring match on a dot, and a dot-disconnected structure is
141
+ # a valid multi-component record rather than an error
142
+ DELETED_REASONS = {
143
+ "atom_label_absent": "unreachable from any mutation in corrupt.py",
144
+ "multiple_components": "a dot is a valid disconnection, not a parse failure",
145
+ }
146
+
147
+ # ---------------------------------------------------------------------------
148
+ # 5. Scope.
149
+ # ---------------------------------------------------------------------------
150
+ SUPPORTED_ELEMENTS = ("C", "H", "N", "O", "S", "P", "F", "Cl", "Br", "I", "B", "Si")
151
+ HEAVY_MIN, HEAVY_MAX = 5, 40
152
+ # 41 to 70 heavy atoms is a diagnostic slice only and never enters training or any
153
+ # headline eval, so the accuracy-versus-atom-count curve shows where the model breaks
154
+ # rather than leaving a reviewer to find it.
155
+ DIAG_HEAVY_MAX = 70
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # 6. The pinned call chain. Named in the card, the CONVENTIONS clause and the scorer.
159
+ # ---------------------------------------------------------------------------
160
+ RDKIT_CALL_CHAIN: dict[str, str] = {
161
+ "parse":
162
+ "Chem.MolFromSmiles(s)",
163
+ "parse_nosanitize":
164
+ "Chem.MolFromSmiles(s, sanitize=False)",
165
+ "element_counts":
166
+ "Counter(a.GetSymbol() for a in Chem.AddHs(Chem.MolFromSmiles(s)).GetAtoms())",
167
+ "formula":
168
+ "rdMolDescriptors.CalcMolFormula(Chem.MolFromSmiles(s))",
169
+ "heavy_atom_count":
170
+ "Chem.MolFromSmiles(s).GetNumHeavyAtoms()",
171
+ "bond_count":
172
+ "Chem.MolFromSmiles(s).GetNumBonds()",
173
+ "atom_at_index":
174
+ "Chem.MolFromSmiles(s).GetAtomWithIdx(k).GetSymbol()",
175
+ "path_len":
176
+ "len(Chem.GetShortestPath(Chem.MolFromSmiles(s), i, j)) - 1",
177
+ "smiles_from_graph":
178
+ "Chem.MolToInchiKey(Chem.MolFromSmiles(pred)) == "
179
+ "Chem.MolToInchiKey(reference built with Chem.RWMol then Chem.SanitizeMol)",
180
+ "chemistry_reason":
181
+ "[p.GetType() for p in "
182
+ "Chem.DetectChemistryProblems(Chem.MolFromSmiles(s, sanitize=False))]",
183
+ "syntax_reason":
184
+ "molperceive.indep_parser.classify_syntax(s) (no rdkit involved)",
185
+ "leak_key":
186
+ "Chem.MolToInchiKey(Chem.MolFromSmiles(s))",
187
+ # Named for the separately reported group so the card can state them too.
188
+ "ring_count":
189
+ "Chem.MolFromSmiles(s).GetRingInfo().NumRings() "
190
+ "(symmetrized SSSR: cubane gives 6, true SSSR gives 5)",
191
+ "rotatable_bonds":
192
+ "rdMolDescriptors.CalcNumRotatableBonds(mol, "
193
+ "rdMolDescriptors.NumRotatableBondsOptions.Strict)",
194
+ "hbd":
195
+ "rdMolDescriptors.CalcNumHBD(mol) (NOT CalcNumLipinskiHBD)",
196
+ "hba":
197
+ "rdMolDescriptors.CalcNumHBA(mol) (NOT Lipinski.NumHAcceptors)",
198
+ }
199
+
200
+ # ---------------------------------------------------------------------------
201
+ # 7. Request trigger phrases. Field selection is scored, so this table is released.
202
+ # ---------------------------------------------------------------------------
203
+ # The REQUEST block is natural language and carries no machine-readable field list, so
204
+ # recovering the requested set from the prose is part of the task. This table is what
205
+ # makes that recoverable at all, and the gate asserts the round trip on every row: the
206
+ # set recovered from the prose must equal the set the row claims to request. Without
207
+ # that assertion an Adaptive Data rewrite could silently change the question.
208
+ #
209
+ # TWELVE phrasing families. Families 9 to 12 are RESERVED: they never appear in
210
+ # training and are the whole content of the mp_para slice.
211
+ PHRASING_FAMILIES = tuple(range(1, 13))
212
+ RESERVED_FAMILIES = (9, 10, 11, 12)
213
+ TRAIN_FAMILIES = tuple(f for f in PHRASING_FAMILIES if f not in RESERVED_FAMILIES)
214
+
215
+ # field -> family -> phrasing. Each phrasing must contain a trigger substring from
216
+ # TRIGGERS[field], which is what the merge gate checks survives an Adaptive Data rewrite.
217
+ TRIGGERS: dict[str, tuple[str, ...]] = {
218
+ # These must be MUTUALLY UNAMBIGUOUS: no trigger of one field may appear inside any
219
+ # phrase written for another. assemble._selftest asserts exactly that over the full
220
+ # 7 x 12 phrase table and it fired on the first run, catching three real collisions:
221
+ # "atom count" matched both element_counts and "the heavy atom count"; "heavy atom"
222
+ # matched heavy_atom_count inside "the bond count between heavy atoms"; and
223
+ # "how many bonds" matched bond_count inside "how many bonds apart". Each would have
224
+ # shipped rows whose recovered field set silently disagreed with the label on a
225
+ # SCORED conjunct.
226
+ "element_counts": ("element count", "element counts", "counts of each element",
227
+ "count of each element", "how many of each element",
228
+ "per element", "atoms of each element"),
229
+ "formula": ("molecular formula", "formula", "empirical composition"),
230
+ "heavy_atom_count": ("heavy atom", "non hydrogen atom", "heavy atoms total"),
231
+ "bond_count": ("bond count", "number of bonds", "total bonds", "how many bonds",
232
+ "bonds are drawn", "bonds present"),
233
+ "atom_at_index": ("which element", "what element", "atom at index",
234
+ "element at position", "sits at index"),
235
+ "path_len": ("shortest path", "bond distance", "path length", "steps between",
236
+ "how far apart"),
237
+ "smiles_from_graph": ("smiles", "smiles string", "as smiles"),
238
+ }
239
+
240
+
241
+ def is_excluded(name: str) -> bool:
242
+ return name.lower() in EXCLUDED
243
+
244
+
245
+ def assert_not_excluded(names) -> None:
246
+ """Called by the generator and by the gate. Refuses rather than warns."""
247
+ bad = sorted(n for n in names if is_excluded(n))
248
+ if bad:
249
+ raise ValueError(
250
+ f"EXCLUDED field(s) requested: {bad}. "
251
+ + "; ".join(f"{n}: {EXCLUDED[n]}" for n in bad))
252
+
253
+
254
+ def hill_formula(counts: dict[str, int]) -> str:
255
+ """Hill notation from an element -> count map.
256
+
257
+ Carbon first, hydrogen second, everything else alphabetical. With NO carbon present,
258
+ every element including hydrogen is alphabetical. That second clause is the part
259
+ people get wrong, and phosphoric acid (H3O4P, not H3PO4) is in the frozen hand set
260
+ precisely to keep us honest about it.
261
+ """
262
+ counts = {k: v for k, v in counts.items() if v}
263
+ parts: list[str] = []
264
+
265
+ def emit(sym: str) -> None:
266
+ n = counts[sym]
267
+ parts.append(sym if n == 1 else f"{sym}{n}")
268
+
269
+ if "C" in counts:
270
+ emit("C")
271
+ if "H" in counts:
272
+ emit("H")
273
+ for sym in sorted(k for k in counts if k not in ("C", "H")):
274
+ emit(sym)
275
+ else:
276
+ for sym in sorted(counts):
277
+ emit(sym)
278
+ return "".join(parts)
279
+
280
+
281
+ def formula_with_charge(counts: dict[str, int], charge: int) -> str:
282
+ """Hill formula plus rdkit's charge suffix, so the two agree by construction."""
283
+ base = hill_formula(counts)
284
+ if charge == 0:
285
+ return base
286
+ sign = "+" if charge > 0 else "-"
287
+ return base + (sign if abs(charge) == 1 else f"{sign}{abs(charge)}")
288
+
289
+
290
+ def _selftest() -> None:
291
+ ok = 0
292
+ # No field may live in two groups at once, which is how a field quietly gets
293
+ # promoted into the headline after the fact.
294
+ assert not (set(HEADLINE) & set(SEPARATE_REPORTED)); ok += 1
295
+ assert not (set(HEADLINE) & set(EXCLUDED)); ok += 1
296
+ assert not (set(SEPARATE_REPORTED) & set(EXCLUDED)); ok += 1
297
+ # Every headline field names its exact rdkit call.
298
+ assert set(HEADLINE) <= set(RDKIT_CALL_CHAIN), sorted(set(HEADLINE) - set(RDKIT_CALL_CHAIN)); ok += 1
299
+ # Every headline field has at least three trigger phrases. The real diversity that
300
+ # matters is the twelve PHRASINGS per field in assemble.PHRASES, not the trigger
301
+ # count, but a field down to one trigger would make recovery a single-string match.
302
+ for f in HEADLINE:
303
+ assert len(TRIGGERS.get(f, ())) >= 3, f
304
+ ok += 1
305
+ # NO trigger of one field may be a substring of a trigger of another. If it were,
306
+ # a phrase could satisfy both fields and recover_fields would return a set the row
307
+ # never claimed, on a conjunct that is scored. Three such collisions existed on the
308
+ # first run of the assemble selftest and this is the check that keeps them gone.
309
+ tcol = [(a, x, b, y)
310
+ for a, ta in TRIGGERS.items() for b, tb in TRIGGERS.items() if a != b
311
+ for x in ta for y in tb if x in y]
312
+ assert not tcol, f"trigger collisions across fields: {tcol}"
313
+ ok += 1
314
+ # assert_not_excluded must actually refuse.
315
+ try:
316
+ assert_not_excluded(["formula", "logp"])
317
+ raise AssertionError("assert_not_excluded failed to fire")
318
+ except ValueError as e:
319
+ assert "logp" in str(e)
320
+ ok += 1
321
+ assert_not_excluded(list(HEADLINE)); ok += 1
322
+ # Hill notation, including the no-carbon clause.
323
+ assert hill_formula({"C": 6, "H": 6, "O": 1}) == "C6H6O"
324
+ assert hill_formula({"C": 1, "Cl": 4}) == "CCl4"
325
+ assert hill_formula({"H": 3, "O": 4, "P": 1}) == "H3O4P"
326
+ assert hill_formula({"B": 1, "F": 4}) == "BF4"
327
+ assert hill_formula({"C": 6, "H": 4, "Br": 1, "F": 1}) == "C6H4BrF"
328
+ ok += 1
329
+ assert formula_with_charge({"C": 4, "H": 12, "N": 1}, 1) == "C4H12N+"
330
+ assert formula_with_charge({"B": 1, "F": 4}, -1) == "BF4-"
331
+ assert formula_with_charge({"C": 1}, -2) == "C-2"
332
+ assert formula_with_charge({"C": 6, "H": 6}, 0) == "C6H6"
333
+ ok += 1
334
+ # Reason codes are disjoint and the deleted ones stay deleted.
335
+ assert len(set(ALL_REASONS)) == len(ALL_REASONS); ok += 1
336
+ assert not (set(ALL_REASONS) & set(DELETED_REASONS)); ok += 1
337
+ # Reserved phrasing families are genuinely held out.
338
+ assert not (set(RESERVED_FAMILIES) & set(TRAIN_FAMILIES))
339
+ assert len(TRAIN_FAMILIES) == 8; ok += 1
340
+ print(f"fields selftest: {ok}/13 OK "
341
+ f"({len(HEADLINE)} headline, {len(SEPARATE_REPORTED)} reported, "
342
+ f"{len(EXCLUDED)} excluded by construction)")
343
+
344
+
345
+ if __name__ == "__main__":
346
+ _selftest()