""" Molecular-formula checksum for parsed oligonucleotide structures. Purpose: make sequence extraction machine-verifiable rather than dependent on a human re-reading the source. If a parsed structure (sequence + per-position sugar + per-linkage backbone) is correct, the molecular formula computed from it must equal the formula stated on the FDA label. A wrong parse will not reproduce that formula. Anything failing this check is dropped or flagged, never shipped as verified. Construction: a linear oligonucleotide of n residues with free 5'- and 3'-OH has n nucleosides and n-1 internucleotide linkages. Each linkage condenses two hydroxyls with phosphoric acid, releasing two waters: Nuc-OH + HO-Nuc' + H3PO4 -> Nuc-O-P(=O)(OH)-O-Nuc' + 2 H2O so each linkage contributes (P + 2 O - H). A phosphorothioate swaps one non-bridging O for S. The sodium salt replaces one acidic hydrogen per linkage. """ import re from collections import Counter # --- nucleoside atom counts -------------------------------------------------- # 2'-deoxyribonucleosides DEOXY = { "A": "C10H13N5O3", "G": "C10H13N5O4", "C": "C9H13N3O4", "T": "C10H14N2O5", # thymidine "m5C": "C10H15N3O4", } # ribonucleosides RIBO = { "A": "C10H13N5O4", "G": "C10H13N5O5", "C": "C9H13N3O5", "U": "C9H12N2O6", "m5U": "C10H14N2O6", # ribothymidine "m5C": "C10H15N3O5", } MOE_ADDON = "C3H6O" # 2'-OH -> 2'-O-CH2CH2OCH3 def parse_formula(s: str) -> Counter: c = Counter() for el, n in re.findall(r"([A-Z][a-z]?)(\d*)", s): if el: c[el] += int(n) if n else 1 return c def render(c: Counter) -> str: order = ["C", "H", "F", "N", "Na", "O", "P", "S"] keys = [k for k in order if c.get(k)] + sorted(k for k in c if k not in order and c[k]) return "".join(f"{k}{c[k]}" if c[k] != 1 else k for k in keys) # This module implements these three sugars and these two linkages only. Other # families - bridged nucleic acids, morpholinos, conjugated siRNAs - are built # by their own parsers. Anything outside this vocabulary used to fall through # silently, a sugar becoming plain RNA and a linkage becoming phosphodiester, # so a mistyped or unsupported token produced a confident wrong formula # instead of an error. They are rejected now. SUGARS = {"DNA", "RNA", "2prime_MOE"} LINKAGES = {"PS", "PO"} def nucleoside(base: str, sugar: str, methylated: bool) -> Counter: """base in ACGTU; sugar in {DNA, RNA, 2prime_MOE}.""" if sugar not in SUGARS: raise ValueError( f"unsupported sugar {sugar!r}; this module implements " f"{sorted(SUGARS)} and the other families have their own parsers") if base not in "ACGTU": raise ValueError(f"unsupported base {base!r}") if sugar == "DNA": key = "m5C" if (methylated and base == "C") else ("T" if base in "TU" else base) return parse_formula(DEOXY[key]) key = base if methylated and base in "CU": key = "m5" + base elif base == "T": key = "m5U" f = parse_formula(RIBO[key]) if sugar == "2prime_MOE": f += parse_formula(MOE_ADDON) return f def oligo_formula(residues, linkages, sodium_salt=True, extra=None) -> Counter: """residues: [(base, sugar, methylated)]; linkages: ['PS'|'PO'] length n-1.""" bad = {lk for lk in linkages} - LINKAGES if bad: raise ValueError(f"unsupported linkage(s) {sorted(bad)}; " f"expected {sorted(LINKAGES)}") # A linear strand of n residues has exactly n-1 internucleotide linkages. # A mismatch means the caller built one of the two lists wrongly, which # would otherwise surface as an unexplained phosphorus discrepancy. if len(linkages) != len(residues) - 1: raise ValueError( f"{len(residues)} residues need {len(residues) - 1} linkages, " f"got {len(linkages)}") total = Counter() for base, sugar, me in residues: total += nucleoside(base, sugar, me) for lk in linkages: total["P"] += 1 total["O"] += 2 total["H"] -= 1 if lk == "PS": total["O"] -= 1 total["S"] += 1 if extra: total += parse_formula(extra) if sodium_salt: n = len(linkages) total["H"] -= n total["Na"] += n return +total def compare(computed: Counter, stated: str): s = parse_formula(stated) diff = {k: computed.get(k, 0) - s.get(k, 0) for k in set(computed) | set(s) if computed.get(k, 0) != s.get(k, 0)} return (not diff), diff # --- proof cases ------------------------------------------------------------- # inotersen: 5-10-5 2'-MOE gapmer, 20-mer, all 19 linkages phosphorothioate. # Cytosines and uracils in the MOE wings are 5-methylated; the label writes the # single gap cytosine as m5C as well. INOTERSEN_SEQ = "TCTTGGTTACATGAAATCCC" INOTERSEN_SUGARS = ["2prime_MOE"] * 5 + ["DNA"] * 10 + ["2prime_MOE"] * 5 # Every pyrimidine in this label carries a 5-methyl (m5rU / m5C), which is # standard for 2'-MOE antisense: 5-methyl-C suppresses CpG immunostimulation, # and MOE-U is written as ribothymidine. Purines are never 5-methylated, so # deriving the flag from the base is equivalent to reading it off the label. INOTERSEN_METHYL = [b in "CU" for b in INOTERSEN_SEQ] def run_proof(): residues = [(b, s, m) for b, s, m in zip(INOTERSEN_SEQ, INOTERSEN_SUGARS, INOTERSEN_METHYL)] print("inotersen (free acid) target C230H318N69O121P19S19") f = oligo_formula(residues, ["PS"] * 19, sodium_salt=False) ok, diff = compare(f, "C230H318N69O121P19S19") print(f" computed {render(f)}") print(f" match={ok}" + (f" diff={diff}" if diff else "")) print("\ninotersen (sodium salt) target C230H299N69Na19O121P19S19") f = oligo_formula(residues, ["PS"] * 19, sodium_salt=True) ok, diff = compare(f, "C230H299N69Na19O121P19S19") print(f" computed {render(f)}") print(f" match={ok}" + (f" diff={diff}" if diff else "")) # Second, independent style of check. Eplontersen is the same ASO with a # GalNAc conjugate and a mixed backbone. Its conjugate formula is not # published separately, so a full atom reconstruction would be circular. # Instead cross-check two unrelated parts of the label against each other: # the "sp" markers in the chemical name versus the S count in the formula. print("\neplontersen cross-check: sp markers in name vs S count in formula") import json from pathlib import Path raw = Path(__file__).with_name("fda_oligo_descriptions.json") if not raw.exists(): # The cached label text is deliberately not redistributed: the dataset # publishes extracted chemical facts, not FDA label text. Re-create it # with `python harvest_fda_chemistry.py`, which retrieves it directly # from DailyMed. print(" skipped - cached label text is not redistributed by design;") print(" run `python harvest_fda_chemistry.py` to retrieve it from DailyMed") return text = json.loads(raw.read_text(encoding="utf-8"))["eplontersen"]["description"] body = re.search(r"\bd\(((?:\[2['′].{0,40}?\]|[-A-Za-z0-9])+?)\)\s*,", text, re.S) toks = _split_depth0(re.sub(r"\s+", "", body.group(1))) n_res = sum(1 for t in toks if t.lower() != "sp") n_ps = sum(1 for t in toks if t.lower() == "sp") stated_s = parse_formula("C296H417N77O156P20S13Na20")["S"] print(f" residues={n_res} linkages={n_res - 1} PS from name={n_ps} " f"S from formula={stated_s}") print(f" match={n_ps == stated_s}") def _split_depth0(s: str) -> list: parts, buf, depth = [], [], 0 for ch in s: if ch in "([": depth += 1 elif ch in ")]": depth -= 1 if ch == "-" and depth == 0: parts.append("".join(buf)) buf = [] else: buf.append(ch) parts.append("".join(buf)) return [p for p in parts if p] if __name__ == "__main__": run_proof()