File size: 6,019 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
"""
Parse the WHO INN systematic oligonucleotide name.

This is the universal format - every INN list prints it, old and new - unlike the
compact shorthand, which appears only in some recent entries. Residues are joined
by (3'->5') and each token states its own sugar, 5-methylation, backbone and base:

  all-P-ambo-2'-O-(2-methoxyethyl)-P-thioadenylyl-(3'->5')-
  2'-O-(2-methoxyethyl)-P-thioguanylyl-(3'->5')-...-
  2'-O-(2-methoxyethyl)-5-methyluridine

  2'-O-(2-methoxyethyl)   2'-MOE        2'-deoxy-2'-fluoro   2'-F
  2'-deoxy                DNA           2'-O-methyl          2'-OMe
  5-methyl                m5 base       P-thio               PS linkage
  ...ylyl                 internal      ...osine/...idine    3' terminus

A "P-thio" prefix marks the linkage leaving that residue, so the final residue
carries no linkage. Parses are accepted only if the rebuilt molecular formula
equals the one WHO states in the same entry.
"""

import re

from formula_checksum import oligo_formula, parse_formula, render, compare

LINK = re.compile(r"\(3['′]?\s*(?:→|->|-)\s*5['′]?\)")

BASE_INTERNAL = {
    "adenylyl": "A", "guanylyl": "G", "cytidylyl": "C",
    "uridylyl": "U", "thymidylyl": "T", "inosinylyl": "I",
}
BASE_TERMINAL = {
    "adenosine": "A", "guanosine": "G", "cytidine": "C",
    "uridine": "U", "thymidine": "T", "inosine": "I",
}


def residue(tok: str):
    """Return (base, sugar, methylated, thio) or None if the token is not a residue."""
    # splitting on the linkage marker leaves the joining hyphens attached
    t = tok.lower().strip("-– ")

    if "2'-deoxy-2'-fluoro" in t or "2′-deoxy-2′-fluoro" in t:
        sugar = "2prime_F"
    elif "methoxyethyl" in t:
        sugar = "2prime_MOE"
    elif re.search(r"2['′]-o-methyl", t):
        sugar = "2prime_OMe"
    elif "deoxy" in t:
        sugar = "DNA"
    else:
        sugar = None  # resolved below from the base

    methyl = bool(re.search(r"5-methyl", t))
    thio = "p-thio" in t

    base = None
    terminal = False
    for k, v in BASE_INTERNAL.items():
        if t.endswith(k):
            base = v
            break
    if base is None:
        for k, v in BASE_TERMINAL.items():
            if t.endswith(k):
                base, terminal = v, True
                break
    if base is None or base == "I":
        return None

    if sugar is None:
        # thymidine/thymidylyl are deoxy by definition; a bare ribo base is RNA
        sugar = "DNA" if base == "T" else "RNA"
    return base, sugar, methyl, thio, terminal


def parse(name: str):
    """Return (residues, linkages) for the longest clean residue run, else (None, None)."""
    s = re.sub(r"\s+", "", name)
    parts = LINK.split(s)
    if len(parts) < 2:
        return None, None

    # the first token carries a stereo prefix; the last trails into free text
    parts[0] = re.sub(r"^.*?(?:all-?p-?ambo-?|tout-?p-?ambo-?)", "", parts[0], flags=re.I)

    # A terminal nucleoside (…osine / …idine rather than …ylyl) ends the
    # molecule. Without stopping there the run bleeds straight into the French
    # and Spanish renderings of the same name, or into the next entry.
    runs, run = [], []
    for tok in parts:
        r = residue(tok) or _trailing(tok)
        if r is None:
            if run:
                runs.append((run, False))
                run = []
            continue
        run.append(r)
        if r[4]:                      # terminal residue closes the molecule
            runs.append((run, True))
            run = []
    if run:
        runs.append((run, False))

    complete = [r for r, closed in runs if closed]
    best = complete[0] if complete else max((r for r, _ in runs), key=len, default=[])
    if len(best) < 5:
        return None, None

    residues = [(b, s, m) for b, s, m, _, _ in best]
    # a residue's P-thio marks the linkage leaving it; the last has none
    linkages = ["PS" if thio else "PO" for *_, thio, _ in best[:-1]]
    return residues, linkages


def _trailing(tok: str):
    """Recover the final residue, which runs straight into the indication text.

    After whitespace stripping the last token reads like
    "2'-O-(2-methoxyethyl)-5-methyluridineantihypertriglyceridaemicagent".
    Trim at the terminal nucleoside - but only for a token that actually looks
    like a residue, otherwise this fires on ordinary prose and truncates runs.
    """
    t = tok.lower()
    if not re.search(r"deoxy|methoxyethyl|methyl|2['′]-o-", t):
        return None
    best = None
    for k in BASE_TERMINAL:
        m = re.search(k, t)
        # take the earliest terminal name, so trailing prose cannot extend it
        if m and (best is None or m.end() < best):
            best = m.end()
    return residue(tok[:best]) if best else None


def validate(name: str, stated_formula: str) -> dict:
    residues, linkages = parse(name)
    if residues is None:
        return {"ok": False, "reason": "unparsed_iupac"}
    stated = parse_formula(stated_formula)
    computed = oligo_formula(residues, linkages,
                             sodium_salt=stated.get("Na", 0) > 0)
    ok, diff = compare(computed, stated_formula)
    sugars = [s for _, s, _ in residues]
    n_ps = linkages.count("PS")
    w5 = next((i for i, s in enumerate(sugars) if s == "DNA"), 0)
    w3 = next((i for i, s in enumerate(reversed(sugars)) if s == "DNA"), 0)
    return {
        "ok": ok,
        "reason": "" if ok else f"formula_mismatch:{diff}",
        "sequence_5to3": "".join(b for b, _, _ in residues),
        "sequence_length": len(residues),
        "sugar_pattern_5to3": "|".join(sugars),
        "gapmer_layout": f"{w5}-{len(sugars) - w5 - w3}-{w3}"
        if "DNA" in sugars and sugars[0] != "DNA" else "",
        "n_phosphorothioate": n_ps,
        "n_phosphodiester": len(linkages) - n_ps,
        "phosphorothioate_fraction": round(n_ps / len(linkages), 4) if linkages else None,
        "computed_formula": render(computed),
        "stated_formula": stated_formula,
    }