scripts/build_context_evidence_graph.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/build_context_evidence_graph.py · SHA-256: 2758ba22e378ffed…
if o.get("assay_or_endpoint"):
oc["assay_or_endpoint"] = clean_text(qid, "assay_or_endpoint", str(o["assay_or_endpoint"]), meta)
if o.get("host_species_or_recipient"):
oc["host_species_or_recipient"] = str(o["host_species_or_recipient"])
if o.get("timepoint"):
oc["timepoint"] = clean_text(qid, "timepoint", str(o["timepoint"]), meta)
if isinstance(o.get("outcome_context_override"), dict):
oco_in = o["outcome_context_override"]
oco_out = {
"study_manuscript_fidelity_tier": oco_in.get("study_manuscript_fidelity_tier"),
"outcome_effective_assay_tier": oco_in.get("outcome_effective_assay_tier"),
"override_reason": clean_text(qid, "override_reason", oco_in.get("override_reason"), meta),
"override_provenance": _scrub_internal_code(str(oco_in.get("override_provenance") or "")),
}
if oco_in.get("assay_model_class"):
oco_out["assay_model_class"] = str(oco_in["assay_model_class"])
oc["outcome_context_override"] = oco_out
if isinstance(o.get("comparator_audit_override"), dict):
cao_in = o["comparator_audit_override"]
keep_cao_keys = (
"corrected_comparison_arms",
"focal_intervention_arm",
"misbound_master_arm_id",
"baseline_comparator_arm",
"assay_context",
"audit_note",
)
oc["comparator_audit_override"] = {
k: clean_text(qid, k, cao_in[k], meta)
for k in keep_cao_keys
if k in cao_in and cao_in[k] is not None
}
if isinstance(o.get("focal_arm_id"), str) and o["focal_arm_id"].strip():
oc["focal_arm_id"] = str(o["focal_arm_id"]).strip()
if isinstance(o.get("intervention_arm_id"), str) and o["intervention_arm_id"].strip():
oc["intervention_arm_id"] = str(o["intervention_arm_id"]).strip()
if isinstance(o.get("intervention_arm_ids"), list):
oc["intervention_arm_ids"] = list(o["intervention_arm_ids"])
if isinstance(o.get("comparator_arm_ids"), list):
oc["comparator_arm_ids"] = list(o["comparator_arm_ids"])
if isinstance(o.get("secondary_source_pins"), list):
oc["secondary_source_pins"] = [dict(sp) for sp in o["secondary_source_pins"] if isinstance(sp, dict)]
outcomes[oid] = oc
edges: list[dict[str, Any]] = []
for e in sorted(raw["edges"], key=lambda item: (item["queue_id"], item["link_index"])):
qid = e["queue_id"]
meta = {
"queue_id": qid,
"edge_id": e["edge_id"],
"relation": e.get("relation") or "unspecified",
"applicability": e.get("applicability") or "unspecified",
"incorporation": e.get("incorporation") or "unspecified",
"cited_outcome_ids": list(e.get("cited_outcome_ids") or []),
}
cited_tuples = [
f"{t[0]}:{t[1]}" if isinstance(t, (list, tuple)) and len(t) == 2 else str(t)
for t in (e.get("cited_outcome_tuples") or [])
]
_raw_pce = e.get("primary_certification_eligible")
if type(_raw_pce) is not bool:
raise ValueError(
f"Raw edge {e.get('edge_id')} primary_certification_eligible must be strict bool, got {_raw_pce!r} ({type(_raw_pce).__name__})"
)
_edge_prov = e.get("evidence_provenance")
_imp_non_emp_prov = frozenset({
"computational_model_or_simulation",
"mixed_measured_and_simulated_model",
"mixed_empirical_and_computational",
"administrative_registry_record",
})
_imp_title_pins = frozenset({"title_or_citation_metadata_only", "title"})
_st_pin_imp_t = (studies[qid].get("source_pin") or {}).get("source_type") if isinstance(studies[qid].get("source_pin"), dict) else None
_cites_nonemp_or_sim = any(
studies.get(outcomes[tok]["queue_id"], {}).get("record_class") != "empirical_primary_study"
or outcomes[tok].get("evidence_provenance") in _imp_non_emp_prov
or (isinstance(outcomes[tok].get("source_pin"), dict) and outcomes[tok]["source_pin"].get("source_type") in _imp_title_pins)
or (
isinstance(studies.get(outcomes[tok]["queue_id"], {}).get("source_pin"), dict)
and studies[outcomes[tok]["queue_id"]]["source_pin"].get("source_type") in _imp_title_pins
)
for tok in cited_tuples
if tok in outcomes
)
ed: dict[str, Any] = {
"edge_id": e["edge_id"],
"queue_id": qid,
"link_index": int(e["link_index"]),
"target_gate_or_module": clean_text(qid, "target_gate_or_module", e.get("target_gate_or_module"), meta),
"relation": e.get("relation"),
"applicability": e.get("applicability"),
"incorporation": e.get("incorporation"),
"readiness": e.get("readiness"),
"primary_certification_eligible": (
False
if (
studies[qid].get("record_class") != "empirical_primary_study"
or e.get("applicability") == "domain_mismatch"
or e.get("relation") == "noninformative"
or e.get("readiness") == "needs_primary_fulltext"
or _st_pin_imp_t in _imp_title_pins
or _edge_prov in _imp_non_emp_prov
or e["edge_id"] in CURATED_INELIGIBLE_EDGE_IDS
or (
e.get("applicability") == "unvalidated_transfer"
and (
qid in {
"PMID:17375075", "PMID:42020736", "PMID:42056515", "PMID:42749803",
"M0300", "PMID:22099783", "PMID:30012675", "PMID:30569273",
"PMID:30967424", "PMID:31180194", "PMID:33632742", "PMID:33658358",
"PMID:37861217", "PMID:39137044", "PMID:40447640", "PMID:40598585",
"PMID:40976248", "PMID:41026533", "PMID:41196293",
}
or (qid == "M1522" and e["edge_id"] not in {"M1522:L1", "M1522:L2"})
)
)
or not cited_tuples
or _cites_nonemp_or_sim
)
else _raw_pce
),
"cited_outcome_ids": list(e.get("cited_outcome_ids") or []),
"cited_outcome_tuples": cited_tuples,
"claim_summary": clean_text(qid, "claim_summary", e.get("claim_summary"), meta),
}
if _edge_prov:
ed["evidence_provenance"] = str(_edge_prov)
if e.get("provenance_note"):
ed["provenance_note"] = clean_text(qid, "provenance_note", e.get("provenance_note"), meta)
if e.get("legacy_certification_adjudication_note"):
ed["legacy_certification_adjudication_note"] = clean_text(qid, "legacy_certification_adjudication_note", e.get("legacy_certification_adjudication_note"), meta)
if e.get("polarity"):
ed["polarity"] = str(e["polarity"])
if "cert_eligible" in e and type(e["cert_eligible"]) is bool:
ed["cert_eligible"] = ed["primary_certification_eligible"]
if e.get("evidence_scope_class"):
ed["evidence_scope_class"] = str(e["evidence_scope_class"])
if e.get("wave_horizon_scope"):
ed["wave_horizon_scope"] = str(e["wave_horizon_scope"])
if e.get("horizon"):
ed["horizon"] = str(e["horizon"])
if e.get("host_species_or_recipient"):
ed["host_species_or_recipient"] = str(e["host_species_or_recipient"])
if e.get("transfer_limits"):
ed["transfer_limits"] = clean_text(qid, "transfer_limits", str(e["transfer_limits"]), meta)
_e_sp_clean = _clean_pin(e.get("source_pin"))
if _e_sp_clean:
ed["source_pin"] = _e_sp_clean
if e.get("candidate_effector_topics"):
ed["candidate_effector_topics"] = list(e["candidate_effector_topics"])
edges.append(ed)
effectors: dict[str, Any] = {}
for eff_id in sorted(raw["effector_nodes"]):
eff = raw["effector_nodes"][eff_id]
effectors[eff_id] = {
"effector_id": eff["effector_id"],
"topic_id": eff["topic_id"],
"label": eff["label"],
"category": eff["category"],
"causal_isolation": eff["causal_isolation"],
"mediation_status": eff["mediation_status"],
"semantic_status": eff.get("semantic_status"),
"linked_study_ids": sorted(eff.get("linked_study_ids") or []),
"linked_variable_ids": sorted(eff.get("linked_variable_ids") or []),
"linked_outcome_tuples": [
f"{t[0]}:{t[1]}" if isinstance(t, (list, tuple)) and len(t) == 2 else str(t)
for t in (eff.get("linked_outcome_tuples") or [])
],
}
# Build graveyard_index directly from the canonical public graveyard file for zero source-prose drift
gy_src = json.loads((repo_root / GRAVEYARD_REL_PATH).read_text(encoding="utf-8"))["graveyard_entries"]
gy_by_id = {row["graveyard_id"]: row for row in gy_src}
graveyard_index: list[dict[str, Any]] = []
for g in raw["graveyard_index"]:
gid = g["graveyard_id"]
canon = gy_by_id.get(gid, {})
graveyard_index.append({
"graveyard_id": gid,
"category": g.get("Category") or canon.get("severity") or "BLOCK",
"severity": canon.get("severity"),
})
l_sum = ledger.get("summary")
if not isinstance(l_sum, dict) or "total_studies" not in l_sum:
raise ValueError("screening_ledger.summary must be a dict containing explicit total_studies and overall_counts")
_oc_counts = l_sum.get("overall_counts")
_wave_counts = l_sum.get("candidate_extraction_waves")
if not isinstance(_oc_counts, dict) or not all(k in _oc_counts for k in ("ADVANCE", "PARK_CONTEXT", "EXCLUDE_OFF_TOPIC")):
raise ValueError("screening_ledger.summary.overall_counts must specify ADVANCE, PARK_CONTEXT, and EXCLUDE_OFF_TOPIC")
if not isinstance(_wave_counts, dict) or "Wave_2B_Supporting_Catalog_P2_P3" not in _wave_counts:
raise ValueError("screening_ledger.summary.candidate_extraction_waves must specify Wave_2B_Supporting_Catalog_P2_P3")
_tot_screened = l_sum["total_studies"]
_r1_screened = l_sum.get("ring1_existing_records_screened", 642)
_new_screened = l_sum.get("new_candidate_records_screened", 3328)
_adv_total = _oc_counts["ADVANCE"]
_park_total = _oc_counts["PARK_CONTEXT"]
_excl_total = _oc_counts["EXCLUDE_OFF_TOPIC"]
_rem_total = _wave_counts["Wave_2B_Supporting_Catalog_P2_P3"]
if not all(type(v) is int and v >= 0 for v in (_tot_screened, _r1_screened, _new_screened, _adv_total, _park_total, _excl_total, _rem_total)):
raise ValueError("screening_ledger counts must be non-negative integers")
if _r1_screened + _new_screened != _tot_screened:
raise ValueError(f"Inconsistent screening_ledger totals: ring1 ({_r1_screened}) + new ({_new_screened}) != total_studies ({_tot_screened})")
if _adv_total + _park_total + _excl_total != _tot_screened:
raise ValueError(f"Inconsistent screening_ledger totals: ADVANCE ({_adv_total}) + PARK_CONTEXT ({_park_total}) + EXCLUDE_OFF_TOPIC ({_excl_total}) != total_studies ({_tot_screened})")
if len(studies) + _rem_total != _adv_total:
raise ValueError(f"Inconsistent screening_ledger totals: extracted ({len(studies)}) + queued ({_rem_total}) != ADVANCE ({_adv_total})")
rc_import = Counter(classify_ceg_study_record(s) for s in studies.values())
screening_funnel = {
"screened_records_total": _tot_screened,
"ring1_existing_records_screened": _r1_screened,
"new_candidate_records_screened": _new_screened,
"candidates_advanced_total": _adv_total,
"contextual_reviews_parked_total": _park_total,
"off_topic_records_excluded_total": _excl_total,
"wave1_ceg_records_extracted_total": len(studies),
"wave1_primary_empirical_extracted_total": rc_import["empirical_primary_study"],
"wave1_trial_registry_protocols_extracted": rc_import["trial_registry_protocol"],
"wave1_regulatory_or_guidance_records_extracted": rc_import["regulatory_or_guidance_document"],
"wave1_computational_models_extracted": rc_import["computational_model_or_simulation"],
"wave1_correspondence_or_secondary_extracted": rc_import["correspondence_or_secondary_summary"],
"wave1_superseded_preprint_duplicates_extracted": rc_import["superseded_preprint_duplicate"],
"wave1_ring1_core_records_extracted_total": sum(1 for q in studies if q.startswith("R1_")),
"wave1_ring1_empirical_core_extracted": sum(1 for q, s in studies.items() if q.startswith("R1_") and classify_ceg_study_record(s) == "empirical_primary_study"),
"wave1_new_empirical_studies_extracted": sum(1 for q, s in studies.items() if not q.startswith("R1_") and classify_ceg_study_record(s) == "empirical_primary_study"),
"wave1_non_r1_records_extracted_total": sum(1 for q in studies if not q.startswith("R1_")),
"remaining_supporting_catalog_queued_for_later_waves": _rem_total,
}
_raw_sf_led = (raw.get("screening_funnel") or {}).get("iip0035_record_level_screening_ledger")
_led_sf_led = l_sum.get("iip0035_record_level_screening_ledger")
if isinstance(_led_sf_led, list) and len(_led_sf_led) == 11:
screening_funnel["iip0035_record_level_screening_ledger"] = list(_led_sf_led)
elif isinstance(_raw_sf_led, list) and len(_raw_sf_led) == 11:
screening_funnel["iip0035_record_level_screening_ledger"] = list(_raw_sf_led)
_raw_hist35 = (raw.get("screening_funnel") or {}).get("historical_iip0035_1182_milestone")
_led_hist35 = l_sum.get("historical_iip0035_1182_milestone")
if isinstance(_led_hist35, dict):
screening_funnel["historical_iip0035_1182_milestone"] = dict(_led_hist35)
elif isinstance(_raw_hist35, dict):
screening_funnel["historical_iip0035_1182_milestone"] = dict(_raw_hist35)
_raw_w5_led = (raw.get("screening_funnel") or {}).get("wave5_delta_screening_ledger")
_led_w5_led = l_sum.get("wave5_delta_screening_ledger")
if isinstance(_led_w5_led, list) and len(_led_w5_led) == 40:
screening_funnel["wave5_delta_screening_ledger"] = list(_led_w5_led)
elif isinstance(_raw_w5_led, list) and len(_raw_w5_led) == 40:
screening_funnel["wave5_delta_screening_ledger"] = list(_raw_w5_led)
_raw_w5_hist = (raw.get("screening_funnel") or {}).get("historical_wave5_1216_milestone")
_led_w5_hist = l_sum.get("historical_wave5_1216_milestone")
if isinstance(_led_w5_hist, dict):