Download code/parse_inn_sirna.py from DBbun/oligotox-phase2-dataset: direct link, hf CLI and curl.
- Browser
- Download file 32.6 kB
-
https://huggingface.co/datasets/DBbun/oligotox-phase2-dataset/resolve/main/code/parse_inn_sirna.py
- Command line
-
hf download hf://datasets/DBbun/oligotox-phase2-dataset/code/parse_inn_sirna.py
-
curl -L -o parse_inn_sirna.py https://huggingface.co/datasets/DBbun/oligotox-phase2-dataset/resolve/main/code/parse_inn_sirna.py
32.6 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| parse_inn_sirna.py | |
| ================== | |
| Extract unconjugated double-stranded siRNA (INN stem -siran) structures from WHO | |
| INN Proposed/Recommended list PDFs and validate each one arithmetically against | |
| the molecular formula WHO states in the same entry. | |
| Scope: GalNAc-conjugated -siran entries are detected and skipped (handled | |
| elsewhere). Only unconjugated duplexes are validated here. | |
| Public API | |
| ---------- | |
| validate(entry_text, stated_formula) -> dict | |
| keys: ok, sense_sequence, antisense_sequence, strand_lengths, | |
| sugar_pattern, n_phosphorothioate, computed_formula, | |
| stated_formula, reason | |
| CLI | |
| --- | |
| python parse_inn_sirna.py --download --pdfdir inn_pdfs --csv sirna_results.csv | |
| WHAT THE CHECK ESTABLISHES | |
| -------------------------- | |
| A molecular formula constrains COMPOSITION ONLY. Agreement proves that the | |
| multiset of residues, sugar modifications, backbone linkages and terminal groups | |
| we parsed has the same atom tally as WHO's stated formula. It does NOT prove the | |
| SEQUENCE ORDER is right: any permutation of a strand -- and, for equal-length | |
| designs, any reshuffling of residues between the two strands -- yields an | |
| identical formula. Nor does it fix stereochemistry ("all-P-ambo" is invisible to | |
| a formula) or WHICH linkages are phosphorothioate (only how many). | |
| Read "verified" as "composition-consistent", never as "sequence-proven". | |
| """ | |
| import os | |
| import re | |
| import csv | |
| import sys | |
| import glob | |
| import argparse | |
| import urllib.request | |
| from collections import Counter | |
| # ---------------------------------------------------------------------------- | |
| # 1. Atom-level chemistry | |
| # ---------------------------------------------------------------------------- | |
| # Free nucleoside formulas (the alcohols, before any phosphate condensation). | |
| RIBO = { | |
| 'A': Counter(C=10, H=13, N=5, O=4), # adenosine | |
| 'G': Counter(C=10, H=13, N=5, O=5), # guanosine | |
| 'C': Counter(C=9, H=13, N=3, O=5), # cytidine | |
| 'U': Counter(C=9, H=12, N=2, O=6), # uridine | |
| 'T': Counter(C=10, H=14, N=2, O=6), # 5-methyluridine (ribo-T) | |
| 'I': Counter(C=10, H=12, N=4, O=5), # inosine | |
| } | |
| # 2'-deoxy nucleosides = ribonucleoside - O | |
| DEOXY = {k: (v - Counter(O=1)) for k, v in RIBO.items()} | |
| DEOXY['T'] = Counter(C=10, H=14, N=2, O=5) # thymidine (2'-deoxythymidine) | |
| H2O = Counter(H=2, O=1) | |
| H3PO4 = Counter(H=3, P=1, O=4) | |
| # --- Derivation of the two sugar modifications ------------------------------- | |
| # | |
| # 2'-O-methyl: the 2'-OH hydrogen is replaced by methyl. | |
| # -OH -> -O-CH3 i.e. -H +CH3 = net +C +2H ("+CH2") | |
| # adenosine C10H13N5O4 -> 2'-O-methyladenosine C11H15N5O4. | |
| # | |
| # 2'-deoxy-2'-fluoro: the 2'-OH is replaced by fluorine. | |
| # -OH -> -F i.e. -O -H +F | |
| # adenosine C10H13N5O4 -> 2'-deoxy-2'-fluoroadenosine C10H12FN5O3. | |
| # The brief's shorthand "ribonucleoside - O + F" is one hydrogen too many; it | |
| # forgets the hydroxyl H. The -O -H +F form is what reproduces WHO's stated | |
| # H counts on the fluorinated entries. | |
| def mod_2ome(base): | |
| return RIBO[base] + Counter(C=1, H=2) | |
| def mod_2f(base): | |
| return RIBO[base] - Counter(O=1, H=1) + Counter(F=1) | |
| def mod_2deoxy(base): | |
| return DEOXY[base] | |
| def mod_ribo(base): | |
| return RIBO[base] | |
| def mod_2moe(base): | |
| # 2'-O-(2-methoxyethyl): -OH -> -O-CH2CH2OCH3 => +C3H6O | |
| return RIBO[base] + Counter(C=3, H=6, O=1) | |
| def mod_2ohex(base): | |
| # 2'-O-hexadecyl: -OH -> -O-C16H33 => +C16H32 | |
| return RIBO[base] + Counter(C=16, H=32) | |
| SUGAR_FN = {'R': mod_ribo, '2OMe': mod_2ome, '2F': mod_2f, | |
| 'dR': mod_2deoxy, '2MOE': mod_2moe, '2OHex': mod_2ohex} | |
| SUGAR_CODE = {'R': 'r', '2OMe': 'm', '2F': 'f', 'dR': 'd', '2MOE': 'e', | |
| '2OHex': 'H'} | |
| # --- Terminal / cap groups, given as the free ALCOHOL that esterifies a P ----- | |
| CAPS = { | |
| # inverted abasic (tetrahydrofuranyl) cap: | |
| # [(2R,3S)-3-hydroxyoxolan-2-yl]methanol -> C5H10O3 | |
| 'invab': Counter(C=5, H=10, O=3), | |
| } | |
| # ---------------------------------------------------------------------------- | |
| # 2. Text normalisation | |
| # ---------------------------------------------------------------------------- | |
| def normalise(text): | |
| """Flatten PDF line wrapping without destroying the chemical name.""" | |
| t = text | |
| t = t.replace('’', "'").replace('ʹ', "'").replace('′', "'") | |
| t = t.replace('β', 'beta').replace('α', 'alpha') | |
| t = t.replace('→', '>').replace('–', '-').replace('‐', '-') | |
| # drop page furniture that can land inside a wrapped entry | |
| t = re.sub(r'(Proposed|Recommended)\s+INN:\s*List\s*\d+', ' ', t) | |
| t = re.sub(r'WHO\s+Drug\s+Information,\s*Vol\.\s*\d+,\s*No\.\s*\d+,\s*\d{4}', | |
| ' ', t) | |
| t = t.replace('\n', ' ') | |
| t = re.sub(r'\s+', ' ', t) | |
| # PDF wraps mid-name after a hyphen -> "2'-O- methyl" / "- (3'>5')" | |
| t = re.sub(r'-\s+', '-', t) | |
| t = re.sub(r'\s+-', '-', t) | |
| # a page number can be injected into a wrapped chemical name, e.g. | |
| # "2'-O-1295 methyluridylyl" -> "2'-O-methyluridylyl" | |
| t = re.sub(r"(?<=-)\d{1,5}\s+(?=[A-Za-z])", '', t) | |
| return t.strip() | |
| def parse_formula(s): | |
| """'C412H520N148O290P40' -> Counter.""" | |
| c = Counter() | |
| for el, n in re.findall(r'([A-Z][a-z]?)(\d*)', s or ''): | |
| if not el: | |
| continue | |
| c[el] += int(n) if n else 1 | |
| return +c | |
| HILL = ['C', 'H', 'F', 'N', 'Na', 'O', 'P', 'S'] | |
| def fmt_formula(c): | |
| out = '' | |
| for el in HILL: | |
| n = c.get(el, 0) | |
| if n: | |
| out += el + (str(n) if n != 1 else '') | |
| for el in sorted(set(c) - set(HILL)): | |
| if c[el]: | |
| out += el + (str(c[el]) if c[el] != 1 else '') | |
| return out | |
| # ---------------------------------------------------------------------------- | |
| # 3. Residue tokenisation | |
| # ---------------------------------------------------------------------------- | |
| BASE_FROM_STEM = { | |
| 'adenyl': 'A', 'adenosine': 'A', | |
| 'guanyl': 'G', 'guanosine': 'G', | |
| 'cytidyl': 'C', 'cytidine': 'C', | |
| 'uridyl': 'U', 'uridine': 'U', | |
| 'thymidyl': 'T', 'thymidine': 'T', | |
| 'inosinyl': 'I', 'inosine': 'I', | |
| } | |
| # Modifier prefixes. The trailing hyphen MUST be optional: WHO writes | |
| # "2'-deoxy-2'-fluoroguanylyl" and "2'-deoxycytidylyl" with no hyphen before | |
| # the nucleoside stem. Longest/most specific alternatives come first so that | |
| # "2'-deoxy-2'-fluoro" is not eaten by the shorter "2'-deoxy". | |
| MOD_TOKEN = ( | |
| r"(?:" | |
| r"all-P-ambo-?" | |
| r"|P-thio-?" | |
| r"|2'-deoxy-2'-fluoro-?" | |
| r"|2'-fluoro-2'-deoxy-?" | |
| r"|2'-O-\(2-methoxyethyl\)-?" | |
| r"|2'-O-methyl-?" | |
| r"|2'-O-hexadecyl-?" | |
| r"|2'-deoxy-?" | |
| r"|2'-fluoro-?" | |
| r"|\(5'E\)-?" | |
| r"|\(5'Z\)-?" | |
| r"|5',C5'-didehydro-?" | |
| r"|O5'-carba-?" | |
| r"|[2345]'-O-" | |
| r"|[2345]'-" | |
| r")") | |
| # Nucleotidyl naming: | |
| # internal residue cytidyl + yl -> "cytidylyl" | |
| # terminal phosphate cytidyl + ate -> "5'-cytidylate" | |
| # cytidyl + ic acid -> "cytidylic acid" | |
| # terminal nucleoside cytidin + e -> "cytidine" | |
| RES_RE = re.compile( | |
| r"(?P<mods>(?:" + MOD_TOKEN + r")*)" | |
| r"(?:" | |
| r"(?P<stem1>adenyl|guanyl|cytidyl|uridyl|thymidyl|inosinyl)" | |
| r"(?P<suf1>ylyl|yl|ate|ic\s+acid)" | |
| r"|" | |
| r"(?P<stem2>adenosine|guanosine|cytidine|uridine|thymidine|inosine)" | |
| r")", | |
| re.I) | |
| LINK_RE = re.compile(r"\((?:3'>5'|5'>3')\)") | |
| class ParseError(Exception): | |
| pass | |
| def tokenise_strand(s): | |
| """Return (residues, caps) for one strand description string.""" | |
| caps = [] | |
| if re.search(r"hydroxy(?:oxolan|tetrahydrofuran)-2-yl\]?methyl", s, re.I): | |
| caps.append('invab') | |
| # Direction the strand is WRITTEN in. WHO names a strand by its linkages: | |
| # (3'->5') links => residues are listed 5'-end first => written 5'->3' | |
| # (5'->3') links => residues are listed 3'-end first => written 3'->5' | |
| links = set(LINK_RE.findall(s)) | |
| if links == {"(3'>5')"}: | |
| written = "5->3" | |
| elif links == {"(5'>3')"}: | |
| written = "3->5" | |
| else: | |
| written = "mixed" | |
| residues = [] | |
| for m in RES_RE.finditer(s): | |
| mods = m.group('mods').lower() | |
| stem = (m.group('stem1') or m.group('stem2')).lower() | |
| suf = (m.group('suf1') or 'e').lower().strip() | |
| base = BASE_FROM_STEM.get(stem) | |
| if base is None: | |
| raise ParseError('unknown nucleoside stem %r' % stem) | |
| if "2'-deoxy-2'-fluoro" in mods or "2'-fluoro-2'-deoxy" in mods: | |
| sugar = '2F' | |
| elif "2'-o-(2-methoxyethyl)" in mods: | |
| sugar = '2MOE' | |
| elif "2'-o-methyl" in mods: | |
| sugar = '2OMe' | |
| elif "2'-o-hexadecyl" in mods: | |
| sugar = '2OHex' | |
| elif "2'-deoxy" in mods: | |
| sugar = 'dR' | |
| elif stem.startswith('thymid'): | |
| sugar = 'dR' # thymidine is 2'-deoxy by definition | |
| else: | |
| sugar = 'R' | |
| thio = 'p-thio' in mods | |
| # 5'-(E)-vinylphosphonate terminus: | |
| # "...-5',C5'-didehydro-O5'-carba-5'-uridylic acid" | |
| # The 5'-oxygen is replaced by carbon and a C5'=C double bond forms: | |
| # ribose-C5'H2-O-PO3H2 -> ribose-C5'H=CH-PO3H2 | |
| # Net change vs the ordinary 5'-phosphate ester: -O +C (H unchanged, | |
| # C5' goes CH2 -> CH while the new vinyl carbon brings one H). | |
| vinylphosphonate = 'carba' in mods | |
| if suf in ('yl', 'ylyl'): | |
| kind = 'internal' # carries the linking phosphate | |
| elif suf == 'ate' or suf.startswith('ic'): | |
| kind = 'terminal_p' # chain-terminal phosphate | |
| else: # bare nucleoside, free 3'/5'-OH | |
| kind = 'terminal_oh' | |
| residues.append(dict(base=base, sugar=sugar, thio=thio, kind=kind, | |
| vp=vinylphosphonate, span=m.span())) | |
| if not residues: | |
| raise ParseError('no residues matched') | |
| return residues, caps, written | |
| def strand_formula(residues, caps): | |
| """Assemble one strand. | |
| Model: sum of the free nucleoside (and cap) ALCOHOLS, then for each | |
| phosphorus add H3PO4 and subtract one H2O per ester bond it forms. | |
| internal linkage -> 2 ester bonds -> net +P +2O -1H | |
| capped terminal P -> 2 ester bonds -> net +P +2O -1H (+ cap alcohol) | |
| free terminal P -> 1 ester bond -> net +P +3O +1H | |
| A phosphorothioate swaps one of that phosphorus' oxygens for sulfur. | |
| """ | |
| tot = Counter() | |
| n_p = 0 | |
| n_thio = 0 | |
| ester_bonds = 0 | |
| caps_left = list(caps) | |
| for r in residues: | |
| tot += SUGAR_FN[r['sugar']](r['base']) | |
| if r['kind'] == 'internal': | |
| n_p += 1 | |
| ester_bonds += 2 | |
| if r['thio']: | |
| n_thio += 1 | |
| elif r['kind'] == 'terminal_p': | |
| n_p += 1 | |
| if r['thio']: | |
| n_thio += 1 | |
| if r.get('vp'): | |
| # vinylphosphonate: C-P bond, not an O-P ester, and the 5'-O is | |
| # swapped for the vinyl carbon => one ester bond, then -O +C | |
| ester_bonds += 1 | |
| tot += Counter(C=1) | |
| tot -= Counter(O=1) | |
| elif caps_left: | |
| caps_left.pop(0) | |
| ester_bonds += 2 | |
| else: | |
| ester_bonds += 1 | |
| for c in caps: | |
| tot += CAPS[c] | |
| tot += Counter({k: v * n_p for k, v in H3PO4.items()}) | |
| tot -= Counter({k: v * ester_bonds for k, v in H2O.items()}) | |
| tot = +tot | |
| if n_thio: | |
| tot['O'] -= n_thio | |
| tot['S'] += n_thio | |
| return tot, n_p, n_thio | |
| # ---------------------------------------------------------------------------- | |
| # 4. Strand-boundary detection | |
| # ---------------------------------------------------------------------------- | |
| # WHO writes a duplex in a handful of English templates. The two strands are | |
| # always joined by a connective, and each strand's internal linkages are | |
| # uniformly (3'>5') or (5'>3'). We try every connective and keep the split | |
| # where both halves carry >=2 linkages and each half is direction-consistent. | |
| SPLIT_PATTERNS = [ | |
| r"\s+with\s+the\s+antisense\s+strand\s+", | |
| r"\s+duplex\s+with\s+", | |
| r"\s+complexed\s+with\s+", | |
| r"\s+with\s+", | |
| r"\s+and\s+", | |
| ] | |
| GALNAC_RE = re.compile(r"galactopyranosyl|galactosamin|triantennar|GalNAc", re.I) | |
| # Non-GalNAc ligands / conjugates we deliberately do not model: fatty-acid and | |
| # lipid conjugates, cholesterol/tocopherol, maleimide-type bioconjugation | |
| # linkers, and 2'-O-lipid chains. | |
| OTHER_CONJ_RE = re.compile( | |
| r"docosanamido|heptadecanamido|octadecanamido|nonadecanamido|" | |
| r"hexadecanamido|tetradecanamido|hexadecyl|octadecyl|cholester|tocopher|" | |
| r"maleimid|dioxopyrrolidin|carbamoyl\]cyclohexyl|oxopyrrolidin-3-yl", re.I) | |
| AMEND_RE = re.compile( | |
| r"replace\s+the\s+(?:molecular\s+formula|structure|chemical\s+name|" | |
| r"description|graphic\s+formula|definition)|insert\s+the|delete\s+the", | |
| re.I) | |
| def split_strands(desc): | |
| """Split a duplex description into (strand1_text, strand2_text).""" | |
| d = re.sub(r"^.*?(?:RNA\s+duplex\s+of|duplex\s+of|siRNA\)\s*;)\s*", '', | |
| desc, count=1, flags=re.I) | |
| cands = [] | |
| for rank, pat in enumerate(SPLIT_PATTERNS): | |
| for m in re.finditer(pat, d, re.I): | |
| a, b = d[:m.start()], d[m.end():] | |
| if len(LINK_RE.findall(a)) >= 2 and len(LINK_RE.findall(b)) >= 2: | |
| da, db = set(LINK_RE.findall(a)), set(LINK_RE.findall(b)) | |
| score = (len(da) == 1) + (len(db) == 1) | |
| cands.append((-score, rank, abs(len(a) - len(b)), a, b)) | |
| if not cands: | |
| return None | |
| cands.sort(key=lambda x: (x[0], x[1], x[2])) | |
| return cands[0][3], cands[0][4] | |
| def duplex_complementarity(sense53, anti53): | |
| """Best Watson-Crick pairing between the two strands. | |
| This is an ORDER-sensitive check that a molecular formula cannot give us. | |
| Pairs sense 5'->3' against the antisense read 3'->5', sliding the register | |
| over a small offset window to absorb 3' overhangs. | |
| Returns (matched_pairs, compared_positions, best_offset). | |
| """ | |
| if not sense53 or not anti53: | |
| return (0, 0, 0) | |
| wc = {('A', 'U'), ('U', 'A'), ('G', 'C'), ('C', 'G')} | |
| a = sense53.replace('T', 'U') | |
| b = anti53[::-1].replace('T', 'U') # antisense 3'->5' | |
| best = (0, 0, 0) | |
| for off in range(-6, 7): | |
| hit = tot = 0 | |
| for i, x in enumerate(a): | |
| j = i + off | |
| if 0 <= j < len(b): | |
| tot += 1 | |
| if (x, b[j]) in wc: | |
| hit += 1 | |
| if tot and (hit, tot) > (best[0], best[1]): | |
| best = (hit, tot, off) | |
| return best | |
| # ---------------------------------------------------------------------------- | |
| # 5. Public validate() | |
| # ---------------------------------------------------------------------------- | |
| NOISE_RE = re.compile( | |
| r"all-P-ambo|hydrogen|duplex|RNA|siRNA|sodium|salt|small|interfering|" | |
| r"inhibitor|production|strand|antisense|sense|the|of|with|and|" | |
| r"hydroxyoxolan|oxolan|methyl|yl|receptor|adrenergic|beta|alpha", | |
| re.I) | |
| def validate(entry_text, stated_formula): | |
| """Parse one WHO INN duplex entry and check it against `stated_formula`.""" | |
| out = dict(ok=False, sense_sequence=None, antisense_sequence=None, | |
| strand_lengths=None, sugar_pattern=None, | |
| n_phosphorothioate=None, computed_formula=None, | |
| stated_formula=stated_formula, reason='', | |
| written_direction=None, sense_sequence_5to3=None, | |
| antisense_sequence_5to3=None, sugar_pattern_5to3=None, | |
| complementarity='', complementarity_frac=None) | |
| desc = normalise(entry_text) | |
| if GALNAC_RE.search(desc): | |
| out['reason'] = 'GalNAc-conjugated (out of scope for this parser)' | |
| return out | |
| m = OTHER_CONJ_RE.search(desc) | |
| if m: | |
| out['reason'] = ('ligand/lipid-conjugated, not an unconjugated duplex ' | |
| '(out of scope; marker %r)' % m.group(0)) | |
| return out | |
| nlink = len(LINK_RE.findall(desc)) | |
| if nlink < 4: | |
| # WHO amendment / cross-reference notice: no structure in this block | |
| if AMEND_RE.search(desc): | |
| out['reason'] = ('WHO amendment notice, no structure in this ' | |
| 'entry block') | |
| else: | |
| out['reason'] = ('no oligonucleotide structure in this entry block ' | |
| '(%d linkages); amendment or name cross-reference' | |
| % nlink) | |
| return out | |
| parts = split_strands(desc) | |
| if parts is None: | |
| out['reason'] = ('no valid strand boundary found (%d linkages seen); ' | |
| 'single-strand or unrecognised duplex template' | |
| % nlink) | |
| return out | |
| strands = [] | |
| for s in parts: | |
| try: | |
| strands.append(tokenise_strand(s)) | |
| except ParseError as e: | |
| out['reason'] = 'strand parse failed: %s' % e | |
| return out | |
| seqs, lens, pats, tot = [], [], [], Counter() | |
| seqs53, pats53, dirs = [], [], [] | |
| n_thio_all = 0 | |
| for res, caps, written in strands: | |
| f, n_p, n_thio = strand_formula(res, caps) | |
| tot += f | |
| n_thio_all += n_thio | |
| seq = ''.join(r['base'] for r in res) | |
| pat = ''.join(SUGAR_CODE[r['sugar']] for r in res) | |
| seqs.append(seq) | |
| pats.append(pat) | |
| lens.append(len(res)) | |
| dirs.append(written) | |
| # normalise to 5'->3' | |
| if written == '3->5': | |
| seqs53.append(seq[::-1]) | |
| pats53.append(pat[::-1]) | |
| else: | |
| seqs53.append(seq) | |
| pats53.append(pat) | |
| out.update(sense_sequence=seqs[0], antisense_sequence=seqs[1], | |
| strand_lengths=lens, sugar_pattern=pats, | |
| n_phosphorothioate=n_thio_all, | |
| computed_formula=fmt_formula(tot), | |
| written_direction=dirs, | |
| sense_sequence_5to3=seqs53[0], | |
| antisense_sequence_5to3=seqs53[1], | |
| sugar_pattern_5to3=pats53) | |
| hit, tot_pos, off = duplex_complementarity(seqs53[0], seqs53[1]) | |
| out['complementarity'] = ('%d/%d' % (hit, tot_pos)) if tot_pos else '' | |
| out['complementarity_frac'] = (round(hit / tot_pos, 3) if tot_pos else None) | |
| # anything in the entry text we did not consume is a red flag | |
| leftovers = [] | |
| for _st, s in zip(strands, parts): | |
| rest = RES_RE.sub(' ', s) | |
| rest = LINK_RE.sub(' ', rest) | |
| rest = NOISE_RE.sub(' ', rest) | |
| rest = re.sub(r"[\s\-,\.;:\(\)\[\]0-9']+", ' ', rest).strip() | |
| if len(rest) > 20: | |
| leftovers.append(rest[:90]) | |
| if not stated_formula: | |
| out['reason'] = 'no stated formula found in entry' | |
| return out | |
| want = parse_formula(stated_formula) | |
| got = +tot | |
| if got == want: | |
| out['ok'] = True | |
| out['reason'] = 'exact match' | |
| else: | |
| diffs = [] | |
| for el in sorted(set(got) | set(want)): | |
| d = got.get(el, 0) - want.get(el, 0) | |
| if d: | |
| diffs.append('%s%+d' % (el, d)) | |
| out['reason'] = 'mismatch ' + ' '.join(diffs) | |
| if leftovers: | |
| out['reason'] += ' | unmodelled text: ' + '; '.join(leftovers) | |
| return out | |
| # ---------------------------------------------------------------------------- | |
| # 6. Corpus harvesting | |
| # ---------------------------------------------------------------------------- | |
| UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' | |
| '(KHTML, like Gecko) Chrome/125.0 Safari/537.36') | |
| BASE = ('https://cdn.who.int/media/docs/default-source/' | |
| 'international-nonproprietary-names-(inn)/') | |
| LISTS = (['pl%d' % n for n in range(100, 136)] + | |
| ['rl%d' % n for n in range(64, 96)]) | |
| def download(outdir): | |
| os.makedirs(outdir, exist_ok=True) | |
| for name in LISTS: | |
| p = os.path.join(outdir, name + '.pdf') | |
| if os.path.exists(p) and os.path.getsize(p) > 20000: | |
| continue | |
| try: | |
| req = urllib.request.Request(BASE + name + '.pdf', | |
| headers={'User-Agent': UA}) | |
| data = urllib.request.urlopen(req, timeout=120).read() | |
| if data.startswith(b'%PDF'): | |
| open(p, 'wb').write(data) | |
| print('downloaded', name) | |
| else: | |
| print('not a PDF:', name, file=sys.stderr) | |
| except Exception as e: | |
| print('FAILED', name, e, file=sys.stderr) | |
| def pdf_text(path): | |
| try: | |
| import fitz | |
| d = fitz.open(path) | |
| t = '\n'.join(pg.get_text('text') for pg in d) | |
| d.close() | |
| return t | |
| except ImportError: | |
| from pypdf import PdfReader | |
| return '\n'.join((p.extract_text() or '') for p in PdfReader(path).pages) | |
| OLIGO_FORM_RE = re.compile( | |
| r'\bC(?:\d{3,4})H(?:\d{3,4})' | |
| r'(?:[A-Z][a-z]?\d{0,4})*?P\d{1,3}(?:[A-Z][a-z]?\d{0,4})*\b') | |
| def harvest(pdfdir, txtdir=None): | |
| """Yield dicts: name, list, entry_text, stated_formula.""" | |
| if txtdir: | |
| os.makedirs(txtdir, exist_ok=True) | |
| for pdf in sorted(glob.glob(os.path.join(pdfdir, '*.pdf'))): | |
| listname = os.path.basename(pdf)[:-4] | |
| cache = os.path.join(txtdir, listname + '.txt') if txtdir else None | |
| if cache and os.path.exists(cache): | |
| text = open(cache, encoding='utf-8').read() | |
| else: | |
| text = pdf_text(pdf) | |
| if cache: | |
| open(cache, 'w', encoding='utf-8').write(text) | |
| for nm in sorted(set(re.findall(r'\b([a-z]{3,}siran)\b', text))): | |
| cands = [] | |
| for m in re.finditer(r'\b' + nm + r'um\b', text): | |
| occ = [x.start() for x in re.finditer( | |
| r'^[ \t]*' + nm + r'[ \t]*$', text[m.end():], re.M)] | |
| if len(occ) < 2: | |
| continue | |
| a, b = m.end() + occ[0], m.end() + occ[1] | |
| entry = text[a:b] | |
| tail = m.end() + (occ[2] if len(occ) >= 3 else occ[1]) | |
| fm = OLIGO_FORM_RE.search(normalise(text[tail:tail + 25000])) | |
| # prefer the block that actually carries the structure | |
| nlink = len(LINK_RE.findall(normalise(entry))) | |
| cands.append((nlink, len(entry), entry, | |
| fm.group(0) if fm else None)) | |
| if not cands: | |
| continue | |
| cands.sort(key=lambda x: (-x[0], -x[1])) | |
| yield dict(name=nm, list=listname, entry_text=cands[0][2], | |
| stated_formula=cands[0][3]) | |
| # ---------------------------------------------------------------------------- | |
| # 7. Self-test of the atom model (no network, no PDFs) | |
| # ---------------------------------------------------------------------------- | |
| def selftest(): | |
| """Check the per-residue increments that the whole parser rests on.""" | |
| ok = True | |
| def chk(label, got, want): | |
| nonlocal ok | |
| good = fmt_formula(+got) == want | |
| ok &= good | |
| print(' %-46s %-22s %s' % (label, fmt_formula(+got), | |
| 'OK' if good else 'EXPECTED ' + want)) | |
| print('nucleoside building blocks') | |
| chk('adenosine', RIBO['A'], 'C10H13N5O4') | |
| chk("2'-O-methyladenosine (ribo +CH2)", mod_2ome('A'), 'C11H15N5O4') | |
| chk("2'-deoxy-2'-fluoroadenosine (ribo -O -H +F)", mod_2f('A'), | |
| 'C10H12FN5O3') | |
| chk("2'-deoxyadenosine (ribo -O)", mod_2deoxy('A'), 'C10H13N5O3') | |
| chk('thymidine', DEOXY['T'], 'C10H14N2O5') | |
| print('linkage increments') | |
| inc = Counter(H3PO4) - Counter({k: 2 * v for k, v in H2O.items()}) | |
| chk('internal phosphodiester (+P +2O -1H)', inc + Counter(H=1), 'HO2P') | |
| print(' internal diester net = %s' % fmt_formula(+Counter( | |
| {k: v for k, v in inc.items() if v > 0})) + ' minus H1') | |
| print('patisiran end-to-end (sense dTdT overhang, no F, no PS)') | |
| s1 = ("guanylyl-(3'>5')-2'-O-methyluridylyl-(3'>5')-adenylyl-(3'>5')-" | |
| "adenylyl-(3'>5')-2'-O-methylcytidylyl-(3'>5')-2'-O-methylcytidylyl-" | |
| "(3'>5')-adenylyl-(3'>5')-adenylyl-(3'>5')-guanylyl-(3'>5')-" | |
| "adenylyl-(3'>5')-guanylyl-(3'>5')-2'-O-methyluridylyl-(3'>5')-" | |
| "adenylyl-(3'>5')-2'-O-methyluridylyl-(3'>5')-2'-O-methyluridylyl-" | |
| "(3'>5')-2'-O-methylcytidylyl-(3'>5')-2'-O-methylcytidylyl-(3'>5')-" | |
| "adenylyl-(3'>5')-2'-O-methyluridylyl-(3'>5')-thymidylyl-(3'>5')-" | |
| "thymidine") | |
| s2 = ("thymidylyl-(5'>3')-thymidylyl-(5'>3')-cytidylyl-(5'>3')-adenylyl-" | |
| "(5'>3')-2'-O-methyluridylyl-(5'>3')-uridylyl-(5'>3')-guanylyl-" | |
| "(5'>3')-guanylyl-(5'>3')-uridylyl-(5'>3')-uridylyl-(5'>3')-" | |
| "cytidylyl-(5'>3')-uridylyl-(5'>3')-cytidylyl-(5'>3')-adenylyl-" | |
| "(5'>3')-2'-O-methyluridylyl-(5'>3')-adenylyl-(5'>3')-adenylyl-" | |
| "(5'>3')-guanylyl-(5'>3')-guanylyl-(5'>3')-uridylyl-(5'>3')-" | |
| "adenosine") | |
| r = validate('RNA duplex of ' + s1 + ' with ' + s2, | |
| 'C412H520N148O290P40') | |
| print(' computed %s stated %s -> %s' | |
| % (r['computed_formula'], r['stated_formula'], | |
| 'OK' if r['ok'] else 'FAIL: ' + r['reason'])) | |
| print(' strand lengths %s, PS linkages %d' | |
| % (r['strand_lengths'], r['n_phosphorothioate'])) | |
| ok &= r['ok'] | |
| # ---- independent calibration against FDA labels (DailyMed) ------------- | |
| # WHO states the FREE ACID; FDA labels state the SODIUM SALT, with exactly | |
| # one Na replacing one acidic H per phosphorus. Checking that relation on | |
| # two marketed products pins down both conventions without circularity. | |
| # DailyMed SPL e87ec36f-b4b4-49d4-aea4-d4ffb09b0970 (ONPATTRO): | |
| # patisiran sodium C412H480N148Na40O290P40 | |
| # DailyMed SPL 6fc0afca-4513-4c35-b594-6544aee29a44 (LEQVIO): | |
| # inclisiran sodium C529H664F12N176Na43O316P43S6 | |
| print('FDA sodium salt <-> WHO free acid (salt = acid - nP H + nP Na)') | |
| for nm, salt, who in [ | |
| ('patisiran', 'C412H480N148Na40O290P40', | |
| 'C412H520N148O290P40'), | |
| ('inclisiran', 'C529H664F12N176Na43O316P43S6', | |
| 'C529H707F12N176O316P43S6')]: | |
| s, a = parse_formula(salt), parse_formula(who) | |
| n_p = a['P'] | |
| derived = Counter(a) | |
| derived['H'] -= n_p | |
| derived['Na'] = derived.get('Na', 0) + n_p | |
| good = +derived == +s | |
| ok &= good | |
| print(' %-11s acid %-30s -> salt %-30s %s' | |
| % (nm, who, fmt_formula(+derived), 'OK' if good else | |
| 'MISMATCH vs label ' + salt)) | |
| print('\nSELFTEST %s' % ('PASSED' if ok else 'FAILED')) | |
| return 0 if ok else 1 | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument('--pdfdir', default='inn_pdfs') | |
| ap.add_argument('--txtdir', default='inn_txt') | |
| ap.add_argument('--csv', default='sirna_results.csv') | |
| ap.add_argument('--download', action='store_true') | |
| ap.add_argument('--verbose', action='store_true') | |
| ap.add_argument('--selftest', action='store_true') | |
| args = ap.parse_args() | |
| if args.selftest: | |
| return selftest() | |
| if args.download: | |
| download(args.pdfdir) | |
| occ = list(harvest(args.pdfdir, args.txtdir)) | |
| # The richest structural entry per INN, used to resolve WHO amendment | |
| # entries ("replace the molecular formula by the following one"), which | |
| # restate a corrected formula but repeat no structure. | |
| struct = {} | |
| for e in occ: | |
| n = len(LINK_RE.findall(normalise(e['entry_text']))) | |
| if n >= 4 and n > struct.get(e['name'], (0,))[0]: | |
| struct[e['name']] = (n, e['list'], e['entry_text']) | |
| rows = [] | |
| for e in occ: | |
| r = validate(e['entry_text'], e['stated_formula']) | |
| # amendment entry: re-check the carried-over structure against the | |
| # corrected formula stated here, and record where the structure came from | |
| if (not r['ok'] and e['stated_formula'] | |
| and e['name'] in struct | |
| and struct[e['name']][1] != e['list'] | |
| and len(LINK_RE.findall(normalise(e['entry_text']))) < 4): | |
| src_list, src_text = struct[e['name']][1], struct[e['name']][2] | |
| r2 = validate(src_text, e['stated_formula']) | |
| note = (' [structure carried over from %s; this entry is a WHO ' | |
| 'amendment restating the formula only]' % src_list) | |
| r2['reason'] += note | |
| r = r2 | |
| pat = r['sugar_pattern'] or ['', ''] | |
| rows.append(dict( | |
| inn_name=e['name'], who_list=e['list'], ok=r['ok'], | |
| strand_lengths=('/'.join(map(str, r['strand_lengths'])) | |
| if r['strand_lengths'] else ''), | |
| sense_sequence=r['sense_sequence'] or '', | |
| antisense_sequence=r['antisense_sequence'] or '', | |
| sense_sequence_5to3=r['sense_sequence_5to3'] or '', | |
| antisense_sequence_5to3=r['antisense_sequence_5to3'] or '', | |
| written_direction=('/'.join(r['written_direction']) | |
| if r['written_direction'] else ''), | |
| sense_sugar_pattern=pat[0] if len(pat) > 0 else '', | |
| antisense_sugar_pattern=pat[1] if len(pat) > 1 else '', | |
| n_phosphorothioate=('' if r['n_phosphorothioate'] is None | |
| else r['n_phosphorothioate']), | |
| complementarity=r.get('complementarity', ''), | |
| computed_formula=r['computed_formula'] or '', | |
| stated_formula=r['stated_formula'] or '', | |
| reason=r['reason'])) | |
| if args.verbose: | |
| print(('PASS' if r['ok'] else 'FAIL'), e['list'], e['name'], | |
| r['reason'][:140]) | |
| cols = ['inn_name', 'who_list', 'ok', 'strand_lengths', | |
| 'sense_sequence', 'antisense_sequence', | |
| 'sense_sequence_5to3', 'antisense_sequence_5to3', | |
| 'written_direction', 'sense_sugar_pattern', | |
| 'antisense_sugar_pattern', 'n_phosphorothioate', | |
| 'complementarity', 'computed_formula', 'stated_formula', 'reason'] | |
| with open(args.csv, 'w', newline='', encoding='utf-8') as fh: | |
| w = csv.DictWriter(fh, fieldnames=cols) | |
| w.writeheader() | |
| for r in rows: | |
| w.writerow(r) | |
| nver = sum(1 for r in rows if r['ok']) | |
| names = set(r['inn_name'] for r in rows) | |
| vnames = sorted(set(r['inn_name'] for r in rows if r['ok'])) | |
| buckets = Counter() | |
| for r in rows: | |
| if r['ok']: | |
| buckets['verified'] += 1 | |
| elif 'GalNAc' in r['reason']: | |
| buckets['GalNAc-conjugated (other worker)'] += 1 | |
| elif 'ligand/lipid-conjugated' in r['reason']: | |
| buckets['other conjugate (out of scope)'] += 1 | |
| elif 'amendment' in r['reason'] or 'cross-reference' in r['reason']: | |
| buckets['amendment/cross-ref block, nothing to check'] += 1 | |
| elif 'no stated formula' in r['reason']: | |
| buckets['no formula published by WHO'] += 1 | |
| else: | |
| buckets['PARSED BUT MISMATCHED'] += 1 | |
| print() | |
| print('entry occurrences parsed : %d (%d distinct INNs)' | |
| % (len(rows), len(names))) | |
| print('VERIFIED occurrences : %d (%d distinct INNs)' | |
| % (nver, len(vnames))) | |
| for k, v in buckets.most_common(): | |
| print(' %-42s %d' % (k, v)) | |
| print('verified INNs : %s' % ', '.join(vnames)) | |
| print('csv : %s' % args.csv) | |
| print() | |
| print('NOTE: a molecular formula fixes COMPOSITION ONLY. These checks do ' | |
| 'not\n establish sequence order, strand assignment of ' | |
| 'equal-length residues,\n P-stereochemistry, or WHICH linkages ' | |
| 'are phosphorothioate.') | |
| return 0 | |
| if __name__ == '__main__': | |
| sys.exit(main() or 0) | |