scripts/build_cross_study_graph.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/build_cross_study_graph.py · SHA-256: 94a7b2be6571d9e1…
gene_to_gates: dict[str, set[str]] = defaultdict(set)
edges_all = []
modifiers_by_class: dict[str, list[dict]] = defaultdict(list)
residual_escapes = []
pleiotropic_bonuses = []
regime_thresholds = []
superseded_preprint_records_excluded = []
project_summary_records_excluded = []
citation_only_records_excluded = []
review_records_excluded = []
for doc in studies:
meta = doc["study_metadata"]
pmid = str(meta.get("pmid"))
label = f"PMID:{pmid} ({meta.get('first_author', '')} {meta.get('pub_year', '')})"
total_arms += len(doc.get("arms", []))
total_atomic_effects += len(doc.get("atomic_effects", []))
total_modifier_interactions += len(doc.get("effect_modifier_interactions", []))
total_causal_edges += len(doc.get("causal_mechanism_edges", []))
src_type = meta.get("source_text_type", "")
sup_by = meta.get("superseded_by_pmid")
if src_type == "Preprint_Superseded_By_Peer_Reviewed" or bool(sup_by):
superseded_preprint_records_excluded.append(
{
"pmid": pmid,
"superseded_by_pmid": sup_by,
"exclusion_reason": (
f"Superseded_By_Peer_Reviewed_PMID:{sup_by}"
if sup_by
else "Preprint_Superseded_By_Peer_Reviewed_Enum"
),
}
)
continue
if src_type == "Review_or_Commentary":
review_records_excluded.append({"pmid": pmid, "exclusion_reason": "Bibliographic review/context, not an independent experimental study"})
continue
if src_type == "Project_Summary":
project_summary_records_excluded.append(pmid)
continue
if src_type == "Citation_Only_No_Abstract_Indexed":
citation_only_records_excluded.append(pmid)
continue
for arm in doc.get("arms", []):
for edit in arm.get("gate2_3_4_genetic_and_epitope_edits", []):
gsym = edit.get("gene_symbol_hgnc")
fgate = edit.get("functional_gate")
if gsym:
gene_to_studies[gsym].add(label)
if fgate:
gene_to_gates[gsym].add(fgate)
for eff in doc.get("atomic_effects", []):
eff_text = f"{eff.get('focal_factor_X', '')} {eff.get('outcome_variable_Y', '')} {eff.get('verbatim_evidence_quote', '')}"
for c in extract_canonical_concepts(eff_text):
concept_to_studies[c].add(label)
for em in doc.get("effect_modifier_interactions", []):
mclass = em.get("modifier_class", "Unknown")
modifiers_by_class[mclass].append({
"study": label,
"focal_factor_X": em.get("focal_factor_X"),
"outcome_Y": em.get("outcome_Y"),
"modifier_variable_Z": em.get("modifier_variable_Z"),
"modification_type": em.get("modification_type"),
"level_1": em.get("level_1_condition_and_effect"),
"level_2": em.get("level_2_condition_and_effect"),
"mechanistic_explanation": em.get("mechanistic_explanation"),
})
for c in extract_canonical_concepts(
f"{em.get('focal_factor_X', '')} {em.get('modifier_variable_Z', '')} {em.get('mechanistic_explanation', '')}"
):
concept_to_studies[c].add(label)
arms_list = doc.get("arms", []) or []
arm_sources = sorted({
(a.get("gate1_substrate_and_differentiation") or {}).get("cell_source_class")
for a in arms_list
if (a.get("gate1_substrate_and_differentiation") or {}).get("cell_source_class")
})
arm_stages = sorted({
(a.get("gate1_substrate_and_differentiation") or {}).get("canonical_differentiation_stage_evaluated")
for a in arms_list
if (a.get("gate1_substrate_and_differentiation") or {}).get("canonical_differentiation_stage_evaluated")
})
for edge in doc.get("causal_mechanism_edges", []):
u = edge["upstream_node"]
v = edge["downstream_node"]
ev_text = f"{u} {v} {edge.get('evidence_source', '')}".lower().replace("β", "beta").replace("α", "alpha").replace("δ", "delta").replace("γ", "gamma")
matched_source = arm_sources[0] if len(arm_sources) == 1 else None
matched_stage = arm_stages[0] if len(arm_stages) == 1 else None
has_rodent_token = any(
k in ev_text
for k in ("c57bl/6", "c57bl6", "mouse", "mice", "murine", "rodent", "rat ", "rats", "nod/scid", "nsg", "balb/c", "nod ")
)
has_explicit_rodent_target = any(
k in ev_text
for k in (
"murine beta", "mouse beta", "murine islet", "mouse islet", "rat islet", "rat beta",
"rodent islet", "rodent beta", "min6", "ins-1", "nit-1", "beta-tc",
)
)
has_explicit_human_target = any(
k in ev_text
for k in (
"sc-islet", "sc-beta", "psc-islet", "ipsc", "hipsc", "hesc", "hues8", "cyt49", "mel1",
"human beta", "human islet", "human sc-", "patient-derived", "cadaveric", "t1d sc-", "znt8 lof sc-",
)
)
has_human_effector = any(
k in ev_text
for k in ("human nk", "human pbmc", "human t cell", "human cd8", "human cd4", "human macrophage", "humanized")
)
has_rodent_effector = any(
k in ev_text
for k in ("mouse nk", "murine nk", "mouse t cell", "murine t cell", "mouse splenocyte", "murine splenocyte", "mouse macrophage")
)
has_human_reagent = any(
k in ev_text
for k in ("human interferon", "human ifn", "human il-", "human tnf", "human cytokine")
)
has_rodent_host = any(
k in ev_text
for k in (
"in mice", "into mice", "in nsg", "nsg mice", "nod/scid", "diabetic mice",
"recipient mice", "grafted mice", "transplanted in mice", "transplanted into mice",
"prevent diabetes in mice", "mice grafted", "animals transplanted",
)
)
has_generic_human = "human" in ev_text and not (has_explicit_rodent_target and (has_human_effector or has_human_reagent))
has_human_target = has_explicit_human_target or (has_generic_human and not has_explicit_rodent_target)
if has_explicit_rodent_target and has_explicit_human_target:
target_cell_species = "Human_and_Rodent_Mixed_Context"
matched_source = matched_source or ("Multi_Arm_Mixed_Context:" + "|".join(arm_sources) if arm_sources else "Human_and_Rodent_Mixed_Context")
matched_stage = matched_stage or "Mixed_Human_and_Rodent_Assay"
elif (has_explicit_rodent_target or has_rodent_token) and not has_human_target:
target_cell_species = "Rodent_or_Murine"
matched_source = "Rodent_or_Murine_Sentence_Specific_Context"
matched_stage = "InVivo_or_ExVivo_Rodent_Assay"
else:
target_cell_species = (
"Human"
if (
has_human_target
or any(
s
in (
"Primary_Human_Islet",
"iPSC_healthy_donor",
"iPSC_T1D_patient",
"iPSC_T1D_or_LADA_patient",
"CiPSC_chemically_induced",
"hPSC_Derived_Unspecified_Line",
"hESC",
)
for s in arm_sources
)
)
else ("NHP" if "NHP_Primary_Islet" in arm_sources else "Unspecified")
)
if len(arm_sources) > 1:
if any(k in ev_text for k in ("rhesus", "macaque", "cynomolgus", "nhp", "monkey")) and "NHP_Primary_Islet" in arm_sources:
matched_source = "NHP_Primary_Islet"
elif any(k in ev_text for k in ("sc-islet", "sc-beta", "ipsc", "hipsc")) and "iPSC_healthy_donor" in arm_sources:
matched_source = "iPSC_healthy_donor"
elif any(k in ev_text for k in ("hesc", "hues8", "cyt49")) and "hESC" in arm_sources:
matched_source = "hESC"
else:
matched_source = "Multi_Arm_Mixed_Context:" + "|".join(arm_sources)
host_recipient_species = (
"Rodent_or_Murine"
if (has_rodent_host or (has_rodent_token and target_cell_species == "Human" and not has_rodent_effector))
else ("NHP" if any(k in ev_text for k in ("rhesus", "macaque", "cynomolgus", "baboon")) else "InVitro_or_Same_As_Target")
)
immune_effector_species = (
"Human"
if has_human_effector
else ("Rodent_or_Murine" if has_rodent_effector else "Unspecified_or_Abiotic")
)
reagent_species = "Human" if has_human_reagent else "Unspecified"
if len(arm_stages) > 1 and matched_stage is None:
matched_stage = "Multi_Arm_Mixed_Stage:" + "|".join(arm_stages)
edge_ctx = {
"cell_source_class": matched_source,
"target_cell_species": target_cell_species,
"host_recipient_species": host_recipient_species,
"immune_effector_species": immune_effector_species,
"reagent_species": reagent_species,
"canonical_differentiation_stage_evaluated": matched_stage,
"study_arm_cell_source_classes": arm_sources,
"study_arm_differentiation_stages": arm_stages,
"max_biological_fidelity_tier": meta.get("max_biological_fidelity_tier"),
"epistemic_class": "Sentence_Heuristic_Candidate_Association",
}
u_concepts = extract_canonical_concepts(u)
v_concepts = extract_canonical_concepts(v)
for c in sorted(set(u_concepts + v_concepts)):
concept_to_studies[c].add(label)
concept_to_evidence[c].append({
"study": label,
"role": "causal_edge",
"statement": f"{u} --[{edge['causal_relation']}]--> {v}",
})
edges_all.append({
"study": label,
"study_context": edge_ctx,
"upstream_node": u,
"upstream_concepts": u_concepts,
"causal_relation": edge["causal_relation"],
"downstream_node": v,
"downstream_concepts": v_concepts,
"evidence_source": edge["evidence_source"],
})
bridges = doc.get("cross_study_discovery_bridges", {})
for pfind in bridges.get("collateral_and_pleiotropic_findings", []):
pleiotropic_bonuses.append({"study": label, **pfind})
for c in extract_canonical_concepts(pfind.get("observation", "")):
concept_to_studies[c].add(label)
concept_to_evidence[c].append({
"study": label,
"role": f"pleiotropy ({pfind.get('is_beneficial_synergy_or_deleterious_tradeoff')})",
"statement": pfind.get("observation", ""),
})
for rvec in bridges.get("residual_failure_and_escape_vectors", []):
residual_escapes.append({"study": label, **rvec})
for c in extract_canonical_concepts(
f"{rvec.get('residual_loss_or_limitation', '')} {rvec.get('escape_mechanism_identified', '')}"
):
concept_to_studies[c].add(label)
concept_to_evidence[c].append({
"study": label,
"role": "residual_bottleneck",
"statement": rvec.get("residual_loss_or_limitation", ""),
})
for rthresh in bridges.get("regime_thresholds", []):
regime_thresholds.append({"study": label, **rthresh})
shared_bridge_nodes = {
k: {
"studies_count": len(v),
"studies": sorted(list(v)),
"linked_mechanisms_and_bottlenecks": concept_to_evidence[k],
}