File size: 29,663 Bytes
f02a121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""

parse_inn_pmo.py -- extract and arithmetically validate phosphorodiamidate

morpholino oligomer (PMO) structures from WHO INN lists.



DBbun LLC (Uri Kartoun) -- NIH OligoTox Open Data Challenge, Phase II.



WHAT THIS DOES

--------------

WHO publishes International Nonproprietary Names (INN) lists as PDFs with a

fully extractable text layer.  Oligonucleotide entries print a systematic

chemical name, then a molecular formula, then (sometimes) a CAS number.



PMOs are NOT named with the word "morpholino" in INN nomenclature.  The

morpholine ring is expressed as a 2',3'-seco ribonucleoside closed by an

imino / azanediyl bridge, and the linkage descriptor is (2'a->5') in the old

style or (2'-N->5') in the modern bracket style.  Those two descriptors --

plus the reversed (5'->2'-N) used in some conjugates -- are the PMO signature

this module keys on.



VALIDATION RULE

---------------

A structure is "verified" only if the molecular formula computed from the

parsed structure equals the formula WHO states in the same entry, exactly,

element for element.  Nothing is hand-adjusted to force agreement; anything

not fully modelled is reported as a failure with the offending text.



THE MORPHOLINO FORMULA MODEL (derived from first principles)

------------------------------------------------------------

Subunit.  Periodate cleavage of the ribose 2',3'-diol followed by reductive

amination closes a six-membered morpholine ring: O4'-C1'-C2'-N(2'a)-C3'-C4'.

C1' carries the nucleobase; C4' carries the exocyclic 5'-CH2OH.  Both ring

carbons are deoxy (hence "P,2',3'-trideoxy" / "P,3'-dideoxy" in the INN name),

so the neutral morpholino sugar fragment, including the ring N-H and the

5'-O-H, is  C5H10NO2 .  Adding the N-linked nucleobase radical gives:



    A : C5H10NO2 + C5H4N5   (adenin-9-yl)    = C10H14N6O2

    C : C5H10NO2 + C4H4N3O  (cytosin-1-yl)   = C9H14N4O3

    G : C5H10NO2 + C5H4N5O  (guanin-9-yl)    = C10H14N6O3

    T : C5H10NO2 + C5H5N2O2 (thymin-1-yl)    = C10H15N3O4

    U : C5H10NO2 + C4H3N2O2 (uracil-1-yl)    = C9H13N3O4



    (m5U, used in WHO lists from ~2024 onward, is thymine: identical to T.)



Linkage.  The phosphorodiamidate bridges the 5'-O of one subunit to the ring

nitrogen (2'a / 2'-N) of the next.  Forming it removes one H from the 5'-OH

and one H from the ring N-H and inserts P(=O)(NR2):



    standard, P-(dimethylamino):  P + O + N(CH3)2 - 2H  =  C2H4NOP

    variant,  P-(piperazin-1-yl): P + O + C4H9N2  - 2H  =  C4H7N2OP



There is no sulfur and no sodium: the phosphorodiamidate is uncharged, so

unlike a phosphorothioate ASO there is no counterion in the formula.



Termini.  The ring-N end is a free secondary amine unless acylated.  The 5'

end is a free CH2OH unless capped.  The common Sarepta/AVI cap is



    5'-{P-[4-({2-[2-(2-hydroxyethoxy)ethoxy]ethoxy}carbonyl)piperazin-1-yl]-

        N,N-dimethylphosphonamidate}



i.e. -O-P(=O)(NMe2)-[piperazine]-C(=O)-O-(CH2CH2O)2CH2CH2OH, which adds

