File size: 26,236 Bytes
67f05a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
"""A SMILES parser that never calls rdkit. The second opinion, kept genuinely second.

WHAT THIS IS FOR. Gate 3 re-derives element_counts, formula, heavy_atom_count and
bond_count from the row's own SMILES with code that shares no line, no table and no
author's assumption with rdkit, and drops any row where the two disagree. That is only
worth anything if this file was written without looking at rdkit's answers, so it was:
its entire acceptance test is data/seed/molperceive/hand_formulas.json, thirty structures
walked atom by atom on paper and frozen with a sha256 before this module existed.

WHAT IT IS NOT FOR. It is not a chemistry toolkit. It handles the SMILES subset this
corpus generates and REFUSES on anything else rather than guessing, because a parser that
quietly guesses is a parser whose agreement rate means nothing. Isotopes, wildcards,
unusual valences and elements outside the supported set raise ParseRefused, the row is
dropped, and the drop is counted and published. That narrows the distribution slightly and
the card says so.

THE VALENCE MODEL, stated so a reviewer can disagree with it specifically:

  1. Bracket atoms take exactly the hydrogen written inside the bracket. [nH] is one,
     [N+] is zero even with four bonds, [Si] is zero. This is the SMILES rule and it is
     why bracket atoms need no valence table at all.
  2. Organic-subset atoms (B C N O P S F Cl Br I) get implicit hydrogen filling the
     LOWEST normal valence that is at least the sum of their bond orders.
  3. A lowercase aromatic atom gets one extra unit of bond order, representing the single
     formal double bond it carries in any Kekule structure. So aromatic c with two ring
     neighbours is 2+1=3 against valence 4 and takes 1 H; with three neighbours it is
     3+1=4 and takes 0. Bare aromatic n with two neighbours is 2+1=3, which fills nitrogen
     exactly, so 0 H: that is the pyridine nitrogen, and the pyrrole nitrogen must be
     written [nH].
  4. Aromatic o and s contribute a lone pair rather than a formal double bond, so rule 3
     does not apply to them and they take 0 implicit hydrogen.

Run it:
    python indep_parser.py --selftest          # the 30 hand-computed structures only
    python indep_parser.py --vs-rdkit <file>   # the measurement, run once, published
"""
from __future__ import annotations

import argparse
import hashlib
import json
import re
from collections import Counter
from pathlib import Path

try:                                    # importable both as a package and as a script
    from .fields import formula_with_charge
except ImportError:                     # pragma: no cover
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
    from molperceive.fields import formula_with_charge

ROOT = Path(__file__).resolve().parents[2]
HAND_PATH = ROOT / "data" / "seed" / "molperceive" / "hand_formulas.json"
HAND_SHA_PATH = ROOT / "data" / "seed" / "molperceive" / "hand_formulas.sha256"
# The aromatic appendix, frozen separately and later. The original 30 are never edited.
APPENDIX_PATH = ROOT / "data" / "seed" / "molperceive" / "hand_formulas_appendix_aromatic.json"
APPENDIX_SHA_PATH = ROOT / "data" / "seed" / "molperceive" / "hand_formulas_appendix_aromatic.sha256"

ORGANIC_SUBSET = ("Br", "Cl", "B", "C", "N", "O", "P", "S", "F", "I")   # longest first
AROMATIC_LOWER = ("b", "c", "n", "o", "p", "s")

# Lowest-first normal valences. Multi-valued entries are tried in order.
VALENCES: dict[str, tuple[int, ...]] = {
    "B": (3,),
    "C": (4,),
    "N": (3,),
    "O": (2,),
    "P": (3, 5),
    "S": (2, 4, 6),
    "F": (1,),
    "Cl": (1,),
    "Br": (1,),
    "I": (1,),
    "Si": (4,),
}

BOND_ORDER = {"-": 1, "=": 2, "#": 3, "$": 4, ":": 1, "/": 1, "\\": 1}

_BRACKET = re.compile(
    r"\[(?P<iso>\d+)?"
    r"(?P<sym>[A-Z][a-z]?|se|as|[bcnops]|\*)"
    r"(?P<chiral>@{1,2}(?:TH|AL|SP|TB|OH)?\d*)?"
    r"(?P<h>H\d*)?"
    r"(?P<chg>(?:\+{1,3}|-{1,3}|\+\d+|-\d+))?"
    r"(?::(?P<cls>\d+))?"
    r"\]")


class ParseRefused(Exception):
    """The parser will not answer. Not the same as: the structure is invalid.

    Kept as a distinct exception so a refusal can never be silently recorded as a
    disagreement with rdkit, which would understate the agreement rate, nor as an
    agreement, which would overstate it. Refusals are counted on their own line.
    """


class SyntaxInvalid(Exception):
    """The string is not well-formed SMILES. Carries one of fields.SYNTAX_REASONS."""

    def __init__(self, code: str, detail: str = "") -> None:
        super().__init__(f"{code}: {detail}" if detail else code)
        self.code = code
        self.detail = detail


class Atom:
    __slots__ = ("idx", "symbol", "aromatic", "bracket", "h_explicit", "charge",
                 "order_sum", "degree")

    def __init__(self, idx: int, symbol: str, aromatic: bool, bracket: bool,
                 h_explicit: int, charge: int) -> None:
        self.idx = idx
        self.symbol = symbol
        self.aromatic = aromatic
        self.bracket = bracket
        self.h_explicit = h_explicit
        self.charge = charge
        self.order_sum = 0.0        # sum of bond orders to heavy neighbours
        self.degree = 0             # number of heavy neighbours

    def __repr__(self) -> str:      # pragma: no cover
        return f"Atom({self.idx},{self.symbol},arom={self.aromatic},deg={self.degree})"


class Molecule:
    def __init__(self) -> None:
        self.atoms: list[Atom] = []
        self.bonds: list[tuple[int, int, float]] = []
        self.adj: dict[int, list[int]] = {}
        # Bonds created by a ring-closure DIGIT rather than by adjacency in the string.
        # Recorded because the derivation is required to show ring closure pairing, and
        # only the parser knows which pair a digit joined: rdkit's RingInfo gives ring
        # membership, from which the closure pair cannot be recovered.
        self.ring_closures: list[tuple[int, int]] = []

    def add_bond(self, a: int, b: int, order: float) -> None:
        if a == b:
            raise SyntaxInvalid("unclosed_ring_bond", f"atom {a} bonded to itself")
        for x, y, _ in self.bonds:
            if {x, y} == {a, b}:
                raise SyntaxInvalid("unclosed_ring_bond",
                                    f"duplicate bond {a}-{b}")
        self.bonds.append((a, b, order))
        self.adj.setdefault(a, []).append(b)
        self.adj.setdefault(b, []).append(a)
        for i in (a, b):
            self.atoms[i].degree += 1
            self.atoms[i].order_sum += order


def _split_charge(tok: str | None) -> int:
    if not tok:
        return 0
    sign = 1 if tok[0] == "+" else -1
    rest = tok[1:]
    if rest.isdigit():
        return sign * int(rest)
    return sign * (1 + len(rest))          # "++" is +2, "---" is -3


def parse(smiles: str) -> Molecule:
    """Build the heavy-atom graph. Raises SyntaxInvalid or ParseRefused."""
    if not smiles or not smiles.strip():
        raise SyntaxInvalid("unknown_element", "empty string")
    s = smiles.strip()

    mol = Molecule()
    branch: list[int] = []
    ring: dict[int, tuple[int, float | None]] = {}
    prev: int | None = None
    pending: float | None = None          # bond symbol seen but not yet consumed
    depth = 0
    i = 0
    n = len(s)

    while i < n:
        ch = s[i]

        if ch == "(":
            if prev is None:
                raise SyntaxInvalid("unbalanced_parenthesis", "branch opens before any atom")
            branch.append(prev)
            depth += 1
            i += 1
            continue
        if ch == ")":
            depth -= 1
            if depth < 0 or not branch:
                raise SyntaxInvalid("unbalanced_parenthesis", f"extra ) at char {i}")
            prev = branch.pop()
            i += 1
            continue
        if ch == ".":
            prev = None
            pending = None
            i += 1
            continue
        if s.startswith("->", i) or s.startswith("<-", i):
            # rdkit's dative bond extension. Well-formed input that this parser will not
            # assign a hydrogen count for, so it REFUSES. Letting it fall through to the
            # bond table would file a valid string as unknown_element and put it into the
            # invalid corpus carrying a fabricated reason code, which is the same bug the
            # bare wildcard case fixes. Every structure that uses it in the measurement
            # set is a metal complex and therefore out of scope by element anyway.
            raise ParseRefused("dative bond notation")
        if ch in BOND_ORDER:
            pending = BOND_ORDER[ch]
            i += 1
            continue
        if ch == "%":
            j = i + 1
            if j + 1 >= n or not s[j:j + 2].isdigit():
                raise SyntaxInvalid("unclosed_ring_bond", f"malformed %nn at char {i}")
            rnum = int(s[j:j + 2])
            prev = _ring_bond(mol, ring, rnum, prev, pending, i)
            pending = None
            i = j + 2
            continue
        if ch.isdigit():
            rnum = int(ch)
            prev = _ring_bond(mol, ring, rnum, prev, pending, i)
            pending = None
            i += 1
            continue

        # An atom.
        if ch == "[":
            m = _BRACKET.match(s, i)
            if not m:
                close = s.find("]", i)
                raise SyntaxInvalid("unknown_element",
                                    f"unparseable bracket atom {s[i:close + 1] if close > 0 else s[i:]!r}")
            sym = m.group("sym")
            if sym == "*":
                raise ParseRefused("wildcard atom")
            if m.group("iso"):
                raise ParseRefused(f"isotope {m.group(0)}")
            hgrp = m.group("h")
            h = 0 if not hgrp else (1 if hgrp == "H" else int(hgrp[1:]))
            aromatic = sym[0].islower()
            canon = sym.capitalize() if aromatic else sym
            if canon not in VALENCES and canon not in ("Se", "As"):
                raise ParseRefused(f"element {canon} outside the supported set")
            if canon in ("Se", "As"):
                raise ParseRefused(f"element {canon} outside the supported set")
            atom = Atom(len(mol.atoms), canon, aromatic, True, h,
                        _split_charge(m.group("chg")))
            mol.atoms.append(atom)
            i = m.end()
        else:
            if ch == "*":
                # A wildcard is well-formed SMILES for an unspecified atom. It is not a
                # syntax error and it is not something this parser will guess a formula
                # for, so it refuses. Filing it as unknown_element would put a valid
                # string into the invalid corpus with a fabricated reason code.
                raise ParseRefused("bare wildcard atom")
            sym = None
            for cand in ORGANIC_SUBSET:
                if s.startswith(cand, i):
                    sym = cand
                    break
            if sym is None:
                for cand in AROMATIC_LOWER:
                    if s.startswith(cand, i):
                        sym = cand
                        break
            if sym is None:
                raise SyntaxInvalid("unknown_element",
                                    f"char {s[i]!r} at position {i} starts no known element")
            aromatic = sym.islower()
            canon = sym.upper() if aromatic else sym
            if canon == "B" and aromatic:
                raise ParseRefused("aromatic boron")
            atom = Atom(len(mol.atoms), canon, aromatic, False, 0, 0)
            mol.atoms.append(atom)
            i += len(sym)

        idx = atom.idx
        if prev is not None:
            order = pending if pending is not None else (
                1.5 if (mol.atoms[prev].aromatic and atom.aromatic) else 1.0)
            mol.add_bond(prev, idx, order)
        pending = None
        prev = idx

    if depth != 0 or branch:
        raise SyntaxInvalid("unbalanced_parenthesis",
                            f"{abs(depth)} unclosed ( at end of string")
    if ring:
        raise SyntaxInvalid("unclosed_ring_bond",
                            f"ring bond number(s) {sorted(ring)} never closed")
    if not mol.atoms:
        raise SyntaxInvalid("unknown_element", "no atoms")
    return mol


def _ring_bond(mol: Molecule, ring: dict, rnum: int, prev: int | None,
               pending: float | None, pos: int) -> int:
    if prev is None:
        raise SyntaxInvalid("unclosed_ring_bond",
                            f"ring bond digit {rnum} at char {pos} with no preceding atom")
    if rnum in ring:
        other, other_pending = ring.pop(rnum)
        order = pending if pending is not None else (
            other_pending if other_pending is not None else
            (1.5 if (mol.atoms[other].aromatic and mol.atoms[prev].aromatic) else 1.0))
        mol.add_bond(other, prev, order)
        mol.ring_closures.append((other, prev))
    else:
        ring[rnum] = (prev, pending)
    return prev


def implicit_h(atom: Atom) -> int:
    """Hydrogen rdkit would add. Bracket atoms get none: the bracket already said."""
    if atom.bracket:
        return 0
    # Aromatic bonds are carried as 1.5 in the graph so a Kekule-free walk still knows
    # they are not plain single bonds. For the valence sum, count each aromatic bond as
    # one and add a single unit back for the one formal double bond the atom carries.
    if atom.aromatic:
        # An aromatic ring needs six pi electrons and each atom supplies them EITHER by
        # contributing one electron through a formal double bond OR by donating a lone
        # pair. It cannot do both, and which one it does follows from how many sigma
        # bonds it has already spent.
        if atom.symbol in ("O", "S"):
            return 0                       # furan / thiophene heteroatom, lone pair donor
        if atom.symbol in ("N", "P"):
            # Two connections is pyridine-type and carries the formal double bond:
            # 2 + 1 = 3. Three connections has spent every sigma bond and must donate
            # the lone pair instead, so no double bond: 3 + 0 = 3. Both land exactly on
            # nitrogen's valence of 3 with nothing left over, so a BARE lowercase
            # aromatic nitrogen never takes an implicit hydrogen either way. The
            # pyrrole NH is written [nH] and takes its hydrogen from the bracket.
            #
            # Added 2026-07-28 after the scorer selftest showed the parser refusing
            # caffeine. Derived from the rule above, which rule 4 already applied to
            # aromatic o and s; the omission was never extending it to nitrogen. Frozen
            # against ten NEWLY hand-computed structures in
            # hand_formulas_appendix_aromatic.json BEFORE this line was written, and
            # the resulting change in the rdkit agreement rate is published as a
            # separate later measurement rather than folded into the first-run number.
            return 0
        order = float(atom.degree) + 1.0
    else:
        order = atom.order_sum
    need = int(order + 0.5) if abs(order - round(order)) > 1e-9 else int(round(order))
    vals = VALENCES.get(atom.symbol)
    if vals is None:
        raise ParseRefused(f"no valence model for {atom.symbol}")
    for v in vals:
        if need <= v:
            return v - need
    # More bonds than any normal valence allows. That is a valence error, not a hydrogen
    # count, and the caller must not be handed a number that looks like an answer.
    raise ParseRefused(
        f"{atom.symbol} at index {atom.idx} has bond order {need}, "
        f"above every normal valence {vals}")


def counts(smiles: str) -> dict:
    """element_counts, formula, heavy_atom_count and bond_count. No rdkit anywhere."""
    mol = parse(smiles)
    c: Counter[str] = Counter()
    h = 0
    for a in mol.atoms:
        c[a.symbol] += 1
        h += a.h_explicit + implicit_h(a)
    ec = dict(c)
    if h:
        ec["H"] = h
    charge = sum(a.charge for a in mol.atoms)
    return {
        "element_counts": dict(sorted(ec.items())),
        "formula": formula_with_charge(ec, charge),
        "heavy_atom_count": len(mol.atoms),
        "bond_count": len(mol.bonds),
        "charge": charge,
        "n_rings": len(mol.bonds) - len(mol.atoms) + _n_components(mol),
    }


def _n_components(mol: Molecule) -> int:
    seen: set[int] = set()
    comps = 0
    for a in mol.atoms:
        if a.idx in seen:
            continue
        comps += 1
        stack = [a.idx]
        while stack:
            x = stack.pop()
            if x in seen:
                continue
            seen.add(x)
            stack.extend(mol.adj.get(x, []))
    return comps


def ring_closure_pairs(smiles: str) -> list[tuple[int, int]]:
    """The atom pairs joined by ring-closure digits, in the order the digits appear."""
    return parse(smiles).ring_closures


def classify_syntax(smiles: str) -> str | None:
    """The syntax reason code for a string rdkit's sanitize-off parse rejected.

    Returns None when the string is syntactically well-formed, which means any failure
    rdkit reported was chemical rather than textual and belongs to DetectChemistryProblems.
    """
    try:
        parse(smiles)
    except SyntaxInvalid as e:
        return e.code
    except ParseRefused:
        return None
    return None


def shortest_path_len(smiles: str, i: int, j: int) -> int | None:
    """Bond-count distance, breadth first. Used only as a cross check on rdkit."""
    mol = parse(smiles)
    if not (0 <= i < len(mol.atoms) and 0 <= j < len(mol.atoms)):
        return None
    if i == j:
        return 0
    dist = {i: 0}
    frontier = [i]
    while frontier:
        nxt = []
        for x in frontier:
            for y in mol.adj.get(x, []):
                if y not in dist:
                    dist[y] = dist[x] + 1
                    if y == j:
                        return dist[y]
                    nxt.append(y)
        frontier = nxt
    return None


# ---------------------------------------------------------------------------
# Acceptance test: the frozen hand set, and nothing else.
# ---------------------------------------------------------------------------
def hand_set(path: Path = HAND_PATH) -> list[dict]:
    return json.loads(path.read_text())["set"]


def hand_sha_ok(path: Path = HAND_PATH,
                sha_path: Path = HAND_SHA_PATH) -> tuple[bool, str, str]:
    got = hashlib.sha256(path.read_bytes()).hexdigest()
    want = sha_path.read_text().split()[0]
    return got == want, got, want


def check_against_hand(verbose: bool = True,
                       path: Path = HAND_PATH) -> tuple[int, int, list[str]]:
    """Compare the parser to the hand computations. Never to rdkit."""
    rows = hand_set(path)
    fails: list[str] = []
    for m in rows:
        try:
            got = counts(m["smiles"])
        except (SyntaxInvalid, ParseRefused) as e:
            fails.append(f"{m['id']} {m['name']}: parser refused or rejected: {e}")
            continue
        for field in ("formula", "heavy_atom_count", "bond_count"):
            if got[field] != m[field]:
                fails.append(f"{m['id']} {m['name']}: {field} "
                             f"parser={got[field]!r} hand={m[field]!r}")
        if got["element_counts"] != dict(sorted(m["element_counts"].items())):
            fails.append(f"{m['id']} {m['name']}: element_counts "
                         f"parser={got['element_counts']} hand={m['element_counts']}")
    if verbose:
        for f in fails:
            print("  FAIL " + f)
    return len(rows) - len({f.split(":")[0].split()[0] for f in fails}), len(rows), fails


def _selftest() -> None:
    all_fails: list[str] = []
    for label, hp, sp in (("hand_formulas.json (the original 30)", HAND_PATH, HAND_SHA_PATH),
                          ("hand_formulas_appendix_aromatic.json (10 more)",
                           APPENDIX_PATH, APPENDIX_SHA_PATH)):
        ok_sha, got, want = hand_sha_ok(hp, sp)
        print(f"{label}\n  sha256 {got[:16]}... "
              f"{'matches the frozen record' if ok_sha else 'DOES NOT MATCH ' + want[:16]}")
        if not ok_sha:
            raise SystemExit(
                "REFUSING to report a parser pass: a frozen hand-computed file has been "
                "edited since it was sealed. Its whole value is that it predates the "
                "parser code it tests.")
        passed, total, fails = check_against_hand(path=hp)
        all_fails += fails
        print(f"  parser agrees with {passed}/{total} hand-computed structures")
    fails = all_fails

    # Syntax classification must fire, one case per code, and must NOT fire on a valid
    # string. A classifier that never returns None would mark every row a syntax error.
    cases = [
        ("c1ccccc1O", None),
        ("CC(C", "unbalanced_parenthesis"),
        ("CCC)C", "unbalanced_parenthesis"),
        ("c1ccccc", "unclosed_ring_bond"),
        ("CCXCC", "unknown_element"),
        ("C1CCCCC1", None),
    ]
    syn_ok = 0
    for s, want_code in cases:
        got_code = classify_syntax(s)
        assert got_code == want_code, (s, got_code, want_code)
        syn_ok += 1
    print(f"syntax classification: {syn_ok}/{len(cases)} cases correct "
          f"({len({c for _, c in cases if c})} distinct codes exercised, "
          f"2 valid strings correctly returned None)")

    # Refusal must stay distinct from disagreement.
    for bad in ("[13C]CO", "[Se]c1ccccc1", "*CC"):
        try:
            counts(bad)
            raise AssertionError(f"expected ParseRefused for {bad}")
        except ParseRefused:
            pass
        except SyntaxInvalid:
            raise AssertionError(f"{bad} was misfiled as a syntax error")
    print("refusal path: 3/3 unsupported inputs refused rather than guessed")

    # The path helper, on a structure whose distances are obvious by inspection.
    assert shortest_path_len("CCCCC", 0, 4) == 4
    assert shortest_path_len("c1ccccc1", 0, 3) == 3
    assert shortest_path_len("CCO.CCO", 0, 4) is None
    print("shortest_path_len: 3/3 OK")

    if fails:
        raise SystemExit(f"{len(fails)} hand-set disagreement(s); see above")
    print("indep_parser selftest: OK")


