OpenIslet

scripts/rank_islet1_stacks.py

Step 5 & 6: Project Islet-1 Sign-Sensitive, Endpoint-Oriented & Locus-Penalized Evaluator (v0.6.9).

script Release v0.8.0 gen-eb955f8266035aba 638 KB · 42 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/rank_islet1_stacks.py · SHA-256: c05d5fe606219e88…

        if not isinstance(metadata, dict) or not isinstance(metadata.get("pmid"), str) or not metadata["pmid"]:
            raise ValueError("Every evidence study requires an explicit PMID identifier")
        if metadata.get("source_text_type") not in source_types:
            raise ValueError(f"Unmapped source_text_type in PMID {metadata['pmid']}")
        effects = study.get("atomic_effects", [])
        if not isinstance(effects, list) or any(not isinstance(effect, dict) for effect in effects):
            raise ValueError("Atomic evidence must be a list of explicit effect records")
        effect_ids = [effect.get("effect_id") for effect in effects]
        if any(not isinstance(eid, str) or not eid for eid in effect_ids) or len(set(effect_ids)) != len(effect_ids):
            raise ValueError("Effect identifiers must be nonempty and unique within each study")
        for effect in effects:
            if effect.get("effect_direction") not in {"Protective_or_Improved", "Neutral_or_NonInferior", "Deleterious_or_Impaired", "Descriptive_or_Unoriented"}:
                raise ValueError("Unknown effect_direction cannot be interpreted as neutral evidence")
            if type(effect.get("secretome_or_differentiation_penalty_observed", False)) is not bool:
                raise ValueError("Evidence penalty flags must be boolean")
            for key in ("focal_factor_X", "verbatim_evidence_quote", "outcome_variable_Y"):
                if key in effect and not isinstance(effect[key], str):
                    if key == "verbatim_evidence_quote" and effect[key] is None and metadata.get("source_text_type") == "Citation_Only_No_Abstract_Indexed":
                        continue
                    raise ValueError(f"Evidence {key} must be a string")
        pmids.append(metadata["pmid"])
    if len(pmids) != len(set(pmids)):
        raise ValueError("Duplicate study PMID would double-count empirical evidence")
    for gene, annotation in omics.items():
        if not isinstance(annotation, dict):
            raise ValueError(f"Omics annotation for {gene} must be a dictionary")
        for key in ("gnomad_pli", "gnomad_loeuf_upper", "opentargets_t1d_score", "curated_literature_prior_t1d_score"):
            value = annotation.get(key)
            if value is not None:
                number = _finite_real(value, f"{gene}.{key}")
                if number < 0 or (key != "gnomad_loeuf_upper" and number > 1):
                    raise ValueError(f"{gene}.{key} is outside its declared domain")
    target_stats: dict[str, dict] = {}

    def ensure_gene(g: str):
        if g not in target_stats:
            om = omics.get(g, {})
            rec_edit = str(om.get("recommended_edit") or "")
            is_gof = (
                g in {"CD47", "HLA-E", "CD274", "SERPINB9", "CASP9", "TNFAIP3", "IL10"}
                or ("knock-in" in rec_edit.lower() and "ko" not in rec_edit.lower())
            )
            target_stats[g] = {
                "gene_symbol": g,
                "gnomad_pli": om.get("gnomad_pli"),
                "gnomad_loeuf_upper": om.get("gnomad_loeuf_upper"),
                "opentargets_t1d_score": om.get("opentargets_t1d_score"),
                "curated_literature_prior_t1d_score": om.get("curated_literature_prior_t1d_score"),
                "opentargets_prior_source": om.get("opentargets_score_source", om.get("opentargets_score_provenance", om.get("opentargets_prior_source", "Unmapped_or_Zero_T1D_Association"))),
                "is_engineered_genetic_target": bool(om.get("is_engineered_genetic_target", g not in {"GCG", "SST", "PECAM1", "GCK", "PCSK1"})),
                "functional_gate": om.get("functional_gate"),
                "recommended_edit": om.get("recommended_edit"),
                "default_perturbation_direction": "Gain_of_Function_or_KnockIn" if is_gof else "Knockout_or_BaseEdit",
                "arm_edit_modalities_observed": [],
                "n_studies_total": 0,
                "n_empirical_studies": 0,
                "n_project_summary_records_excluded_from_weights": 0,
                "n_citation_only_records_excluded_from_weights": 0,
                "n_review_records_excluded_from_weights": 0,
                "n_superseded_preprint_records_excluded_from_weights": 0,
                "n_confounded_nonislet_records_excluded_from_weights": 0,
                "n_human_tier1_to_3_studies": 0,
                "n_rodent_tier4_studies": 0,
                "n_protective_effects": 0,
                "n_deleterious_or_penalty_effects": 0,
                "n_neutral_effects": 0,
                "n_ko_lof_effects": 0,
                "n_gof_oe_effects": 0,
                "n_associational_or_untyped_effects": 0,
                "weighted_protective_score": 0.0,
                "weighted_deleterious_penalty_score": 0.0,
                "ko_weighted_protective_score": 0.0,
                "ko_weighted_deleterious_score": 0.0,
                "gof_weighted_protective_score": 0.0,
                "gof_weighted_deleterious_score": 0.0,
                "signed_lrr_weighted_sum": 0.0,
                "signed_lrr_weight_total": 0.0,
                "ko_signed_lrr_weighted_sum": 0.0,
                "ko_signed_lrr_weight_total": 0.0,
                "gof_signed_lrr_weighted_sum": 0.0,
                "gof_signed_lrr_weight_total": 0.0,
                "supporting_pmids": [],
                "counter_evidence_pmids": [],
            }

    for g in omics:
        ensure_gene(g)

    alias_map = {
        "ZN-T8": "SLC30A8",
        "ZNT8": "SLC30A8",
        "IGRP": "G6PC2",
        "GAD65": "GAD2",
        "IA-2": "PTPRN",
        "PD-L1": "CD274",
        "PDL1": "CD274",
        "A20": "TNFAIP3",
        "PI-9": "SERPINB9",
        "MDA5": "IFIH1",
        "CAR": "CXADR",
        "ICASP9": "CASP9",
        "IND-CASP9": "CASP9",
        "IL-10": "IL10",
    }
    for canonical in sorted(set(alias_map.values())):
        ensure_gene(canonical)

    _expand_gene_symbol = expand_gene_symbol_tokens

    # Pre-register all study_genes across studies in sorted order so target_stats is 100% invariant to input study order (AT-03)
    all_study_genes = sorted({
        g_atom
        for doc in studies
        for arm in doc.get("arms", [])
        for ed in arm.get("gate2_3_4_genetic_and_epitope_edits", [])
        for g_atom in _expand_gene_symbol(str(ed.get("gene_symbol_hgnc") or ""))
    })
    for g in all_study_genes:
        ensure_gene(g)

    ordered_studies = sorted(
        studies, key=lambda d: str(d.get("study_metadata", {}).get("pmid", ""))
    )
    for doc in ordered_studies:
        meta = doc.get("study_metadata", {})
        pmid = str(meta.get("pmid", ""))
        src_type = meta.get("source_text_type", "")
        is_project_summary = src_type == "Project_Summary"
        is_citation_only = src_type == "Citation_Only_No_Abstract_Indexed"
        is_review = src_type == "Review_or_Commentary"
        is_superseded_preprint = (
            src_type == "Preprint_Superseded_By_Peer_Reviewed"
            or bool(meta.get("superseded_by_pmid"))
        )
        arms_list = doc.get("arms", [])
        _conditioning_tokens = (
            "lymphodeplet", "fludarabine", "cyclophosphamide", "flu/cy",
            "bendamustine", "myeloablat", "total body irradiation",
            "conditioning", "busulfan", "melphalan",
        )
        is_confounded_nonislet_conditioned = bool(arms_list) and all(
            (a.get("gate1_substrate_and_differentiation") or {}).get("cell_source_class")
            == "NonIslet_Immune_Endothelial_or_Hematopoietic_Model"
            and (
                (a.get("gate5_engraftment_niche") or {}).get("clinical_conditioning_regimen_class")
                == "Lymphodepleting_or_Myeloablative_Conditioning"
                or any(
                    tok in str((a.get("gate5_engraftment_niche") or {}).get("systemic_immunosuppression_regimen") or "").lower()
                    for tok in _conditioning_tokens
                )
            )
            for a in arms_list
        )
        _vascular_endothelial_tokens = ("vascular", "endotheli", "ecfc")
        is_nonislet_vascular_endothelial_mhc = (
            bool(arms_list)
            and all(
                (a.get("gate1_substrate_and_differentiation") or {}).get("cell_source_class")
                == "NonIslet_Immune_Endothelial_or_Hematopoietic_Model"
                for a in arms_list
            )
            and (
                all(
                    any(
                        tok in str(a.get("arm_label") or "").lower()
                        for tok in _vascular_endothelial_tokens
                    )
                    for a in arms_list
                )
                or any(
                    tok in str(meta.get("title") or "").lower()
                    for tok in _vascular_endothelial_tokens
                )
            )
            and bool(
                {
                    str(ed.get("gene_symbol_hgnc") or "")
                    for a in arms_list
                    for ed in a.get("gate2_3_4_genetic_and_epitope_edits", [])
                }
                & {"B2M", "CIITA"}
            )
        )
        is_non_weighted_record = (
            is_project_summary
            or is_citation_only
            or is_superseded_preprint
            or is_review
            or is_confounded_nonislet_conditioned
            or is_nonislet_vascular_endothelial_mhc
        )
        tier = meta.get("max_biological_fidelity_tier", "Tier_4_Rodent_or_Xenogeneic_Only")
        if tier not in FIDELITY_WEIGHTS:
            raise ValueError(f"Unmapped max_biological_fidelity_tier {tier!r} in PMID {pmid}")
        w = FIDELITY_WEIGHTS[tier]
        is_human = tier not in ("Tier_4_Rodent_or_Xenogeneic_Only", "Tier_2C_NHP_Allogeneic_or_Autologous_NonIslet")

        study_genes = set()
        study_gene_edit_types: dict[str, set[str]] = {}
        for arm in doc.get("arms", []):
            for ed in arm.get("gate2_3_4_genetic_and_epitope_edits", []):
                raw_g = str(ed.get("gene_symbol_hgnc") or "")
                for g in _expand_gene_symbol(raw_g):
                    study_genes.add(g)
                    ensure_gene(g)
                    et = str(ed.get("edit_modality") or ed.get("edit_type") or "").strip()
                    if et:
                        study_gene_edit_types.setdefault(g, set()).add(et)
                        if et not in target_stats[g]["arm_edit_modalities_observed"]:
                            target_stats[g]["arm_edit_modalities_observed"].append(et)

        for g in study_genes:
            st = target_stats[g]
            st["n_studies_total"] += 1
            if is_project_summary:
                st["n_project_summary_records_excluded_from_weights"] += 1
            elif is_citation_only:
                st["n_citation_only_records_excluded_from_weights"] += 1
            elif is_superseded_preprint:
                st["n_superseded_preprint_records_excluded_from_weights"] += 1
            elif is_review:
                st["n_review_records_excluded_from_weights"] += 1
            elif is_confounded_nonislet_conditioned or is_nonislet_vascular_endothelial_mhc:
                st["n_confounded_nonislet_records_excluded_from_weights"] += 1
            else:
                st["n_empirical_studies"] += 1
            if is_human:
                st["n_human_tier1_to_3_studies"] += 1
            else:
                st["n_rodent_tier4_studies"] += 1
            if pmid and not is_non_weighted_record and pmid not in st["supporting_pmids"]:
                st["supporting_pmids"].append(pmid)

        study_effs = doc.get("atomic_effects", [])
        n_effs_in_study = max(1, len(study_effs))
        # Citation_Only_No_Abstract_Indexed (42430558), Project_Summary, and Preprint_Superseded_By_Peer_Reviewed (40832357 -> 41202120) are excluded from quantitative evidence weights (A02/A08/A10 + IIP-0040)
        eff_weight = 0.0 if is_non_weighted_record else (0.12 * w) / float(n_effs_in_study)

        marker_readout_genes = {"INS", "GCG", "SST", "CHGA", "NKX6-1", "PDX1", "MAFA"}
        for eff in study_effs:
            focal_only = eff.get("focal_factor_X") or ""
            focal_only_upper = focal_only.upper()
            q_str = eff.get("verbatim_evidence_quote") or ""
            for field_name, field_text in (("focal_factor_X", focal_only), ("verbatim_evidence_quote", q_str)):
                if "[REDACTED_NON_OA_EXCERPT:" in field_text or "[REDACTED_CONSERVATIVE_EXCERPT:" in field_text:
                    declared_field = re.search(r"\bfield=([A-Za-z0-9_]+)", field_text)
                    if not validate_public_excerpt_token(field_text, expected_pmid=pmid) or declared_field is None or declared_field[1] != field_name:
                        raise ValueError(f"{pmid}:{eff.get('effect_id')}: invalid source-bound opaque {field_name}")
            fx = focal_only + " " + q_str
            fx_upper = fx.upper()