C13H26N3O6P (one H removed from the 5'-OH).  Note this cap CARRIES A

PHOSPHORUS, so for a capped PMO  P = L  (length), while for an uncapped PMO

P = L - 1.  WHO's "10-hydroxy-2,5,8-trioxadecanoyl" spelling of the same

tail is recognised as the identical group.



WORKED ARITHMETIC -- golodirsen, 25-mer, capped (WHO Recommended List 77)

------------------------------------------------------------------------

sequence 5'-GTTGCCTCCGGTTCTGAAGGTGTTC-3'  ->  A 2, C 7, G 7, T 9



    2 x A  C10H14N6O2   =  C20  H28  N12 O4

    7 x C  C9H14N4O3    =  C63  H98  N28 O21

    7 x G  C10H14N6O3   =  C70  H98  N42 O21

    9 x T  C10H15N3O4   =  C90  H135 N27 O36

    subunits                C243 H359 N109 O82

    24 x linkage C2H4NOP = C48  H96  N24 O24 P24

    1 x 5' cap C13H26N3O6P= C13  H26  N3  O6  P1

    TOTAL                   C305 H481 N138 O112 P25



WHO states C305H481N138O112P25.  Exact match.



USAGE

-----

    from parse_inn_pmo import validate

    r = validate(entry_text, "C305H481N138O112P25")

    r["ok"], r["sequence_5to3"], r["computed_formula"], r["reason"]



    python parse_inn_pmo.py --run      # download WHO lists, write pmo_results.csv

    python parse_inn_pmo.py --selftest # arithmetic self-test, no network



Dependencies: standard library only for validate(); PyMuPDF (fitz) for --run.

"""

from __future__ import annotations

import argparse
import csv
import os
import re
import sys
from collections import Counter

__all__ = ["validate", "compute_formula", "parse_formula", "format_formula",
           "find_pmo_entries", "PMO_MARKERS"]

# ---------------------------------------------------------------------------
# element arithmetic
# ---------------------------------------------------------------------------

_ELEMENT_ORDER = ["C", "H", "N", "O", "P", "S", "Na", "F", "Cl", "Br", "I"]


def _f(**kw) -> Counter:
    return Counter({k: v for k, v in kw.items() if v})


def _add(a: Counter, b: Counter, n: int = 1) -> Counter:
    out = Counter(a)
    for k, v in b.items():
        out[k] += v * n
    for k in [k for k, v in out.items() if v == 0]:
        del out[k]
    return out


def parse_formula(text: str) -> Counter:
    """'C305H481N138O112P25' -> Counter({'C':305, ...}).  Raises on junk."""
    s = re.sub(r"\s+", "", text or "")
    if not s:
        raise ValueError("empty formula")
    out = Counter()
    pos = 0
    for m in re.finditer(r"([A-Z][a-z]?)(\d*)", s):
        if m.start() != pos:
            raise ValueError("unparsable formula %r" % text)
        pos = m.end()
        out[m.group(1)] += int(m.group(2)) if m.group(2) else 1
    if pos != len(s):
        raise ValueError("unparsable formula %r" % text)
    return out


def format_formula(c: Counter) -> str:
    known = "".join("%s%d" % (e, c[e]) for e in _ELEMENT_ORDER if c.get(e))
    rest = "".join("%s%d" % (e, c[e])
                   for e in sorted(c) if e not in _ELEMENT_ORDER and c[e])
    return known + rest


# ---------------------------------------------------------------------------
# morpholino chemistry model
# ---------------------------------------------------------------------------

# morpholine ring (4 C, 1 N, 1 O) + exocyclic 5'-CH2OH, ring N-H and 5'-OH intact
MORPHOLINO_SUGAR = _f(C=5, H=10, N=1, O=2)

NUCLEOBASE_YL = {
    "A": _f(C=5, H=4, N=5),      # adenin-9-yl
    "C": _f(C=4, H=4, N=3, O=1),  # cytosin-1-yl
    "G": _f(C=5, H=4, N=5, O=1),  # guanin-9-yl
    "T": _f(C=5, H=5, N=2, O=2),  # thymin-1-yl (= 5-methyluracil-1-yl, m5U)
    "U": _f(C=4, H=3, N=2, O=2),  # uracil-1-yl
}

SUBUNIT = {b: _add(MORPHOLINO_SUGAR, y) for b, y in NUCLEOBASE_YL.items()}

# internal phosphorodiamidate linkages, keyed by the P substituent named in
# the INN ("P-(dimethylamino)" etc.).  Net = P + =O + NR2 - 2 H.
LINKAGE = {
    "dimethylamino": _f(C=2, H=4, N=1, O=1, P=1),
    "piperazin-1-yl": _f(C=4, H=7, N=2, O=1, P=1),
}

# 5'-terminal caps.  Net contribution after losing the 5'-OH hydrogen.
CAP_EG3_PIPERAZINE = _f(C=13, H=26, N=3, O=6, P=1)
_CAP_LABEL = "EG3-carbonylpiperazinyl-P(=O)NMe2 cap (carries 1 P)"

# WHO spells the triethyleneglycol tail of that cap two different ways.
_EG3_TAIL_SPELLINGS = (
    "{2-[2-(2-hydroxyethoxy)ethoxy]ethoxy}carbonyl",
    "10-hydroxy-2,5,8-trioxadecanoyl",
)


def _cap_tokens():
    """Recognised 5'-cap spellings (whitespace-stripped, lowercased)."""
    toks = []
    for tail in _EG3_TAIL_SPELLINGS:
        core = "p-[4-(%s)piperazin-1-yl]-n,n-dimethylphosphonamid" % tail
        # modern bracket style, cap printed after the sequence
        toks.append("5'-{%sate}" % core)
        # radavirsen style, cap printed as a 5'-O substituent
        toks.append("5'-o-{%soyl}" % core)
        # radavirsen prints the cap as a base-less pseudo-subunit whose own
        # P descriptor and trailing (2'a->5') are part of the cap group; the
        # phosphorus is the cap's, confirmed by the P count and the formula.
        toks.append("p,2',3'-trideoxy-p-(dimethylamino)-5'-o-{%soyl}-(2'a→5')"
                    % core)
    # longest first so the pseudo-subunit form wins over its own substring
    return sorted(toks, key=len, reverse=True)


TERMINAL_5PRIME = [(t, CAP_EG3_PIPERAZINE, _CAP_LABEL) for t in _cap_tokens()]

# Acyl groups that can sit on the terminal ring nitrogen (2'-N).  Net
# contribution = acyl radical minus the N-H hydrogen it replaces.
_ARG_RES = _f(C=6, H=12, N=4, O=1)
_GLY_RES = _f(C=2, H=3, N=1, O=1)
_ACETYL = _f(C=2, H=3, O=1)


def _ac_arg6_gly() -> Counter:
    acyl = Counter(_ACETYL)
    acyl = _add(acyl, _ARG_RES, 6)
    acyl = _add(acyl, _GLY_RES, 1)
    acyl["H"] -= 1                      # replaces the ring N-H
    return acyl


TERMINAL_2PRIME_N = [
    ("2'-n-(n2-acetyl-l-arginyl-l-arginyl-l-arginyl-l-arginyl-l-arginyl-"
     "l-arginylglycyl)", _ac_arg6_gly(), "N-acetyl-(L-Arg)6-Gly (cell-penetrating peptide)"),
]

# ---------------------------------------------------------------------------
# name parsing
# ---------------------------------------------------------------------------

PMO_MARKERS = ("(2'a→5')", "(2'-n→5')", "(5'→2'-n)")

_BASE_FROM_YL = {
    "adenylyl": "A", "cytidylyl": "C", "guanylyl": "G", "guanyly": "G",
    "thymidylyl": "T", "uridylyl": "U",
}
_BASE_FROM_OSE = {
    "adenosine": "A", "cytidine": "C", "guanosine": "G",
    "thymidine": "T", "uridine": "U",
}


def _normalise(text: str) -> str:
    """Unify the typographic characters WHO's PDFs use."""
    if text is None:
        return ""
    t = text
    for a, b in (("’", "'"), ("′", "'"), ("ʼ", "'"),
                 ("‐", "-"), ("‑", "-"), ("‒", "-"),
                 ("–", "-"), ("—", "-"), ("−", "-"),
                 (" ", " "), ("ff", "ff"), ("→", "→")):
        t = t.replace(a, b)
    t = t.replace("->", "→")
    return t


def _squash(text: str) -> str:
    """Whitespace-stripped, lowercased form used for token matching."""
    return re.sub(r"\s+", "", _normalise(text)).lower()


_ENGLISH_STOP = re.compile(
    r"(?:tout-p-ambo|todo-p-ambo)", re.I)

_LONG_RESIDUE = re.compile(
    r"p,(?:2',)?3'-(?:tri|di)deoxy-p-"
    r"\(?(dimethylamino|piperazin-1-yl)\)?"
    r"-2',3'-imino-2',3'-seco(adenylyl|cytidylyl|guanylyl|guanyly|thymidylyl|uridylyl)"
    r"-\(2'a→5'\)")

_LONG_TERMINAL = re.compile(
    r"(?:p,)?(?:2',)?3'-(?:tri|di)deoxy-(?:p-\(?(?:dimethylamino|piperazin-1-yl)\)?-)?"
    r"2',3'-imino-2',3'-seco(adenosine|cytidine|guanosine|thymidine|uridine)")

_COMPACT = re.compile(
    r"\[2',3'-azanediyl[^\]]*?\]"
    r"\((2'-n→5'|5'→2'-n)\)"
    r"\(([^)]*?)\)")

_COMPACT_P = re.compile(r"p-\(?(dimethylamino|piperazin-1-yl)\)?")

_SEQ_TOKEN = re.compile(r"m5u|[acgtu]")


def _parse_compact_sequence(raw: str):
    """Sequence letters inside the (...) of a bracket-style INN name."""
    s = raw.replace("-", "").replace("'", "").replace("5o", "")
    s = re.sub(r"\s+", "", s)
    bases, pos = [], 0
    while pos < len(s):
        m = _SEQ_TOKEN.match(s, pos)
        if not m:
            return None, s[pos:pos + 20]
        tok = m.group(0)
        bases.append("T" if tok == "m5u" else tok.upper())
        pos = m.end()
    return bases, None


def _strip_known(squashed: str, pieces) -> str:
    out = squashed
    for p in pieces:
        out = out.replace(p, "", 1)
    return out


def _residual_is_trivial(residual: str) -> bool:
    r = residual.strip("-,.;:{}[]() ")
    return r in ("", "-", "all-p-ambo", "ambo")


# ---------------------------------------------------------------------------
# the public entry point
# ---------------------------------------------------------------------------

def validate(entry_text: str, stated_formula: str) -> dict:
    """Parse one WHO INN entry's English chemical name and check its formula.



    Returns a dict with: ok, sequence_5to3, sequence_length, backbone_chemistry,

    linkage_profile, terminus_5prime, terminus_3prime, phosphorus_count,

    computed_formula, stated_formula, reason.



    ok is True only when the computed formula matches the stated one exactly,

    element for element.

    """
    res = _validate_core(entry_text, stated_formula)
    if not res["ok"] and not res["stated_formula"]:
        note = "the entry prints no molecular formula, so nothing can be checked"
        res["reason"] = (res["reason"] + "; " + note) if res["reason"] else note
    return res


def _validate_core(entry_text: str, stated_formula: str) -> dict:
    res = {
        "ok": False,
        "sequence_5to3": "",
        "sequence_length": 0,
        "backbone_chemistry": "phosphorodiamidate morpholino (PMO)",
        "linkage_profile": "",
        "terminus_5prime": "",
        "terminus_3prime": "",
        "phosphorus_count": 0,
        "computed_formula": "",
        "stated_formula": (stated_formula or "").strip(),
        "reason": "",
    }

    text = _normalise(entry_text or "")
    if not text.strip():
        res["reason"] = "empty entry text"
        return res

    sq = _squash(text)
    if not any(m in sq for m in PMO_MARKERS):
        res["reason"] = ("no PMO linkage descriptor ((2'a->5'), (2'-N->5') or "
                         "(5'->2'-N)) in entry; not a morpholino oligomer")
        return res

    # The English chemical name opens with the "all-P-ambo" stereodescriptor.
    anchor = sq.find("all-p-ambo")
    if anchor < 0:
        res["reason"] = "no 'all-P-ambo' descriptor; cannot delimit the chemical name"
        return res
    body = sq[anchor + len("all-p-ambo"):].lstrip("-")

    # The name is parsed FORWARD into three regions -- a prefix of terminal
    # modifiers, the oligomer core, and an optional trailing 5' cap -- so that
    # the indication prose and the French/Spanish names that follow in the
    # PDF are never mistaken for structure.
    bases = []
    link_names = []
    reversed_direction = False

    m = _COMPACT.search(body)
    if m:                       # bracket style, 2016 onward
        prefix, trailer = body[:m.start()], body[m.end():]
        bracket = m.group(0)[:m.group(0).index("](")]
        pm = _COMPACT_P.search(bracket)
        if not pm:
            res["reason"] = ("bracket descriptor names no P substituent: %r"
                             % bracket[:120])
            return res
        bases, bad = _parse_compact_sequence(m.group(2))
        if bases is None:
            res["reason"] = "unrecognised residue symbol in sequence: %r" % bad
            return res
        reversed_direction = (m.group(1) == "5'→2'-n")
        if reversed_direction:          # (5'->2'-N) prints the sequence 3'->5'
            bases = list(reversed(bases))
        link_names = [pm.group(1)] * max(0, len(bases) - 1)
    else:                       # residue-by-residue style, 2010-2012
        resid = list(_LONG_RESIDUE.finditer(body))
        term = list(_LONG_TERMINAL.finditer(body))
        if not resid or not term:
            res["reason"] = ("neither the bracket form nor a complete "
                             "residue-by-residue chain could be parsed")
            return res
        tm = term[-1]
        prefix, trailer = body[:resid[0].start()], body[tm.end():]
        for rm in resid:
            link_names.append(rm.group(1))
            bases.append(_BASE_FROM_YL[rm.group(2)])
        bases.append(_BASE_FROM_OSE[tm.group(1)])
        if len(link_names) != len(bases) - 1:
            res["reason"] = ("%d linkage descriptors for %d residues"
                             % (len(link_names), len(bases)))
            return res

    if len(bases) < 2:
        res["reason"] = "fewer than two morpholino residues parsed"
        return res

    res["sequence_5to3"] = "".join(bases)
    res["sequence_length"] = len(bases)

    # ---------------- termini ----------------
    total = Counter()
    cap5, term3 = "free 5'-OH", "free ring N-H (2'-N)"

    # (a) prefix region: terminal modifiers printed before the oligomer core
    rest = prefix
    for token, contrib, label in TERMINAL_5PRIME:
        if token in rest:
            rest = rest.replace(token, "", 1)
            total = _add(total, contrib)
            cap5 = label
            break
    for token, contrib, label in TERMINAL_2PRIME_N:
        if token in rest:
            rest = rest.replace(token, "", 1)
            total = _add(total, contrib)
            term3 = label
            break
    if not _residual_is_trivial(rest):
        res["reason"] = ("unmodelled structural feature preceding the oligomer "
                         "core (conjugate linker or unrecognised terminal "
                         "group): %r" % rest[:160])
        return res

    # (b) trailer region: only a 5' cap may legitimately follow the core.
    trailer = trailer.lstrip("-")
    if trailer.startswith("5'"):
        hit = None
        for token, contrib, label in TERMINAL_5PRIME:
            if trailer.startswith(token):
                hit = (contrib, label)
                break
        if hit is None:
            res["reason"] = ("unrecognised 5'-terminal group after the "
                             "oligomer core: %r" % trailer[:160])
            return res
        if cap5 != "free 5'-OH":
            res["reason"] = "two 5'-terminal groups parsed for one molecule"
            return res
        total = _add(total, hit[0])
        cap5 = hit[1]

    res["terminus_5prime"] = cap5
    res["terminus_3prime"] = term3

    # ---------------- build the formula ----------------
    for b in bases:
        if b not in SUBUNIT:
            res["reason"] = "no model for residue %r" % b
            return res
        total = _add(total, SUBUNIT[b])
    prof = Counter()
    for ln in link_names:
        if ln not in LINKAGE:
            res["reason"] = "no model for linkage %r" % ln
            return res
        total = _add(total, LINKAGE[ln])
        prof[ln] += 1
    res["linkage_profile"] = ", ".join("%d x P-%s" % (v, k)
                                       for k, v in sorted(prof.items()))
    res["phosphorus_count"] = total.get("P", 0)
    res["computed_formula"] = format_formula(total)

    if total.get("S") or total.get("Na"):
        res["reason"] = "computed formula contains S or Na; not a PMO"
        return res

    # ---------------- compare ----------------
    if not res["stated_formula"]:
        res["reason"] = "entry states no molecular formula; nothing to check against"
        return res
    try:
        stated = parse_formula(res["stated_formula"])
    except ValueError as exc:
        res["reason"] = "stated formula unparsable: %s" % exc
        return res

    if Counter({k: v for k, v in stated.items() if v}) == \
       Counter({k: v for k, v in total.items() if v}):
        res["ok"] = True
        res["reason"] = ""
        return res

    diffs = []
    for el in sorted(set(stated) | set(total), key=lambda e: (
            _ELEMENT_ORDER.index(e) if e in _ELEMENT_ORDER else 99, e)):
        a, b = total.get(el, 0), stated.get(el, 0)
        if a != b:
            diffs.append("%s computed %d vs stated %d" % (el, a, b))
    res["reason"] = "formula mismatch: " + "; ".join(diffs)
    return res


# ---------------------------------------------------------------------------
# WHO list harvesting (the --run path)
# ---------------------------------------------------------------------------

WHO_BASE = ("https://cdn.who.int/media/docs/default-source/"
            "international-nonproprietary-names-(inn)/")
WHO_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
          "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")