def _vs_rdkit(path: Path, limit: int, emit: Path | None) -> None:
    """THE MEASUREMENT. Run once. The number it prints is the number we publish."""
    from rdkit import Chem, RDLogger
    from rdkit.Chem import rdMolDescriptors
    RDLogger.DisableLog("rdApp.*")

    smis: list[str] = []
    for line in path.read_text().splitlines():
        line = line.strip()
        if not line:
            continue
        if line.startswith("{"):
            r = json.loads(line)
            s = r.get("smiles") or r.get("SMILES") or ""
        else:
            s = line.split()[0]
        if s:
            smis.append(s)
    if limit:
        smis = smis[:limit]

    agree = 0
    refused = 0
    rdkit_rejected = 0
    disagreements: list[dict] = []
    for s in smis:
        mol = Chem.MolFromSmiles(s)
        if mol is None:
            rdkit_rejected += 1
            continue
        try:
            got = counts(s)
        except ParseRefused as e:
            refused += 1
            continue
        except SyntaxInvalid as e:
            disagreements.append({"smiles": s, "field": "parse",
                                  "parser": f"SyntaxInvalid {e.code}", "rdkit": "parsed"})
            continue
        ref = {
            "formula": rdMolDescriptors.CalcMolFormula(mol),
            "heavy_atom_count": mol.GetNumHeavyAtoms(),
            "bond_count": mol.GetNumBonds(),
            "element_counts": dict(sorted(
                Counter(a.GetSymbol() for a in Chem.AddHs(mol).GetAtoms()).items())),
        }
        diffs = [f for f in ref if got[f] != ref[f]]
        if diffs:
            for f in diffs:
                disagreements.append({"smiles": s, "field": f,
                                      "parser": got[f], "rdkit": ref[f]})
        else:
            agree += 1

    compared = agree + len({d["smiles"] for d in disagreements})
    rate = 100.0 * len({d["smiles"] for d in disagreements}) / max(1, compared)
    print("=" * 72)
    print("INDEPENDENT PARSER versus RDKIT, FIRST RUN. This number is published as measured.")
    print("=" * 72)
    print(f"  structures read              {len(smis)}")
    print(f"  rdkit itself rejected        {rdkit_rejected}   (not comparable, excluded)")
    print(f"  parser REFUSED to answer     {refused}   (isotope, unsupported element, "
          f"valence above every normal value; counted, never scored as agreement)")
    print(f"  compared                     {compared}")
    print(f"  molecules agreeing on all 4  {agree}")
    print(f"  molecules disagreeing        {compared - agree}")
    print(f"  FIRST RUN DISAGREEMENT RATE  {rate:.2f}%")
    if disagreements:
        print("\n  every disagreement, for classification as parser bug or rdkit convention:")
        for d in disagreements[:60]:
            print(f"    {d['smiles']}\n      {d['field']}: parser={d['parser']!r} "
                  f"rdkit={d['rdkit']!r}")
        if len(disagreements) > 60:
            print(f"    ... and {len(disagreements) - 60} more (see the emitted file)")
    if emit:
        emit.write_text(json.dumps({
            "compared": compared, "agree": agree, "refused": refused,
            "rdkit_rejected": rdkit_rejected, "first_run_disagreement_pct": round(rate, 2),
            "disagreements": disagreements}, indent=2))
        print(f"\n  wrote {emit}")


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--vs-rdkit", default="", help="file of SMILES or jsonl with a smiles key")
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--emit", default="")
    a = ap.parse_args()
    if a.vs_rdkit:
        _vs_rdkit(Path(a.vs_rdkit), a.limit, Path(a.emit) if a.emit else None)
    else:
        _selftest()


if __name__ == "__main__":
    main()