File size: 17,731 Bytes
fe85344
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
"""The MolPerceive field contract. Written BEFORE any corpus row exists, on purpose.

This module is the single place that answers "what is scored, what is only reported, and
what may never be asked at all". Nothing downstream is allowed to invent a field: the
generator draws from HEADLINE, the scorer scores HEADLINE, and EXCLUDED is a hard refusal
list that the gate re-asserts against every shipped row.

WHY EXCLUDED EXISTS AND WHY IT IS FROZEN FIRST. The chart entry learned that a scorer
silently decides what is winnable (HANDOFF 5.4: a perfect pie chart scores 0). The
inverse failure is worse and is what this file prevents: shipping a field that is either
unscoreable in principle, or so easy that the number flatters us. Deciding the field set
after seeing which fields score well is how a benchmark gets built backwards.

THE CALL CHAIN IS PINNED, NOT MERELY THE VERSION. RDKit exposes several mutually
inconsistent answers for the same chemical question inside ONE release: CalcNumHBD versus
CalcNumLipinskiHBD, Lipinski.NumHAcceptors delegating to the general CalcNumHBA (RDKit
issue 6206), symmetrized SSSR ring counts (cubane gives 6, true SSSR gives 5). Stating
"rdkit 2026.03.4" is therefore not enough to make a label reproducible. RDKIT_CALL_CHAIN
below names the exact expression for every field we score or report, and the scorer prints
it, so a reviewer can reproduce a label without reading our source.
"""
from __future__ import annotations

# The rdkit build every label in this entry was computed with. The scorer WARNS on a
# mismatch rather than failing, so a reviewer with a different pip still gets a usable
# run and can see for themselves which fields moved.
RDKIT_PINNED = "2026.03.4"

# ---------------------------------------------------------------------------
# 1. HEADLINE. Every one carries a verified near-zero external floor.
# ---------------------------------------------------------------------------
# floor evidence, all fetched from the primary source rather than a summary:
#   ChemIQ (arXiv 2505.07735, body text not abstract): GPT-4o carbon counting from
#   SMILES 4.0% (n=50), shortest path canonical 11.1% (n=54), shortest path random
#   5.6% (n=54), atom mapping semi-canonical 0.0% (n=92), atom mapping random 0.0%
#   (n=92).
#   MolBasic (arXiv 2607.03007, Table 1): Qwen3-8B heavy atom counting 6.09%, total
#   bond counting 3.07%; graph-to-SMILES near zero across every model tested.
HEADLINE: dict[str, str] = {
    "element_counts": "symbol to int map, includes hydrogen",
    "formula": "Hill notation string",
    "heavy_atom_count": "int",
    "bond_count": "int, bonds between heavy atoms only",
    "atom_at_index": "element symbol at a given rdkit atom index",
    "path_len": "shortest bond path between two atom indices",
    "smiles_from_graph": "SMILES string, scored by InChIKey identity",
}

# Fields that take an argument from the request, and the argument names they carry.
FIELD_PARAMS: dict[str, tuple[str, ...]] = {
    "atom_at_index": ("k",),
    "path_len": ("i", "j"),
}

# Fields whose value is determined by the molecular GRAPH rather than by a bulk tally.
# Gate 7 requires at least one of these per scored row, so a model cannot pass by
# learning composition statistics without ever traversing the structure.
GRAPH_DETERMINED = ("element_counts", "atom_at_index", "path_len", "smiles_from_graph")

# ---------------------------------------------------------------------------
# 2. SEPARATELY REPORTED. Computed and published, never pooled into the headline.
# ---------------------------------------------------------------------------
SEPARATE_REPORTED: dict[str, str] = {
    "ring_count":
        "GPT-4o already scores 45.8% on ChemIQ ring counting (n=48), which the ChemIQ "
        "authors attribute to their sampled molecules having at most six rings. Not a "
        "near-zero floor, so it is not a headline.",
    "aromatic_ring_count":
        "same compressed denominator as ring_count.",
    "bond_count_by_type":
        "Qwen3-8B already scores 45.81% on MolBasic specific bond type counting.",
    "rotatable_bonds":
        "definition drift: CalcNumRotatableBonds default versus "
        "NumRotatableBondsOptions.Strict give different answers in one rdkit build.",
    "hbd":
        "CalcNumHBD versus CalcNumLipinskiHBD disagree inside a single rdkit version.",
    "hba":
        "Lipinski.NumHAcceptors delegates to the general CalcNumHBA (rdkit issue 6206).",
    "stereocenters":
        "FindPotentialStereo versus the removed legacy implementation disagree.",
    "formal_charge":
        "near constant on this corpus, so it would be free points. See gate 7, the "
        "label entropy check, which is what caught it.",
    "degree_unsaturation":
        "near constant on this corpus for the same reason.",
    "mw":
        "decimal arithmetic on a base whose card reports GSM8K 38.4. Any tolerance we "
        "pick would be arbitrary and would decide the score.",
}

