redacted_genes_matches = re.findall(r"\bgenes=([A-Za-z0-9_,-]+)", fx) if ("[REDACTED_NON_OA_EXCERPT:" in fx or "[REDACTED_CONSERVATIVE_EXCERPT:" in fx) else [] if redacted_genes_matches: g_tag_val = redacted_genes_matches[-1] matched_genes = set() if g_tag_val != "NONE": for g_tok in g_tag_val.split(","): g_tok = g_tok.strip() if g_tok: # Opaque metadata permits the same public aliases # as source text. Preserve the target identity and # deduplicate aliases before accumulating evidence. g_tok = alias_map.get(g_tok, g_tok) ensure_gene(g_tok) matched_genes.add(g_tok) else: matched_genes = set() for g in list(target_stats.keys()): text_for_g = focal_only if (g in marker_readout_genes and g not in study_genes) else fx text_for_g_upper = focal_only_upper if (g in marker_readout_genes and g not in study_genes) else fx_upper if g.upper() in text_for_g_upper: if MATCH(g, text_for_g, text_for_g_upper): matched_genes.add(g) for alias, canonical in alias_map.items(): text_for_a = focal_only if (canonical in marker_readout_genes and canonical not in study_genes) else fx text_for_a_upper = focal_only_upper if (canonical in marker_readout_genes and canonical not in study_genes) else fx_upper if alias in text_for_a_upper: if AMATCH(alias, text_for_a, text_for_a_upper): ensure_gene(canonical) matched_genes.add(canonical) # Only attribute to study_genes if the study perturbs a single target gene (no multi-gene broadcast!) if not matched_genes and len(study_genes) == 1: matched_genes = set(study_genes) direction = eff.get("effect_direction", "Neutral_or_NonInferior") penalty = bool(eff.get("secretome_or_differentiation_penalty_observed", False)) lrr = eff.get("log_response_ratio_or_smd") if lrr is not None: lrr = _finite_real(lrr, f"{pmid}:{eff.get('effect_id')} LRR") orient_sign = _effect_orientation(eff) redacted_pert_matches = re.findall(r"\bpert=(GOF_OE|KO_LOF|BOTH|NONE)\b", fx) if ("[REDACTED_NON_OA_EXCERPT:" in fx or "[REDACTED_CONSERVATIVE_EXCERPT:" in fx) else [] if redacted_pert_matches: p_tag_val = redacted_pert_matches[-1] has_explicit_gof_tokens = p_tag_val in ("GOF_OE", "BOTH") has_explicit_ko_tokens = p_tag_val in ("KO_LOF", "BOTH") else: has_explicit_gof_tokens = any( tok in focal_only_upper or tok in fx_upper for tok in ( "OVEREXPRESSION", "OVEREXPRESS", "KNOCK-IN", "KNOCKIN", "TRANSGENE", "TRANSGENIC", "ECTOPIC", "LENTIVIRAL", "GAIN-OF-FUNCTION", "GAIN OF FUNCTION", "FORCED EXPRESSION", "CONSTITUTIVE EXPRESSION", "INDUCIBLE EXPRESSION", ) ) has_explicit_ko_tokens = any( tok in focal_only_upper or tok in fx_upper for tok in ( "KNOCKOUT", " KO ", " KO,", " KO.", "-/-", "−/−", "DEFICIENT", "DEFICIENCY", "DELETION", "NULL", "ABLATION", "SILENCING", "SHRNA", "SIRNA", "LOSS-OF-FUNCTION", "LOSS OF FUNCTION", "INHIBITION", "INHIBITOR", "BLOCKADE", ) ) for g in matched_genes: st = target_stats[g] if pmid and not is_non_weighted_record and pmid not in st["supporting_pmids"]: st["supporting_pmids"].append(pmid) arm_ets = " ".join(sorted(study_gene_edit_types.get(g, set()))).upper() is_gof_default = st.get("default_perturbation_direction") == "Gain_of_Function_or_KnockIn" if has_explicit_gof_tokens and not has_explicit_ko_tokens: pert_dir = "GOF_OE" elif has_explicit_ko_tokens and not has_explicit_gof_tokens: pert_dir = "KO_LOF" elif any( t in arm_ets for t in ( "OVEREXPRESSION", "KNOCKIN", "KNOCK-IN", "TRANSGENE", "GAIN", "LENTIVIRAL_OR_TRANSPOSON_OE", "SAFEHARBOR_KI_AAVS1_GAPDH_CLYBL", "CRISPRA_ACTIVATION", "TRANSIENT_MRNA_OR_SURFACE_TETHERING", ) ) and not any(t in arm_ets for t in ("KNOCKOUT", "CRISPR_CAS9_KO", "CRISPR_CAS12A_MULTIPLEX_KO", "CRISPR_CAS12B_MULTIPLEX_KO", "DELETION", "LOSS")): pert_dir = "GOF_OE" elif any(t in arm_ets for t in ("KNOCKOUT", "KO", "DELETION", "BASEEDIT", "PRIMEEDIT", "SHRNA", "LOSS")): pert_dir = "KO_LOF" else: pert_dir = "ASSOCIATIONAL_OR_UNTYPED" if pert_dir == "GOF_OE": st["n_gof_oe_effects"] += 1 elif pert_dir == "KO_LOF": st["n_ko_lof_effects"] += 1 else: st["n_associational_or_untyped_effects"] += 1 explicit_dir = ( "GOF_OE" if (has_explicit_gof_tokens and not has_explicit_ko_tokens) else ("KO_LOF" if (has_explicit_ko_tokens and not has_explicit_gof_tokens) else None) ) eff_bucket = pert_dir if eff_bucket == "ASSOCIATIONAL_OR_UNTYPED": st.setdefault("contextual_untyped_effects", []).append({ "pmid": pmid, "effect_id": eff.get("effect_id"), "direction": direction, "reason": "No donor intervention type; not consumed as KO/GOF efficacy"}) continue # Compute oriented signed LRR (preserving exact sign-flip sensitivity) oriented_lrr = None if isinstance(lrr, (int, float)): clipped_raw = max(-3.0, min(3.0, float(lrr))) oriented_lrr = orient_sign * clipped_raw accumulate(st, "signed_lrr_weighted_sum", eff_weight * oriented_lrr) accumulate(st, "signed_lrr_weight_total", eff_weight) if eff_bucket == "GOF_OE": accumulate(st, "gof_signed_lrr_weighted_sum", eff_weight * oriented_lrr) accumulate(st, "gof_signed_lrr_weight_total", eff_weight) else: accumulate(st, "ko_signed_lrr_weighted_sum", eff_weight * oriented_lrr) accumulate(st, "ko_signed_lrr_weight_total", eff_weight) is_harmful = ( (direction == "Deleterious_or_Impaired") or penalty or (oriented_lrr is not None and oriented_lrr < 0) ) if is_harmful: del_w = direction_weights["deleterious"] pen_w = direction_weights["secretome_or_differentiation_penalty_addon"] st["n_deleterious_or_penalty_effects"] += 1 harm_weight = del_w * eff_weight + (pen_w * eff_weight if penalty else 0.0) accumulate(st, "weighted_deleterious_penalty_score", harm_weight) if eff_bucket == "GOF_OE": accumulate(st, "gof_weighted_deleterious_score", harm_weight) else: accumulate(st, "ko_weighted_deleterious_score", harm_weight) if pmid and not is_non_weighted_record and pmid not in st["counter_evidence_pmids"]: st["counter_evidence_pmids"].append(pmid) elif direction == "Protective_or_Improved": prot_w = direction_weights["protective"] st["n_protective_effects"] += 1 prot_val = prot_w * eff_weight accumulate(st, "weighted_protective_score", prot_val) if eff_bucket == "GOF_OE": accumulate(st, "gof_weighted_protective_score", prot_val) else: accumulate(st, "ko_weighted_protective_score", prot_val) else: st["n_neutral_effects"] += 1 # Finalize posterior means and integrate perturbation-direction-aware gnomAD + OpenTargets constraints prior_w = shrink_parameters["prior_weight"] emp_slope = shrink_parameters["per_empirical_study_slope"] shrunk_mult = direction_weights["shrunk_lrr_multiplier"] pli_slope = omics_weights["gnomad_pli_ko_slope"] loeuf_slope = omics_weights["gnomad_loeuf_ko_slope"] ot_slope = omics_weights["opentargets_t1d_slope"] for g, st in target_stats.items(): w_tot = st["signed_lrr_weight_total"] n_emp = st.get("n_empirical_studies", st["n_studies_total"]) raw_mean_lrr = (st["signed_lrr_weighted_sum"] / w_tot) if w_tot > 0 else 0.0 def shrunk_mean(weight: float, signed_sum: float) -> float: if weight <= 0: return 0.0 denominator = _finite_real(weight + prior_w + emp_slope * n_emp, f"{g} shrinkage denominator") return _finite_real(signed_sum / denominator, f"{g} shrunk mean") shrunk_lrr = shrunk_mean(w_tot, st["signed_lrr_weighted_sum"]) ko_w_tot = st["ko_signed_lrr_weight_total"] gof_w_tot = st["gof_signed_lrr_weight_total"] ko_shrunk_lrr = shrunk_mean(ko_w_tot, st["ko_signed_lrr_weighted_sum"]) gof_shrunk_lrr = shrunk_mean(gof_w_tot, st["gof_signed_lrr_weighted_sum"]) pli = st["gnomad_pli"] loeuf = st["gnomad_loeuf_upper"] ot = ( st["opentargets_t1d_score"] if st.get("opentargets_t1d_score") is not None else st.get("curated_literature_prior_t1d_score") ) pli_penalty = pli_slope * float(pli) if isinstance(pli, (int, float)) else 0.0 loeuf_bonus = loeuf_slope * min(2.0, float(loeuf)) if isinstance(loeuf, (int, float)) else 0.0 ot_bonus = ot_slope * float(ot) if isinstance(ot, (int, float)) else 0.0 omics_ko_constraint_score = round(pli_penalty + loeuf_bonus + ot_bonus, 4) omics_gof_constraint_score = round(ot_bonus, 4) ko_base_ev = ( st["ko_weighted_protective_score"] - st["ko_weighted_deleterious_score"] + shrunk_mult * ko_shrunk_lrr ) gof_base_ev = ( st["gof_weighted_protective_score"] - st["gof_weighted_deleterious_score"] + shrunk_mult * gof_shrunk_lrr ) is_gof_default = st.get("default_perturbation_direction") == "Gain_of_Function_or_KnockIn" net_ko_score = ko_base_ev + omics_ko_constraint_score net_gof_score = gof_base_ev + omics_gof_constraint_score net_preserve_score = ( st["weighted_protective_score"] - st["weighted_deleterious_penalty_score"] + shrunk_mult * shrunk_lrr + omics_gof_constraint_score ) net_default_score = net_gof_score if is_gof_default else net_ko_score st["posterior_mean_log_rr"] = round(raw_mean_lrr, 4) st["shrunk_posterior_log_rr"] = round(shrunk_lrr, 4) st["omics_ko_constraint_adjustment"] = omics_ko_constraint_score st["omics_gof_constraint_adjustment"] = omics_gof_constraint_score st["net_evidence_ko_score"] = round(net_ko_score, 4) st["net_evidence_gof_score"] = round(net_gof_score, 4) st["net_evidence_preserve_score"] = round(net_preserve_score, 4) st["net_evidence_and_constraint_score"] = round(net_default_score, 4) st["total_evidence_contrasts_in_ring1"] = ( st["n_protective_effects"] + st["n_deleterious_or_penalty_effects"] + st["n_neutral_effects"] ) def_g_se_p = dispersion_parameters["default_gene_se"] heur_se = round((0.40 * (def_g_se_p / 0.35)) / math.sqrt(max(0.25, w_tot + 0.25 * n_emp)), 4) st["posterior_se"] = heur_se st["heuristic_evidence_sparsity_se"] = heur_se st["uncertainty_field_note"] = ( "Heuristic inverse-root evidence-weight dispersion index (NOT a calibrated Bayesian posterior standard error)." ) st["supporting_pmids"] = sorted(st["supporting_pmids"])[:25] st["counter_evidence_pmids"] = sorted(st["counter_evidence_pmids"])[:25] for key, value in st.items(): if isinstance(value, float): _finite_real(value, f"{g}.{key} derived profile") return target_stats _GRAVEYARD_CACHE: dict = {"mtime": None, "entries": None} EXPECTED_GRAVEYARD_IDS = frozenset(['GRAVEYARD_001_STAT1_JAK1_KO_WITH_GAS_IND_PROMOTER', 'GRAVEYARD_002_LINEAGE_RESTRICTED_G6PC2_OR_INS_ICASP9_SUICIDE_SWITCH', 'GRAVEYARD_003_G6PC2_NULL_FASTING_HYPOGLYCEMIA_RISK', 'GRAVEYARD_004_RNLS_KO_HUMAN_IPSC_BETA_GSIS_AND_OCR_TRADEOFF', 'GRAVEYARD_005_HLA_C_MINUS21T_LEADER_PEPTIDE_NKG2A_BLINDSPOT', 'GRAVEYARD_006_MULTIPLEX_BASE_PRIME_EDIT_NICKASE_TRANSLOCATIONS', 'GRAVEYARD_007_HIGH_PLI_KNOCKOUTS_PTPN2_TNFAIP3_GAD2', 'GRAVEYARD_008_CONSTITUTIVE_IL10_VIRAL_OVEREXPRESSION', 'GRAVEYARD_009_RESTING_B2M_PROMOTER_HOUR0_INNATE_DENSITY_DEFICIT', 'GRAVEYARD_010_MHC_NULL_INDIRECT_APC_BYSTANDER_BLINDSPOT']) def _load_graveyard_entries_by_id() -> dict[str, dict]: """Load the complete implemented rule set; malformed policy fails closed.""" try: stat = GRAVEYARD_PATH.stat() identity = (str(GRAVEYARD_PATH.resolve()), stat.st_dev, stat.st_ino, stat.st_ctime_ns, stat.st_mtime_ns, stat.st_size) if _GRAVEYARD_CACHE.get("identity") != identity or _GRAVEYARD_CACHE["entries"] is None: