oligotox-phase2-dataset / code /integrate_measured_layer.py
kartoun's picture
v2.0: two-layer release - measured layer (clinical AEs + formula-verified structures) and labelled simulation layer
f02a121 verified
Raw History Blame Contribute Delete
19.3 kB
"""
Integrate the measured real-world layer into the OligoTox dataset.
The v1.0 release is entirely computationally generated. This adds a parallel,
clearly separated layer of retrieved and measured data, using the same schema
conventions, identifier style and provenance fields as the existing tables so
the two join rather than sit side by side.
New tables, all under measured/:
clinical_adverse_events.csv observed AE counts per trial arm
oligo_chemistry_verified.csv sequences validated by formula checksum
oligo_modification_positions_verified.csv position-level chemistry for those
oligo_characterization.csv formulas, masses, PS and F counts
New metadata:
metadata/inn_corpus_index.csv every oligonucleotide INN located,
with extraction status - a gap map of
what public chemistry exists and what
remains to be extracted
Every row carries data_layer = measured_real, against computationally_generated
for the original tables, so no user can confuse the two.
"""
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"
OUT = DATA / "measured"
MEASURED = "measured_real"
NEW_SOURCES = [
{
"source_id": "CTGOV_RESULTS_REGISTRY",
"title": "ClinicalTrials.gov registered trial results (adverse event tables)",
"year": "2026",
"source_type": "public_trial_registry",
"doi_or_url": "https://clinicaltrials.gov/",
"license_or_access": "US Government work, public domain, open API",
"source_role": "measured human adverse-event outcomes for oligonucleotide therapeutics",
"modality_focus": "ASO, siRNA, aptamer, oligo therapeutics in clinical development",
"hepatotoxicity_relevance": "direct",
"use_in_core_dataset": "yes",
"notes": "Per-arm, per-MedDRA-term counts retrieved via API v2. Values are "
"observed counts reported by trial sponsors, not generated.",
"record_origin": "retrieved_measured",
"original_pdf_redistributed": "not_applicable",
"license_for_generated_output": "CC BY 4.0",
},
{
"source_id": "FDA_DAILYMED_LABELS",
"title": "FDA product labeling (DailyMed Structured Product Labels)",
"year": "2026",
"source_type": "regulatory_label",
"doi_or_url": "https://dailymed.nlm.nih.gov/",
"license_or_access": "US Government work, public domain, open API",
"source_role": "authoritative oligo chemistry, molecular formula and characterization",
"modality_focus": "approved oligonucleotide therapeutics",
"hepatotoxicity_relevance": "supporting",
"use_in_core_dataset": "yes",
"notes": "Chemical name, molecular formula and molecular weight parsed from "
"the DESCRIPTION section. Label text not redistributed; set ids given.",
"record_origin": "retrieved_measured",
"original_pdf_redistributed": "no",
"license_for_generated_output": "CC BY 4.0",
},
{
"source_id": "WHO_INN_LISTS",
"title": "WHO International Nonproprietary Names, Proposed and Recommended lists",
"year": "2026",
"source_type": "nomenclature_standard",
"doi_or_url": "https://www.who.int/teams/health-product-and-policy-standards/inn",
"license_or_access": "WHO publication, publicly downloadable",
"source_role": "authoritative sequence and position-level modification chemistry",
"modality_focus": "all oligonucleotide therapeutics receiving an INN",
"hepatotoxicity_relevance": "supporting",
"use_in_core_dataset": "yes",
"notes": "Systematic names parsed from lists pl100-135 and rl64-95. Each "
"accepted structure reproduces the WHO-stated molecular formula "
"exactly; non-matching parses are excluded, not corrected.",
"record_origin": "retrieved_measured",
"original_pdf_redistributed": "no",
"license_for_generated_output": "CC BY 4.0",
},
]
def dna_alphabet(seq: str, sugars: list) -> str:
"""Write ASO-class sequences in one alphabet.
The parsers emit U for 2'-modified ribo residues and T for deoxy ones, which
is chemically faithful but leaves a single ASO spelled in two alphabets.
Thymine and 5-methyluracil are the same nucleobase, so an ASO is written
throughout in DNA letters; a sequence with no deoxy residue at all is RNA
and keeps U.
"""
if "DNA" not in sugars:
return seq
return seq.replace("U", "T")
from formula_structure import OTHER_CONJUGATES
def _salt_form(formula):
"""Which form of the molecule a formula describes.
WHO INN lists print the free acid; FDA labelling usually prints the
sodium salt. Both are correct and they differ by one sodium per acidic
phosphate, but a reader joining the two tables sees two formulas for one
molecule, so each row says which form it carries.
"""
if not isinstance(formula, str) or not formula:
return ""
from formula_checksum import parse_formula
return "sodium_salt" if parse_formula(formula).get("Na", 0) else "free_acid"
def _ps_count(r):
"""Phosphorothioate linkages, from the label or else from the formula."""
stated = r.get("n_phosphorothioate_linkages")
if pd.notna(stated):
return stated
from formula_structure import structural_facts, PHOSPHATE_BACKBONES
formula = r.get("molecular_formula")
conj = (r.get("galnac_conjugated") == 1) or r["drug"] in OTHER_CONJUGATES
phos = r.get("backbone_chemistry") in PHOSPHATE_BACKBONES
if not isinstance(formula, str) or not formula:
return None
if conj:
# The cross-check these molecules receive compares the phosphorothioate
# markers in the published name against the formula's sulfur count, and
# eplontersen's thirteen markers match its S13. Agreement establishes
# that the conjugate carries no sulfur, so the sulfur count is the
# phosphorothioate count and leaving the field blank discards a result
# the check already produced. Linkage counts stay withheld, because
# phosphorus is what the conjugate does contribute.
from formula_checksum import parse_formula
return parse_formula(formula).get("S", 0) or None
if not phos:
return None
return structural_facts(formula, conjugated=conj,
phosphate_backbone=phos)["n_S_phosphorothioate"]
def build_chemistry() -> pd.DataFrame:
rows = []
fda = pd.read_csv(WORK / "fda_oligo_chemistry.csv")
for _, r in fda.iterrows():
if not isinstance(r.get("sequence_5to3"), str) or not r["sequence_5to3"]:
continue
sugars = str(r.get("sugar_pattern_5to3", "")).split("|")
rows.append({
"oligo_name_inn": r["drug"],
"sequence_5to3": dna_alphabet(r["sequence_5to3"], sugars),
"sequence_alphabet": "DNA" if "DNA" in sugars else "RNA",
"sequence_length": r.get("sequence_length"),
"sugar_pattern_5to3": r.get("sugar_pattern_5to3"),
"gapmer_layout": r.get("gapmer_layout"),
"backbone_chemistry": r.get("backbone_chemistry"),
"molecular_formula_stated": r.get("molecular_formula"),
"salt_form": _salt_form(r.get("molecular_formula")),
"molecular_weight_da": r.get("molecular_weight_da"),
# The label does not always print the linkage counts. Where the
# molecule is an unconjugated phosphate-backbone strand, the
# formula's sulfur count is the phosphorothioate count, so the
# blank can be filled from it. Where it is not - eplontersen - the
# count stays blank rather than being guessed, because the
# conjugate contributes its own atoms.
"n_phosphorothioate": _ps_count(r),
# Without this the row gives no sign that the molecule is
# conjugated, which is the whole reason it gets a narrower check
# and leaves the linkage count blank. The ligand itself is not
# modelled, so it is described rather than given a formula.
"conjugate_description":
"tri-antennary GalNAc ligand, per FDA labeling; not modelled "
"by this parser, so the stated formula was not reconstructed "
"and backbone counts are not derived from it"
if r.get("galnac_conjugated") == 1 else "",
"n_phosphodiester": r.get("n_phosphodiester_linkages"),
"phosphorothioate_fraction": r.get("phosphorothioate_fraction"),
# A conjugated molecule's formula includes the conjugate, which
# this parser does not model, so no full reconstruction is done for
# it. Eplontersen is the case in point: what was actually checked
# is that the phosphorothioate markers in its published name match
# the sulfur count in its formula. Claiming reconstruction for it
# would overstate the evidence, so the narrower check is named.
"verification_method":
"phosphorothioate_count_cross_check"
if r.get("galnac_conjugated") == 1
else "molecular_formula_reconstruction",
"value_origin": "retrieved_from_fda_label",
"source_id": "FDA_DAILYMED_LABELS",
"source_url": r.get("source_url"),
})
inn = pd.read_csv(WORK / "inn_oligo_chemistry.csv")
inn = inn[inn.verified == 1].drop_duplicates("inn_name")
for _, r in inn.iterrows():
sugars = str(r.get("sugar_pattern_5to3", "")).split("|")
rows.append({
"oligo_name_inn": r["inn_name"],
"sequence_5to3": dna_alphabet(str(r["sequence_5to3"]), sugars),
"sequence_alphabet": "DNA" if "DNA" in sugars else "RNA",
"sequence_length": r.get("sequence_length"),
"sugar_pattern_5to3": r.get("sugar_pattern_5to3"),
"gapmer_layout": r.get("gapmer_layout"),
"backbone_chemistry": "mixed_PS_PO_backbone"
if r.get("n_phosphodiester", 0) else "full_phosphorothioate",
"n_phosphorothioate": r.get("n_phosphorothioate"),
"n_phosphodiester": r.get("n_phosphodiester"),
"phosphorothioate_fraction": r.get("phosphorothioate_fraction"),
"molecular_formula_stated": r.get("molecular_formula_stated"),
"salt_form": _salt_form(r.get("molecular_formula_stated")),
"cas_number": r.get("cas_number"),
"verification_method": "molecular_formula_reconstruction",
"value_origin": "retrieved_from_who_inn",
"source_id": "WHO_INN_LISTS",
"source_url": r.get("source_url"),
})
df = pd.DataFrame(rows)
df.insert(0, "measured_oligo_id",
["RWOLIGO_%03d" % (i + 1) for i in range(len(df))])
df["data_layer"] = MEASURED
df["record_origin"] = "retrieved_measured"
df["license_for_generated_output"] = "CC BY 4.0"
return df
def build_positions(chem: pd.DataFrame) -> pd.DataFrame:
"""Expand verified sequences to position level, mirroring the generated table."""
rows = []
for _, r in chem.iterrows():
seq = str(r["sequence_5to3"])
sugars = str(r["sugar_pattern_5to3"]).split("|")
if len(sugars) != len(seq):
continue
labels = region_labels(sugars, "single")
for i, (b, sug, 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"],
"strand": "single",
"position": i,
"base": b,
"sugar_modification": sug,
"region": region,
"modification_provenance": r["value_origin"],
"data_layer": MEASURED,
"source_id": r["source_id"],
"source_url": r["source_url"],
})
return pd.DataFrame(rows)
def main() -> None:
OUT.mkdir(exist_ok=True)
# 1. adverse events -------------------------------------------------------
ae = pd.read_csv(WORK / "ctgov_oligo_adverse_events.csv")
ae["data_layer"] = MEASURED
ae["record_origin"] = "retrieved_measured"
ae["source_id"] = "CTGOV_RESULTS_REGISTRY"
ae["license_for_generated_output"] = "CC BY 4.0"
ae.to_csv(OUT / "clinical_adverse_events.csv", index=False)
print(f" clinical_adverse_events.csv {len(ae):>7,} rows")
# 2. verified chemistry and position-level expansion ----------------------
chem = build_chemistry()
chem.to_csv(OUT / "oligo_chemistry_verified.csv", index=False)
print(f" oligo_chemistry_verified.csv {len(chem):>7,} rows")
pos = build_positions(chem)
pos.to_csv(OUT / "oligo_modification_positions_verified.csv", index=False)
print(f" oligo_modification_positions_verified.csv {len(pos):>2,} rows")
# 3. characterization -----------------------------------------------------
fs = pd.read_csv(WORK / "fda_oligo_formula_structure.csv")
fs["salt_form"] = fs.molecular_formula.map(_salt_form)
fs["data_layer"] = MEASURED
fs["value_origin"] = "retrieved_from_fda_label"
fs["source_id"] = "FDA_DAILYMED_LABELS"
fs.to_csv(OUT / "oligo_characterization.csv", index=False)
print(f" oligo_characterization.csv {len(fs):>7,} rows")
# 4. INN corpus index - the gap map --------------------------------------
inn = pd.read_csv(WORK / "inn_oligo_chemistry.csv")
# Several lists print the same INN, and the harvester's old forward window
# sometimes read a neighbouring entry's formula, so one name can carry two
# conflicting CAS numbers. Picking the first row left inclisiran holding
# fitusiran's. A CAS identifies one substance, so a CAS that appears under
# two different INN names is the borrowed one; prefer the row whose CAS is
# unique to the name, and prefer having a CAS at all over having none.
# Rank a row's identity: a CAS unique to this name beats a CAS shared with
# another name, which in turn beats no CAS at all. Both halves matter. The
# first discards inclisiran's borrowed entry in favour of its own; the
# second keeps fitusiran's CAS, which is genuinely fitusiran's and only
# looked shared because inclisiran had taken a copy of it.
shared = (inn[inn.cas_number.notna()]
.groupby("cas_number").inn_name.nunique())
has_cas = inn.cas_number.notna()
unique_cas = has_cas & ~inn.cas_number.map(shared).gt(1).fillna(False)
inn = inn.assign(_cas_rank=unique_cas.astype(int) * 2 + has_cas.astype(int))
idx = (inn.sort_values(["verified", "_cas_rank"], ascending=False)
.drop_duplicates("inn_name")
.loc[:, ["inn_name", "cas_number", "molecular_formula_stated",
"verified", "verification", "source_list", "source_url"]]
.rename(columns={"verified": "structure_extracted_and_verified",
"verification": "extraction_status"}))
# Whatever preference could not resolve - a name for which every row
# carries a borrowed CAS - has its identity fields withheld rather than
# shipped wrong.
dup = idx.cas_number.notna() & (idx.cas_number.astype(str) != "") & idx.duplicated("cas_number", keep=False)
if dup.any():
# keep the entry whose structure verified against the formula
keep = dup & (idx.structure_extracted_and_verified == 1)
drop = dup & ~keep
idx.loc[drop, ["cas_number", "molecular_formula_stated"]] = ""
idx.loc[drop, "extraction_status"] = "entry_formula_not_isolated"
print(f" cleared borrowed CAS/formula on {int(drop.sum())} INN row(s): "
f"{', '.join(idx.loc[drop, 'inn_name'])}")
idx["extraction_barrier"] = idx["extraction_status"].map(
lambda s: "" if str(s).startswith("molecular_formula_match")
else "entry_formula_not_isolated_in_source_list"
if "entry_formula_not_isolated" in str(s)
else "notation_vocabulary_not_yet_implemented"
if "unparsed" in str(s)
else "parsed_structure_failed_formula_check_"
"(commonly a conjugate whose linker is not modelled)")
idx["data_layer"] = MEASURED
idx["value_origin"] = "retrieved_from_who_inn"
idx["source_id"] = "WHO_INN_LISTS"
idx.to_csv(DATA / "metadata" / "inn_corpus_index.csv", index=False)
n_ok = int(idx.structure_extracted_and_verified.sum())
print(f" metadata/inn_corpus_index.csv {len(idx):>7,} INN names "
f"({n_ok} verified, {len(idx) - n_ok} located but not extracted)")
# 5. register sources and provenance -------------------------------------
src_path = DATA / "metadata" / "sources.csv"
src = pd.read_csv(src_path, dtype=str)
add = pd.DataFrame(NEW_SOURCES)
src = pd.concat([src, add[~add.source_id.isin(src.source_id)]], ignore_index=True)
src.to_csv(src_path, index=False)
prov_path = DATA / "metadata" / "provenance.csv"
prov = pd.read_csv(prov_path, dtype=str)
counts = {
"CTGOV_RESULTS_REGISTRY": len(ae),
"FDA_DAILYMED_LABELS": len(fs) + int((chem.source_id == "FDA_DAILYMED_LABELS").sum()),
"WHO_INN_LISTS": int((chem.source_id == "WHO_INN_LISTS").sum()) + len(idx),
}
new_prov = [{
"provenance_id": f"PROV_{s['source_id']}",
"source_id": s["source_id"],
"source_title": s["title"],
"source_type": s["source_type"],
"doi_or_url": s["doi_or_url"],
"source_license_or_access": s["license_or_access"],
"source_role": s["source_role"],
"records_generated_from_source": str(counts[s["source_id"]]),
"source_pdf_redistributed": "no",
"source_figures_or_tables_redistributed": "no",
"generation_method": "retrieved and parsed programmatically; structures "
"accepted only on exact molecular-formula match",
"record_origin_default": "retrieved_measured",
"output_license": "CC BY 4.0",
} for s in NEW_SOURCES]
np_df = pd.DataFrame(new_prov)
prov = pd.concat([prov, np_df[~np_df.source_id.isin(prov.source_id)]],
ignore_index=True)
prov.to_csv(prov_path, index=False)
print(f"\n registered {len(NEW_SOURCES)} sources and provenance records")
if __name__ == "__main__":
main()