File size: 10,581 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""

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()