Download code/qa_v2.py from DBbun/oligotox-phase2-dataset: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/datasets/DBbun/oligotox-phase2-dataset/resolve/main/code/qa_v2.py
- Command line
-
hf download hf://datasets/DBbun/oligotox-phase2-dataset/code/qa_v2.py
-
curl -L -o qa_v2.py https://huggingface.co/datasets/DBbun/oligotox-phase2-dataset/resolve/main/code/qa_v2.py
10.6 kB
| """ | |
| Quality-assurance pass over the built v2.0 dataset. | |
| Checks the things a reviewer or a first user would hit: | |
| 1. referential integrity between tables | |
| 2. every column the notebook references actually exists | |
| 3. files promised by the manifest are present and sized as recorded | |
| 4. the data dictionary covers the columns that exist | |
| 5. layer labelling is complete and consistent | |
| 6. no measured row carries a generated provenance label, or vice versa | |
| """ | |
| import json | |
| import pathlib | |
| import re | |
| from pathlib import Path | |
| import pandas as pd | |
| WORK = Path(r"C:\DBBun\Misc\NIH-OligoTox Phase II\_v2_work") | |
| DATA = WORK / "dataset_root_v2" | |
| PASS, FAIL, WARN = "PASS", "FAIL", "WARN" | |
| results = [] | |
| def check(name, status, detail=""): | |
| results.append((status, name, detail)) | |
| def load(rel): | |
| return pd.read_csv(DATA / rel, low_memory=False) | |
| def main() -> None: | |
| # ---- 1. referential integrity ------------------------------------------ | |
| o = load("oligos.csv") | |
| ids = set(o.oligo_id) | |
| for rel, col in [("chemical_modifications.csv", "oligo_id"), | |
| ("biophysical_properties.csv", "oligo_id"), | |
| ("dose_exposure.csv", "oligo_id"), | |
| ("assays.csv", "oligo_id"), | |
| ("toxicity_readouts.csv", "oligo_id"), | |
| ("oligo_modification_positions.csv", "oligo_id")]: | |
| p = DATA / rel | |
| if not p.exists(): | |
| check(f"integrity {rel}", FAIL, "file missing") | |
| continue | |
| d = load(rel) | |
| orphans = set(d[col].dropna()) - ids | |
| check(f"integrity {rel}", PASS if not orphans else FAIL, | |
| "" if not orphans else f"{len(orphans)} ids absent from oligos.csv") | |
| a = load("assays.csv") | |
| t = load("toxicity_readouts.csv") | |
| orphan_assays = set(t.assay_id.dropna()) - set(a.assay_id) | |
| check("integrity toxicity_readouts.assay_id", PASS if not orphan_assays else FAIL, | |
| "" if not orphan_assays else f"{len(orphan_assays)} unknown assay ids") | |
| # ---- 2. notebook column references ------------------------------------- | |
| nb_path = DATA / "OligoTox_Phase2_Optional_Analysis_Notebook.ipynb" | |
| if not nb_path.exists(): | |
| check("notebook present", FAIL, "notebook missing from dataset") | |
| else: | |
| nb = json.loads(nb_path.read_text(encoding="utf-8")) | |
| src = "\n".join("".join(c["source"]) for c in nb["cells"] | |
| if c["cell_type"] == "code") | |
| # columns the notebook names in quotes | |
| quoted = set(re.findall(r'"([a-z0-9_]{4,})"', src)) | |
| available = set() | |
| for p in DATA.rglob("*.csv"): | |
| try: | |
| available |= set(pd.read_csv(p, nrows=0).columns) | |
| except Exception: | |
| pass | |
| # only consider tokens that look like column names used for selection | |
| # Static analysis cannot tell a dataset column from a column of a frame | |
| # the notebook builds in memory, so it produces false alarms either way. | |
| # Executing the notebook against the dataset is the definitive check and | |
| # is what a first user actually does. | |
| import warnings | |
| warnings.filterwarnings("ignore") | |
| try: | |
| import nbformat | |
| from nbclient import NotebookClient | |
| from nbclient.exceptions import CellExecutionError | |
| doc = nbformat.read(str(nb_path), as_version=4) | |
| try: | |
| NotebookClient(doc, timeout=900, kernel_name="python3", | |
| resources={"metadata": {"path": str(DATA)}}).execute() | |
| check("notebook executes against this dataset", PASS) | |
| except CellExecutionError: | |
| where = next((f"cell {i}: {o.get('ename')}: " | |
| f"{str(o.get('evalue'))[:120]}" | |
| for i, c in enumerate(doc.cells) | |
| for o in c.get("outputs", []) | |
| if o.get("output_type") == "error"), "unknown cell") | |
| check("notebook executes against this dataset", FAIL, where) | |
| except ImportError: | |
| check("notebook executes against this dataset", WARN, | |
| "nbclient not available - not executed") | |
| # read_csv targets only; files the notebook writes are not inputs | |
| read = set(re.findall( | |
| r'(?:load_csv|read_csv)\([^)]*?"([a-z0-9_/]+\.csv)"', src)) | |
| missing_files = {f for f in read | |
| if not any(q.name == pathlib.Path(f).name | |
| for q in DATA.rglob("*.csv"))} | |
| check("notebook input files present", PASS if not missing_files else FAIL, | |
| "" if not missing_files else f"absent: {sorted(missing_files)}") | |
| # ---- 3. manifest --------------------------------------------------------- | |
| man = json.loads((DATA / "dataset_manifest.json").read_text(encoding="utf-8")) | |
| missing, wrong = [], [] | |
| for f in man.get("files", []): | |
| p = DATA / f["path"] | |
| if not p.exists(): | |
| missing.append(f["path"]) | |
| elif "size_bytes" in f and p.stat().st_size != f["size_bytes"]: | |
| wrong.append(f["path"]) | |
| check("manifest files present", PASS if not missing else FAIL, | |
| "" if not missing else f"{len(missing)} missing") | |
| check("manifest sizes current", PASS if not wrong else WARN, | |
| "" if not wrong else f"{len(wrong)} size mismatch (regenerate manifest last)") | |
| # ---- 4. data dictionary coverage ---------------------------------------- | |
| dd = pd.read_csv(DATA / "data_dictionary.csv", dtype=str) | |
| documented = set(zip(dd.table_name.fillna(""), dd.column_name.fillna(""))) | |
| core = ["oligos.csv", "chemical_modifications.csv", "biophysical_properties.csv", | |
| "dose_exposure.csv", "assays.csv", "toxicity_readouts.csv", | |
| "controls.csv", "oligo_modification_positions.csv"] | |
| undocumented = [] | |
| for rel in core: | |
| p = DATA / rel | |
| if not p.exists(): | |
| continue | |
| for c in pd.read_csv(p, nrows=0).columns: | |
| if (rel, c) not in documented: | |
| undocumented.append(f"{rel}:{c}") | |
| check("data dictionary covers core tables", | |
| PASS if not undocumented else WARN, | |
| "" if not undocumented else | |
| f"{len(undocumented)} undocumented, e.g. {undocumented[:4]}") | |
| # ---- 5. layer labelling -------------------------------------------------- | |
| meas = list((DATA / "measured").glob("*.csv")) | |
| bad = [p.name for p in meas | |
| if "data_layer" not in pd.read_csv(p, nrows=0).columns | |
| or not (pd.read_csv(p, usecols=["data_layer"], low_memory=False) | |
| .data_layer == "measured_real").all()] | |
| check("measured tables labelled", PASS if not bad else FAIL, | |
| "" if not bad else f"unlabelled: {bad}") | |
| # ---- 6. provenance consistency ------------------------------------------ | |
| gen_origins = set(o.value_origin.dropna().unique()) | |
| leaked = {v for v in gen_origins if "measured" in str(v).lower()} | |
| check("no measured provenance in generated layer", | |
| PASS if not leaked else FAIL, | |
| "" if not leaked else f"found {leaked}") | |
| chem = load("measured/oligo_chemistry_verified.csv") | |
| unverified = chem[chem.verification_method.isna()] | |
| check("every verified structure states its verification method", | |
| PASS if unverified.empty else FAIL, | |
| "" if unverified.empty else f"{len(unverified)} missing") | |
| # A molecule can appear in both measured tables with two different | |
| # formulas, because WHO INN lists print the free acid and FDA labelling | |
| # usually prints the sodium salt. That is legitimate, but only if the two | |
| # differ by sodium replacing acidic hydrogen and by nothing else. Checking | |
| # it turns a label into an enforced relationship. | |
| import sys as _sys | |
| _sys.path.insert(0, str(WORK)) | |
| from formula_checksum import parse_formula | |
| ver = load("measured/oligo_chemistry_verified.csv") | |
| car = load("measured/oligo_characterization.csv") | |
| pair = ver[["oligo_name_inn", "molecular_formula_stated"]].merge( | |
| car[["drug", "molecular_formula"]], | |
| left_on="oligo_name_inn", right_on="drug") | |
| bad = [] | |
| for _, r in pair.iterrows(): | |
| a, b = r.molecular_formula_stated, r.molecular_formula | |
| if not isinstance(a, str) or not isinstance(b, str) or a == b: | |
| continue | |
| fa, fb = parse_formula(a), parse_formula(b) | |
| na = fb.get("Na", 0) - fa.get("Na", 0) | |
| dh = fa.get("H", 0) - fb.get("H", 0) | |
| others = {k for k in set(fa) | set(fb) | |
| if k not in ("H", "Na") and fa.get(k, 0) != fb.get(k, 0)} | |
| if na <= 0 or na != dh or others: | |
| bad.append(r.oligo_name_inn) | |
| check("cross-table formulas differ only as salt form", | |
| PASS if not bad else FAIL, | |
| f"{len(pair)} shared, {len(bad)} unexplained" | |
| + (f": {', '.join(bad)}" if bad else "")) | |
| # A linear strand of n residues has n-1 internucleotide linkages, so a | |
| # phosphorothioate count above that is describing something other than a | |
| # linkage and must not be reported as one. | |
| def _links(r): | |
| if isinstance(r.strand_lengths, str) and "/" in r.strand_lengths: | |
| return sum(int(x) - 1 for x in r.strand_lengths.split("/")) | |
| return (r.sequence_length - 1) if pd.notna(r.sequence_length) else None | |
| ver2 = load("measured/oligo_chemistry_verified.csv") | |
| over = [r.oligo_name_inn for _, r in ver2.iterrows() | |
| if pd.notna(r.n_phosphorothioate) and _links(r) is not None | |
| and r.n_phosphorothioate > _links(r)] | |
| check("phosphorothioate count never exceeds available linkages", | |
| PASS if not over else FAIL, | |
| "" if not over else f"{len(over)}: {', '.join(over)}") | |
| # ---- report -------------------------------------------------------------- | |
| width = max(len(n) for _, n, _ in results) | |
| for status, name, detail in results: | |
| print(f" [{status}] {name:<{width}} {detail}") | |
| n_fail = sum(1 for s, _, _ in results if s == FAIL) | |
| n_warn = sum(1 for s, _, _ in results if s == WARN) | |
| print(f"\n{len(results)} checks: {len(results)-n_fail-n_warn} pass, " | |
| f"{n_warn} warn, {n_fail} fail") | |
| if __name__ == "__main__": | |
| main() | |