PROPOSED_RANGE = range(100, 136)      # pl100 .. pl135
RECOMMENDED_RANGE = range(64, 96)     # rl64 .. rl95

_HEADWORD = re.compile(r"\n[ \t]*([a-z][a-zéíó \-]{2,40})um[ \t]*#?[ \t]*\n")
_FORMULA_TOKEN = re.compile(r"\bC\d{2,4}H\d{2,4}(?:[A-Z][a-z]?\d*)*\b")
_CAS = re.compile(r"\b\d{2,7}-\d{2}-\d\b")


def download_lists(dest: str, lists=None, verbose=True):
    """Fetch the WHO INN PDFs.  The CDN 403s urllib's default UA, so send a

    browser User-Agent."""
    import urllib.request
    names = lists or ([f"pl{i}" for i in PROPOSED_RANGE] +
                      [f"rl{i}" for i in RECOMMENDED_RANGE])
    os.makedirs(dest, exist_ok=True)
    got = []
    for n in names:
        path = os.path.join(dest, n + ".pdf")
        if os.path.exists(path) and os.path.getsize(path) > 10000:
            got.append((n, path))
            continue
        req = urllib.request.Request(WHO_BASE + n + ".pdf",
                                     headers={"User-Agent": WHO_UA})
        try:
            data = urllib.request.urlopen(req, timeout=120).read()
        except Exception as exc:                       # noqa: BLE001
            if verbose:
                print("  ! %s: %s" % (n, exc), file=sys.stderr)
            continue
        with open(path, "wb") as fh:
            fh.write(data)
        got.append((n, path))
        if verbose:
            print("  downloaded %s (%d bytes)" % (n, len(data)))
    return got


def pdf_text(path: str) -> str:
    import fitz
    doc = fitz.open(path)
    try:
        return "\n".join(page.get_text() for page in doc)
    finally:
        doc.close()


def find_pmo_entries(text: str, source: str = ""):
    """Yield dicts for every English-language PMO chemical name in one list."""
    t = _normalise(text)
    out = []
    # WHO's PDFs hyphenate across line breaks, so the stereodescriptors are
    # matched whitespace-insensitively.
    anchor_en = re.compile(r"all-P-\s*ambo")
    anchor_other = re.compile(r"(?:tout|todo)-P-\s*ambo")
    for m in anchor_en.finditer(t):
        start = m.start()
        nxt = anchor_other.search(t, start)
        end = nxt.start() if nxt else start + 9000
        block = t[start:end]
        if not any(mk in _squash(block) for mk in PMO_MARKERS):
            continue

        # INN headword: nearest preceding "<name>um" line
        pre = t[max(0, start - 2000):start]
        hw = list(_HEADWORD.finditer(pre))
        inn = hw[-1].group(1).strip() if hw else ""
        if inn and t[max(0, start - 2000):start].rfind(hw[-1].group(0)) < len(pre) - 1200:
            inn = inn + " (embedded)"

        # formula: first plausible token after the Spanish block, bounded by
        # the next INN headword so we never steal a neighbour's formula.
        tail = t[end:end + 9000]
        nxt = _HEADWORD.search(tail, 200)
        window = tail[:nxt.start()] if nxt else tail[:4000]
        fm = _FORMULA_TOKEN.search(window)
        formula = fm.group(0) if fm else ""
        cas = _CAS.search(window)
        out.append({
            "source": source,
            "inn": inn,
            "entry_text": block,
            "stated_formula": formula,
            "cas": cas.group(0) if cas else "",
        })
    return out


# formulas WHO does not print in the entry itself, taken from the FDA label
# (DailyMed SPL, DESCRIPTION section) and labelled as such in the output.
EXTERNAL_FORMULAS = {
    "eteplirsen": ("C364H569N177O122P30",
                   "FDA label via DailyMed SPL 33bff678-7829-479e-9110-b8e33a0bc0aa "
                   "(EXONDYS 51)"),
}


def run(workdir: str, out_csv: str, verbose: bool = True):
    pdfdir = os.path.join(workdir, "pdfs")
    if verbose:
        print("Downloading WHO INN lists into %s ..." % pdfdir)
    files = download_lists(pdfdir, verbose=verbose)

    rows = []
    for name, path in files:
        try:
            text = pdf_text(path)
        except Exception as exc:                       # noqa: BLE001
            if verbose:
                print("  ! text extraction failed for %s: %s" % (name, exc),
                      file=sys.stderr)
            continue
        for e in find_pmo_entries(text, source=name):
            stated = e["stated_formula"]
            src = "WHO INN entry"
            key = e["inn"].split(" ")[0].lower()
            if not stated and key in EXTERNAL_FORMULAS:
                stated, src = EXTERNAL_FORMULAS[key]
            r = validate(e["entry_text"], stated)
            rows.append({
                "who_list": name,
                "list_type": "Proposed" if name.startswith("pl") else "Recommended",
                "inn": e["inn"],
                "cas": e["cas"],
                "sequence_5to3": r["sequence_5to3"],
                "sequence_length": r["sequence_length"],
                "backbone_chemistry": r["backbone_chemistry"],
                "linkage_profile": r["linkage_profile"],
                "terminus_5prime": r["terminus_5prime"],
                "terminus_3prime": r["terminus_3prime"],
                "phosphorus_count": r["phosphorus_count"],
                "computed_formula": r["computed_formula"],
                "stated_formula": r["stated_formula"],
                "formula_source": src if r["stated_formula"] else "none stated",
                "verified": "YES" if r["ok"] else "NO",
                "reason": r["reason"],
            })

    rows.sort(key=lambda d: (d["inn"], d["who_list"]))
    with open(out_csv, "w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()) if rows else
                           ["who_list", "inn", "verified", "reason"])
        w.writeheader()
        w.writerows(rows)

    ok = sum(1 for r in rows if r["verified"] == "YES")
    if verbose:
        print("\n%d PMO entries found, %d verified, %d not." %
              (len(rows), ok, len(rows) - ok))
        for r in rows:
            print(" %-6s %-16s %-4s %-22s %s" %
                  (r["who_list"], r["inn"][:16], r["verified"],
                   r["computed_formula"], r["reason"][:90]))
        print("\nwrote %s" % out_csv)
    return rows


# ---------------------------------------------------------------------------
# self-test: the four marketed PMOs, no network needed
# ---------------------------------------------------------------------------

_SELFTEST = [
    # (name, sequence 5'->3', capped?, stated formula)
    ("eteplirsen",  "CTCCAACATCAAGGAAGATGGCATTTCTAG", True,
     "C364H569N177O122P30"),
    ("golodirsen",  "GTTGCCTCCGGTTCTGAAGGTGTTC", True,
     "C305H481N138O112P25"),
    ("viltolarsen", "CCTCCGGTTCTGAAGGTGTTC", False,
     "C244H381N113O88P20"),
    ("casimersen",  "CAATGCCATCCTGGAGTTCCTG", True,
     "C268H424N124O95P22"),
]


def compute_formula(sequence, capped=False, linkages=None,

                    extra_termini=()) -> Counter:
    """Formula for a PMO of `sequence` (5'->3').  `linkages` is an optional

    list of len(sequence)-1 P-substituent names; default all dimethylamino."""
    seq = [b.upper() for b in sequence]
    links = linkages or ["dimethylamino"] * (len(seq) - 1)
    total = Counter()
    for b in seq:
        total = _add(total, SUBUNIT[b])
    for ln in links:
        total = _add(total, LINKAGE[ln])
    if capped:
        total = _add(total, CAP_EG3_PIPERAZINE)
    for extra in extra_termini:
        total = _add(total, extra)
    return total


