OpenIslet

scripts/verify_iip0041_clinical_h1_cd64t_siglec.py

EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite

script Release v0.8.0 gen-eb955f8266035aba 984 KB · 69 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/verify_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…

                    "outcome_variable_Y": "Increased Fc gamma RI binding and immune-cell transcript enrichment of alternatively spliced 4.1G",
                    "outcome_domain": "Surface_HLA_or_Transgene_Expression_Level", "effect_direction": "Descriptive_or_Unoriented",
                    "quote": "4.1G product to be associated with increased Fc gamma RI binding",
                    "measurement_unit": "qualitative_statement", "statistic_type": "single_arm_descriptive_only",
                    "contrast_type": "single_arm_descriptive_only",
                    "polarity_class": "Qualitative_or_Unoriented_Endpoint", "orientation_sign": 0, "matched_lexicon_term": "none_or_mixed",
                    "n_unit": "in_vitro_monoculture_replicates", "cell_source": "NonIslet_Immune_Endothelial_or_Hematopoietic_Model", "site": "InVitro_Only",
                    "tier": "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse", "population_or_model": "Yeast two-hybrid & immune-cell transcript profiling",
                },
            ],
            "ceg_arms": [
                {"arm_id": "A1_fcgr1a_cy_mutants", "label": "Fc gamma RI cytosolic-tail truncation and alanine-substitution mutants", "edits": ["FCGR1A_CY_Truncation_AlanineScan"], "n": "Yeast two-hybrid mutant panel (n not reported in abstract)", "iso": "Direct paired transgene comparison"},
                {"arm_id": "A2_fcgr1a_wt_cy_ctrl", "label": "Wild-type human Fc gamma RI cytosolic tail construct", "edits": [], "n": "Yeast two-hybrid reference & immune-cell transcripts", "iso": "Baseline comparator"},
            ],
            "ceg_outcomes": [
                {"oid": "O1", "endpoint": "Protein 4.1G docking motif within Fc gamma RI cytoplasmic tail", "comp": "A1_fcgr1a_cy_mutants vs A2_fcgr1a_wt_cy_ctrl", "dir": "descriptive_or_neutral", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Membrane-proximal cytosolic HxxBxxxBB core + downstream hydrophobic/acidic residues", "summary": "Truncation and alanine scanning localized Protein 4.1G interaction to a membrane-proximal Fc gamma RI cytosolic core motif (HxxBxxxBB) followed by hydrophobic and acidic residues.", "quote_eff": "pmid18023480_eff1_hxxbxxxbb_motif"},
                {"oid": "O2", "endpoint": "Alternatively spliced 4.1G isoform binding and immune-cell transcript enrichment", "comp": "A2_fcgr1a_wt_cy_ctrl (isoform binding)", "dir": "descriptive_or_neutral", "stat": "qualitative_no_pvalue", "tier": "T5_Rodent_or_CellLine", "ival": "Elevated CD64 Y2H binding & selective immune-cell enrichment", "summary": "A splice isoform of EPB41L2 showed stronger CD64 cytosolic-tail binding in Y2H screens and selective immune-cell transcript enrichment.", "quote_eff": "pmid18023480_eff2_spliced_4p1g_enrichment"},
            ],
            "ceg_relation": "scoping_qualification", "ceg_applicability": "justified_bridge",
            "ceg_edge_claim": "Protein 4.1G binds the membrane-proximal HxxBxxxBB cytosolic motif immediately downstream of the FCGR1A transmembrane domain (deleted in tailless CD64t[1-313] where Arg314-Tyr374 is excised).",
        },
    ]

    dossiers: dict[str, dict[str, Any]] = {}
    dshas: dict[str, str] = {}
    ring1_records: list[dict[str, Any]] = []
    ceg_new_studies: dict[str, Any] = {}
    ceg_new_arms: dict[str, Any] = {}
    ceg_new_outcomes: dict[str, Any] = {}
    ceg_new_edges: list[dict[str, Any]] = []

    for sp in study_specs:
        pmid = sp["pmid"]
        rp = live_pm[pmid]
        ft_sec = sp.get("ft_sections")
        dos: dict[str, Any] = {
            "pmid": pmid,
            "pmcid": rp.get("pmcid"),
            "doi": rp.get("doi"),
            "pub_year": rp.get("pub_year"),
            "journal": rp.get("journal") or "",
            "first_author": rp.get("first_author"),
            "senior_author": rp.get("senior_author"),
            "title": rp.get("title") or "",
            "abstract": rp.get("abstract") or "",
            "publication_types": rp.get("publication_types") or ["Journal Article"],
            "mesh_terms": [], "keywords": [],
            "matched_pillars": sp["pillars"],
            "linked_geo_datasets": [],
            "has_parsed_fulltext_xml": bool(ft_sec),
            "fulltext_data_sections": ft_sec,
        }
        if sp.get("oa_lic"):
            dos["license"] = sp["oa_lic"]
        raw_b = json.dumps(dos, sort_keys=True, ensure_ascii=False).encode("utf-8")
        (DOSSIERS_DIR / f"{pmid}.json").write_bytes(raw_b)
        dossiers[pmid] = dos
        dshas[pmid] = sha256_bytes(raw_b)

        eff_objs: list[dict[str, Any]] = []
        eff_by_id: dict[str, dict[str, Any]] = {}
        for ef in sp["effects"]:
            eo = make_effect(
                pmid=pmid,
                effect_id=ef["effect_id"],
                dossier=dos,
                dos_sha=dshas[pmid],
                focal_arm_id=ef["focal_arm_id"],
                comparator_arm_id=ef["comparator_arm_id"],
                cohort_id=ef["cohort_id"],
                focal_factor_X=ef["focal_factor_X"],
                comparator_X0=ef["comparator_X0"],
                comparator_label=ef["comparator_label"],
                outcome_variable_Y=ef["outcome_variable_Y"],
                outcome_domain=ef["outcome_domain"],
                effect_direction=ef["effect_direction"],
                quote_substring=ef["quote"],
                stage=ef.get("stage"),
                cell_source=ef["cell_source"],
                site=ef["site"],
                tier=ef["tier"],
                treatment_mean=ef.get("treatment_mean"),
                control_mean=ef.get("control_mean"),
                point_estimate=ef.get("point_estimate"),
                effect_notes=ef.get("effect_notes"),
                treatment_n=ef.get("treatment_n"),
                control_n=ef.get("control_n"),
                measurement_unit=ef.get("measurement_unit", "qualitative_statement"),
                statistic_type=ef.get("statistic_type", "qualitative_statement_only"),
                contrast_type=ef.get("contrast_type", "qualitative_statement_only"),
                polarity_class=ef.get("polarity_class", "Qualitative_or_Unoriented_Endpoint"),
                orientation_sign=int(ef.get("orientation_sign", 0)),
                matched_lexicon_term=ef.get("matched_lexicon_term", "none_or_mixed"),
                n_unit=ef.get("n_unit", "unspecified_in_source"),
                censoring_note=ef.get("censoring_note", "Not_Time_To_Event_Endpoint"),
                timepoint=ef.get("timepoint"),
                population_or_model=ef.get("population_or_model"),
                penalty_flag=bool(ef.get("penalty_flag", False)),
            )
            eff_objs.append(eo)
            eff_by_id[ef["effect_id"]] = eo

        doc = {
            "schema_version": "0.2.0",
            "study_metadata": {
                "pmid": pmid, "pmcid": dos.get("pmcid"), "doi": dos.get("doi"), "nct_id": None,
                "geo_accessions": [], "title": dos["title"], "first_author": dos.get("first_author"),
                "senior_author": dos.get("senior_author"), "pub_year": dos["pub_year"], "journal": dos["journal"],
                "source_text_type": "FullText_XML_or_PDF" if ft_sec else "Abstract_Only",
                "pillars_covered": sp["pillars"], "max_biological_fidelity_tier": sp["tier"],
            },
            "screening_decision": {"included": True, "is_crispr_or_high_throughput_screen": False, "screen_library_size_genes": None, "exclusion_reason": None},
            "arms": sp["arms"],
            "atomic_effects": eff_objs,
            "effect_modifier_interactions": [],
            "causal_mechanism_edges": [],
            "cross_study_discovery_bridges": {
                "collateral_and_pleiotropic_findings": [], "residual_failure_and_escape_vectors": [],
                "regime_thresholds": [], "high_throughput_screen_hits": [],
            },
        }
        ring1_records.append(doc)

        qid = sp["ceg_qid"]
        eid = f"{qid}:L1"
        vids = []
        for ca in sp["ceg_arms"]:
            vid = f"VAR:{qid}:{ca['arm_id']}"
            vids.append(vid)
            ceg_new_arms[vid] = {
                "variable_id": vid, "queue_id": qid, "context_id": f"CTX:{qid}", "arm_id": ca["arm_id"],
                "label": ca["label"], "edits_or_interventions": ca["edits"],
                "n_donors_or_animals": ca["n"], "causal_isolation": ca["iso"],
            }
        cited_oids = []
        cited_otuples = []
        for co in sp["ceg_outcomes"]:
            oid_short = co["oid"]
            oid = f"{qid}:{oid_short}"
            cited_oids.append(oid_short)
            cited_otuples.append(oid)
            ref_eff = eff_by_id[co["quote_eff"]]
            src_type = "abstract" if ref_eff["source_span"].startswith("abstract") else ("figure_legend" if "figure_legends" in ref_eff["source_span"] else "results_text")
            ceg_new_outcomes[oid] = {
                "outcome_node_id": oid, "queue_id": qid, "outcome_id": oid_short,
                "endpoint_name": co["endpoint"], "comparison_arms": co["comp"],
                "direction": co["dir"], "stat_type": co["stat"],
                "quantitative_summary": co["summary"], "manuscript_tier": co["tier"],
                "intervention_value": co["ival"],
                "source_pin": {"source_type": src_type, "pmid": pmid, "span": ref_eff["source_span"]},
                "quote_sha256": sha256_str(ref_eff["verbatim_evidence_quote"]),
                "cited_by_edge_ids": [eid],
            }
        st_obj: dict[str, Any] = {
            "context_id": f"CTX:{qid}", "queue_id": qid, "id_type": "PMID", "id_value": pmid,
            "pmid": pmid, "pmcid": dos.get("pmcid"), "citation_short": sp["citation_short"],
            "fidelity_tier": sp["ceg_tier"], "biological_model": sp["ceg_model"],
            "immune_context": sp["ceg_immune"], "donor_or_cell_source": sp["ceg_donor_source"],
            "follow_up": sp["ceg_follow_up"], "variable_arm_ids": vids,
            "blueprint_targets": [sp["ceg_target"]], "outcomes_count": len(cited_oids), "links_count": 1,
            "candidate_effector_topics": sp["ceg_topics"],
        }
        st_obj["record_class"] = bceg.classify_ceg_study_record(st_obj)
        if not (st_obj["record_class"] == "empirical_primary_study"):
            raise ValueError(f"Unexpected record_class on {qid}: {st_obj['record_class']}")
        ceg_new_studies[qid] = st_obj
        ceg_new_edges.append({
            "edge_id": eid, "queue_id": qid, "link_index": 0,
            "target_gate_or_module": sp["ceg_target"], "relation": sp["ceg_relation"],
            "applicability": sp["ceg_applicability"], "incorporation": "not_yet_accounted_for",
            "readiness": "semantically_verified", "primary_certification_eligible": False,
            "cited_outcome_ids": cited_oids, "cited_outcome_tuples": cited_otuples,
            "claim_summary": sp["ceg_edge_claim"], "candidate_effector_topics": sp["ceg_topics"],
        })

    # --- RUN ALL LIVE OPENISLET PRODUCTION VALIDATOR GATES ---
    gates: dict[str, Any] = {}
    spec_by_pm = {s["pmid"]: s for s in study_specs}

    # G1: jsonschema Draft202012Validator (raw records checked here; public records checked below in G1b/G2b)
    schema_v02 = json.loads((OPENISLET_ROOT / "schemas/extraction_schema_v0.2.json").read_text(encoding="utf-8"))
    v02 = jsonschema.Draft202012Validator(schema_v02)
    g1_errs = [f"{r['study_metadata']['pmid']}: {list(e.path)} -> {e.message}" for r in ring1_records for e in v02.iter_errors(r)]
    gates["G1_schema_v02_Draft202012"] = {"records_tested": len(ring1_records), "errors": g1_errs, "passed": len(g1_errs) == 0}

    # G2: Live extract_ring1_corpus.validate_study_semantics on source-bound raw records
    orig_dir = erc.DOSSIER_DIR
    g2_errs, g2_rows = [], []
    try:
        erc.DOSSIER_DIR = DOSSIERS_DIR
        for rec in ring1_records:
            pm_id = rec["study_metadata"]["pmid"]
            try:
                erc.validate_study_semantics(rec, dossiers[pm_id])
                for ae in rec["atomic_effects"]:
                    if not (type(ae["endpoint_polarity_registry"]["orientation_sign"]) is int):
                        raise ValueError('Verification check failed: type(ae["endpoint_polarity_registry"]["orientation_sign"]) is int')
                g2_rows.append({"pmid": pm_id, "status": "PASS", "arms": len(rec["arms"]), "effects": len(rec["atomic_effects"])})
            except Exception as exc:
                g2_errs.append(f"{pm_id}: {exc}")
                g2_rows.append({"pmid": pm_id, "status": "FAIL", "error": str(exc)})
    finally:
        erc.DOSSIER_DIR = orig_dir
    gates["G2_live_validate_study_semantics_raw_source_bound"] = {
        "records_passed": sum(1 for r in g2_rows if r["status"] == "PASS"),
        "records_tested": len(ring1_records),
        "total_arms": sum(len(r["arms"]) for r in ring1_records),
        "total_atomic_effects": sum(len(r["atomic_effects"]) for r in ring1_records),
        "per_study": g2_rows,
        "errors": g2_errs, "passed": len(g2_errs) == 0,
    }

    # G3: public_excerpt_policy bounded metadata & redaction tokens
    g3_errs, g3_tokens = [], {}
    for rec in ring1_records:
        sm = rec["study_metadata"]
        pm_id = sm["pmid"]
        cs = spec_by_pm[pm_id]["citation_short"]
        if not pep.is_bounded_metadata(pm_id, "pmid"):
            g3_errs.append(f"{pm_id}: invalid pmid")
        if sm["doi"] and not pep.is_bounded_metadata(sm["doi"], "doi"):
            g3_errs.append(f"{pm_id}: invalid doi")
        if not pep.is_bounded_metadata(cs, "citation_short", bibliographic=True):
            g3_errs.append(f"{pm_id}: invalid citation_short {cs}")
        for ae in rec["atomic_effects"]:
            pfx = "[REDACTED_CONSERVATIVE_EXCERPT:" if live_pm[pm_id].get("epmc_oa_license") == "cc by-nc-nd" else "[REDACTED_NON_OA_EXCERPT:"
            tok = f"{pfx} see PMID:{pm_id} field=verbatim_evidence_quote quote_sha256={sha256_str(ae['verbatim_evidence_quote'])}]"
            if not pep.validate_token(tok, expected_pmid=pm_id, source_quote=ae["verbatim_evidence_quote"], expected_field="verbatim_evidence_quote"):
                g3_errs.append(f"{pm_id}: invalid PEP token")
            g3_tokens[ae["effect_id"]] = tok
    gates["G3_public_excerpt_policy"] = {"errors": g3_errs, "redacted_non_oa_count": sum(1 for s in study_specs if not s["oa_pub_allowed"]), "passed": len(g3_errs) == 0}

    # G4: <= 240c aggregate verbatim chars across ALL fields (both raw AND public-exported!) + explicit public-record validation
    g4_errs, g4_detail = [], {}
    public_ring1_records = []
    for rec in ring1_records:
        pm_id = rec["study_metadata"]["pmid"]
        dos = dossiers[pm_id]
        src_parts = [dos.get("title") or "", dos.get("abstract") or ""]
        if dos.get("fulltext_data_sections"):
            src_parts.extend(dos["fulltext_data_sections"].get("results_paragraphs") or [])
            src_parts.extend(fg.get("caption") or "" for fg in (dos["fulltext_data_sections"].get("figure_legends") or []))
        src_blob = "\n".join(src_parts)
        raw_sh = compute_aggregate_verbatim_chars(rec, src_blob)
        pub_rec = copy.deepcopy(rec)
        for ae in pub_rec["atomic_effects"]:
            if not spec_by_pm[pm_id]["oa_pub_allowed"]:
                ae["verbatim_evidence_quote"] = g3_tokens[ae["effect_id"]]
        public_ring1_records.append(pub_rec)
        pub_sh = compute_aggregate_verbatim_chars(pub_rec, src_blob)