OpenIslet

scripts/build_context_evidence_graph.py

Build and verify the Layer-1 Context-Evidence Graph (`CEG`) public artifacts.

script Release v0.8.0 gen-eb955f8266035aba 229 KB · 16 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/build_context_evidence_graph.py · SHA-256: 2758ba22e378ffed…

            sorted(["M0051:L1", "M0051:L2", "M0051:L3", "M0154:L1", "M0154:L2", "M0159:L1", "M0159:L2", "M0206:L1", "M0206:L2", "M0241:L1", "M0241:L2"])
            if has_src_35
            else []
        ),
        "iip0035_sourceguard_scan_scope": (
            "executed_on_6_new_study_families_11_new_edges_27_touched_legacy_outcomes_and_11_adjudicated_legacy_edges"
            if has_src_35
            else "skipped_public_bundle_no_local_dossiers"
        ),
        "reused_m1522_outcomes_exact_span_verified": False,
        "reused_legacy_crosslink_outcomes_exact_span_verified": False,
        "izadifar_dossier_contains_figure_legends": False,
        "m1522_reused_outcomes_note": "M1522:O6/O7/O15/O16 use figure/panel + digest pins outside the exact-span pass (Izadifar dossier carries no figure legends) and remain ineligible scoping references on M1522:L4.",
        "iip0035_reused_crosslink_outcomes_note": "Reused legacy cross-linked outcomes on M0051:L4, M0154:L3, M0159:L3, M0206:L3, and M0241:L3 carry prior CEG source pins outside the IIP-0035 8-new-outcome exact-span pass and remain primary_certification_eligible=False scoping qualifications only.",
        "wave6_verification_mode": "source_recomputed_verified" if has_src_w6 else "structural_pin_verified",
        "wave6_source_verification_executed": bool(has_src_w6),
        "wave6_structural_span_pin_count": (_w6_prim_cnt + _w6_sec_abs_cnt + _w6_sec_ft_cnt),
        "wave6_source_recomputed_span_count": (_w6_prim_cnt + _w6_sec_abs_cnt + _w6_sec_ft_cnt) if has_src_w6 else 0,
        "wave6_authorized_edge_bindings_verified": True,
        "wave6_valid_evidence_scope_classes_enforced": True,
        "wave6_semantic_claim_binding_verified": True,
        "wave6_study_semantic_digests_verified": 25,
        "wave6_arm_semantic_digests_verified": 61,
        "wave6_outcome_semantic_digests_verified": 46,
        "wave6_edge_semantic_digests_verified": 32,
        "wave6_verified_study_ids": _w6_qids_sorted if has_src_w6 else [],
        "wave6_verified_studies_count": len(_w6_qids_sorted) if has_src_w6 else 0,
        "wave6_verified_primary_span_count": _w6_prim_cnt if has_src_w6 else 0,
        "wave6_verified_secondary_abstract_span_count": _w6_sec_abs_cnt if has_src_w6 else 0,
        "wave6_verified_secondary_fulltext_span_count": _w6_sec_ft_cnt if has_src_w6 else 0,
        "wave6_verified_total_spans_count": (_w6_prim_cnt + _w6_sec_abs_cnt + _w6_sec_ft_cnt) if has_src_w6 else 0,
        "wave6_authorized_cert_eligible_edge_ids": ["PMID:30449685:L1"],
        "wave6_certification_approval_receipt_verified": True,
        "wave6_approved_certification_phase": (ceg.get("wave6_certification_approval_receipt") or {}).get("approved_certification_phase"),
        "wave6_approval_receipt_id": (ceg.get("wave6_certification_approval_receipt") or {}).get("approval_receipt_id"),
        "wave6_approved_wave6_graph_digest": (ceg.get("wave6_certification_approval_receipt") or {}).get("approved_wave6_graph_digest"),
        "wave6_publication_certification_granted": bool((ceg.get("wave6_certification_approval_receipt") or {}).get("publication_certification_granted")),
        "wave6_phase_approved_cert_eligible_edge_ids": list((ceg.get("wave6_certification_approval_receipt") or {}).get("approved_cert_eligible_edge_ids") or []),
    }


