diff --git a/examples/keep_closure_mode_audit.ipynb b/examples/keep_closure_mode_audit.ipynb new file mode 100644 index 0000000000..716f6df8f5 --- /dev/null +++ b/examples/keep_closure_mode_audit.ipynb @@ -0,0 +1,306 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "66ed17f4", + "metadata": {}, + "source": [ + "# KEEP graph closure analysis: connectivity, mapping coverage, and learning limits\n", + "\n", + "Filtered direct ontology relationships and separation-one ancestry pairs can yield different traversal graphs. We investigated whether PyHealth's closure option changes useful connectivity and mapping coverage, and whether those observations say anything about the representations supplied to learning.\n", + "\n", + "**Core finding:** separation-one ancestry augmentation can improve traversal-graph connectivity and mapping coverage on the measured Athena bundle. **Its effect on embedding quality or downstream learning is inconclusive with the current output.** More reachable concepts and paths do not by themselves establish better representations.\n", + "\n", + "PyHealth's existing `path_source=\"closure\"` option provides the augmentation capability. This contribution adds a reproducible analysis of that behavior; it does not introduce the option or change production defaults. The notebook begins with executable synthetic examples. Recorded full-release findings are presented separately; rerunning real input requires an explicit Athena path.\n" + ] + }, + { + "cell_type": "markdown", + "id": "c111f3e0", + "metadata": {}, + "source": [ + "## What closure means here\n", + "\n", + "Let `U` be the uncut subtree of valid standard SNOMED Condition concepts under Disease (OMOP concept `4274025`). `D` contains valid direct `Is a` edges with both endpoints in `U`, oriented parent → child. `P` contains unique ancestry pairs with minimum separation **exactly one**, with both endpoints in `U`.\n", + "\n", + "- Direct mode traverses `D`; closure mode traverses `D ∪ P`. Direct provenance wins on overlap.\n", + "- Athena minimum root separations remain authoritative in both modes. The target cutoff does not truncate deep sources or intermediate nodes.\n", + "- The primary comparison fixes cutoff five, excludes the root, disables orphan rescue, and runs both `first_retained` and `all_retained`. Neither target policy is author-verified here.\n", + "- This overlay is distinct from arbitrary transitive closure or longer orphan-rescue shortcuts. OHDSI describes ancestry as a derived table; it should not be assumed identical to a consumer's filtered direct subgraph. See the [OMOP ancestry table definition](https://ohdsi.github.io/CommonDataModel/cdm54.html#concept_ancestor).\n", + "\n", + "Three graph layers matter: the factory's **base KnowledgeGraph remains direct** in both modes; the processor's **traversal index** gains the overlay; generated **sample graphs** contain the union of successful mapping paths and may therefore change. The Athena export itself is not modified." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f5e72650", + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "import sys\n", + "import tempfile\n", + "\n", + "repo = Path.cwd() if (Path.cwd() / 'pyhealth').is_dir() else Path.cwd().parent\n", + "assert (repo / 'pyhealth').is_dir(), 'Start Jupyter in the repository or examples directory'\n", + "sys.path.insert(0, str(repo))\n", + "from examples.keep_closure_mode_audit import write_synthetic_bundle, run_audit\n", + "from pyhealth.medcode import OMOPVocabulary\n", + "from pyhealth.tasks import build_keep_omop_ancestor_rollup\n", + "\n", + "temporary = tempfile.TemporaryDirectory()\n", + "folder = Path(temporary.name) / 'synthetic'\n", + "write_synthetic_bundle(folder)\n", + "summary = run_audit(folder, Path(temporary.name) / 'audit', synthetic=True)\n", + "summary['graph_counts']" + ] + }, + { + "cell_type": "markdown", + "id": "8de3da3e", + "metadata": {}, + "source": [ + "## Synthetic expectations\n", + "\n", + "Twelve Condition concepts are in U, with six eligible targets and five deep sources. Two added edges have different effects: `104 → 201` recovers an orphan; `102 → 204` adds a first-retained target already reachable under all-retained. A filtered Observation between `104` and `202` needs a longer shortcut, so separation-one overlay cannot repair that mapping.\n", + "\n", + "These tables intentionally stress authoritative depths, including disagreement with adjacency distances. Their hand-authored ancestry rows are a semantic fixture, not a simulated complete Athena release." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "aac1fc90", + "metadata": {}, + "outputs": [], + "source": [ + "assert summary['graph_counts'] == dict(U=12, D=9, P=11, intersection=9, P_minus_D=2, D_minus_P=0, union=11)\n", + "for policy, result in summary['policies'].items():\n", + " population = result['populations']['all']\n", + " assert population['denominator'] == 12\n", + " assert population['direct_no_target'] == 3\n", + " assert population['closure_no_target'] == 2\n", + " assert population['categories']['recovered_no_target'] == 1\n", + " print(policy, population['categories'])" + ] + }, + { + "cell_type": "markdown", + "id": "dc6603dd", + "metadata": {}, + "source": [ + "## Branch stopping, graph gaps, and failures\n", + "\n", + "Both policies preserve old targets when acyclic edges are only added at fixed eligibility. An existing path to a first-retained target still exists with no newly eligible internal node.\n", + "\n", + "A disconnected eligible source (`203`) maps to itself; a deep source (`202`) stays `no_target`. The excluded root is also `no_target` and is counted separately from deep failures. Diagnostic enumeration uses `on_unmapped=\"empty\"`; the production default is `\"error\"`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e13e359c", + "metadata": {}, + "outputs": [], + "source": [ + "vocabulary = OMOPVocabulary(folder)\n", + "for mode in ('direct', 'closure'):\n", + " processor = build_keep_omop_ancestor_rollup(vocabulary, target_policy='first_retained', include_root=False, path_source=mode, on_unmapped='empty')\n", + " rows = processor.rollup_codes(['201', '202', '203', '204'])\n", + " print(mode, [(r.source, r.targets, r.reason) for r in rows])\n", + " assert rows[1].reason == 'no_target'\n", + " assert rows[2].targets == ('203',)\n", + " eligible = build_keep_omop_ancestor_rollup(vocabulary, target_policy='first_retained', include_root=False, path_source=mode, max_depth=7, on_unmapped='empty')\n", + " assert eligible.rollup_codes(['202'])[0].targets == ('202',)\n", + "assert summary['policies']['first_retained']['populations']['all']['categories']['changed_nonempty_targets'] == 2\n", + "assert summary['policies']['all_retained']['populations']['all']['categories']['changed_nonempty_targets'] == 0" + ] + }, + { + "cell_type": "markdown", + "id": "9806a182", + "metadata": {}, + "source": [ + "## Recorded Athena findings — distinct from the synthetic execution\n", + "\n", + "Measured on 2026-11-25 using the user-supplied export. These results cover every concept in that bundle's uncut Disease subtree, not every vocabulary available through Athena. They are recorded observations, not outputs of the synthetic cells above.\n", + "\n", + "The bundle identifies OMOP Standardized Vocabularies as `v5.0 29-AUG-26`. Its SNOMED version is International `2026-02-01`, US `2026-03-01`, and UK `2026-04-08`. The `Vocabulary` metadata row has no version; modification/download dates are not inferred release identities.\n", + "\n", + "| Graph quantity | Count |\n", + "| --- | ---: |\n", + "| Concepts in U | 92,676 |\n", + "| Eligible targets, both modes | 69,445 |\n", + "| Deep sources, depth > 5 | 23,230 |\n", + "| Excluded root | 1 |\n", + "| Direct edges D | 206,783 |\n", + "| Separation-one pairs P | 207,117 |\n", + "| D ∩ P | 206,783 |\n", + "| P − D: closure-only edges | 334 |\n", + "| D − P | 0 |\n", + "| D ∪ P | 207,117 |\n", + "\n", + "Factory provenance agrees with the reference counts: `closure_only_edge_count = 334 = |P − D|`. The additional edges are 0.162% of the direct edge count; that fraction alone does not establish their importance.\n", + "\n", + "| Structural metric | Direct | Closure |\n", + "| --- | ---: | ---: |\n", + "| Non-root nodes without an incoming parent edge | 36 | 11 |\n", + "| Of those: eligible / deep | 23 / 13 | 8 / 3 |\n", + "| Nodes unreachable from Disease along selected edges | 190 | 133 |\n", + "| Of those: eligible / deep | 77 / 113 | 46 / 87 |\n", + "\n", + "These counts establish improved structural connectivity under the tested settings, not guaranteed connectivity. An eligible disconnected source still maps to itself; a deep source can reach an eligible target in a branch disconnected from Disease. Structural gaps and mapping failures therefore need separate measurements." + ] + }, + { + "cell_type": "markdown", + "id": "d82e0bc2", + "metadata": {}, + "source": [ + "## Mapping coverage and failure rates\n", + "\n", + "Every source in U was evaluated once per mode and target policy, in deterministic batches with the same depths and eligible targets. Diagnostic `on_unmapped=\"empty\"` preserves typed failures for enumeration; production defaults to `\"error\"`.\n", + "\n", + "| Outcome | first_retained | all_retained |\n", + "| --- | ---: | ---: |\n", + "| All-U denominator | 92,676 | 92,676 |\n", + "| Identical target sets, all U | 92,624 | 92,611 |\n", + "| Changed nonempty target sets | 26 | 39 |\n", + "| Direct no_target recovered by closure | 26 | 26 |\n", + "| Any changed target set | 52 | 65 |\n", + "| Lost mappings | 0 | 0 |\n", + "| Identity mappings, either mode | 69,445 | 69,445 |\n", + "| Direct / closure rolled-up mappings | 23,197 / 23,223 | 23,197 / 23,223 |\n", + "| Direct / closure unmapped, all U | 34 / 8 | 34 / 8 |\n", + "| Deep denominator | 23,230 | 23,230 |\n", + "| Direct / closure no_target, deep | 33 / 7 | 33 / 7 |\n", + "\n", + "Both policies recover **26 of 33 deep failures (78.8%)**. The deep mapping failure rate falls from **0.142% to 0.030%**, an absolute decrease of **0.112 percentage points**. Seven deep failures remain. All-U failures additionally include the expected excluded-root `no_target`; external-code failure reasons are zero within this deliberately restricted U population.\n", + "\n", + "Use **mapping failure rate**, not semantic error rate: finding an ancestor establishes reachability, not independent clinical correctness. Concept-level rates are not diagnosis-event or patient-level rates. All observed ordered-target changes also change sets. Fixed-eligibility target sets are preserved when edges are added under both policies.\n", + "\n", + "A separate diagnostic scan found eligible ancestry for all seven residual deep failures: nearest eligible separations were three for three sources, four for three, and five for one. There is still no selected traversal path to those targets. This demonstrates the difference between separation-one augmentation and longer ancestry lookup; it does not establish that the existing orphan-rescue algorithm would repair all seven." + ] + }, + { + "cell_type": "markdown", + "id": "146ed1d3", + "metadata": {}, + "source": [ + "## What this means for generated graphs and embeddings\n", + "\n", + "Closure can change the representation supplied to learning in three ways:\n", + "\n", + "1. **Coverage:** previously unmapped observations can contribute a graph.\n", + "2. **Conceptual scope:** additional targets or intermediate concepts can become represented.\n", + "3. **Topology:** additional successful paths can change graph input even when target sets stay identical.\n", + "\n", + "For example, direct traversal might produce `T → A → X`, while augmentation adds `T → X`. Both modes still map X to retained target T, yet their generated graphs differ. Depending on edge direction and architecture, the shortcut changes neighborhoods, degrees and the number of message-passing steps between concepts. For a GCN, adjacency and degree normalization directly enter the computation; see the [original GCN paper](https://arxiv.org/abs/1609.02907).\n", + "\n", + "Greater connectivity can restore useful context, but additional shared context could also make representations less discriminative. Those are hypotheses. **Current output establishes structural and coverage changes, not improved embeddings.** A separate embedding trainer consuming only the unchanged base KnowledgeGraph would not automatically receive the overlay.\n", + "\n", + "The all-U mapping census measures recovery and target changes, with selected projected-path witnesses. It does not yet measure the full population's generated-graph changes, diagnosis-weighted exposure, trained embeddings or predictive performance. A small vocabulary-edge delta may affect common sample paths, or rarely occur in the intended data; we have not measured which. Retraining shared parameters could also change predictions for samples whose own graphs remain unchanged.\n", + "\n", + "The supported conclusion is to retain an explicit augmentation capability based on demonstrated connectivity and coverage on this bundle, while leaving defaults, orphan rescue and embedding-training graph choices open. This is not evidence of author-artifact parity, clinical benefit or a universally better graph representation." + ] + }, + { + "cell_type": "markdown", + "id": "ccc2a10c", + "metadata": {}, + "source": [ + "## Methodological extensions, not completed results\n", + "\n", + "The contribution is a reproducible validation workflow for a consequential graph-preprocessing choice. The next evidence should explain what information and structure closure introduces into learning input.\n", + "\n", + "| Priority | Next measurement | Purpose |\n", + "| --- | --- | --- |\n", + "| Generated graph scope | Stream paired `process([source])` outputs across U; compare decoded node/edge sets, targets, seeds, masks and size distributions; cross-tabulate graph changes against target changes | Detect topology changes hidden by identical mappings |\n", + "| Independent correctness | Test-only path enumeration and independent table extraction on coherent synthetic fixtures; validate multi-source union graphs, feature alignment, duplicate handling and optional batch/unbatch behavior | Reduce dependence on shared reader/traversal logic |\n", + "| Sensitivity | Matched cutoff sweep 3–7 for both policies with recomputed eligible/deep denominators; controlled missing-link and filtered-intermediate fixtures | Identify dependence on eligibility and the limits of recovery |\n", + "| Exposure and learning | Authorized sample-level exposure counts, then a separately scoped matched learning experiment | Determine practical frequency and whether representation changes improve a task |\n", + "\n", + "Compare decoded concept IDs and edges, not local indices or fingerprints as substitutes for graph contents. An edgeless identity graph is valid; an empty graph for an unmapped source is a coverage outcome rather than a malformed graph. Separate graph-contract violations, construction exceptions and mapping failures. Keep synthetic composed samples separate from claims about patient frequencies.\n", + "\n", + "The current factory and reference share the public OMOP reader, so their agreement cannot exclude a shared extraction bug. An independent synthetic reference and table extraction strengthen the method. A second authorized release would test replication; the current census does not establish cross-release robustness. Report exact counts rather than treating correlated ontology concepts as independent random samples for confidence intervals.\n", + "\n", + "A future learning comparison should retain identical cohorts and splits, matched initial embeddings/model settings, paired training seeds and an explicit empty/unmapped-sample policy. First isolate generated-graph effects; retraining embeddings on alternate graphs is another intervention. A frozen-model input swap measures sensitivity, not benefit from retraining. Selective sample dropping must not masquerade as improved prediction. None of these learning experiments has been performed." + ] + }, + { + "cell_type": "markdown", + "id": "fb67937b", + "metadata": {}, + "source": [ + "## Reproducibility and validation record\n", + "\n", + "The measured production baseline is `33c2cb635572a493dae428c4666a5ec503c5ee77`, before the separate loading optimization. The subsequently published helper/notebook/test commit is `b2a5150`; this notebook's narrative is updated after that checkpoint. The measured local JSON records exact source hashes, input metadata, configuration, dirty state and processor fingerprints. Do not attribute these measurements to the later loader optimization.\n", + "\n", + "| Input table | Bytes | SHA-256 |\n", + "| --- | ---: | --- |\n", + "| CONCEPT | 203,864,313 | `5be10a0d8900083c9b56cf2e53f17a7e15195879184615512c03690a98da65a4` |\n", + "| CONCEPT_RELATIONSHIP | 433,313,452 | `aa2f23b52c5d5f97519b6176469087dad965b7838e73eb62e18160e3696736b8` |\n", + "| CONCEPT_ANCESTOR | 174,318,785 | `5e97d2d88d0ffac721e914e683d2af8c92c57721b0415f03377bc9c9f67a29e5` |\n", + "| VOCABULARY | 3,710 | `1f5e1fa97c8be54d9f5afeb7d673d5040952c0e9318db125957aa71209e7eb6a` |\n", + "\n", + "Python 3.12.12, PyHealth 2.1.0 from the checkout, Polars 1.35.2, PyTorch 2.15.0, NetworkX 3.7 and torch-geometric 2.8.1 were used on macOS arm64 with 18 reported logical CPUs.\n", + "\n", + "The helper writes aggregate `summary.json`, per-policy `*_differences.tsv` and `*_failures.tsv`, full ordered mapping digests and up to three path witnesses per category. Difference tables contain changed sources; failure tables retain every failed source, including the excluded root. Absent aggregate reason keys mean zero. Keep licensed input and release-specific rows local.\n", + "\n", + "The original focused and existing OMOP/roll-up checks passed **140 tests and 8 subtests**; the synthetic notebook ran in a fresh kernel with saved outputs cleared. Two full-release runs with batch sizes 512 and 137 reproduced non-resource summaries, processor fingerprints, ordered mapping digests and byte-identical difference/failure tables. Timing, memory, dirty-state text and batch-size fields were excluded from that comparison.\n", + "\n", + "The public reference reader and this baseline factory materialize full uncut ancestry. Main-run reference extraction took 0.447 s; direct/closure builds took 1.039/1.118 s for first-retained and 1.030/1.114 s for all-retained. Full mapping took 0.103/0.208 s and 0.296/0.401 s respectively. Lifetime process peak RSS was 2,217,984,000 bytes (about 2.07 GiB), measured with `getrusage(RUSAGE_SELF)` across all phases. Input hashing, assertions, serialization and witness projection are outside mapping timings. Concurrent validation work makes these resource context, not controlled speed comparisons; full projected-graph costs have not been measured.\n", + "\n", + "Run the default synthetic example from the repository root with `python -m examples.keep_closure_mode_audit`. For a real release, pass `--athena-dir /path/to/authorized/export --output-dir .artifacts/graph-closure-analysis`. No dataset discovery or download occurs. The opt-in cell below uses the same helper; the recorded release findings above do not imply that cell ran in this notebook execution." + ] + }, + { + "cell_type": "markdown", + "id": "b213d06a", + "metadata": {}, + "source": [ + "## Explicit opt-in release audit\n", + "\n", + "Set `ATHENA_DIR` to an authorized local export and choose `LOCAL_RESULTS` outside shared artifacts. No path discovery or automatic fallback occurs. The helper evaluates every concept once per mode and policy in batches. It records release metadata, table hashes, failures, differences and small path witnesses. Full ancestor tables are materialized by the public reference reader and this baseline factory; this is included in resource reporting.\n", + "\n", + "Release-specific rows remain local. Vocabulary behavior does not establish diagnosis prevalence, clinical benefit, embedding quality, or fidelity to unpublished author artifacts." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7f1152f5", + "metadata": {}, + "outputs": [], + "source": [ + "ATHENA_DIR = None # Explicit Path('/your/authorized/athena-export') to opt in.\n", + "LOCAL_RESULTS = repo / '.artifacts' / 'graph-closure-analysis-athena'\n", + "if ATHENA_DIR is not None:\n", + " real_summary = run_audit(Path(ATHENA_DIR), LOCAL_RESULTS, synthetic=False)\n", + " print(real_summary['graph_counts'])\n", + "else:\n", + " print('Athena execution skipped; synthetic results only in this execution.')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "db92320d", + "metadata": {}, + "outputs": [], + "source": [ + "temporary.cleanup()" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/examples/keep_closure_mode_audit.py b/examples/keep_closure_mode_audit.py new file mode 100644 index 0000000000..212cf05d37 --- /dev/null +++ b/examples/keep_closure_mode_audit.py @@ -0,0 +1,636 @@ +# Author: lee-leonardo (NetID: ll37) +# Description: Analyze the KEEP graph separation-one ancestry overlay. +"""Compare direct/closure traversal without changing production behavior. + +Run from the repository root: ``python -m examples.keep_closure_mode_audit``. +Only an explicit ``--athena-dir`` enables real input. Generated data stays local. +""" + +from __future__ import annotations + +import argparse +import csv +import gc +import hashlib +import json +import os +import platform +import resource +import subprocess +import tempfile +from collections import Counter, defaultdict +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from time import perf_counter + +import polars as pl + +from pyhealth.medcode import OMOPVocabulary +from pyhealth.tasks import build_keep_omop_ancestor_rollup + +ROOT = "4274025" +POLICIES = ("first_retained", "all_retained") +CATEGORIES = ( + "identical_targets", + "changed_nonempty_targets", + "recovered_no_target", + "lost_mapping", + "other_target_change", +) + + +def write_synthetic_bundle( + folder: Path, *, overlay: bool = True, duplicate_pairs: bool = False +) -> None: + """Write a tiny Athena-format fixture with explicit, invented concepts. + + Args: + folder: Destination for synthetic tables. + overlay: Include two separation-one links absent from direct rows. + duplicate_pairs: Duplicate and reverse ancestor rows to test set semantics. + """ + folder.mkdir(parents=True, exist_ok=True) + depths = { + ROOT: 0, + **{str(100 + i): i + 1 for i in range(5)}, + "200": 6, + "201": 6, + "202": 7, + "203": 3, + "204": 6, + "205": 7, + } + direct = [ + (ROOT, "100"), + ("100", "101"), + ("101", "102"), + ("102", "103"), + ("103", "104"), + ("104", "200"), + ("103", "204"), + ("104", "204"), + ("204", "205"), + ] + concepts = [ + ( + code, + f"Synthetic {code}", + "Condition", + "SNOMED", + "Clinical Finding", + "S", + f"S{code}", + "", + ) + for code in depths + ] + # Non-Condition intermediate; a standard Condition outside Disease; + # nonstandard and invalid canaries must not become graph entities. + concepts += [ + ( + "900", + "Filtered intermediate", + "Observation", + "SNOMED", + "Finding", + "S", + "S900", + "", + ), + ("901", "Outside Disease", "Condition", "SNOMED", "Finding", "S", "S901", ""), + ("902", "Nonstandard", "Condition", "SNOMED", "Finding", "", "S902", ""), + ("903", "Invalid", "Condition", "SNOMED", "Finding", "S", "S903", "D"), + ] + relationships = [(child, parent, "Is a", "") for parent, child in direct] + relationships += [ + ("900", "104", "Is a", ""), + ("202", "900", "Is a", ""), + ("203", "900", "Is a", ""), + ("201", "104", "Is a", "D"), + ] + pairs = direct + ([("104", "201"), ("102", "204")] if overlay else []) + # Root depths deliberately authoritative, independent of adjacency distances. + ancestors = [(ROOT, code, depth, depth) for code, depth in depths.items()] + ancestors += [(parent, child, 1, 1) for parent, child in pairs if parent != ROOT] + ancestors += [ + ("104", "202", 2, 2), + ("100", "203", 2, 2), + (ROOT, "900", 6, 6), + (ROOT, "902", 2, 2), + (ROOT, "903", 2, 2), + ] + if duplicate_pairs: + ancestors = list(reversed(ancestors + ancestors)) + tables = { + "CONCEPT": ( + [ + "concept_id", + "concept_name", + "domain_id", + "vocabulary_id", + "concept_class_id", + "standard_concept", + "concept_code", + "invalid_reason", + ], + concepts, + ), + "CONCEPT_RELATIONSHIP": ( + ["concept_id_1", "concept_id_2", "relationship_id", "invalid_reason"], + relationships, + ), + "CONCEPT_ANCESTOR": ( + [ + "ancestor_concept_id", + "descendant_concept_id", + "min_levels_of_separation", + "max_levels_of_separation", + ], + ancestors, + ), + "VOCABULARY": ( + ["vocabulary_id", "vocabulary_version"], + [("SNOMED", "SYNTHETIC")], + ), + } + for name, (header, rows) in tables.items(): + with (folder / f"{name}.csv").open("w", newline="") as handle: + writer = csv.writer(handle, delimiter="\t", lineterminator="\n") + writer.writerow(header) + writer.writerows(rows) + + +def reference_graph(vocabulary: OMOPVocabulary) -> tuple[dict, set, set]: + """Extract U, D, P independently of the factory via public reader tables. + + Returns: + String-ID depths and unique parent-to-child direct/separation-one sets. + This path materializes the full uncut ancestor table, not only P. + """ + hierarchy = vocabulary.condition_hierarchy( + max_depth=None, depth_measure="min", connect_orphans=False + ) + depths = { + str(code): int(depth) + for code, depth in hierarchy.nodes.select("concept_id", "depth").iter_rows() + } + direct = { + (str(parent), str(child)) + for parent, child in hierarchy.edges.select("parent_id", "child_id").iter_rows() + } + pairs = { + (str(parent), str(child)) + for child, parent in hierarchy.ancestors.filter(pl.col("distance") == 1) + .select("concept_id", "ancestor_id") + .iter_rows() + } + return depths, direct, pairs + + +def structural_gaps(depths: dict, edges: set, eligible: set, max_depth: int) -> dict: + """Count parentless and root-unreachable nodes, independently of mapping.""" + children = defaultdict(list) + incoming = set() + for parent, child in edges: + children[parent].append(child) + incoming.add(child) + reachable, pending = set(), [ROOT] + while pending: + node = pending.pop() + if node not in reachable: + reachable.add(node) + pending.extend(children[node]) + + def counts(nodes): + return { + "total": len(nodes), + "eligible": len(nodes & eligible), + "deep": sum(depths[code] > max_depth for code in nodes), + "excluded_root": int(ROOT in nodes), + } + + # Eligible excludes the root; deep is a separate fixed-depth population. + nonroot = set(depths) - {ROOT} + return { + "parentless_nonroot": counts(nonroot - incoming), + "root_unreachable": counts(set(depths) - reachable), + } + + +def _category(left, right): + if set(left.targets) == set(right.targets): + return "identical_targets" + if left.reason == "no_target" and right.targets: + return "recovered_no_target" + if left.targets and right.targets: + return "changed_nonempty_targets" + if left.targets and not right.targets: + return "lost_mapping" + return "other_target_change" + + +def _witness(processor, source: str) -> dict: + """Decode one small projected graph, including exact overlay edges.""" + try: + graph = processor.process([source]) + except ImportError: + return {"projection": "unavailable: torch-geometric is not installed"} + id_to_code = processor.id2entity + codes = [id_to_code[node] for node in graph.node_ids.tolist()] + edges = [ + (codes[parent], codes[child]) + for parent, child in zip(*graph.edge_index.tolist()) + ] + return { + "projected_edges": edges, + "closure_only_edges": [ + edge for edge, added in zip(edges, graph.closure_only.tolist()) if added + ], + } + + +def compare_policy( + vocabulary: OMOPVocabulary, + depths: dict, + direct: set, + pairs: set, + *, + policy: str, + max_depth: int, + destination: Path, + batch_size: int = 512, +) -> dict: + """Evaluate all U in bounded batches and write a deterministic difference TSV. + + Returns: + Graph checks, structural gaps, population/reason counts, local witnesses, + fingerprints, and separate factory/mapping timings for one target policy. + """ + config = { + "target_policy": policy, + "include_root": False, + "max_depth": max_depth, + "on_unmapped": "empty", + } + processors, timings = {}, {} + for mode in ("direct", "closure"): + start = perf_counter() + processors[mode] = build_keep_omop_ancestor_rollup( + vocabulary, path_source=mode, **config + ) + timings[f"{mode}_factory_seconds"] = perf_counter() - start + left, right = processors["direct"], processors["closure"] + eligible = { + code for code, depth in depths.items() if depth <= max_depth and code != ROOT + } + assert left.retained_codes == right.retained_codes == eligible + for mode, processor in processors.items(): + assert set(processor.knowledge_graph.entity2id) == set(depths) + graph = processor.knowledge_graph + id_to_code = processor.id2entity + decoded = set( + zip( + (id_to_code[i] for i in graph.edge_index[0].tolist()), + (id_to_code[i] for i in graph.edge_index[1].tolist()), + ) + ) + assert decoded == direct + assert int(processor.provenance["direct_edge_count"]) == len(direct) + assert int(processor.provenance["closure_only_edge_count"]) == ( + len(pairs - direct) if mode == "closure" else 0 + ) + assert int(right.provenance["closure_pair_count"]) == len(pairs) + populations = {} + for name in ("all", "deep"): + populations[name] = { + "denominator": 0, + "categories": dict.fromkeys(CATEGORIES, 0), + "direct_reasons": Counter(), + "closure_reasons": Counter(), + "ordered_targets_differ": 0, + "reason_changes": 0, + } + witnesses = defaultdict(list) + columns = [ + "concept_id", + "depth", + "direct_reason", + "closure_reason", + "direct_targets", + "closure_targets", + "added_targets", + "removed_targets", + "category", + ] + sources = sorted(depths) + mapping_digests = {mode: hashlib.sha256() for mode in processors} + timings.update(direct_mapping_seconds=0.0, closure_mapping_seconds=0.0) + with ( + (destination / f"{policy}_differences.tsv").open("w", newline="") as handle, + (destination / f"{policy}_failures.tsv").open("w", newline="") as failures, + ): + writer = csv.DictWriter( + handle, fieldnames=columns, delimiter="\t", lineterminator="\n" + ) + writer.writeheader() + failure_writer = csv.DictWriter( + failures, fieldnames=columns, delimiter="\t", lineterminator="\n" + ) + failure_writer.writeheader() + for offset in range(0, len(sources), batch_size): + batch = sources[offset : offset + batch_size] + results = {} + for mode, processor in processors.items(): + start = perf_counter() + results[mode] = processor.rollup_codes(batch) + timings[f"{mode}_mapping_seconds"] += perf_counter() - start + for source, a, b in zip(batch, results["direct"], results["closure"]): + for mode, result in (("direct", a), ("closure", b)): + mapping_digests[mode].update( + ( + json.dumps( + [ + source, + result.source_depth, + result.reason, + result.targets, + ] + ) + + "\n" + ).encode() + ) + assert a.source_depth == b.source_depth == depths[source] + assert set(a.targets) <= set(b.targets), ( + "Adding edges at fixed eligibility must preserve targets", + source, + ) + category = _category(a, b) + for name in ("all", "deep"): + if name == "deep" and depths[source] <= max_depth: + continue + stats = populations[name] + stats["denominator"] += 1 + stats["categories"][category] += 1 + stats["direct_reasons"][a.reason] += 1 + stats["closure_reasons"][b.reason] += 1 + stats["ordered_targets_differ"] += a.targets != b.targets + stats["reason_changes"] += a.reason != b.reason + row = dict( + zip( + columns, + [ + source, + depths[source], + a.reason, + b.reason, + a.targets, + b.targets, + sorted(set(b.targets) - set(a.targets)), + sorted(set(a.targets) - set(b.targets)), + category, + ], + ) + ) + if category != "identical_targets" or a.reason != b.reason: + writer.writerow( + { + key: json.dumps(value) + if isinstance(value, (tuple, list)) + else value + for key, value in row.items() + } + ) + if not a.targets or not b.targets: + failure_writer.writerow( + { + key: json.dumps(value) + if isinstance(value, (tuple, list)) + else value + for key, value in row.items() + } + ) + witness_kind = ( + category + if category != "identical_targets" + else ("remaining_no_target" if b.reason == "no_target" else None) + ) + if witness_kind and len(witnesses[witness_kind]) < 3: + witnesses[witness_kind].append( + { + **row, + "direct_path": _witness(left, source), + "closure_path": _witness(right, source), + } + ) + for stats in populations.values(): + total = stats["denominator"] + assert sum(stats["categories"].values()) == total + for mode in processors: + reasons = stats[f"{mode}_reasons"] + assert sum(reasons.values()) == total + mapped = reasons["retained"] + reasons["rolled_up"] + stats[f"{mode}_mapped"] = mapped + stats[f"{mode}_unmapped"] = total - mapped + stats[f"{mode}_no_target"] = reasons["no_target"] + result = { + "config": config, + "eligible_target_count": len(eligible), + "populations": populations, + "witnesses": dict(witnesses), + "provenance": {mode: dict(p.provenance) for mode, p in processors.items()}, + "fingerprints": {mode: p.fingerprint for mode, p in processors.items()}, + "structural_gaps": { + "direct": structural_gaps(depths, direct, eligible, max_depth), + "closure": structural_gaps(depths, direct | pairs, eligible, max_depth), + }, + "timings": timings, + "ordered_mapping_sha256": { + mode: digest.hexdigest() for mode, digest in mapping_digests.items() + }, + } + return result + + +def _input_identity(folder: Path) -> dict: + tables = {} + for table in ("CONCEPT", "CONCEPT_RELATIONSHIP", "CONCEPT_ANCESTOR", "VOCABULARY"): + path = folder / f"{table}.csv" + if not path.exists(): + tables[table] = {"status": "missing"} + continue + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + tables[table] = {"sha256": digest.hexdigest(), "bytes": path.stat().st_size} + path = folder / "VOCABULARY.csv" + if path.exists(): + with path.open(encoding="utf-8", errors="replace") as handle: + release = list( + csv.DictReader(handle, delimiter="\t", quoting=csv.QUOTE_NONE) + ) + else: + release = "missing: no release identity inferred" + return {"tables": tables, "vocabulary_rows": release} + + +def _environment() -> dict: + def git(*args): + result = subprocess.run( + ["git", *args], + capture_output=True, + text=True, + cwd=Path(__file__).resolve().parents[1], + check=False, + ) + return result.stdout.strip() if result.returncode == 0 else "unavailable" + + packages = {} + for name in ("torch", "polars", "networkx", "torch-geometric", "pyhealth"): + try: + packages[name] = version(name) + except PackageNotFoundError: + packages[name] = "not installed as distribution" + repo = Path(__file__).resolve().parents[1] + source_paths = [ + "examples/keep_closure_mode_audit.py", + "pyhealth/tasks/keep.py", + "pyhealth/processors/ancestor_rollup_processor.py", + "pyhealth/medcode/omop/vocabulary.py", + "pyhealth/medcode/omop/condition_hierarchy.py", + ] + return { + "revision": git("rev-parse", "HEAD"), + "dirty_state": git("status", "--short", "--untracked-files=normal"), + "python": platform.python_version(), + "packages": packages, + "platform": platform.platform(), + "machine": platform.machine(), + "logical_cpus": os.cpu_count(), + "source_root": str(Path(__file__).resolve().parents[1]), + "source_sha256": { + path: hashlib.sha256((repo / path).read_bytes()).hexdigest() + for path in source_paths + }, + } + + +def run_audit( + folder: Path, + destination: Path, + *, + synthetic: bool, + max_depth: int = 5, + batch_size: int = 512, +) -> dict: + """Run both paired policies; keep all release-specific artifacts local. + + Args: + folder: Explicit Athena-format input directory. + destination: Directory for summary JSON and local per-source differences. + synthetic: Label invented input separately from release observations. + max_depth: Target eligibility cutoff over authoritative root depths. + batch_size: Maximum number of source results held at a time. + + Returns: + JSON-compatible aggregate summary, also written to ``summary.json``. + """ + if batch_size < 1 or max_depth < 0: + raise ValueError("batch_size must be positive and max_depth nonnegative") + folder, destination = Path(folder), Path(destination) + destination.mkdir(parents=True, exist_ok=True) + identity = _input_identity(folder) + environment = _environment() + vocabulary = OMOPVocabulary(folder) + start = perf_counter() + depths, direct, pairs = reference_graph(vocabulary) + extraction_seconds = perf_counter() - start + gc.collect() + counts = { + "U": len(depths), + "D": len(direct), + "P": len(pairs), + "intersection": len(direct & pairs), + "P_minus_D": len(pairs - direct), + "D_minus_P": len(direct - pairs), + "union": len(direct | pairs), + } + assert counts["union"] == counts["D"] + counts["P_minus_D"] + policies = {} + for policy in POLICIES: + policies[policy] = compare_policy( + vocabulary, + depths, + direct, + pairs, + policy=policy, + max_depth=max_depth, + destination=destination, + batch_size=batch_size, + ) + gc.collect() + summary = { + "schema_version": 1, + "input_kind": "synthetic" if synthetic else "athena", + "input_identity": identity, + "environment": environment, + "config": { + "root": ROOT, + "depth_measure": "min", + "max_depth": max_depth, + "include_root": False, + "connect_orphans": False, + "on_unmapped": "empty", + "batch_size": batch_size, + "population": "every concept in uncut standard SNOMED Condition U", + }, + "graph_counts": counts, + "policies": policies, + "resources": { + "reference_extraction_seconds": extraction_seconds, + "reference_method": "public uncut reader; full ancestors materialized", + "peak_rss": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + "peak_rss_unit": "bytes" if platform.system() == "Darwin" else "KiB", + "peak_rss_method": "getrusage RUSAGE_SELF lifetime high-water mark; all phases", + }, + } + (destination / "summary.json").write_text( + json.dumps(summary, indent=2, sort_keys=True) + "\n" + ) + return summary + + +def main() -> None: + """Run the synthetic default or a release supplied explicitly by the user.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--athena-dir", type=Path) + parser.add_argument( + "--output-dir", type=Path, default=Path(".artifacts/keep-closure-audit") + ) + parser.add_argument("--max-depth", type=int, default=5) + parser.add_argument("--batch-size", type=int, default=512) + args = parser.parse_args() + if args.athena_dir is None: + with tempfile.TemporaryDirectory() as temp: + write_synthetic_bundle(Path(temp)) + summary = run_audit( + Path(temp), + args.output_dir, + synthetic=True, + max_depth=args.max_depth, + batch_size=args.batch_size, + ) + else: + summary = run_audit( + args.athena_dir, + args.output_dir, + synthetic=False, + max_depth=args.max_depth, + batch_size=args.batch_size, + ) + print(json.dumps(summary["graph_counts"], indent=2)) + print(f"Local summary: {args.output_dir / 'summary.json'}") + + +if __name__ == "__main__": + main() diff --git a/tests/core/test_keep_closure_mode_audit.py b/tests/core/test_keep_closure_mode_audit.py new file mode 100644 index 0000000000..6222e7f3c7 --- /dev/null +++ b/tests/core/test_keep_closure_mode_audit.py @@ -0,0 +1,263 @@ +# Author: lee-leonardo (NetID: ll37) +# Description: Independent synthetic expectations for graph closure analysis. +"""Graph closure analysis: mapping, provenance, and target-set monotonicity.""" + +import json +import tempfile +import unittest +from pathlib import Path + +from examples.keep_closure_mode_audit import ( + ROOT, + reference_graph, + run_audit, + structural_gaps, + write_synthetic_bundle, +) +from pyhealth.graph import KnowledgeGraph +from pyhealth.medcode import OMOPVocabulary +from pyhealth.processors import AncestorRollupProcessor, UnmappedCodeError +from pyhealth.tasks import build_keep_omop_ancestor_rollup + + +class TestClosureAudit(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.folder = Path(self.temp.name) / "input" + self.destination = Path(self.temp.name) / "results" + write_synthetic_bundle(self.folder) + self.vocabulary = OMOPVocabulary(self.folder) + + def build(self, mode="direct", policy="first_retained", **options): + return build_keep_omop_ancestor_rollup( + self.vocabulary, + path_source=mode, + target_policy=policy, + include_root=False, + **{"max_depth": 5, "on_unmapped": "empty", **options}, + ) + + def test_exact_graph_sets_and_authoritative_depths(self): + depths, direct, pairs = reference_graph(self.vocabulary) + expected = { + (ROOT, "100"), + ("100", "101"), + ("101", "102"), + ("102", "103"), + ("103", "104"), + ("104", "200"), + ("103", "204"), + ("104", "204"), + ("204", "205"), + } + self.assertEqual(direct, expected) + self.assertEqual(pairs, expected | {("104", "201"), ("102", "204")}) + self.assertEqual(len(depths), 12) + self.assertEqual(depths["204"], 6) # Direct shortest path is five. + for mode in ("direct", "closure"): + processor = self.build(mode) + self.assertNotIn("204", processor.retained_codes) + self.assertEqual(processor.rollup_codes(["204"])[0].source_depth, 6) + self.assertEqual( + processor.retained_codes, + frozenset(["100", "101", "102", "103", "104", "203"]), + ) + + def test_recovery_and_branch_local_added_target(self): + direct, closure = self.build(), self.build("closure") + self.assertEqual(direct.rollup_codes(["201"])[0].reason, "no_target") + self.assertEqual(closure.rollup_codes(["201"])[0].targets, ("104",)) + self.assertEqual(direct.rollup_codes(["204"])[0].targets, ("103", "104")) + self.assertEqual( + closure.rollup_codes(["204"])[0].targets, ("102", "103", "104") + ) + all_direct = self.build(policy="all_retained") + all_closure = self.build("closure", "all_retained") + expected = ("100", "101", "102", "103", "104") + self.assertEqual(all_direct.rollup_codes(["204"])[0].targets, expected) + self.assertEqual(all_closure.rollup_codes(["204"])[0].targets, expected) + + def test_filtered_intermediate_and_default_error(self): + for mode in ("direct", "closure"): + processor = self.build(mode) + self.assertEqual(processor.rollup_codes(["202"])[0].reason, "no_target") + self.assertEqual(processor.rollup_codes(["203"])[0].targets, ("203",)) + eligible = self.build(mode, max_depth=7) + self.assertEqual(eligible.rollup_codes(["202"])[0].targets, ("202",)) + # Omit on_unmapped: exercise the actual production default. + processor = build_keep_omop_ancestor_rollup( + self.vocabulary, target_policy="first_retained", include_root=False + ) + with self.assertRaises(UnmappedCodeError): + processor.rollup_codes(["202"]) + + def test_external_classification_is_aligned(self): + for mode in ("direct", "closure"): + results = self.build(mode).rollup_codes(["900", "901", "902", "903"]) + self.assertEqual( + [r.reason for r in results], + ["outside_domain", "unreachable", "unknown_code", "unknown_code"], + ) + + def test_provenance_and_projection_decode(self): + processor = self.build("closure") + self.assertEqual(processor.provenance["closure_only_edge_count"], "2") + try: + graph = processor.process(["204"]) + except ImportError: + self.skipTest("torch-geometric not installed") + codes = [processor.id2entity[node] for node in graph.node_ids.tolist()] + edges = list(zip(*graph.edge_index.tolist())) + decoded = [(codes[a], codes[b]) for a, b in edges] + self.assertEqual(set(decoded), {("102", "204"), ("103", "204"), ("104", "204")}) + self.assertEqual( + {edge for edge, flag in zip(decoded, graph.closure_only) if flag}, + {("102", "204")}, + ) + self.assertEqual( + {codes[i] for i, flag in enumerate(graph.target_mask) if flag}, + {"102", "103", "104"}, + ) + + def test_aggregates_reconcile_to_hand_counts(self): + summary = run_audit(self.folder, self.destination, synthetic=True) + self.assertEqual( + summary["graph_counts"], + { + "U": 12, + "D": 9, + "P": 11, + "intersection": 9, + "P_minus_D": 2, + "D_minus_P": 0, + "union": 11, + }, + ) + for policy, changed, identical in [ + ("first_retained", 2, 9), + ("all_retained", 0, 11), + ]: + result = summary["policies"][policy] + stats = result["populations"]["all"] + self.assertEqual(stats["denominator"], 12) + self.assertEqual( + stats["direct_reasons"], {"retained": 6, "rolled_up": 3, "no_target": 3} + ) + self.assertEqual( + stats["closure_reasons"], + {"retained": 6, "rolled_up": 4, "no_target": 2}, + ) + self.assertEqual(stats["categories"]["recovered_no_target"], 1) + self.assertEqual(stats["categories"]["changed_nonempty_targets"], changed) + self.assertEqual(stats["categories"]["identical_targets"], identical) + self.assertEqual(result["populations"]["deep"]["denominator"], 5) + self.assertEqual(result["populations"]["deep"]["direct_no_target"], 2) + self.assertEqual(result["populations"]["deep"]["closure_no_target"], 1) + self.assertEqual( + result["structural_gaps"]["direct"]["root_unreachable"], + {"total": 3, "eligible": 1, "deep": 2, "excluded_root": 0}, + ) + self.assertEqual( + result["structural_gaps"]["closure"]["root_unreachable"], + {"total": 2, "eligible": 1, "deep": 1, "excluded_root": 0}, + ) + lines = ( + (self.destination / f"{policy}_differences.tsv") + .read_text() + .splitlines() + ) + self.assertEqual(len(lines), changed + 2) + self.assertEqual( + json.loads((self.destination / "summary.json").read_text())["graph_counts"], + summary["graph_counts"], + ) + + def test_overlap_and_duplicate_order_invariance(self): + write_synthetic_bundle(self.folder, overlay=False) + vocabulary = OMOPVocabulary(self.folder) + depths, direct, pairs = reference_graph(vocabulary) + self.assertEqual(direct, pairs) + for policy in ("first_retained", "all_retained"): + config = { + "target_policy": policy, + "include_root": False, + "on_unmapped": "empty", + } + a = build_keep_omop_ancestor_rollup( + vocabulary, path_source="direct", **config + ) + b = build_keep_omop_ancestor_rollup( + vocabulary, path_source="closure", **config + ) + self.assertEqual( + a.rollup_codes(sorted(depths)), b.rollup_codes(sorted(depths)) + ) + self.assertEqual(b.provenance["closure_only_edge_count"], "0") + write_synthetic_bundle(self.folder) + before = self.build("closure") + expected = reference_graph(self.vocabulary) + write_synthetic_bundle(self.folder, duplicate_pairs=True) + after = self.build("closure") + self.assertEqual(reference_graph(self.vocabulary), expected) + self.assertEqual( + before.rollup_codes(sorted(depths)), after.rollup_codes(sorted(depths)) + ) + self.assertEqual(before.fingerprint, after.fingerprint) + + def test_both_policies_preserve_targets_when_edges_are_added(self): + # Exhaust every possible acyclic overlay on this ordered four-node DAG. + # Fixed depths/eligibility: paths to old first-retained targets survive. + candidates = [ + ("R", "A"), + ("R", "B"), + ("R", "X"), + ("A", "B"), + ("A", "X"), + ("B", "X"), + ] + graph = KnowledgeGraph( + triples=[("A", "is_a", "X")], + entity2id={c: i for i, c in enumerate(["R", "A", "B", "X"])}, + relation2id={"is_a": 0}, + ) + for policy in ("first_retained", "all_retained"): + config = { + "knowledge_graph": graph, + "domain_by_code": {c: "Condition" for c in "RABX"}, + "hierarchy_relation": "is_a", + "root": "R", + "target_policy": policy, + "include_root": False, + "max_depth": 2, + "on_unmapped": "empty", + "root_depths": {"R": 0, "A": 1, "B": 2, "X": 3}, + } + baseline = AncestorRollupProcessor(**config).rollup_codes(["X"])[0] + for mask in range(1 << len(candidates)): + pairs = [edge for i, edge in enumerate(candidates) if mask & (1 << i)] + result = AncestorRollupProcessor( + **config, path_source="closure", closure_pairs=pairs + ).rollup_codes(["X"])[0] + self.assertLessEqual(set(baseline.targets), set(result.targets)) + + def test_self_edges_and_cycles_rejected(self): + graph = KnowledgeGraph(triples=[("R", "is_a", "A")]) + config = { + "knowledge_graph": graph, + "domain_by_code": {c: "Condition" for c in "RA"}, + "hierarchy_relation": "is_a", + "root": "R", + "target_policy": "first_retained", + "include_root": False, + "path_source": "closure", + } + for pairs in [[("A", "A")], [("A", "R")]]: + with self.assertRaises(ValueError): + AncestorRollupProcessor(**config, closure_pairs=pairs) + + def test_structural_deep_population_uses_cutoff_even_without_eligible_nodes(self): + self.assertEqual( + structural_gaps({ROOT: 0, "X": 2}, set(), set(), 5)["root_unreachable"], + {"total": 1, "eligible": 0, "deep": 0, "excluded_root": 0}, + )