# ---------------------------------------------------------------------------
# 3. EXCLUDED BY CONSTRUCTION. Never a model output, in any slice, ever.
# ---------------------------------------------------------------------------
# Note the deliberate asymmetry on InChIKey: it is excluded as an OUTPUT and is
# simultaneously our dedup key, our train-to-eval leak key, and the scoring key for
# smiles_from_graph. Those are the correct uses of a hash. Emitting one is not.
EXCLUDED: dict[str, str] = {
    "inchikey":
        "a SHA-derived hash of the structure. A chemist who understands the molecule "
        "perfectly scores 0, so the field measures hash recall, not chemistry. It is "
        "the internal dedup key, the leak key and the scoring key for smiles_from_graph "
        "instead.",
    "canonical_smiles":
        "scored by string equality it measures agreement with one implementation's "
        "atom-ranking algorithm. A chemically correct answer can differ from rdkit's "
        "string. smiles_from_graph is scored by InChIKey identity for exactly this "
        "reason.",
    "monoisotopic_mass":
        "four-decimal arithmetic. See mw: any tolerance decides the score.",
    "logp":
        "a fitted parameter sum (Crippen). There is no ground truth to recompute, only "
        "agreement with one parameterisation.",
    "tpsa":
        "a fitted parameter sum (Ertl). Same objection as logp.",
    "iupac_name":
        "no deterministic permissively licensed reference implementation exists, so we "
        "could not recompute the label at scoring time, which is the whole claim.",
}

# ---------------------------------------------------------------------------
# 4. Reason codes, split by what they actually require.
# ---------------------------------------------------------------------------
# CHEMISTRY is the headline abstention number. Establishing these needs rdkit's
# sanitisation to run and report a typed problem; no string inspection can do it.
CHEMISTRY_REASONS = ("valence_error", "kekulization_failure")

# SYNTAX codes are pure string checks and require no chemistry at all. They stay in the
# corpus because a chemist typo is a chemist typo, and they are reported on their own
# line, never pooled into the abstention headline. Pooling them would inflate the one
# number the entry is built around.
SYNTAX_REASONS = ("unbalanced_parenthesis", "unclosed_ring_bond", "unknown_element")

OUT_OF_SCOPE_REASONS = ("element_not_supported", "size_out_of_range")

ALL_REASONS = CHEMISTRY_REASONS + SYNTAX_REASONS + OUT_OF_SCOPE_REASONS
STATUSES = ("ok", "invalid_structure", "out_of_scope")

# Deleted on purpose, recorded so nobody re-adds them:
#   atom_label_absent   unreachable, no generator mutation can produce it
#   multiple_components a substring match on a dot, and a dot-disconnected structure is
#                       a valid multi-component record rather than an error
DELETED_REASONS = {
    "atom_label_absent": "unreachable from any mutation in corrupt.py",
    "multiple_components": "a dot is a valid disconnection, not a parse failure",
}

# ---------------------------------------------------------------------------
# 5. Scope.
# ---------------------------------------------------------------------------
SUPPORTED_ELEMENTS = ("C", "H", "N", "O", "S", "P", "F", "Cl", "Br", "I", "B", "Si")
HEAVY_MIN, HEAVY_MAX = 5, 40
# 41 to 70 heavy atoms is a diagnostic slice only and never enters training or any
# headline eval, so the accuracy-versus-atom-count curve shows where the model breaks
# rather than leaving a reviewer to find it.
DIAG_HEAVY_MAX = 70

# ---------------------------------------------------------------------------
# 6. The pinned call chain. Named in the card, the CONVENTIONS clause and the scorer.
# ---------------------------------------------------------------------------
RDKIT_CALL_CHAIN: dict[str, str] = {
    "parse":
        "Chem.MolFromSmiles(s)",
    "parse_nosanitize":
        "Chem.MolFromSmiles(s, sanitize=False)",
    "element_counts":
        "Counter(a.GetSymbol() for a in Chem.AddHs(Chem.MolFromSmiles(s)).GetAtoms())",
    "formula":
        "rdMolDescriptors.CalcMolFormula(Chem.MolFromSmiles(s))",
    "heavy_atom_count":
        "Chem.MolFromSmiles(s).GetNumHeavyAtoms()",
    "bond_count":
        "Chem.MolFromSmiles(s).GetNumBonds()",
    "atom_at_index":
        "Chem.MolFromSmiles(s).GetAtomWithIdx(k).GetSymbol()",
    "path_len":
        "len(Chem.GetShortestPath(Chem.MolFromSmiles(s), i, j)) - 1",
    "smiles_from_graph":
        "Chem.MolToInchiKey(Chem.MolFromSmiles(pred)) == "
        "Chem.MolToInchiKey(reference built with Chem.RWMol then Chem.SanitizeMol)",
    "chemistry_reason":
        "[p.GetType() for p in "
        "Chem.DetectChemistryProblems(Chem.MolFromSmiles(s, sanitize=False))]",
    "syntax_reason":
        "molperceive.indep_parser.classify_syntax(s)   (no rdkit involved)",
    "leak_key":
        "Chem.MolToInchiKey(Chem.MolFromSmiles(s))",
    # Named for the separately reported group so the card can state them too.
    "ring_count":
        "Chem.MolFromSmiles(s).GetRingInfo().NumRings()   "
        "(symmetrized SSSR: cubane gives 6, true SSSR gives 5)",
    "rotatable_bonds":
        "rdMolDescriptors.CalcNumRotatableBonds(mol, "
        "rdMolDescriptors.NumRotatableBondsOptions.Strict)",
    "hbd":
        "rdMolDescriptors.CalcNumHBD(mol)   (NOT CalcNumLipinskiHBD)",
    "hba":
        "rdMolDescriptors.CalcNumHBA(mol)   (NOT Lipinski.NumHAcceptors)",
}

# ---------------------------------------------------------------------------
# 7. Request trigger phrases. Field selection is scored, so this table is released.
# ---------------------------------------------------------------------------
# The REQUEST block is natural language and carries no machine-readable field list, so
# recovering the requested set from the prose is part of the task. This table is what
# makes that recoverable at all, and the gate asserts the round trip on every row: the
# set recovered from the prose must equal the set the row claims to request. Without
# that assertion an Adaptive Data rewrite could silently change the question.
#
# TWELVE phrasing families. Families 9 to 12 are RESERVED: they never appear in
# training and are the whole content of the mp_para slice.
PHRASING_FAMILIES = tuple(range(1, 13))
RESERVED_FAMILIES = (9, 10, 11, 12)
TRAIN_FAMILIES = tuple(f for f in PHRASING_FAMILIES if f not in RESERVED_FAMILIES)

# field -> family -> phrasing. Each phrasing must contain a trigger substring from
# TRIGGERS[field], which is what the merge gate checks survives an Adaptive Data rewrite.
TRIGGERS: dict[str, tuple[str, ...]] = {
    # These must be MUTUALLY UNAMBIGUOUS: no trigger of one field may appear inside any
    # phrase written for another. assemble._selftest asserts exactly that over the full
    # 7 x 12 phrase table and it fired on the first run, catching three real collisions:
    # "atom count" matched both element_counts and "the heavy atom count"; "heavy atom"
    # matched heavy_atom_count inside "the bond count between heavy atoms"; and
    # "how many bonds" matched bond_count inside "how many bonds apart". Each would have
    # shipped rows whose recovered field set silently disagreed with the label on a
    # SCORED conjunct.
    "element_counts": ("element count", "element counts", "counts of each element",
                       "count of each element", "how many of each element",
                       "per element", "atoms of each element"),
    "formula": ("molecular formula", "formula", "empirical composition"),
    "heavy_atom_count": ("heavy atom", "non hydrogen atom", "heavy atoms total"),
    "bond_count": ("bond count", "number of bonds", "total bonds", "how many bonds",
                   "bonds are drawn", "bonds present"),
    "atom_at_index": ("which element", "what element", "atom at index",
                      "element at position", "sits at index"),
    "path_len": ("shortest path", "bond distance", "path length", "steps between",
                 "how far apart"),
    "smiles_from_graph": ("smiles", "smiles string", "as smiles"),
}


def is_excluded(name: str) -> bool:
    return name.lower() in EXCLUDED


def assert_not_excluded(names) -> None:
    """Called by the generator and by the gate. Refuses rather than warns."""
    bad = sorted(n for n in names if is_excluded(n))
    if bad:
        raise ValueError(
            f"EXCLUDED field(s) requested: {bad}. "
            + "; ".join(f"{n}: {EXCLUDED[n]}" for n in bad))


