""" Merge the four chemistry families into one verified-structures table. Each family needed its own naming vocabulary - 2'-MOE antisense, morpholinos, siRNA duplexes, and LNA/cEt/ENA bridged gapmers - but every family is admitted on the same terms: the molecular formula recomputed from the parsed structure must equal the formula the source states, element for element. The formula check constrains composition, not order. Two sequences that are permutations of one another share a formula; bamosiran and asvasiran are a live example in this dataset, both C401H500N150O290P40 and entirely different molecules. Where an independent order check is available it is recorded in order_evidence: Watson-Crick complementarity between the parsed strands of a duplex, which breaks immediately on a mis-ordered parse. """ import json from pathlib import Path import pandas as pd from regions import regions as region_labels WORK = Path(r"C:\DBBun\Misc\NIH-OligoTox Phase II\_v2_work") DATA = WORK / "dataset_root_v2" OUT = DATA / "measured" # WHO renamed renapersen to renadirsen (pl120). Both names appear in the lists # with an identical sequence and formula, so they are one molecule, not two. SUPERSEDED_NAMES = {"renapersen": "renadirsen", "votrisiran": "vutrisiran"} # Antisense oligonucleotides are written in the DNA alphabet by convention even # when no deoxy residue is present: nusinersen is fully 2'-MOE and is published # as TCACTTTCATAATGCTGG. Keying the alphabet on the presence of a deoxy residue # wrote two fully-MOE antisense molecules with U instead of T. ASO_FAMILIES = {"2prime_MOE_antisense", "bridged_nucleic_acid", "phosphorodiamidate_morpholino"} # Every WHO list is published at a predictable address, so a record that names # its list can also give the document itself. Most rows carried the list code # but no URL, which left a reader with nothing to click through to. INN_BASE = ("https://cdn.who.int/media/docs/default-source/" "international-nonproprietary-names-(inn)") def _base(name, family, src): return {"oligo_name_inn": name, "chemistry_family": family, "verification_method": "molecular_formula_reconstruction", "value_origin": "retrieved_from_who_inn", "source_id": "WHO_INN_LISTS", "source_list": src, "source_url": f"{INN_BASE}/{src}.pdf" if src else "", "data_layer": "measured_real", "record_origin": "retrieved_measured", "license_for_generated_output": "CC BY 4.0"} def _family_from_sugars(pattern) -> str: """Name the family from the residues actually present.""" toks = {t.strip() for t in str(pattern).split("|")} if any("morpholino" in t for t in toks): return "phosphorodiamidate_morpholino" if any(t in ("LNA", "cEt", "ENA", "AmNA") for t in toks): return "bridged_nucleic_acid" if any("MOE" in t for t in toks): return "2prime_MOE_antisense" if toks == {"DNA"}: return "dna_antisense" return "other_antisense" def from_existing() -> list: """The 2'-MOE antisense set produced by integrate_measured_layer. This function reads the same file it later writes, so it must preserve a chemistry_family already present rather than re-tagging every row - a re-run would otherwise relabel all four families as 2'-MOE antisense. """ d = pd.read_csv(OUT / "oligo_chemistry_verified.csv") rows = [] for _, r in d.iterrows(): # Defaulting every row of unknown family to 2'-MOE antisense mislabelled # prexigebersen, whose exported sugar pattern is DNA throughout with no # MOE residue anywhere. The family follows the chemistry that is there. fam = r.get("chemistry_family") if not fam or pd.isna(fam): fam = _family_from_sugars(r.get("sugar_pattern_5to3")) rec = _base(r.oligo_name_inn, fam, r.get("source_list", "")) rec.update({ "sequence_5to3": r.sequence_5to3, "sequence_alphabet": r.get("sequence_alphabet"), "sequence_length": r.get("sequence_length"), "sugar_pattern_5to3": r.get("sugar_pattern_5to3"), "gapmer_layout": r.get("gapmer_layout"), "n_phosphorothioate": r.get("n_phosphorothioate"), "molecular_formula_stated": r.get("molecular_formula_stated"), "cas_number": r.get("cas_number"), # Keep the method the producing stage recorded. Overwriting it # with this module's default would relabel eplontersen's narrower # sulfur-count check as a full reconstruction. "verification_method": r.get("verification_method") or rec["verification_method"], "conjugate_description": r.get("conjugate_description", ""), "salt_form": r.get("salt_form", ""), "value_origin": r.get("value_origin"), "source_id": r.get("source_id"), "source_url": r.get("source_url") or rec["source_url"], "order_evidence": r.get("order_evidence", "") if "order_evidence" in d.columns else "", }) rows.append(rec) return rows def from_pmo() -> list: d = pd.read_csv(WORK / "pmo_results.csv") d = d[d.verified == "YES"].drop_duplicates("inn") rows = [] for _, r in d.iterrows(): rec = _base(r.inn, "phosphorodiamidate_morpholino", r.who_list) rec.update({ "sequence_5to3": r.sequence_5to3, "sequence_alphabet": "DNA", "sequence_length": r.sequence_length, "sugar_pattern_5to3": "|".join(["morpholino"] * int(r.sequence_length)), "gapmer_layout": "", "n_phosphorothioate": 0, "backbone_chemistry": r.backbone_chemistry, "molecular_formula_stated": r.stated_formula, "cas_number": r.get("cas"), "order_evidence": "", }) rows.append(rec) return rows def from_sirna() -> list: """Unconjugated siRNA duplexes. The parser reports the sequence normalised to 5'->3' but leaves the sugar pattern in the order the INN name was written. Where those differ the two fall out of register, so a dTdT overhang ends up annotated as ribose and the 5'-terminal ribonucleotide as deoxy. A molecular formula cannot detect this - reversal preserves composition exactly - and neither can strand complementarity. The pattern is reversed here whenever the sequence was. """ d = pd.read_csv(WORK / "sirna_results.csv") d = d[d.ok == True].drop_duplicates("inn_name") rows = [] for _, r in d.iterrows(): anti_rev = str(r.antisense_sequence) != str(r.antisense_sequence_5to3) sense_rev = str(r.sense_sequence) != str(r.sense_sequence_5to3) anti_pat = str(r.antisense_sugar_pattern) sense_pat = str(r.sense_sugar_pattern) if anti_rev: anti_pat = anti_pat[::-1] if sense_rev: sense_pat = sense_pat[::-1] rec = _base(r.inn_name, "siRNA_duplex", r.who_list) rec.update({ # the guide (antisense) strand is the one that enters RISC, so it is # the sequence a toxicity model should key on "sequence_5to3": r.antisense_sequence_5to3, "sense_sequence_5to3": r.sense_sequence_5to3, "sequence_alphabet": "RNA", "sequence_length": len(str(r.antisense_sequence_5to3)), "strand_lengths": r.strand_lengths, "sugar_pattern_5to3": anti_pat, "sense_sugar_pattern": sense_pat, "gapmer_layout": "", "n_phosphorothioate": r.n_phosphorothioate, "molecular_formula_stated": r.stated_formula, "order_evidence": f"watson_crick_complementarity {r.complementarity}", }) rows.append(rec) return rows def from_galnac() -> list: """GalNAc-conjugated siRNA duplexes. The conjugate is parsed from the systematic name rather than treated as opaque. The same tri-antennary cluster formula is derived from differently-worded names across many molecules, which is what distinguishes a model from a per-molecule fit. """ d = pd.read_csv(WORK / "galnac_results.csv") d = d[d.ok == True].drop_duplicates("inn") rows = [] for _, r in d.iterrows(): rec = _base(r.inn, "GalNAc_conjugated_siRNA", r.source_list) rec.update({ "sequence_5to3": r.antisense_sequence_5to3, "sense_sequence_5to3": r.sense_sequence_5to3, "sequence_alphabet": "RNA", "sequence_length": len(str(r.antisense_sequence_5to3)), "strand_lengths": r.strand_lengths, "sugar_pattern_5to3": r.sugar_pattern_antisense, "sense_sugar_pattern": r.sugar_pattern_sense, "gapmer_layout": "", "n_phosphorothioate": r.n_phosphorothioate, "molecular_formula_stated": r.stated_formula, "conjugate_description": r.conjugate_description, "conjugate_formula": r.conjugate_formula, "order_evidence": f"watson_crick {r.complementarity}", }) rows.append(rec) return rows def from_bridged() -> list: d = pd.read_csv(WORK / "bridged_results.csv") d = d[d.ok == True].drop_duplicates("inn_name") rows = [] for _, r in d.iterrows(): rec = _base(r.inn_name, "bridged_nucleic_acid", r.source_list) rec.update({ "sequence_5to3": r.sequence_5to3, "sequence_alphabet": "DNA", "sequence_length": r.sequence_length, "sugar_pattern_5to3": r.sugar_pattern_5to3, "gapmer_layout": r.gapmer_layout, "n_phosphorothioate": r.n_phosphorothioate, "molecular_formula_stated": r.stated_formula, "order_evidence": "", }) rows.append(rec) return rows SUGAR_LETTER = {"L": "LNA", "E": "2prime_cEt", "N": "2prime_ENA", "M": "2prime_MOE", "d": "DNA", "r": "RNA", "m": "2prime_OMe", "f": "2prime_F", "D": "DNA", "R": "RNA"} # The family parsers encode sugar patterns three different ways: single letters # (bridged, siRNA), pipe-delimited names (MOE antisense, morpholino) and # comma-delimited names (GalNAc). Falling through to the family label left all # 34 GalNAc records with no per-position chemistry at all. SUGAR_NAME = {"OMe": "2prime_OMe", "2'F": "2prime_F", "2F": "2prime_F", "dR": "DNA", "R": "RNA", "Me": "2prime_OMe", "MOE": "2prime_MOE", "LNA": "LNA", "cEt": "2prime_cEt", "morpholino": "morpholino"} def _sugar_tokens(pattern, n_residues): """Split a sugar pattern into exactly one token per residue, or return None.""" p = str(pattern or "").strip() if not p or p == "nan": return None for delim in (",", "|"): if delim in p: toks = [t.strip() for t in p.split(delim)] return toks if len(toks) == n_residues else None if len(p) == n_residues: # single-letter encoding return list(p) return None def _normalise_sugar(tok): return SUGAR_NAME.get(tok, SUGAR_LETTER.get(tok, tok)) def expand_positions(chem: pd.DataFrame) -> pd.DataFrame: """One record per residue, matching the generated position table's shape. Duplexes get both strands. Emitting only the guide strand left roughly 950 sense-strand residues out of a table the documents describe as complete. """ rows = [] for _, r in chem.iterrows(): strands = [("antisense" if r.chemistry_family in DUPLEX else "single", str(r.sequence_5to3), r.sugar_pattern_5to3)] if r.chemistry_family in DUPLEX and isinstance( r.get("sense_sequence_5to3"), str): strands.append(("sense", r.sense_sequence_5to3, r.get("sense_sugar_pattern"))) for strand, seq, pattern in strands: _emit(rows, r, strand, str(seq), pattern) return pd.DataFrame(rows) DUPLEX = {"siRNA_duplex", "GalNAc_conjugated_siRNA"} def _emit(rows, r, strand, seq, pattern): if not seq or seq == "nan": return toks = _sugar_tokens(pattern, len(seq)) sugars = ([_normalise_sugar(t) for t in toks] if toks else ["not_resolved"] * len(seq)) labels = region_labels(sugars, strand) for i, (b, s, region) in enumerate(zip(seq, sugars, labels), start=1): rows.append({ "measured_oligo_id": r.measured_oligo_id, "oligo_name_inn": r.oligo_name_inn, "chemistry_family": r.chemistry_family, "strand": strand, "position": i, "base": b, "sugar_modification": s, "region": region, "modification_provenance": r.value_origin, "data_layer": "measured_real", "source_id": r.source_id, }) def main() -> None: rows = (from_existing() + from_pmo() + from_sirna() + from_bridged() + from_galnac()) chem = pd.DataFrame(rows) # Each family parser carries its own formula, so the salt form is derived # once here for every row rather than threaded through five parsers. WHO # INN lists print the free acid and FDA labelling usually prints the sodium # salt, which is why one molecule can appear in two tables with two # formulas; naming the form makes that legible instead of contradictory. from integrate_measured_layer import _salt_form chem["salt_form"] = chem.molecular_formula_stated.map(_salt_form) # A linear strand of n residues has n-1 internucleotide linkages, so a # phosphorothioate count above that is not a linkage count. Renadirsen is # the case here: S18 and P18 against 17 linkages, the excess being a # terminal phosphorothioate monoester. Reporting 18 as linkages overstates # the backbone, so the count is held to the linkages and the extra group is # described instead of being folded in silently. def _cap_ps(r): if pd.isna(r.n_phosphorothioate): return r.n_phosphorothioate, r.get("conjugate_description", "") if isinstance(r.strand_lengths, str) and "/" in r.strand_lengths: n_link = sum(int(x) - 1 for x in r.strand_lengths.split("/")) elif pd.notna(r.sequence_length): n_link = int(r.sequence_length) - 1 else: return r.n_phosphorothioate, r.get("conjugate_description", "") if r.n_phosphorothioate <= n_link: return r.n_phosphorothioate, r.get("conjugate_description", "") extra = int(r.n_phosphorothioate - n_link) note = (f"{extra} phosphorothioate group(s) beyond the {n_link} " f"internucleotide linkages, consistent with a terminal " f"phosphorothioate monoester; the linkage count excludes them") have = r.get("conjugate_description", "") have = "" if not isinstance(have, str) else have return float(n_link), (have + "; " + note if have else note) capped = chem.apply(_cap_ps, axis=1, result_type="expand") chem["n_phosphorothioate"], chem["conjugate_description"] = capped[0], capped[1] # Run-length layouts were written as count immediately followed by the # chemistry name. Most names are alphabetic so that is readable, but a # name can itself start with a digit: farabursen's three 2'-F residues # came out as "32F", which reads as thirty-two fluorines. Splitting on # the known vocabulary rather than on the first non-digit resolves it. LAYOUT_TOKENS = ("LNA", "DNA", "MOE", "cEt", "ENA", "AmNA", "2F", "2OMe", "OMe", "F") def _space_layout(v): if not isinstance(v, str) or not v.startswith("mixed: "): return v parts = [] for part in v[len("mixed: "):].split("-"): for i in range(1, len(part)): if part[:i].isdigit() and part[i:] in LAYOUT_TOKENS: parts.append(f"{part[:i]}x{part[i:]}") break else: parts.append(part) return "mixed: " + "-".join(parts) chem["gapmer_layout"] = chem.gapmer_layout.map(_space_layout) # The family names a sugar chemistry; it was also being read as an # architecture, which made miravirsen and cobomarsen "gapmers" when they # are LNA/DNA mixmers acting by steric blockade rather than RNase H. The # architecture is recorded separately, from the region labels that the # position table already derives. def _architecture(r): if r.chemistry_family in DUPLEX or ( isinstance(r.strand_lengths, str) and "/" in str(r.strand_lengths)): return "duplex" toks = _sugar_tokens(r.sugar_pattern_5to3, len(str(r.sequence_5to3))) sug = [_normalise_sugar(t) for t in toks] if toks else [] if not sug: return "" labels = set(region_labels(sug, "single")) if "central_gap" in labels: return "gapmer" if any(x.startswith("mixmer") for x in labels): return "mixmer" # No DNA at all, but more than one modified sugar: a chimera such as # renadirsen's ENA/2'-OMe, which is neither uniform nor a gapmer. return "uniform" if len(set(sug)) == 1 else "chimera" chem["architecture"] = chem.apply(_architecture, axis=1) # An empty order_evidence field reads as an oversight. It is not: for a # single strand there is no independent check of residue order, only the # published name the parse came from. Saying so is better than a blank. chem["order_evidence"] = chem.order_evidence.fillna("").replace( "", "none independent of the source naming the residue order") # collapse superseded INN names onto the name WHO now uses chem["superseded_name"] = "" for old, new in SUPERSEDED_NAMES.items(): hit = chem.oligo_name_inn.str.lower() == old if hit.any() and (chem.oligo_name_inn.str.lower() == new).any(): chem.loc[chem.oligo_name_inn.str.lower() == new, "superseded_name"] = old chem = chem[~hit] else: chem.loc[hit, "oligo_name_inn"] = new chem.loc[hit, "superseded_name"] = old # ASO-class molecules take the DNA alphabet regardless of a deoxy gap aso = chem.chemistry_family.isin(ASO_FAMILIES) chem.loc[aso, "sequence_5to3"] = chem.loc[aso, "sequence_5to3"].astype(str).str.replace("U", "T", regex=False) chem.loc[aso, "sequence_alphabet"] = "DNA" chem = chem.drop_duplicates("oligo_name_inn") chem = chem.sort_values(["chemistry_family", "oligo_name_inn"]).reset_index(drop=True) chem.insert(0, "measured_oligo_id", ["RWOLIGO_%03d" % (i + 1) for i in range(len(chem))]) chem.to_csv(OUT / "oligo_chemistry_verified.csv", index=False) pos = expand_positions(chem) pos.to_csv(OUT / "oligo_modification_positions_verified.csv", index=False) print(f" verified structures {len(chem)}") print(chem.chemistry_family.value_counts().to_string()) print(f" position-level records {len(pos):,}") n_order = int((chem.order_evidence.fillna("") != "").sum()) print(f" with independent order evidence {n_order}") # Refresh the corpus index. Two corrections matter. The index was built by an # early harvester whose scan missed molecules the later family parsers found, # so verified structures absent from it are appended rather than left # contradicting the structures table. And the old barrier text blamed # unmodelled conjugate linkers, which is no longer the reason for anything, # since GalNAc conjugates are now parsed - so barriers are re-derived. idx = pd.read_csv(DATA / "metadata" / "inn_corpus_index.csv") now = set(chem.oligo_name_inn.str.lower()) missing = sorted(now - set(idx.inn_name.str.lower())) if missing: add = pd.DataFrame([{**{c: "" for c in idx.columns}, "inn_name": m} for m in missing]) idx = pd.concat([idx, add], ignore_index=True) ok = idx.inn_name.str.lower().isin(now) idx["structure_extracted_and_verified"] = ok.astype(int) # The index was harvested independently of the parsers, and for some names # it picked up the wrong formula entirely - renadirsen as a small molecule, # tivanisiran with 19 phosphorus for a duplex needing 40, patisiran with # the sodium salt's hydrogen count but no sodium. Where a structure passed # the formula check, that table is the authority, so its formula, CAS and # verification method are copied over rather than left to disagree. auth = (chem.drop_duplicates("oligo_name_inn") .set_index(chem.drop_duplicates("oligo_name_inn") .oligo_name_inn.str.lower())) key = idx.inn_name.str.lower() for col, src in (("molecular_formula_stated", "molecular_formula_stated"), ("cas_number", "cas_number"), ("extraction_status", "verification_method")): vals = key.map(auth[src]) idx.loc[ok & vals.notna(), col] = vals[ok & vals.notna()] idx.loc[ok, "extraction_barrier"] = "" # A formula with no phosphorus is not an oligonucleotide. Seven unverified # rows carry small-molecule formulas the harvester read from the wrong # entry, and mipomersen's has no phosphorus at all. Shipping them invites a # reader to treat them as the published formula, so they are withheld. import re as _re bogus = (~ok) & idx.molecular_formula_stated.fillna("").str.match( r"^C\d+H\d+") & ~idx.molecular_formula_stated.fillna("").str.contains("P") idx.loc[bogus, "molecular_formula_stated"] = "" idx.loc[bogus, "extraction_status"] = "entry_formula_not_isolated" print(f" withheld {int(bogus.sum())} phosphorus-free formulas as misread") # Superseded names are the same molecule under an older INN, which the # structures table already records. Counting them as separate unverified # entries overstates both the corpus and the gap. sup = {k.lower() for k in SUPERSEDED_NAMES} idx.loc[key.isin(sup), "extraction_status"] = "superseded_name" idx.loc[key.isin(sup), "extraction_barrier"] = ( "superseded INN; the current name carries the verified structure") idx.loc[~ok, "extraction_barrier"] = ( "naming vocabulary for this molecule class not yet implemented, or the " "published entry carries no molecular formula to check against") idx["data_layer"] = "measured_real" idx["value_origin"] = "retrieved_from_who_inn" idx["source_id"] = "WHO_INN_LISTS" idx.to_csv(DATA / "metadata" / "inn_corpus_index.csv", index=False) print(f" INN index verified {int(ok.sum())} of {len(idx)}" f" ({len(missing)} appended)") if __name__ == "__main__": main()