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…
for k, v in sorted(concept_to_studies.items(), key=lambda x: (-len(x[1]), x[0]))
if len(v) >= 2
}
target_gene_atlas = {
g: {
"studies_count": len(s_set),
"functional_gates": sorted(list(gene_to_gates[g])),
"studies": sorted(list(s_set)),
}
for g, s_set in sorted(gene_to_studies.items(), key=lambda x: (-len(x[1]), x[0]))
}
# Build Multi-Hop Cross-Study Causal Chains: Study A (Node_U -> Node_M) + Study B (Node_M -> Node_V)
# where Study A != Study B and Node_U != Node_M != Node_V
incoming_by_concept: dict[str, list[dict[str, Any]]] = defaultdict(list)
outgoing_by_concept: dict[str, list[dict[str, Any]]] = defaultdict(list)
for edge in edges_all:
u_nodes = sorted(set(edge["upstream_concepts"]))
v_nodes = sorted(set(edge["downstream_concepts"]))
for un in u_nodes:
for vn in v_nodes:
if un != vn:
outgoing_by_concept[un].append({"mid": vn, **edge})
incoming_by_concept[vn].append({"start": un, **edge})
TERMINAL_OUTCOME_ONLY_NODES = {
"BetaCell_Survival_and_Glycemic_Cure",
"Biphasic_GSIS_and_Calcium_Coupling",
"Alloreactive_CD8_CD4_TCell_or_DSA_Attack",
"Primary_NK_or_Macrophage_Innate_Cytotoxicity",
}
candidates_by_bridge: dict[str, list[dict[str, Any]]] = defaultdict(list)
seen_chains = set()
for mid_node, in_edges in sorted(incoming_by_concept.items()):
if mid_node in TERMINAL_OUTCOME_ONLY_NODES:
continue
out_edges = outgoing_by_concept.get(mid_node, [])
for e1 in in_edges[:25]:
for e2 in out_edges[:25]:
if e1["study"] == e2["study"]:
continue
v_end = e2["mid"]
if len({e1["start"], mid_node, v_end}) < 3:
continue
chain_key = (e1["start"], mid_node, v_end, e1["study"], e2["study"])
if chain_key in seen_chains:
continue
seen_chains.add(chain_key)
c1 = e1.get("study_context") or {}
c2 = e2.get("study_context") or {}
same_ctx = _has_matched_cell_source_and_stage(c1, c2)
candidates_by_bridge[mid_node].append({
"origin_node": e1["start"],
"hop1_study": e1["study"],
"hop1_relation": e1["causal_relation"],
"hop1_context": c1,
"bridge_node": mid_node,
"hop2_study": e2["study"],
"hop2_relation": e2["causal_relation"],
"hop2_context": c2,
"terminal_node": v_end,
"cross_context_compatibility_note": (
"Matched cell source and differentiation stage across Hop 1 and Hop 2"
if same_ctx
else "Cross-context hypothesis path (requires experimental validation across differing cell sources/stages/species)"
),
"hop1_evidence": e1["evidence_source"],
"hop2_evidence": e2["evidence_source"],
})
for mid_node, ch_list in candidates_by_bridge.items():
ch_list.sort(
key=lambda ch: (
0 if str(ch.get("cross_context_compatibility_note", "")).startswith("Matched cell source") else 1,
-(
len(concept_to_studies.get(ch["origin_node"], ()))
+ len(concept_to_studies.get(ch["bridge_node"], ()))
+ len(concept_to_studies.get(ch["terminal_node"], ()))
),
ch["origin_node"],
ch["terminal_node"],
ch["hop1_study"],
ch["hop2_study"],
)
)
untruncated_bridge_counts = {k: len(v) for k, v in sorted(candidates_by_bridge.items())}
chains_total_before_cap = sum(untruncated_bridge_counts.values())
multi_hop_chains = []
bridge_keys = sorted(candidates_by_bridge.keys())
rr_idx = 0
while len(multi_hop_chains) < 500:
added_in_round = False
for bk in bridge_keys:
if rr_idx < len(candidates_by_bridge[bk]):
multi_hop_chains.append(candidates_by_bridge[bk][rr_idx])
added_in_round = True
if len(multi_hop_chains) >= 500:
break
if not added_in_round:
break
rr_idx += 1
exported_bridge_counts: dict[str, int] = defaultdict(int)
for ch in multi_hop_chains:
exported_bridge_counts[ch["bridge_node"]] += 1
tier_counts: dict[str, int] = defaultdict(int)
source_type_counts: dict[str, int] = defaultdict(int)
direction_counts: dict[str, int] = defaultdict(int)
orientation_sign_counts: dict[str, int] = defaultdict(int)
penalty_effects_count = 0
exact_span_verified_count = 0
quantitative_lrr_count = 0
active_arms_count = 0
active_effects_count = 0
active_modifiers_count = 0
active_causal_edges_count = 0
non_superseded_arms_count = 0
non_superseded_effects_count = 0
non_superseded_modifiers_count = 0
non_superseded_causal_edges_count = 0
for doc in studies:
m = doc.get("study_metadata", {})
src_type = m.get("source_text_type", "")
is_sup = src_type == "Preprint_Superseded_By_Peer_Reviewed" or bool(m.get("superseded_by_pmid"))
if not is_sup:
non_superseded_arms_count += len(doc.get("arms", []))
non_superseded_effects_count += len(doc.get("atomic_effects", []))
non_superseded_modifiers_count += len(doc.get("effect_modifier_interactions", []))
non_superseded_causal_edges_count += len(doc.get("causal_mechanism_edges", []))
if is_sup or src_type in ("Project_Summary", "Citation_Only_No_Abstract_Indexed"):
continue
active_arms_count += len(doc.get("arms", []))
active_modifiers_count += len(doc.get("effect_modifier_interactions", []))
active_causal_edges_count += len(doc.get("causal_mechanism_edges", []))
tier_counts[str(m.get("max_biological_fidelity_tier", "Unknown"))] += 1
source_type_counts[str(src_type or "Unknown")] += 1
for eff in doc.get("atomic_effects", []):
active_effects_count += 1
direction_counts[str(eff.get("effect_direction", "Unknown"))] += 1
if (
eff.get("is_functional_or_developmental_penalty") is True
or eff.get("secretome_or_differentiation_penalty_observed") in (True, "True", "Borderline")
):
penalty_effects_count += 1
sp_val = eff.get("source_span")
if (isinstance(sp_val, dict) and sp_val.get("norm") == "exact") or ("norm=exact" in str(sp_val or "")):
exact_span_verified_count += 1
if eff.get("log_response_ratio_or_smd") is not None:
quantitative_lrr_count += 1
osign = (eff.get("endpoint_polarity_registry") or {}).get("orientation_sign")
if osign is not None:
orientation_sign_counts[str(osign)] += 1
matched_ctx_chains = sum(
1 for ch in multi_hop_chains
if str(ch.get("cross_context_compatibility_note", "")).startswith("Matched cell source")
)
active_studies_list = [
doc for doc in studies
if doc.get("study_metadata", {}).get("source_text_type") not in (
"Preprint_Superseded_By_Peer_Reviewed",
"Project_Summary",
"Citation_Only_No_Abstract_Indexed",
)
and not bool(doc.get("study_metadata", {}).get("superseded_by_pmid"))
]
review_pmids_dynamic = sorted(
str(doc["study_metadata"]["pmid"])
for doc in active_studies_list
if doc["study_metadata"].get("source_text_type") == "Review_or_Commentary"
or "review" in str((doc.get("screening_decision") or {}).get("exclusion_reason") or "").lower()
)
active_preprint_pmids_dynamic = sorted(
str(doc["study_metadata"]["pmid"])
for doc in active_studies_list
if any(
tok in str(doc["study_metadata"].get("journal") or "").lower()
for tok in ("biorxiv", "medrxiv", "preprint")
)
)
n_active_dedup = len(active_studies_list)
n_review_dyn = len(review_pmids_dynamic)
n_preprint_dyn = len(active_preprint_pmids_dynamic)
n_active_empirical = n_active_dedup - n_review_dyn
n_strict_peer_reviewed_empirical = n_active_dedup - n_review_dyn - n_preprint_dyn
graph_out = {
"schema_version": "0.2.0",
"validated_studies_count": len(studies),
"superseded_preprint_records_excluded_from_graph": superseded_preprint_records_excluded,
"project_summary_records_excluded_from_graph": project_summary_records_excluded,
"citation_only_records_excluded_from_graph": citation_only_records_excluded,
"review_records_excluded_from_graph": review_records_excluded,
"total_arms_extracted": total_arms,
"total_atomic_effects_extracted": total_atomic_effects,
"total_effect_modifier_interactions_extracted": total_modifier_interactions,
"total_causal_mechanism_edges_extracted": total_causal_edges,
"multi_hop_cross_study_causal_chains_count": len(multi_hop_chains),
"corpus_epistemic_and_fidelity_diagnostics": {
"active_deduplicated_studies_count": n_active_dedup,
"active_empirical_studies_count": n_active_empirical,
"non_superseded_studies_count": len(studies) - len(superseded_preprint_records_excluded),
"superseded_preprint_studies_excluded_count": len(superseded_preprint_records_excluded),
"project_summary_studies_excluded_count": len(project_summary_records_excluded),
"citation_only_studies_excluded_count": len(citation_only_records_excluded),
"review_studies_in_corpus_count": n_review_dyn,
"review_studies_pmids": review_pmids_dynamic,
"active_preprints_without_in_corpus_peer_reviewed_twin_pmids": active_preprint_pmids_dynamic,
"ring1_corpus_count_reconciliation": {
"validated_studies_total": len(studies),
"superseded_preprints_excluded": len(superseded_preprint_records_excluded),
"project_summaries_excluded": len(project_summary_records_excluded),
"citation_only_records_excluded": len(citation_only_records_excluded),
"non_superseded_studies_total": len(studies) - len(superseded_preprint_records_excluded),
"active_deduplicated_studies_total": n_active_dedup,
"review_records_flagged": n_review_dyn,
"active_preprints_without_in_corpus_twin_flagged": n_preprint_dyn,
"strict_active_peer_reviewed_empirical_studies_total": n_strict_peer_reviewed_empirical,
},
"active_deduplicated_arms_count": active_arms_count,
"active_deduplicated_effects_count": active_effects_count,
"active_deduplicated_modifier_interactions_count": active_modifiers_count,
"active_deduplicated_causal_edges_count": active_causal_edges_count,
"non_superseded_arms_count": non_superseded_arms_count,
"non_superseded_effects_count": non_superseded_effects_count,
"non_superseded_modifier_interactions_count": non_superseded_modifiers_count,
"non_superseded_causal_edges_count": non_superseded_causal_edges_count,
"studies_by_biological_fidelity_tier": dict(sorted(tier_counts.items())),
"studies_by_source_text_type": dict(sorted(source_type_counts.items())),
"exact_source_span_verified_effects_count": exact_span_verified_count,
"quantitative_lrr_effects_count": quantitative_lrr_count,
"heuristic_penalty_effects_count": penalty_effects_count,
"direction_and_penalty_method_counts": dict(Counter(
effect.get("direction_adjudication_method", "rule_based_heuristic")
for study in active_studies_list for effect in study.get("atomic_effects", [])
)),
"adjudication_semantics": "Rule-based heuristic extraction; no independent manual accuracy dataset is attached. Classifier agreement is not measured sensitivity or specificity.",
"adjudicated_penalty_effects_count": penalty_effects_count,
"deprecated_field_aliases": {
"adjudicated_penalty_effects_count": {
"alias_of": "heuristic_penalty_effects_count",
"reason": "Legacy label; these flags were not independently adjudicated accuracy observations."
}
},