def selftest() -> bool:
    allok = True
    for name, seq, capped, stated in _SELFTEST:
        got = format_formula(compute_formula(seq, capped))
        ok = got == stated
        allok &= ok
        print("%-12s n=%-3d %-22s %s %s" %
              (name, len(seq), got, "==" if ok else "!=", stated))
    # radavirsen: 20-mer, capped, three P-(piperazin-1-yl) linkages
    rad_seq = "CGGTTAGAAGACTCATCTTT"
    rad_links = ["dimethylamino"] * 19
    for i in (3, 11, 16):
        rad_links[i] = "piperazin-1-yl"
    got = format_formula(compute_formula(rad_seq, True, rad_links))
    ok = got == "C253H398N116O87P20"
    allok &= ok
    print("%-12s n=%-3d %-22s %s %s" %
          ("radavirsen", 20, got, "==" if ok else "!=", "C253H398N116O87P20"))
    # vesleteplirsen: eteplirsen + Ac-(Arg)6-Gly on the terminal ring nitrogen
    got = format_formula(compute_formula(_SELFTEST[0][1], True,
                                         extra_termini=[_ac_arg6_gly()]))
    ok = got == "C404H646N202O130P30"
    allok &= ok
    print("%-12s n=%-3d %-22s %s %s" %
          ("vesletepl.", 30, got, "==" if ok else "!=", "C404H646N202O130P30"))
    print("\nself-test:", "PASS" if allok else "FAIL")
    return allok


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[2])
    ap.add_argument("--run", action="store_true",
                    help="download WHO lists and write pmo_results.csv")
    ap.add_argument("--selftest", action="store_true")
    ap.add_argument("--workdir", default=os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "who_inn_cache"))
    ap.add_argument("--out", default=os.path.join(
        os.path.dirname(os.path.abspath(__file__)), "pmo_results.csv"))
    a = ap.parse_args(argv)
    if a.selftest:
        return 0 if selftest() else 1
    if a.run:
        run(a.workdir, a.out)
        return 0
    ap.print_help()
    return 0


if __name__ == "__main__":
    sys.exit(main())