Download code/parse_inn_bridged.py from DBbun/oligotox-phase2-dataset: direct link, hf CLI and curl.
- Browser
- Download file 38.9 kB
-
https://huggingface.co/datasets/DBbun/oligotox-phase2-dataset/resolve/main/code/parse_inn_bridged.py
- Command line
-
hf download hf://datasets/DBbun/oligotox-phase2-dataset/code/parse_inn_bridged.py
-
curl -L -o parse_inn_bridged.py https://huggingface.co/datasets/DBbun/oligotox-phase2-dataset/resolve/main/code/parse_inn_bridged.py
38.9 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| parse_inn_bridged.py | |
| ==================== | |
| Extract bridged / constrained-sugar antisense gapmer structures (LNA, cEt, ENA, | |
| and the 2'-MOE / 2'-OMe / DNA residues they are mixed with) from WHO INN | |
| Proposed- and Recommended-list PDFs, and validate every structure by | |
| recomputing its molecular formula from first principles and comparing it, | |
| element for element, with the formula WHO prints in the same entry. | |
| A structure is "verified" ONLY if computed == stated exactly. No formula is | |
| ever nudged to make it agree. | |
| Source PDFs | |
| ----------- | |
| https://cdn.who.int/media/docs/default-source/international-nonproprietary-names-(inn)/pl<N>.pdf N = 100..135 | |
| https://cdn.who.int/media/docs/default-source/international-nonproprietary-names-(inn)/rl<N>.pdf N = 64..95 | |
| The WHO CDN rejects urllib's default User-Agent with HTTP 403, so a browser UA | |
| is sent. | |
| Chemistry | |
| --------- | |
| Residues are joined by "(3'->5')". Each residue token carries its own sugar | |
| descriptor, optional 5-methylation and backbone marker. "P-thio" marks the | |
| phosphorothioate linkage leaving that residue. The 3'-terminal residue is a | |
| nucleoside (-osine / -idine), not a -ylyl. | |
| Nucleoside atom counts (free nucleosides): | |
| 2'-deoxy: A C10H13N5O3 | G C10H13N5O4 | C C9H13N3O4 | T C10H14N2O5 | m5C C10H15N3O4 | |
| ribo: A C10H13N5O4 | G C10H13N5O5 | C C9H13N3O5 | U C9H12N2O6 | |
| m5U C10H14N2O6 | m5C C10H15N3O5 | |
| Sugar modifications, all applied to the RIBO nucleoside: | |
| 2'-O-methyl + CH2 | |
| 2'-O-(2-methoxyethyl) (MOE) + C3H6O | |
| 2'-O,4'-C-methylene (LNA) + C <- derivation below | |
| 2'-O,4'-C-[(1S)-ethane-1,1-diyl] ((S)-cEt) + C2H2 | |
| 2'-O,4'-C-(ethane-1,2-diyl) (ENA) + C2H2 | |
| 2'-deoxy-2'-fluoro (2'-F) deoxy nucleoside, - H + F | |
| DERIVATION OF THE BRIDGED SUGARS | |
| -------------------------------- | |
| LNA, "2'-O,4'-C-methylene": a methylene group is inserted between the 2'-oxygen | |
| and the 4'-carbon of the ribo sugar, closing a 2,5-dioxabicyclo[2.2.1]heptane. | |
| Forming that bridge consumes the hydrogen of the 2'-OH (the 2'-O becomes a | |
| disubstituted ether) and the single hydrogen on C4' (which becomes quaternary: | |
| C3', C5', O4', CH2-bridge). So, starting from the ribo nucleoside, | |
| + CH2 (the bridge) - 2 H (one from O2'-H, one from C4'-H) | |
| = + C1 H0 | |
| i.e. the LNA nucleoside is the ribo nucleoside with exactly one extra carbon and | |
| the SAME hydrogen count. Example: LNA-A = C11H13N5O4, LNA-G = C11H13N5O5, | |
| LNA-5-methyl-C = C11H15N3O5, LNA-5-methyl-U = C11H14N2O6. | |
| (S)-cEt, "2'-O,4'-C-[(1S)-ethane-1,1-diyl]": identical bridge topology, but the | |
| bridging unit is the divalent ethane-1,1-diyl fragment -CH(CH3)-, i.e. C2H4, | |
| in place of -CH2-. Same two hydrogens are lost from O2' and C4': | |
| + C2H4 - 2 H = + C2 H2 | |
| ENA, "2'-O,4'-C-(ethane-1,2-diyl)": the bridge is -CH2CH2-, also C2H4 as a | |
| divalent fragment, bridging the same two atoms, so it gives the same increment: | |
| + C2H4 - 2 H = + C2 H2 | |
| (cEt and ENA are constitutional isomers; they are distinguished in the parsed | |
| sugar pattern but are arithmetically identical, as they must be.) | |
| Assembly | |
| -------- | |
| For n residues there are n-1 internucleoside linkages. Each linkage condenses a | |
| 3'-OH and a 5'-OH with phosphoric acid: | |
| + P + 2 O - 1 H | |
| A phosphorothioate linkage additionally replaces one of its oxygens with sulfur | |
| (- O + S). The sodium salt replaces one acidic hydrogen per linkage with Na | |
| (- H + Na per linkage). | |
| Self-test | |
| --------- | |
| Running this file executes a built-in self-test on inotersen (TCTTGGTTACATG | |
| AAATCCC, 5-10-5 2'-MOE gapmer, all 19 linkages phosphorothioate, every | |
| pyrimidine 5-methylated), which must give C230H318N69O121P19S19 as the free acid | |
| and C230H299N69Na19O121P19S19 as the sodium salt, and on the LNA gapmer | |
| apazunersen (WHO Recommended List 94), C184H224N67O96P17S17. | |
| Usage | |
| ----- | |
| python parse_inn_bridged.py --self-test | |
| python parse_inn_bridged.py --run # download, parse, write CSV | |
| python parse_inn_bridged.py --run --cache DIR --out bridged_results.csv | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import concurrent.futures | |
| import csv | |
| import os | |
| import re | |
| import sys | |
| import urllib.request | |
| from collections import Counter, OrderedDict | |
| # --------------------------------------------------------------------------- # | |
| # 0. Constants | |
| # --------------------------------------------------------------------------- # | |
| WHO_BASE = ("https://cdn.who.int/media/docs/default-source/" | |
| "international-nonproprietary-names-(inn)/") | |
| BROWSER_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_LISTS = [f"pl{n}" for n in range(100, 136)] | |
| RECOMMENDED_LISTS = [f"rl{n}" for n in range(64, 96)] | |
| ALL_LISTS = PROPOSED_LISTS + RECOMMENDED_LISTS | |
| ARROW = "(3'→5')" # (3'->5') as printed, with the Unicode arrow | |
| ARROW_ASCII = "(3'->5')" | |
| # WHO's typesetting is not consistent: some lists (and sometimes different | |
| # residues within one name) use the typographic prime U+2032 or a curly | |
| # apostrophe U+2019 where others use the ASCII apostrophe. Everything is | |
| # normalised to the ASCII apostrophe before parsing. | |
| _PRIME_MAP = {ord("′"): "'", ord("″"): "''", ord("’"): "'", | |
| ord("‘"): "'", ord("´"): "'", | |
| ord("‐"): "-", ord("‑"): "-", ord("−"): "-", | |
| ord("–"): "-", ord(" "): " ", ord("➔"): "→", | |
| ord("➜"): "→", ord("⇢"): "→"} | |
| def normalise_typography(s): | |
| """Map prime/apostrophe/dash/arrow variants onto their ASCII equivalents.""" | |
| return s.translate(_PRIME_MAP) | |
| # Hill-order-ish element print order used by WHO: C, H, N, (metals), O, P, S, F | |
| ELEMENT_ORDER = ["C", "H", "B", "Br", "Cl", "F", "I", "K", "N", "Na", "O", "P", "S"] | |
| # --------------------------------------------------------------------------- # | |
| # 1. Formula arithmetic | |
| # --------------------------------------------------------------------------- # | |
| def _f(**kw): | |
| """Build a formula Counter from keyword atom counts.""" | |
| return Counter({k: v for k, v in kw.items() if v}) | |
| def fadd(a, b, mult=1): | |
| out = Counter(a) | |
| for el, n in b.items(): | |
| out[el] += n * mult | |
| return out | |
| def formula_to_string(f): | |
| """Render a Counter as a WHO-style formula string.""" | |
| parts = [] | |
| known = [e for e in ELEMENT_ORDER if f.get(e, 0)] | |
| extra = sorted(e for e in f if f[e] and e not in ELEMENT_ORDER) | |
| for el in known + extra: | |
| n = f[el] | |
| parts.append(el if n == 1 else f"{el}{n}") | |
| return "".join(parts) | |
| _FORMULA_TOKEN = re.compile(r"([A-Z][a-z]?)(\d*)") | |
| def parse_formula(s): | |
| """Parse a molecular formula string into a Counter. Returns None if invalid.""" | |
| if not s: | |
| return None | |
| s = s.strip().replace(" ", "") | |
| if not re.fullmatch(r"(?:[A-Z][a-z]?\d*)+", s): | |
| return None | |
| out = Counter() | |
| for el, n in _FORMULA_TOKEN.findall(s): | |
| out[el] += int(n) if n else 1 | |
| return out | |
| def formulas_equal(a, b): | |
| if a is None or b is None: | |
| return False | |
| els = set(a) | set(b) | |
| return all(a.get(e, 0) == b.get(e, 0) for e in els) | |
| def formula_diff(computed, stated): | |
| """Human-readable element-by-element difference computed - stated.""" | |
| els = sorted(set(computed) | set(stated), key=lambda e: (ELEMENT_ORDER.index(e) | |
| if e in ELEMENT_ORDER else 99, e)) | |
| bits = [] | |
| for e in els: | |
| d = computed.get(e, 0) - stated.get(e, 0) | |
| if d: | |
| bits.append(f"{e}{d:+d}") | |
| return " ".join(bits) if bits else "(none)" | |
| # --------------------------------------------------------------------------- # | |
| # 2. Nucleoside atom counts | |
| # --------------------------------------------------------------------------- # | |
| # Free 2'-deoxyribonucleosides | |
| DEOXY = { | |
| "A": _f(C=10, H=13, N=5, O=3), | |
| "G": _f(C=10, H=13, N=5, O=4), | |
| "C": _f(C=9, H=13, N=3, O=4), | |
| "T": _f(C=10, H=14, N=2, O=5), # = 5-methyl-2'-deoxyuridine (thymidine) | |
| "mC": _f(C=10, H=15, N=3, O=4), # 5-methyl-2'-deoxycytidine | |
| "U": _f(C=9, H=12, N=2, O=4 + 1), # 2'-deoxyuridine, C9H12N2O5 | |
| } | |
| # Free ribonucleosides | |
| RIBO = { | |
| "A": _f(C=10, H=13, N=5, O=4), | |
| "G": _f(C=10, H=13, N=5, O=5), | |
| "C": _f(C=9, H=13, N=3, O=5), | |
| "U": _f(C=9, H=12, N=2, O=6), | |
| "mU": _f(C=10, H=14, N=2, O=6), # 5-methyluridine (ribothymidine) | |
| "mC": _f(C=10, H=15, N=3, O=5), # 5-methylcytidine | |
| "I": _f(C=10, H=12, N=4, O=5), # inosine | |
| } | |
| # Sugar increments applied to the RIBO nucleoside. | |
| # See the module docstring for the derivation of each bridged sugar. | |
| SUGAR_INCREMENT = { | |
| "MOE": _f(C=3, H=6, O=1), # 2'-O-(2-methoxyethyl) | |
| "OMe": _f(C=1, H=2), # 2'-O-methyl | |
| "LNA": _f(C=1), # 2'-O,4'-C-methylene : +CH2 -2H | |
| "cEt": _f(C=2, H=2), # 2'-O,4'-C-[(1S)-ethane-1,1-diyl] : +C2H4 -2H | |
| "ENA": _f(C=2, H=2), # 2'-O,4'-C-(ethane-1,2-diyl) : +C2H4 -2H | |
| } | |
| RIBO_SUGARS = set(SUGAR_INCREMENT) | {"RNA"} | |
| BRIDGED_SUGARS = {"LNA", "cEt", "ENA"} | |
| LINKAGE = _f(P=1, O=2, H=-1) # per internucleoside phosphodiester | |
| THIO_SWAP = _f(O=-1, S=1) # phosphodiester -> phosphorothioate | |
| NA_SWAP = _f(H=-1, Na=1) # one acidic H -> Na, per linkage | |
| def nucleoside_formula(base, sugar, methylated): | |
| """ | |
| Atom count of a single free nucleoside. | |
| base : 'A' | 'G' | 'C' | 'U' | 'T' | 'I' | |
| sugar : 'DNA' | 'RNA' | 'OMe' | 'MOE' | 'LNA' | 'cEt' | 'ENA' | '2F' | |
| methylated : True if the pyrimidine carries a 5-methyl group | |
| """ | |
| if sugar == "DNA": | |
| if base == "T": | |
| return Counter(DEOXY["T"]) | |
| if base == "U": | |
| return Counter(DEOXY["T"]) if methylated else Counter(DEOXY["U"]) | |
| if base == "C": | |
| return Counter(DEOXY["mC"] if methylated else DEOXY["C"]) | |
| if base in ("A", "G"): | |
| return Counter(DEOXY[base]) | |
| raise ValueError(f"no 2'-deoxy count for base {base!r}") | |
| if sugar == "2F": | |
| # 2'-deoxy-2'-fluoro: the 2'-deoxy nucleoside with one H replaced by F | |
| core = nucleoside_formula(base, "DNA", methylated) | |
| core["H"] -= 1 | |
| core["F"] += 1 | |
| return core | |
| # all remaining sugars are built on the ribo nucleoside | |
| if base == "T": | |
| # "thymidylyl" with a ribo-type sugar means 5-methyluridine | |
| core = Counter(RIBO["mU"]) | |
| elif base == "U": | |
| core = Counter(RIBO["mU"] if methylated else RIBO["U"]) | |
| elif base == "C": | |
| core = Counter(RIBO["mC"] if methylated else RIBO["C"]) | |
| elif base in ("A", "G", "I"): | |
| core = Counter(RIBO[base]) | |
| else: | |
| raise ValueError(f"no ribo count for base {base!r}") | |
| if sugar != "RNA": | |
| core = fadd(core, SUGAR_INCREMENT[sugar]) | |
| return core | |
| def assemble(residues, sodium=False, terminal_ester=None): | |
| """ | |
| residues : list of dicts with keys base, sugar, methyl, thio, term_phosphate | |
| (the last residue's `thio` describes its 3'-terminal phosphate, | |
| if it has one; otherwise it has no outgoing linkage) | |
| terminal_ester : formula Counter of the FREE alcohol esterifying a 3'-terminal | |
| phosphate, or None for a free 3'-phosphoric acid. Ignored unless | |
| the last residue is a -3'-...ylate. | |
| Returns the molecular formula Counter of the assembled oligonucleotide. | |
| """ | |
| total = Counter() | |
| for r in residues: | |
| total = fadd(total, nucleoside_formula(r["base"], r["sugar"], r["methyl"])) | |
| # internucleoside linkages | |
| n_link = len(residues) - 1 | |
| total = fadd(total, LINKAGE, n_link) | |
| n_thio = sum(1 for r in residues[:-1] if r["thio"]) | |
| # a 3'-terminal phosphate(-ester) is arithmetically one more linkage, joining | |
| # the 3'-OH of the last nucleoside to an alcohol R-OH (water if free acid) | |
| last = residues[-1] | |
| if last.get("term_phosphate"): | |
| total = fadd(total, LINKAGE) | |
| total = fadd(total, terminal_ester if terminal_ester is not None else WATER) | |
| n_link += 1 | |
| if last["thio"]: | |
| n_thio += 1 | |
| total = fadd(total, THIO_SWAP, n_thio) | |
| if sodium: | |
| total = fadd(total, NA_SWAP, n_link) | |
| return total | |
| # --------------------------------------------------------------------------- # | |
| # 3. Residue-token parsing | |
| # --------------------------------------------------------------------------- # | |
| # Sugar descriptors, longest/most specific first. Each entry is | |
| # (regex, sugar code, implies 5-methyl). | |
| SUGAR_PATTERNS = [ | |
| (r"2'-O,4'-C-\[\(1[SR]\)-ethane-1,1-diyl\]", "cEt", False), | |
| (r"2'-O,4'-C-\[\([SR]\)-ethylidene\]", "cEt", False), | |
| (r"2'-O,4'-C-\(ethane-1,2-diyl\)", "ENA", False), | |
| (r"2'-O,4'-C-ethylene", "ENA", False), | |
| (r"2'-O,4'-C-methylene", "LNA", False), | |
| (r"2'-O-\(2-methoxyethyl\)", "MOE", False), | |
| (r"2'-O,5-dimethyl", "OMe", True), # 2'-OMe + 5-Me | |
| (r"2'-O-methyl", "OMe", False), | |
| (r"2'-deoxy-2'-fluoro", "2F", False), | |
| (r"2'-deoxy", "DNA", False), | |
| ] | |
| SUGAR_RE = [(re.compile(p), code, meth) for p, code, meth in SUGAR_PATTERNS] | |
| # Base stems. -ylyl = internal residue, -osine/-idine = 3'-terminal nucleoside, | |
| # -3'-...ylate = 3'-terminal residue that still carries a 3'-phosphate(-ester). | |
| BASE_STEMS = [ | |
| ("3'-adenylate", "A", True, True), ("3'-guanylate", "G", True, True), | |
| ("3'-cytidylate", "C", True, True), ("3'-uridylate", "U", True, True), | |
| ("3'-thymidylate", "T", True, True), ("3'-inosinate", "I", True, True), | |
| ("adenylyl", "A", False, False), ("adenosine", "A", True, False), | |
| ("guanylyl", "G", False, False), ("guanosine", "G", True, False), | |
| ("cytidylyl", "C", False, False), ("cytidine", "C", True, False), | |
| ("uridylyl", "U", False, False), ("uridine", "U", True, False), | |
| ("thymidylyl", "T", False, False), ("thymidine", "T", True, False), | |
| ("inosinyl", "I", False, False), ("inosine", "I", True, False), | |
| ] | |
| # Alcohols that WHO names as the ester of a 3'-terminal phosphate, written as a | |
| # leading "O-(...)" word in front of the oligonucleotide name. The value is the | |
| # atom count of the FREE alcohol R-OH; a free 3'-phosphate uses water instead. | |
| TERMINAL_ESTER_ALCOHOLS = { | |
| "O-(2-hydroxyethyl)": _f(C=2, H=6, O=2), # ethylene glycol, HOCH2CH2OH | |
| } | |
| WATER = _f(H=2, O=1) | |
| # Printing typos observed in the WHO text layer. These are repairs to the | |
| # PRINTED STRING only - they do not change any atom count, and each one is a | |
| # transposition of characters within one descriptor. "2-O'-methyl" for | |
| # "2'-O-methyl" occurs in the English renapersen / renadirsen entries. | |
| TEXT_TYPO_FIXES = [ | |
| (re.compile(r"2-O'-methyl"), "2'-O-methyl"), | |
| ] | |
| # Stereo / salt / backbone prefixes that carry no atoms of their own | |
| STRIPPABLE_PREFIXES = re.compile( | |
| r"^(?:all-P-ambo-|tout-P-ambo-|todo-P-ambo-|all-P-[RS]-|P-ambo-)") | |
| # Anything that signals a conjugate / cap / non-standard construct we do not | |
| # attempt to count. Presence of one of these makes the entry a reported failure. | |
| UNSUPPORTED_RE = re.compile( | |
| r"poly\(oxyethylene\)|phospha|carbonyl|amino\)|galactopyranos|GalNAc|" | |
| r"acetamido|-oyl\)|oxy\)\(hydroxy\)phosphoryl|\(5'→3'\)|\(5'->3'\)|" | |
| r"4'-C-\(chloromethyl\)|morpholin|-oxy\]|\]oxy") | |
| class ParseError(Exception): | |
| pass | |
| def parse_residue(tok): | |
| """ | |
| Parse one residue token, e.g. | |
| "5-methyl-2'-O,4'-C-methylene-P-thiocytidylyl" | |
| "2'-deoxy-P-thioadenylyl" | |
| "P-thiothymidylyl" | |
| "2'-O,4'-C-methyleneguanosine" | |
| Returns dict(base, sugar, methyl, thio, terminal). | |
| """ | |
| original = tok | |
| tok = STRIPPABLE_PREFIXES.sub("", tok) | |
| # 5-methyl marker. WHO prints it either before or after the sugar | |
| # descriptor ("5-methyl-2'-O,4'-C-methylene-..." and | |
| # "2'-O-(2-methoxyethyl)-5-methyl-..." both occur), and on a 3'-terminal | |
| # nucleoside it runs straight into the base stem ("5-methylcytidine"). | |
| methyl = False | |
| m5 = re.search(r"(?:^|-)5-methyl(?!ene)", tok) | |
| if m5: | |
| methyl = True | |
| tok = (tok[:m5.start()] + "-" + tok[m5.end():]).strip("-") | |
| # sugar | |
| sugar = None | |
| for rx, code, implies_methyl in SUGAR_RE: | |
| m = rx.search(tok) | |
| if m: | |
| sugar = code | |
| if implies_methyl: | |
| methyl = True | |
| tok = (tok[:m.start()] + tok[m.end():]).strip("-") | |
| break | |
| # backbone | |
| thio = False | |
| if re.search(r"(?:^|-)P-thio", tok): | |
| thio = True | |
| tok = re.sub(r"(?:^|-)P-thio", "-", tok, count=1).lstrip("-") | |
| tok = tok.strip("-") | |
| # base | |
| base = terminal = None | |
| term_phos = False | |
| for stem, b, is_term, is_phos in BASE_STEMS: | |
| if tok.endswith(stem): | |
| base, terminal, term_phos = b, is_term, is_phos | |
| tok = tok[:-len(stem)].strip("-") | |
| break | |
| if base is None: | |
| raise ParseError(f"unrecognised base stem in residue {original!r}") | |
| # thymidine/thymidylyl without an explicit sugar descriptor is 2'-deoxy | |
| if sugar is None: | |
| if base == "T": | |
| sugar = "DNA" | |
| else: | |
| raise ParseError(f"no sugar descriptor in residue {original!r}") | |
| if base == "T": | |
| methyl = True # thymine IS 5-methyluracil | |
| # anything left over is an unaccounted substituent -> refuse to guess | |
| if tok: | |
| raise ParseError(f"unaccounted substituent {tok!r} in residue {original!r}") | |
| return dict(base=base, sugar=sugar, methyl=methyl, thio=thio, | |
| terminal=terminal, term_phosphate=term_phos) | |
| SUGAR_SYMBOL = { | |
| "DNA": "d", "RNA": "r", "OMe": "m", "MOE": "M", | |
| "LNA": "L", "cEt": "E", "ENA": "N", "2F": "f", | |
| } | |
| def sugar_pattern(residues): | |
| return "".join(SUGAR_SYMBOL[r["sugar"]] for r in residues) | |
| def gapmer_layout(residues): | |
| """ | |
| Describe the wing-gap-wing layout, e.g. '3-11-4 (LNA/DNA)'. | |
| Returns 'uniform' or 'mixed' when the chain is not a clean 3-block gapmer. | |
| """ | |
| classes = [] | |
| for r in residues: | |
| if r["sugar"] == "DNA": | |
| classes.append("DNA") | |
| elif r["sugar"] in BRIDGED_SUGARS or r["sugar"] in ("MOE", "OMe", "2F", "RNA"): | |
| classes.append(r["sugar"]) | |
| else: | |
| classes.append(r["sugar"]) | |
| # run-length encode | |
| runs = [] | |
| for c in classes: | |
| if runs and runs[-1][0] == c: | |
| runs[-1][1] += 1 | |
| else: | |
| runs.append([c, 1]) | |
| if len(runs) == 1: | |
| return f"uniform {runs[0][1]} x {runs[0][0]}" | |
| if len(runs) == 3 and runs[1][0] == "DNA" and runs[0][0] == runs[2][0]: | |
| return f"{runs[0][1]}-{runs[1][1]}-{runs[2][1]} ({runs[0][0]}/DNA)" | |
| # Separate the run length from the chemistry name. Without it farabursen's | |
| # three 2'-F residues render as "32F", which reads as thirty-two fluorines. | |
| return "mixed: " + "-".join(f"{n}x{c}" for c, n in runs) | |
| SEQ_LETTER = {"A": "A", "G": "G", "C": "C", "U": "U", "T": "T", "I": "I"} | |
| def seq_letter(r): | |
| """ | |
| Base letter for the reported sequence. 5-Methyluracil IS thymine, so a | |
| 5-methyluridylyl residue on any sugar is reported as T (the convention used | |
| on antisense drug labels); an unmethylated uridine stays U. 5-Methylcytosine | |
| is still reported as C. | |
| """ | |
| if r["base"] in ("U", "T"): | |
| return "T" if r["methyl"] else "U" | |
| return SEQ_LETTER[r["base"]] | |
| # --------------------------------------------------------------------------- # | |
| # 4. The public validator | |
| # --------------------------------------------------------------------------- # | |
| def _blank(stated_formula, reason): | |
| return dict(ok=False, sequence_5to3="", sequence_length=0, | |
| sugar_pattern_5to3="", gapmer_layout="", n_phosphorothioate=0, | |
| computed_formula="", stated_formula=stated_formula or "", | |
| reason=reason) | |
| def validate(entry_text, stated_formula): | |
| """ | |
| Validate a single WHO INN oligonucleotide entry. | |
| entry_text : the systematic chemical name as printed (line breaks and | |
| whitespace are tolerated; the Unicode arrow or '->' both | |
| work). | |
| stated_formula : the molecular formula WHO prints for the same entry. | |
| Returns a dict with keys: | |
| ok, sequence_5to3, sequence_length, sugar_pattern_5to3, | |
| gapmer_layout, n_phosphorothioate, computed_formula, | |
| stated_formula, reason | |
| """ | |
| if not entry_text: | |
| return _blank(stated_formula, "empty entry text") | |
| name = re.sub(r"\s+", "", normalise_typography(entry_text)) | |
| name = name.replace(ARROW_ASCII, ARROW).replace("(3'→5')", ARROW) | |
| for rx, rep in TEXT_TYPO_FIXES: | |
| name = rx.sub(rep, name) | |
| if ARROW not in name: | |
| return _blank(stated_formula, "no (3'->5') linkages found in entry text") | |
| # The whole entry block is screened, not just the residue chain, so that a | |
| # 5'- or 3'-conjugate printed before or after the chain cannot be silently | |
| # dropped and then produce a spurious "match". | |
| bad = UNSUPPORTED_RE.search(name) | |
| if bad: | |
| return _blank(stated_formula, | |
| f"unsupported construct (conjugate/cap/branch): {bad.group(0)!r}") | |
| # A bare leading "hydrogen" means WHO printed this oligonucleotide as the | |
| # hydrogen (mono)ester of a terminal phosphate whose OTHER ester group - | |
| # typically a GalNAc cluster or a lipid - is named in the preceding part of | |
| # the entry. That conjugate is not counted here, so this is a failure. | |
| if name.startswith("hydrogen"): | |
| return _blank(stated_formula, | |
| "unsupported construct: printed as a 'hydrogen' phosphate " | |
| "monoester, i.e. conjugated to a group named outside the " | |
| "oligonucleotide chain") | |
| # A 3'-terminal phosphate may be printed as its ester, with the alcohol | |
| # named as a leading "O-(...)" word. | |
| terminal_ester = None | |
| for label, formula in TERMINAL_ESTER_ALCOHOLS.items(): | |
| key = label.replace(" ", "") | |
| if name.startswith(key): | |
| terminal_ester = formula | |
| name = name[len(key):] | |
| break | |
| if re.match(r"^O-\(", name): | |
| return _blank(stated_formula, | |
| f"unrecognised terminal ester alcohol: {name[:40]!r}") | |
| stated = parse_formula(stated_formula) | |
| if stated is None: | |
| return _blank(stated_formula, "no molecular formula stated in this entry" | |
| if not stated_formula else | |
| f"could not parse stated formula {stated_formula!r}") | |
| toks = name.split("-" + ARROW + "-") | |
| if len(toks) < 2: | |
| return _blank(stated_formula, "could not split residues on -(3'->5')-") | |
| residues = [] | |
| try: | |
| for i, t in enumerate(toks): | |
| r = parse_residue(t) | |
| if r["terminal"] and i != len(toks) - 1: | |
| raise ParseError(f"terminal nucleoside at position {i+1} of " | |
| f"{len(toks)}") | |
| if not r["terminal"] and i == len(toks) - 1: | |
| raise ParseError("last residue is not a terminal nucleoside " | |
| "(name looks truncated)") | |
| residues.append(r) | |
| except ParseError as e: | |
| return _blank(stated_formula, str(e)) | |
| seq = "".join(seq_letter(r) for r in residues) | |
| pat = sugar_pattern(residues) | |
| layout = gapmer_layout(residues) | |
| n_ps = sum(1 for r in residues[:-1] if r["thio"]) | |
| if residues[-1].get("term_phosphate") and residues[-1]["thio"]: | |
| n_ps += 1 # the 3'-terminal phosphorothioate monoester | |
| sodium = stated.get("Na", 0) > 0 | |
| computed = assemble(residues, sodium=sodium, terminal_ester=terminal_ester) | |
| comp_s = formula_to_string(computed) | |
| ok = formulas_equal(computed, stated) | |
| reason = ("exact match" if ok | |
| else "formula mismatch, computed - stated = " | |
| + formula_diff(computed, stated)) | |
| return dict(ok=ok, | |
| sequence_5to3=seq, | |
| sequence_length=len(residues), | |
| sugar_pattern_5to3=pat, | |
| gapmer_layout=layout, | |
| n_phosphorothioate=n_ps, | |
| computed_formula=comp_s, | |
| stated_formula=formula_to_string(stated), | |
| reason=reason) | |
| # --------------------------------------------------------------------------- # | |
| # 5. PDF acquisition and text extraction | |
| # --------------------------------------------------------------------------- # | |
| def download_list(name, cache_dir): | |
| """Download pl<N>.pdf / rl<N>.pdf into cache_dir. Returns path or None.""" | |
| os.makedirs(cache_dir, exist_ok=True) | |
| path = os.path.join(cache_dir, name + ".pdf") | |
| if os.path.exists(path) and os.path.getsize(path) > 50_000: | |
| return path | |
| req = urllib.request.Request(WHO_BASE + name + ".pdf", | |
| headers={"User-Agent": BROWSER_UA}) | |
| try: | |
| data = urllib.request.urlopen(req, timeout=180).read() | |
| except Exception as e: | |
| sys.stderr.write(f" [warn] {name}: download failed: {e}\n") | |
| return None | |
| with open(path, "wb") as fh: | |
| fh.write(data) | |
| return path | |
| def pdf_text(path): | |
| """Extract the text layer. Prefers PyMuPDF, falls back to pdfplumber/pypdf.""" | |
| try: | |
| import fitz # PyMuPDF | |
| doc = fitz.open(path) | |
| try: | |
| return "\n".join(p.get_text() for p in doc) | |
| finally: | |
| doc.close() | |
| except ImportError: | |
| pass | |
| try: | |
| import pdfplumber | |
| with pdfplumber.open(path) as pdf: | |
| return "\n".join(p.extract_text() or "" for p in pdf.pages) | |
| except ImportError: | |
| pass | |
| from pypdf import PdfReader | |
| return "\n".join(p.extract_text() or "" for p in PdfReader(path).pages) | |
| def glue_lines(text): | |
| """ | |
| WHO wraps systematic names mid-token, always immediately after a hyphen. | |
| Joining a line to the previous one whenever the previous one ends in '-' | |
| reconstructs each chemical name as a single whitespace-free token. | |
| """ | |
| text = normalise_typography(text) | |
| out = [] | |
| for raw in text.split("\n"): | |
| s = raw.strip() | |
| if not s: | |
| continue | |
| if out and out[-1].endswith("-"): | |
| out[-1] = out[-1] + s | |
| else: | |
| out.append(s) | |
| return out | |
| # French / Spanish name markers - the same molecule is printed three times per | |
| # entry and only the English name is parsed. | |
| NON_ENGLISH = re.compile( | |
| r"méth|désoxy|desoxi|metileno|méthylène|tio[a-z]*ilil|" | |
| r"ilil-|tout-P-ambo|todo-P-ambo|-ilil|citidilil|guanilil|adenilil|" | |
| r"thiodésoxy|méthoxyéthyl") | |
| TERMINAL_RE = re.compile( | |
| r"(adenosine|guanosine|cytidine|uridine|thymidine|inosine|" | |
| r"3'-adenylate|3'-guanylate|3'-cytidylate|3'-uridylate|3'-thymidylate)") | |
| FORMULA_RE = re.compile(r"^C\d+H\d+[A-Za-z0-9]*$") | |
| INN_NAME_RE = re.compile(r"^[a-z][a-z\-]{4,}$") | |
| BRIDGE_MARKER = re.compile( | |
| r"2'-O,4'-C-methylene|2'-O,4'-C-\[\(1?[SR]\)-eth|2'-O,4'-C-\(ethane|" | |
| r"2'-O,4'-C-ethylene|constrained ethyl|2',4'-BNA|\bLNA\b|\(S\)-cEt|\bcEt\b") | |
| def find_entries(text, source): | |
| """ | |
| Walk a WHO list's glued text and yield one record per English-language | |
| oligonucleotide name that contains a bridged-sugar residue. | |
| Yields dicts: source, inn_name, chemical_name, stated_formula. | |
| """ | |
| lines = glue_lines(text) | |
| n = len(lines) | |
| out = [] | |
| i = 0 | |
| while i < n: | |
| L = lines[i] | |
| if ARROW not in L: | |
| i += 1 | |
| continue | |
| if NON_ENGLISH.search(L): | |
| i += 1 | |
| continue | |
| # The glued element normally IS the complete systematic name, including | |
| # any 5'- or 3'-conjugate printed with it. It is kept UNTRIMMED and | |
| # handed to validate() whole: trimming it here would silently discard a | |
| # conjugate and could turn a non-match into a false "verified". | |
| block = L.strip() | |
| j = i | |
| guard = 0 | |
| while guard < 20 and _trim_name(block) is None: | |
| # The name was split across a page break; stitch the next fragment. | |
| guard += 1 | |
| j += 1 | |
| if j >= n: | |
| break | |
| nxt = lines[j].strip() | |
| if (" " in nxt or not nxt | |
| or nxt.lower().startswith(("who", "proposed", "recommended")) | |
| or nxt.isdigit()): | |
| continue | |
| if NON_ENGLISH.search(nxt): | |
| break | |
| block = block + nxt | |
| if not BRIDGE_MARKER.search(block): | |
| i += 1 | |
| continue | |
| # Back up for the INN name (the plain lowercase word just above). | |
| inn = "" | |
| for k in range(i - 1, max(-1, i - 6), -1): | |
| cand = lines[k].strip() | |
| if INN_NAME_RE.match(cand) and not cand.endswith("um"): | |
| inn = cand | |
| break | |
| if INN_NAME_RE.match(cand): | |
| inn = cand | |
| # Forward for the molecular formula. The search stops at the next | |
| # entry's Latin INN (".....um" on a line of its own) so that an entry | |
| # which prints no formula cannot borrow the next drug's formula and | |
| # produce a bogus mismatch - or, worse, a bogus match. | |
| stated = "" | |
| for k in range(max(i, j), min(n, max(i, j) + 140)): | |
| cand = lines[k].strip().replace(" ", "") | |
| if re.fullmatch(r"[a-z]{6,}um", cand): | |
| break | |
| if FORMULA_RE.match(cand) and "P" in cand: | |
| stated = cand | |
| break | |
| out.append(dict(source=source, inn_name=inn, chemical_name=block, | |
| stated_formula=stated)) | |
| i = max(i, j) + 1 | |
| return out | |
| def _trim_name(tok): | |
| """ | |
| Trim a glued token down to the systematic name: cut after the 3'-terminal | |
| nucleoside that follows the final (3'->5') linkage. Returns None if the | |
| token does not yet contain a terminal nucleoside (i.e. it is a fragment that | |
| must be stitched to the next line). | |
| """ | |
| pos = tok.rfind(ARROW) | |
| if pos < 0: | |
| return None | |
| m = TERMINAL_RE.search(tok, pos) | |
| if not m: | |
| return None | |
| return tok[:m.end()] | |
| # --------------------------------------------------------------------------- # | |
| # 6. Driver | |
| # --------------------------------------------------------------------------- # | |
| def run(cache_dir, out_csv, lists=None, workers=6): | |
| lists = lists or ALL_LISTS | |
| print(f"Fetching {len(lists)} WHO INN lists into {cache_dir} ...") | |
| paths = {} | |
| with concurrent.futures.ThreadPoolExecutor(workers) as ex: | |
| futs = {ex.submit(download_list, nm, cache_dir): nm for nm in lists} | |
| for fut in concurrent.futures.as_completed(futs): | |
| nm = futs[fut] | |
| p = fut.result() | |
| if p: | |
| paths[nm] = p | |
| print(f" {len(paths)}/{len(lists)} available\n") | |
| entries = [] | |
| for nm in lists: | |
| if nm not in paths: | |
| continue | |
| try: | |
| txt = pdf_text(paths[nm]) | |
| except Exception as e: | |
| sys.stderr.write(f" [warn] {nm}: text extraction failed: {e}\n") | |
| continue | |
| found = find_entries(txt, nm) | |
| if found: | |
| print(f" {nm}: {len(found)} bridged-sugar entr" | |
| f"{'y' if len(found)==1 else 'ies'}") | |
| entries.extend(found) | |
| print(f"\nTotal bridged-sugar entries found: {len(entries)}") | |
| rows = [] | |
| for e in entries: | |
| res = validate(e["chemical_name"], e["stated_formula"]) | |
| rows.append(OrderedDict( | |
| source_list=e["source"], | |
| inn_name=e["inn_name"], | |
| ok=res["ok"], | |
| sequence_5to3=res["sequence_5to3"], | |
| sequence_length=res["sequence_length"], | |
| sugar_pattern_5to3=res["sugar_pattern_5to3"], | |
| gapmer_layout=res["gapmer_layout"], | |
| n_phosphorothioate=res["n_phosphorothioate"], | |
| computed_formula=res["computed_formula"], | |
| stated_formula=res["stated_formula"] or e["stated_formula"], | |
| reason=res["reason"], | |
| chemical_name=e["chemical_name"], | |
| )) | |
| with open(out_csv, "w", newline="", encoding="utf-8") as fh: | |
| w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()) if rows else | |
| ["source_list", "inn_name", "ok", "reason"]) | |
| w.writeheader() | |
| for r in rows: | |
| w.writerow(r) | |
| nver = sum(1 for r in rows if r["ok"]) | |
| print(f"Verified (exact formula match): {nver} / {len(rows)}") | |
| print(f"Wrote {out_csv}\n") | |
| for r in rows: | |
| flag = "OK " if r["ok"] else "FAIL" | |
| print(f" [{flag}] {r['source_list']:>6} {r['inn_name'] or '?':<16} " | |
| f"{r['sugar_pattern_5to3'] or '-'}") | |
| if not r["ok"]: | |
| print(f" reason: {r['reason']}") | |
| return rows | |
| # --------------------------------------------------------------------------- # | |
| # 7. Self-test | |
| # --------------------------------------------------------------------------- # | |
| INOTERSEN_NAME = ( | |
| "all-P-ambo-2'-O-(2-methoxyethyl)-5-methyl-P-thiouridylyl-(3'→5')-2'-O-" | |
| "(2-methoxyethyl)-5-methyl-P-thiocytidylyl-(3'→5')-2'-O-(2-methoxyethyl" | |
| ")-5-methyl-P-thiouridylyl-(3'→5')-2'-O-(2-methoxyethyl)-5-methyl-P-thi" | |
| "ouridylyl-(3'→5')-2'-O-(2-methoxyethyl)-P-thioguanylyl-(3'→5')-2'-deox" | |
| "y-P-thioguanylyl-(3'→5')-P-thiothymidylyl-(3'→5')-P-thiothymidylyl-(3'" | |
| "→5')-2'-deoxy-P-thioadenylyl-(3'→5')-2'-deoxy-5-methyl-P-thiocytidylyl" | |
| "-(3'→5')-2'-deoxy-P-thioadenylyl-(3'→5')-P-thiothymidylyl-(3'→5')-2'-d" | |
| "eoxy-P-thioguanylyl-(3'→5')-2'-deoxy-P-thioadenylyl-(3'→5')-2'-deoxy-P" | |
| "-thioadenylyl-(3'→5')-2'-O-(2-methoxyethyl)-P-thioadenylyl-(3'→5')-2'-" | |
| "O-(2-methoxyethyl)-5-methyl-P-thiouridylyl-(3'→5')-2'-O-(2-methoxyethy" | |
| "l)-5-methyl-P-thiocytidylyl-(3'→5')-2'-O-(2-methoxyethyl)-5-methyl-P-t" | |
| "hiocytidylyl-(3'→5')-2'-O-(2-methoxyethyl)-5-methylcytidine") | |
| # Verbatim English systematic name as printed in WHO Proposed List 115 / | |
| # Recommended List 77 (inotersen). Not reconstructed. | |
| APAZUNERSEN_NAME = ( | |
| "all-P-ambo-2'-O,4'-C-methylene-P-thioadenylyl-(3'→5')-" | |
| "2'-O,4'-C-methylene-P-thioguanylyl-(3'→5')-" | |
| "2'-O,4'-C-methylene-P-thioadenylyl-(3'→5')-" | |
| "2'-deoxy-P-thioadenylyl-(3'→5')-P-thiothymidylyl-(3'→5')-" | |
| "2'-deoxy-P-thioguanylyl-(3'→5')-2'-deoxy-P-thioguanylyl-(3'→5')-" | |
| "2'-deoxy-P-thiocytidylyl-(3'→5')-2'-deoxy-P-thioadenylyl-(3'→5')-" | |
| "2'-deoxy-P-thiocytidylyl-(3'→5')-2'-deoxy-P-thioadenylyl-(3'→5')-" | |
| "P-thiothymidylyl-(3'→5')-2'-deoxy-P-thiocytidylyl-(3'→5')-" | |
| "P-thiothymidylyl-(3'→5')-" | |
| "5-methyl-2'-O,4'-C-methylene-P-thiocytidylyl-(3'→5')-" | |
| "5-methyl-2'-O,4'-C-methylene-P-thiouridylyl-(3'→5')-" | |
| "5-methyl-2'-O,4'-C-methylene-P-thiouridylyl-(3'→5')-" | |
| "2'-O,4'-C-methyleneguanosine") | |
| def self_test(): | |
| ok = True | |
| # Bridged-sugar atom counts, as derived in the module docstring. | |
| expect = { | |
| ("A", "LNA", False): "C11H13N5O4", | |
| ("G", "LNA", False): "C11H13N5O5", | |
| ("C", "LNA", True): "C11H15N3O5", | |
| ("U", "LNA", True): "C11H14N2O6", | |
| ("A", "cEt", False): "C12H15N5O4", | |
| ("C", "cEt", True): "C12H17N3O5", | |
| ("A", "ENA", False): "C12H15N5O4", | |
| ("C", "ENA", True): "C12H17N3O5", | |
| ("A", "MOE", False): "C13H19N5O5", | |
| ("A", "DNA", False): "C10H13N5O3", | |
| } | |
| for (b, s, m), want in expect.items(): | |
| got = formula_to_string(nucleoside_formula(b, s, m)) | |
| flag = "OK" if got == want else "FAIL" | |
| if got != want: | |
| ok = False | |
| print(f"nucleoside {s:<4} {'m5' if m else ' '}{b}: {got} " | |
| f"(expected {want}) {flag}") | |
| print(f"bridged/modified nucleoside atom counts: {len(expect)} checked") | |
| r = validate(INOTERSEN_NAME, "C230H318N69O121P19S19") | |
| print("inotersen free acid :", r["computed_formula"], | |
| "| stated C230H318N69O121P19S19 |", "OK" if r["ok"] else "FAIL " + r["reason"]) | |
| print(" seq", r["sequence_5to3"], r["sugar_pattern_5to3"], r["gapmer_layout"], | |
| "PS=", r["n_phosphorothioate"]) | |
| ok &= r["ok"] and r["sequence_5to3"] == "TCTTGGTTACATGAAATCCC" | |
| r = validate(INOTERSEN_NAME, "C230H299N69Na19O121P19S19") | |
| print("inotersen Na salt :", r["computed_formula"], | |
| "| stated C230H299N69Na19O121P19S19 |", "OK" if r["ok"] else "FAIL " + r["reason"]) | |
| ok &= r["ok"] | |
| r = validate(APAZUNERSEN_NAME, "C184H224N67O96P17S17") | |
| print("apazunersen (LNA) :", r["computed_formula"], | |
| "| stated C184H224N67O96P17S17 |", "OK" if r["ok"] else "FAIL " + r["reason"]) | |
| print(" seq", r["sequence_5to3"], r["sugar_pattern_5to3"], r["gapmer_layout"], | |
| "PS=", r["n_phosphorothioate"]) | |
| ok &= r["ok"] | |
| print("\nSELF-TEST", "PASSED" if ok else "FAILED") | |
| return 0 if ok else 1 | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--self-test", action="store_true") | |
| ap.add_argument("--run", action="store_true") | |
| ap.add_argument("--cache", default="inn_pdfs") | |
| ap.add_argument("--out", default="bridged_results.csv") | |
| ap.add_argument("--lists", nargs="*", default=None) | |
| a = ap.parse_args() | |
| rc = 0 | |
| if a.self_test or not a.run: | |
| rc = self_test() | |
| if a.run: | |
| run(a.cache, a.out, a.lists) | |
| return rc | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |