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…

        screening_funnel["historical_wave5_1216_milestone"] = dict(_led_w5_hist)
    elif isinstance(_raw_w5_hist, dict):
        screening_funnel["historical_wave5_1216_milestone"] = dict(_raw_w5_hist)
    _raw_44_led = (raw.get("screening_funnel") or {}).get("ceg_v1_cutover_record_level_screening_ledger")
    _led_44_led = l_sum.get("ceg_v1_cutover_record_level_screening_ledger")
    if isinstance(_led_44_led, list) and len(_led_44_led) == 21:
        screening_funnel["ceg_v1_cutover_record_level_screening_ledger"] = list(_led_44_led)
    elif isinstance(_raw_44_led, list) and len(_raw_44_led) == 21:
        screening_funnel["ceg_v1_cutover_record_level_screening_ledger"] = list(_raw_44_led)
    _raw_pre_w6 = (raw.get("screening_funnel") or {}).get("historical_baseline_pre_wave6_milestone")
    _led_pre_w6 = l_sum.get("historical_baseline_pre_wave6_milestone")
    if isinstance(_led_pre_w6, dict):
        screening_funnel["historical_baseline_pre_wave6_milestone"] = dict(_led_pre_w6)
    elif isinstance(_raw_pre_w6, dict):
        screening_funnel["historical_baseline_pre_wave6_milestone"] = dict(_raw_pre_w6)
    _raw_h1234 = (raw.get("screening_funnel") or {}).get("historical_ceg_v1_1234_milestone")
    _led_h1234 = l_sum.get("historical_ceg_v1_1234_milestone")
    if isinstance(_led_h1234, dict):
        screening_funnel["historical_ceg_v1_1234_milestone"] = dict(_led_h1234)
    elif isinstance(_raw_h1234, dict):
        screening_funnel["historical_ceg_v1_1234_milestone"] = dict(_raw_h1234)
    _raw_w6_led = (raw.get("screening_funnel") or {}).get("wave6_delta_record_level_screening_ledger")
    _led_w6_led = l_sum.get("wave6_delta_record_level_screening_ledger")
    if isinstance(_led_w6_led, list) and len(_led_w6_led) == 25:
        screening_funnel["wave6_delta_record_level_screening_ledger"] = list(_led_w6_led)
    elif isinstance(_raw_w6_led, list) and len(_raw_w6_led) == 25:
        screening_funnel["wave6_delta_record_level_screening_ledger"] = list(_raw_w6_led)

    ceg_payload: dict[str, Any] = {
        "schema_version": "openislet_context_evidence_graph_v1.0",
        "graph_name": "OpenIslet T1D Context-Evidence Graph",
        "graph_acronym": "CEG",
        "license": "CC-BY-4.0",
        "quote_and_rights_policy": {
            "verbatim_quote_status": "WITHHELD_IN_PUBLIC_CEG_SEE_QUOTE_SHA256_AND_SOURCE_PIN",
            "non_oa_prose_overlap_policy": (
                "All inline verbatim_quote strings are withheld (preserving 64-hex quote_sha256 and source_pin), "
                "and any string field sharing a >=6-word normalized source shingle or >=40-character local dossier "
                "substring is replaced with a deterministic non-expressive structured descriptor."
            ),
            "omitted_outcome_field_defaults": {
                "verbatim_quote": None,
                "intervention_value": "not reported",
                "comparator_value": "not reported",
                "p_value_or_ci": "not reported",
                "n_summary": "not reported",
                "requires_figure_digitization": False,
                "cited_by_edge_ids": [],
            },
        },
        "evidence_hierarchy_and_scoring_note": (
            f"Context-indexed evidence graph across {len(studies):,} total CEG records ("
            f"{rc_import['empirical_primary_study']:,} empirical_primary_study + "
            f"{rc_import['trial_registry_protocol']:,} trial_registry_protocol + "
            f"{rc_import['regulatory_or_guidance_document']:,} regulatory_or_guidance_document + "
            f"{rc_import['computational_model_or_simulation']:,} computational_model_or_simulation + "
            f"{rc_import['correspondence_or_secondary_summary']:,} correspondence_or_secondary_summary + "
            f"{rc_import['superseded_preprint_duplicate']:,} superseded_preprint_duplicate), "
            f"{len(arms):,} arms, {len(outcomes):,} outcomes, and {len(edges):,} blueprint links. "
            "Layer-1 2,160-stack prior-anchored scenario scores remain invariant on the 642-study Ring-1 baseline "
            "(+0.00 pp under Wave-5 IIP-0041/IIP-0042/IIP-0043, the DEC-124 CEG v1 quality sweep, and Wave-6 staged CEG delta) "
            "unless explicitly updated through an accepted Islet Improvement Proposal."
        ),
        "counts": {
            "screened_records_total": screening_funnel["screened_records_total"],
            "candidates_advanced_total": screening_funnel["candidates_advanced_total"],
            "studies": len(studies),
            "record_class_counts": dict(sorted(rc_import.items())),
            "arms": len(arms),
            "outcomes": len(outcomes),
            "edges": len(edges),
            "effectors": len(effectors),
            "graveyard_entries_indexed": len(graveyard_index),
            "unresolved_exact_outcome_mentions": 0,
        },
        "screening_funnel": screening_funnel,
        "studies": studies,
        "arms": arms,
        "outcomes": outcomes,
        "edges": edges,
        "effectors": effectors,
        "graveyard_index": graveyard_index,
    }
    if isinstance(raw.get("wave6_certification_approval_receipt"), dict):
        ceg_payload["wave6_certification_approval_receipt"] = dict(raw["wave6_certification_approval_receipt"])
    _w6_imp_raw_rec = json.loads('{"approval_authority_id": "OPENISLET_DEC124_RELEASE_GOVERNANCE_V1", "approval_receipt_id": "W6-DEC124-APPROVAL-STAGED-PRE-FOLDIN-RAW-V1", "approved_cert_eligible_edge_ids": [], "approved_certification_phase": "STAGED_PRE_FOLDIN", "approved_wave6_graph_digest": "76ce65551d935b306908746fdf1182b9dc09c630e60e09afe80eb25fa2103b1e", "expected_study_certification_status": "STAGED_TYPED_DELTA_PENDING_FULL_GRAPH_REBUILD", "graph_representation": "raw", "publication_certification_granted": false, "receipt_sha256": "928817167f0974b41e99dcd541a5ea9e168aaa6e9f715ce597fb97bf1043a130", "schema_version": "wave6_certification_approval_receipt_v1"}')
    _w6_imp_mat_rec = json.loads('{"approval_authority_id": "OPENISLET_DEC124_RELEASE_GOVERNANCE_V1", "approval_receipt_id": "W6-DEC124-APPROVAL-STAGED-PRE-FOLDIN-MAT-V1", "approved_cert_eligible_edge_ids": [], "approved_certification_phase": "STAGED_PRE_FOLDIN", "approved_wave6_graph_digest": "693f33c2342b555d8b10b06117c30dcd581182855ea3ba373ddb9cee84866a0d", "expected_study_certification_status": "STAGED_TYPED_DELTA_PENDING_FULL_GRAPH_REBUILD", "graph_representation": "materialized", "publication_certification_granted": false, "receipt_sha256": "fb9206912ddc219a0f7fe8ad98889510c9c6482070d7b716db448201a356f610", "schema_version": "wave6_certification_approval_receipt_v1"}')
    _w6_raw_rec_in = raw.get("wave6_certification_approval_receipt")
    if isinstance(_w6_raw_rec_in, dict) and (_w6_raw_rec_in == _w6_imp_raw_rec or _w6_raw_rec_in == _w6_imp_mat_rec):
        ceg_payload["wave6_certification_approval_receipt"] = dict(_w6_imp_mat_rec)
    elif _w6_raw_rec_in is not None:
        ceg_payload["wave6_certification_approval_receipt"] = _w6_raw_rec_in

    verify_ceg_payload(ceg_payload, repo_root=repo_root)
    atlas_payload = build_layer1_atlas_from_ceg(ceg_payload)
    return ceg_payload, atlas_payload


def main() -> None:
    parser = argparse.ArgumentParser(description="Build or verify OpenIslet Layer-1 Context-Evidence Graph artifacts.")
    parser.add_argument("--root", type=Path, default=REPO_ROOT, help="OpenIslet repository root")
    parser.add_argument("--verify", action="store_true", help="Verify existing artifacts without modifying files")
    parser.add_argument("--import-raw-graph", type=Path, default=None, help="Optional raw CEG JSON to import")
    parser.add_argument("--import-screening-ledger", type=Path, default=None, help="Optional screening ledger JSON")
    parser.add_argument("--source-packets-dir", type=Path, default=None, help="Optional directory of source packets for shingle scrubbing")
    args = parser.parse_args()

    root = args.root.resolve()
    ceg_path = root / CEG_REL_PATH
    atlas_path = root / ATLAS_REL_PATH

    if args.import_raw_graph is not None:
        if args.import_screening_ledger is None or args.source_packets_dir is None:
            raise ValueError("--import-raw-graph requires --import-screening-ledger and --source-packets-dir")
        ceg_payload, atlas_payload = import_and_materialize(
            args.import_raw_graph.resolve(),
            args.import_screening_ledger.resolve(),
            args.source_packets_dir.resolve(),
            repo_root=root,
        )
        ceg_bytes = (json.dumps(ceg_payload, ensure_ascii=False, allow_nan=False, separators=(",", ":")) + "\n").encode("utf-8")
        atlas_bytes = (json.dumps(atlas_payload, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
        ceg_path.parent.mkdir(parents=True, exist_ok=True)
        ceg_path.write_bytes(ceg_bytes)
        atlas_path.write_bytes(atlas_bytes)
        print(
            f"Materialized {CEG_REL_PATH} ({len(ceg_bytes) / 1024 / 1024:.2f} MB) "
            f"and {ATLAS_REL_PATH} ({len(atlas_bytes) / 1024 / 1024:.2f} MB)."
        )
        return

    if not ceg_path.is_file():
        raise FileNotFoundError(f"Missing {ceg_path}")
    import math as _math
    def _bceg_no_dup(pairs):
        out = {}
        for k, v in pairs:
            if k in out:
                raise ValueError(f"Duplicate JSON key in CEG: {k!r}")
            out[k] = v
        return out
    def _bceg_no_nan(tok):
        raise ValueError(f"Non-standard JSON constant in CEG: {tok!r}")
    def _bceg_finite_float(tok):
        v = float(tok)
        if not _math.isfinite(v):
            raise ValueError(f"Non-finite JSON float overflow in CEG: {tok!r}")
        return v
    ceg_payload = json.loads(ceg_path.read_text(encoding="utf-8"), object_pairs_hook=_bceg_no_dup, parse_constant=_bceg_no_nan, parse_float=_bceg_finite_float)
    detail = verify_ceg_payload_detailed(ceg_payload, repo_root=root)
    counts = detail["counts"]
    expected_atlas = (json.dumps(build_layer1_atlas_from_ceg(ceg_payload), indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
    if args.verify:
        if not atlas_path.is_file() or atlas_path.read_bytes() != expected_atlas:
            raise ValueError(f"{ATLAS_REL_PATH} is missing or out of sync with {CEG_REL_PATH}")
        print(f"Verified CEG ({counts['studies']} studies, {counts['outcomes']} outcomes, {counts['edges']} links; mode={detail['verification_mode']}, exact_spans_verified={detail['iip0035_verified_exact_span_outcome_count']}, sourceguard_executed={detail['iip0035_sourceguard_executed']}) and Layer-1 atlas.")
    else:
        atlas_path.write_bytes(expected_atlas)
        print(f"Verified CEG and wrote {ATLAS_REL_PATH} ({len(expected_atlas) / 1024 / 1024:.2f} MB).")


if __name__ == "__main__":
    main()