def hill_formula(counts: dict[str, int]) -> str:
    """Hill notation from an element -> count map.

    Carbon first, hydrogen second, everything else alphabetical. With NO carbon present,
    every element including hydrogen is alphabetical. That second clause is the part
    people get wrong, and phosphoric acid (H3O4P, not H3PO4) is in the frozen hand set
    precisely to keep us honest about it.
    """
    counts = {k: v for k, v in counts.items() if v}
    parts: list[str] = []

    def emit(sym: str) -> None:
        n = counts[sym]
        parts.append(sym if n == 1 else f"{sym}{n}")

    if "C" in counts:
        emit("C")
        if "H" in counts:
            emit("H")
        for sym in sorted(k for k in counts if k not in ("C", "H")):
            emit(sym)
    else:
        for sym in sorted(counts):
            emit(sym)
    return "".join(parts)


def formula_with_charge(counts: dict[str, int], charge: int) -> str:
    """Hill formula plus rdkit's charge suffix, so the two agree by construction."""
    base = hill_formula(counts)
    if charge == 0:
        return base
    sign = "+" if charge > 0 else "-"
    return base + (sign if abs(charge) == 1 else f"{sign}{abs(charge)}")


def _selftest() -> None:
    ok = 0
    # No field may live in two groups at once, which is how a field quietly gets
    # promoted into the headline after the fact.
    assert not (set(HEADLINE) & set(SEPARATE_REPORTED)); ok += 1
    assert not (set(HEADLINE) & set(EXCLUDED)); ok += 1
    assert not (set(SEPARATE_REPORTED) & set(EXCLUDED)); ok += 1
    # Every headline field names its exact rdkit call.
    assert set(HEADLINE) <= set(RDKIT_CALL_CHAIN), sorted(set(HEADLINE) - set(RDKIT_CALL_CHAIN)); ok += 1
    # Every headline field has at least three trigger phrases. The real diversity that
    # matters is the twelve PHRASINGS per field in assemble.PHRASES, not the trigger
    # count, but a field down to one trigger would make recovery a single-string match.
    for f in HEADLINE:
        assert len(TRIGGERS.get(f, ())) >= 3, f
    ok += 1
    # NO trigger of one field may be a substring of a trigger of another. If it were,
    # a phrase could satisfy both fields and recover_fields would return a set the row
    # never claimed, on a conjunct that is scored. Three such collisions existed on the
    # first run of the assemble selftest and this is the check that keeps them gone.
    tcol = [(a, x, b, y)
            for a, ta in TRIGGERS.items() for b, tb in TRIGGERS.items() if a != b
            for x in ta for y in tb if x in y]
    assert not tcol, f"trigger collisions across fields: {tcol}"
    ok += 1
    # assert_not_excluded must actually refuse.
    try:
        assert_not_excluded(["formula", "logp"])
        raise AssertionError("assert_not_excluded failed to fire")
    except ValueError as e:
        assert "logp" in str(e)
        ok += 1
    assert_not_excluded(list(HEADLINE)); ok += 1
    # Hill notation, including the no-carbon clause.
    assert hill_formula({"C": 6, "H": 6, "O": 1}) == "C6H6O"
    assert hill_formula({"C": 1, "Cl": 4}) == "CCl4"
    assert hill_formula({"H": 3, "O": 4, "P": 1}) == "H3O4P"
    assert hill_formula({"B": 1, "F": 4}) == "BF4"
    assert hill_formula({"C": 6, "H": 4, "Br": 1, "F": 1}) == "C6H4BrF"
    ok += 1
    assert formula_with_charge({"C": 4, "H": 12, "N": 1}, 1) == "C4H12N+"
    assert formula_with_charge({"B": 1, "F": 4}, -1) == "BF4-"
    assert formula_with_charge({"C": 1}, -2) == "C-2"
    assert formula_with_charge({"C": 6, "H": 6}, 0) == "C6H6"
    ok += 1
    # Reason codes are disjoint and the deleted ones stay deleted.
    assert len(set(ALL_REASONS)) == len(ALL_REASONS); ok += 1
    assert not (set(ALL_REASONS) & set(DELETED_REASONS)); ok += 1
    # Reserved phrasing families are genuinely held out.
    assert not (set(RESERVED_FAMILIES) & set(TRAIN_FAMILIES))
    assert len(TRAIN_FAMILIES) == 8; ok += 1
    print(f"fields selftest: {ok}/13 OK  "
          f"({len(HEADLINE)} headline, {len(SEPARATE_REPORTED)} reported, "
          f"{len(EXCLUDED)} excluded by construction)")


if __name__ == "__main__":
    _selftest()