def import_and_materialize(
    raw_graph_path: Path,
    screening_ledger_path: Path,
    source_packets_dir: Path,
    repo_root: Path = REPO_ROOT,
) -> tuple[dict[str, Any], dict[str, Any]]:
    raw = json.loads(raw_graph_path.read_text(encoding="utf-8"))
    ledger = json.loads(screening_ledger_path.read_text(encoding="utf-8"))

    study_shingles: dict[str, set[tuple[str, ...]]] = {}
    study_years: dict[str, int] = {}
    for pkt_file in sorted(source_packets_dir.glob("*packets*.json")):
        data = json.loads(pkt_file.read_text(encoding="utf-8"))
        if not isinstance(data, list):
            continue
        for pkt in data:
            if not isinstance(pkt, dict) or "queue_id" not in pkt:
                continue
            qid = str(pkt["queue_id"])
            yr = pkt.get("year")
            if isinstance(yr, int) and not isinstance(yr, bool) and 1900 <= yr <= 2100:
                study_years[qid] = yr
            ws = _words(" ".join(_leaves(pkt)))
            study_shingles.setdefault(qid, set()).update(
                tuple(ws[i : i + 6]) for i in range(max(0, len(ws) - 5))
            )

    pmid_to_qid = {
        str(s.get("pmid")): qid
        for qid, s in raw["study_contexts"].items()
        if s.get("pmid")
    }
    dossier_texts: list[str] = []
    dossier_dir = repo_root / "data" / "dossiers"
    if dossier_dir.is_dir():
        for fp in sorted(dossier_dir.glob("*.json")):
            d_obj = json.loads(fp.read_text(encoding="utf-8"))
            d_txt = " ".join(_leaves(d_obj))
            dossier_texts.append(d_txt)
            qid = pmid_to_qid.get(fp.stem)
            if qid:
                ws = _words(d_txt)
                study_shingles.setdefault(qid, set()).update(
                    tuple(ws[i : i + 6]) for i in range(max(0, len(ws) - 5))
                )

    guard = _SourceGuard(study_shingles, dossier_texts)

    def clean_text(qid: str, field: str, value: Any, meta: dict[str, Any]) -> Any:
        if not isinstance(value, str):
            return value
        text = _scrub_progeny_and_internal_tokens(value)
        if not text:
            return text
        if guard.overlaps(qid, value) or guard.overlaps(qid, text):
            return _structured_replacement(field, text, meta)
        return text

    studies: dict[str, Any] = {}
    for qid in sorted(raw["study_contexts"]):
        s = raw["study_contexts"][qid]
        meta = {"queue_id": qid}
        st: dict[str, Any] = {
            "context_id": s["context_id"],
            "queue_id": qid,
            "id_type": s["id_type"],
            "id_value": s["id_value"],
            "fidelity_tier": s.get("fidelity_tier"),
            "biological_model": clean_text(qid, "biological_model", s.get("biological_model"), meta),
            "immune_context": clean_text(qid, "immune_context", s.get("immune_context"), meta),
            "donor_or_cell_source": clean_text(qid, "donor_or_cell_source", s.get("donor_or_cell_source"), meta),
            "follow_up": clean_text(qid, "follow_up", s.get("follow_up"), meta),
            "variable_arm_ids": list(s.get("variable_arm_ids") or []),
            "blueprint_targets": [clean_text(qid, "blueprint_target", bt, meta) for bt in (s.get("blueprint_targets") or [])],
            "outcomes_count": int(s.get("outcomes_count") or 0),
            "links_count": int(s.get("links_count") or 0),
        }
        if qid in study_years:
            st["pub_year"] = study_years[qid]
        elif isinstance(s.get("pub_year"), int) and not isinstance(s.get("pub_year"), bool):
            st["pub_year"] = s["pub_year"]
        for opt in (
            "pmid",
            "pmcid",
            "doi",
            "title",
            "first_author",
            "senior_author",
            "journal",
            "citation_short",
            "curated_gene_tags",
            "curated_gene_scope",
            "superseded_by_queue_id",
            "superseded_by_pmid",
            "publication_type",
            "same_patient_followup_of_queue_id",
            "same_patient_followup_of_pmid",
            "same_patient_linked_queue_id",
            "correspondence_pin_status",
            "dec124_certification_status",
            "assay_model_class",
        ):
            if s.get(opt):
                st[opt] = s[opt]
        if "has_experimental_subcomponent" in s and s["has_experimental_subcomponent"] is not None:
            st["has_experimental_subcomponent"] = bool(s["has_experimental_subcomponent"])
        if s.get("experimental_subcomponent_note"):
            st["experimental_subcomponent_note"] = clean_text(
                qid, "experimental_subcomponent_note", s.get("experimental_subcomponent_note"), meta
            )
        if s.get("tier_qualification_note"):
            st["tier_qualification_note"] = clean_text(
                qid, "tier_qualification_note", s.get("tier_qualification_note"), meta
            )
        if s.get("candidate_effector_topics"):
            st["candidate_effector_topics"] = list(s["candidate_effector_topics"])
        st_pin = _clean_pin(s.get("source_pin"))
        if st_pin:
            st["source_pin"] = st_pin
        _raw_rc = s.get("record_class")
        if _raw_rc is not None and _raw_rc not in VALID_CEG_RECORD_CLASSES:
            raise ValueError(f"Raw study {qid} has invalid record_class={_raw_rc!r}")
        _pre_rc = classify_ceg_study_record(s)
        _post_rc = classify_ceg_study_record(st)
        st["record_class"] = (
            _pre_rc
            if _pre_rc != "empirical_primary_study"
            else (_raw_rc if _raw_rc in VALID_CEG_RECORD_CLASSES and _raw_rc != "empirical_primary_study" else _post_rc)
        )
        studies[qid] = st

    arms: dict[str, Any] = {}
    for vid in sorted(raw["variable_nodes"]):
        v = raw["variable_nodes"][vid]
        qid = v["queue_id"]
        meta = {
            "queue_id": qid,
            "arm_id": v["arm_id"],
            "causal_isolation": v.get("causal_isolation") or "NOT_ESTABLISHED",
        }
        ar: dict[str, Any] = {
            "variable_id": vid,
            "queue_id": qid,
            "context_id": v["context_id"],
            "arm_id": v["arm_id"],
            "label": clean_text(qid, "label", v.get("label"), meta),
            "edits_or_interventions": [
                clean_text(qid, "edits_or_interventions", ed, meta)
                for ed in (v.get("edits_or_interventions") or [])
            ],
            "n_donors_or_animals": clean_text(qid, "n_donors_or_animals", v.get("n_donors_or_animals"), meta),
            "causal_isolation": v.get("causal_isolation"),
        }
        if v.get("arm_role"):
            ar["arm_role"] = str(v["arm_role"])
        if v.get("arm_role"):
            ar["arm_role"] = str(v["arm_role"])
        if v.get("host_species_or_recipient"):
            ar["host_species_or_recipient"] = str(v["host_species_or_recipient"])
        if v.get("candidate_effector_topics"):
            ar["candidate_effector_topics"] = list(v["candidate_effector_topics"])
        arms[vid] = ar

    outcomes: dict[str, Any] = {}
    for oid in sorted(raw["outcome_nodes"]):
        o = raw["outcome_nodes"][oid]
        qid = o["queue_id"]
        pin = _clean_pin(o.get("source_pin"))
        vq = str(o.get("verbatim_quote") or "")
        meta = {
            "queue_id": qid,
            "outcome_id": o["outcome_id"],
            "direction": o.get("direction") or "unspecified",
            "stat_type": o.get("stat_type") or "unspecified",
            "pin_tag": _pin_tag(pin),
        }
        reach = o.get("outcome_reachability") or {}
        cited_edges = list(reach.get("cited_by_blueprint_link_edge_ids") or o.get("cited_by_edge_ids") or [])
        oc: dict[str, Any] = {
            "outcome_node_id": oid,
            "queue_id": qid,
            "outcome_id": o["outcome_id"],
            "endpoint_name": clean_text(qid, "endpoint_name", o.get("endpoint_name"), meta),
            "comparison_arms": clean_text(qid, "comparison_arms", o.get("comparison_arms"), meta),
            "direction": o.get("direction"),
            "stat_type": o.get("stat_type"),
            "quantitative_summary": clean_text(qid, "quantitative_summary", o.get("quantitative_summary"), meta),
            "manuscript_tier": o.get("manuscript_tier"),
        }
        for val_key in ("intervention_value", "comparator_value", "p_value_or_ci", "n_summary"):
            raw_v = o.get(val_key)
            if raw_v is not None and str(raw_v).strip() and str(raw_v).strip().lower() != "not reported":
                oc[val_key] = clean_text(qid, val_key, str(raw_v), meta)
        if o.get("requires_figure_digitization"):
            oc["requires_figure_digitization"] = True
        if pin:
            oc["source_pin"] = pin
        if vq:
            oc["quote_sha256"] = _sha256_str(vq)
        elif o.get("quote_sha256"):
            oc["quote_sha256"] = str(o["quote_sha256"])
        if o.get("evidence_provenance"):
            oc["evidence_provenance"] = str(o["evidence_provenance"])
        if cited_edges:
            oc["cited_by_edge_ids"] = cited_edges
        if o.get("candidate_effector_topics"):
            oc["candidate_effector_topics"] = list(o["candidate_effector_topics"])
        if o.get("assay_model_class"):
            oc["assay_model_class"] = str(o["assay_model_class"])