or any(v is not None for v in (_pe, _ci_lo, _ci_hi)) ) if isinstance(_cm_type, str) and _cm_type.startswith("between_arm_comparative_") and c_id is None: raise ValueError(f"{eid}: comparative contrast_type {_cm_type!r} requires non-null comparator_arm_id") if _requires_ci_comp: if c_id is None: raise ValueError(f"{eid}: comparative adjusted-difference / CI effect requires non-null comparator_arm_id") if stat_type == "adjusted_mean_difference_with_95ci_and_pvalue" and any(v is None for v in (_pe, _ci_lo, _ci_hi)): raise ValueError(f"{eid}: adjusted_mean_difference_with_95ci_and_pvalue requires non-null point_estimate, ci_95_lower, and ci_95_upper") if _ci_lo is not None and _ci_hi is not None: if float(_ci_lo) > float(_ci_hi): raise ValueError(f"{eid}: reversed 95% CI bounds ({_ci_lo} > {_ci_hi})") if float(_ci_lo) == float(_ci_hi): raise ValueError(f"{eid}: degenerate 95% CI bounds (ci_95_lower == ci_95_upper == {_ci_lo}; strict interior required)") if _pe is not None and _ci_lo is not None and _ci_hi is not None: if not (float(_ci_lo) <= float(_pe) <= float(_ci_hi)): raise ValueError(f"{eid}: point_estimate {_pe} lies outside [ci_95_lower={_ci_lo}, ci_95_upper={_ci_hi}]") if float(_pe) == float(_ci_lo) or float(_pe) == float(_ci_hi): raise ValueError(f"{eid}: point_estimate {_pe} equals a 95% CI endpoint ({_ci_lo}, {_ci_hi}); strict interior required") if c_id is not None: if _cm_type in ("between_arm_comparative_adjusted_difference", "between_arm_comparative_descriptive"): if c_id not in arms_by_id: raise ValueError(f"{eid}: comparative non-LRR effect missing valid comparator_arm_id {c_id!r}") if c_id == f_id: raise ValueError(f"{eid}: self-referential comparator_arm_id {c_id!r}") if arms_by_id[f_id].get("is_reference_control", False) or not arms_by_id[c_id].get("is_reference_control", False): raise ValueError(f"{eid}: comparative non-LRR effect requires treatment focal arm and reference-control comparator arm") _cm_clab = str((eff.get("contrast_metadata") or {}).get("comparator_label") or "").strip() _arm_clab = str(arms_by_id[c_id].get("arm_label") or "").strip() if _cm_clab and _arm_clab and not _cm_clab.startswith("[REDACTED_") and not _arm_clab.startswith("[REDACTED_"): _c_stop = {"the", "and", "for", "with", "from", "control", "cohort", "placebo", "matched", "reference", "comparator", "condition", "between", "arm", "group", "groups", "islet", "islets", "cells", "in", "of", "to", "a", "an", "or", "vs", "negative"} _t_cm = {t for t in re.findall(r"[a-z0-9]{3,}", _cm_clab.lower()) if t not in _c_stop} _t_arm = {t for t in re.findall(r"[a-z0-9]{3,}", _arm_clab.lower()) if t not in _c_stop} if _t_cm and _t_arm and not (_t_cm & _t_arm): raise ValueError(f"{eid}: comparator_arm_id {c_id!r} arm_label {_arm_clab!r} conflicts with contrast_metadata.comparator_label {_cm_clab!r}") else: raise ValueError(f"{eid}: non-comparative effect must have comparator_arm_id=None, got {c_id!r}") if stat_type in ("log_response_ratio_paired_means", "log_response_ratio_fold_change", "standardized_mean_difference"): raise ValueError(f"{eid}: null LRR cannot have comparative statistic_type {stat_type!r}") if eff.get("verbatim_evidence_quote") is None and eff.get("source_span") is None: # Permitted strictly on Citation_Only_No_Abstract_Indexed with abstract_indexed=False # (already enforced by validate_record_quote_and_locator_provenance above). q = "" else: span = eff.get("source_span") or "" m_sp = re.match( r"^(abstract|title|fulltext_data_sections\.(results_paragraphs|figure_legends|methods_paragraphs)\[(\d+)\](\.caption)?)\[(\d+):(\d+)\]\|norm=(exact|whitespace_normalized)$", span, ) if not m_sp: raise ValueError(f"{eid}: invalid source_span format {span!r}") sec_path, sec_kind, sec_idx, _, s_idx, e_idx, norm_mode = m_sp.groups() s_i, e_i = int(s_idx), int(e_idx) if sec_path == "abstract": sec_txt = source_dossier.get("abstract") or "" elif sec_path == "title": sec_txt = source_dossier.get("title") or "" elif sec_kind == "results_paragraphs": sections = source_ft.get("results_paragraphs", []) if not isinstance(sections, list) or int(sec_idx) >= len(sections): raise ValueError(f"{eid}: source_span section index is outside the declared source") sec_txt = sections[int(sec_idx)] elif sec_kind == "figure_legends": sections = source_ft.get("figure_legends", []) if not isinstance(sections, list) or int(sec_idx) >= len(sections) or not isinstance(sections[int(sec_idx)], dict): raise ValueError(f"{eid}: source_span figure index is outside the declared source") sec_txt = sections[int(sec_idx)].get("caption") or "" else: sections = source_ft.get("methods_paragraphs", []) if not isinstance(sections, list) or int(sec_idx) >= len(sections): raise ValueError(f"{eid}: source_span section index is outside the declared source") sec_txt = sections[int(sec_idx)] if not isinstance(sec_txt, str) or not 0 <= s_i < e_i <= len(sec_txt): raise ValueError(f"{eid}: source_span offsets are outside the declared source field") sliced = sec_txt[s_i:e_i] q = eff.get("verbatim_evidence_quote") or "" if norm_mode == "exact": if sliced != q: raise ValueError(f"{eid}: exact source_span slice mismatch") else: if re.sub(r"\s+", " ", sliced).strip() != re.sub(r"\s+", " ", q).strip(): raise ValueError(f"{eid}: normalized source_span slice mismatch") if not q.startswith("[REDACTED_") and f_id in arms_by_id: _flab_chk = str(arms_by_id[f_id].get("arm_label") or "") if not _flab_chk.startswith("[REDACTED_"): _q_toks = _tok_text(q) _y_str = str(eff.get("outcome_variable_Y") or "") _y_unredacted = "" if (_y_str.startswith("[REDACTED_") or (_y_str.startswith("[Endpoint: ") and " | polarity=" in _y_str)) else _y_str _ev_y_toks = _q_toks | _tok_text(_y_unredacted) _y_figs, _y_tabs = _fig_table_refs(_y_unredacted) _f_figs, _f_tabs = _figs_by_arm.get(f_id, (set(), set())) if (_y_figs and _f_figs and _y_figs.isdisjoint(_f_figs)) or (_y_tabs and _f_tabs and _y_tabs.isdisjoint(_f_tabs)): raise ValueError(f"{eid}: focal_arm_id {f_id!r} figure/table ref (figs={sorted(_f_figs)}, tabs={sorted(_f_tabs)}) conflicts with outcome_variable_Y ref (figs={sorted(_y_figs)}, tabs={sorted(_y_tabs)})") if c_id is not None: _c_figs, _c_tabs = _figs_by_arm.get(c_id, (set(), set())) if (_y_figs and _c_figs and _y_figs.isdisjoint(_c_figs)) or (_y_tabs and _c_tabs and _y_tabs.isdisjoint(_c_tabs)): raise ValueError(f"{eid}: comparator_arm_id {c_id!r} figure/table ref (figs={sorted(_c_figs)}, tabs={sorted(_c_tabs)}) conflicts with outcome_variable_Y ref (figs={sorted(_y_figs)}, tabs={sorted(_y_tabs)})") if len(_focal_arm_ids) >= 2 and f_id in _disc_focal: _f_q_hits = _tok_matches(_disc_focal[f_id], _q_toks) _other_f_q = {_of: sorted(_tok_matches(_uniq_focal[_of], _q_toks)) for _of in _focal_arm_ids if _of != f_id and _tok_matches(_uniq_focal[_of], _q_toks)} if not _f_q_hits and _other_f_q: raise ValueError(f"{eid}: verbatim_evidence_quote conflicts with focal_arm_id {f_id!r} (matches other focal arm(s) {_other_f_q})") if c_id is not None: _f_ev_hits = _tok_matches(_disc_focal[f_id], _ev_y_toks) _other_f_ev = {_of: sorted(_tok_matches(_uniq_focal[_of], _ev_y_toks)) for _of in _focal_arm_ids if _of != f_id and _tok_matches(_uniq_focal[_of], _ev_y_toks)} if not _f_ev_hits and _other_f_ev: raise ValueError(f"{eid}: outcome/quote cohort tokens conflict with focal_arm_id {f_id!r} (matches other focal arm(s) {_other_f_ev})") if c_id is not None and c_id in arms_by_id: _clab_chk = str(arms_by_id[c_id].get("arm_label") or "") if not _clab_chk.startswith("[REDACTED_"): _fncts = set(re.findall(r"\bnct\d{8}\b", _flab_chk.lower())) _cncts = set(re.findall(r"\bnct\d{8}\b", _clab_chk.lower())) if _fncts and _cncts and _fncts.isdisjoint(_cncts): raise ValueError(f"{eid}: cross-trial comparator_arm_id {c_id!r} ({sorted(_cncts)}) mismatches focal_arm {f_id!r} ({sorted(_fncts)})") if len(_ref_arm_ids) >= 2: _ev_ctx = _toks_by_arm[f_id] | _q_toks _c_hits = _tok_matches(_uniq_ref[c_id], _ev_ctx) _better_refs = {_rc: sorted(_tok_matches(_uniq_ref[_rc], _ev_ctx)) for _rc in _ref_arm_ids if _rc != c_id and _tok_matches(_uniq_ref[_rc], _ev_ctx)} _q_comp = _q_toks - _toks_by_arm[f_id] _c_q_hits = _tok_matches(_uniq_ref[c_id], _q_comp) _better_q_refs = {_rc: sorted(_tok_matches(_uniq_ref[_rc], _q_comp)) for _rc in _ref_arm_ids if _rc != c_id and _tok_matches(_uniq_ref[_rc], _q_comp)} if not _c_q_hits and _better_q_refs: raise ValueError(f"{eid}: verbatim_evidence_quote conflicts with comparator_arm_id {c_id!r} (matches other comparator arm(s) {_better_q_refs})") if not _c_hits and _better_refs: raise ValueError(f"{eid}: comparator_arm_id {c_id!r} cross-wired/conflicts with focal_arm {f_id!r} / quote (better comparator(s): {_better_refs})") if len(_focal_arm_ids) >= 2 and not _c_hits: _other_f_c = {_of: sorted(_tok_matches(_uniq_ref[c_id], _toks_by_arm[_of])) for _of in _focal_arm_ids if _of != f_id and _tok_matches(_uniq_ref[c_id], _toks_by_arm[_of])} if _other_f_c: raise ValueError(f"{eid}: comparator_arm_id {c_id!r} cross-wired to other focal arm(s) {_other_f_c}, not {f_id!r}") if not q.startswith("[REDACTED_"): _q_norm_ci = re.sub(r"(\d)\u00b7(\d)", r"\1.\2", q or "").replace("\u2212", "-") _q_no_p = re.sub(r"(?i)\bp\s*(?:<=|>=|<|>|=|\u2264|\u2265)\s*[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?", " ", _q_norm_ci) for _ci_fn in ("point_estimate", "ci_95_lower", "ci_95_upper"): _ci_v = eff.get(_ci_fn) if _ci_v is not None and not _num_in_quote(_ci_v, _q_no_p, _ci_fn): raise ValueError(f"{eid}: {_ci_fn}={_ci_v!r} is grounded only inside a p-value clause or absent outside p-value in verbatim_evidence_quote") _ci_lo_q = eff.get("ci_95_lower") _ci_hi_q = eff.get("ci_95_upper") if _ci_lo_q is not None and _ci_hi_q is not None: _ci_spans = [ (float(_m_ci.group(1)), float(_m_ci.group(2))) for _m_ci in re.finditer( r"(?:95%\s*CI\s*:?\s*|\(\s*)([+-]?\d+(?:\.\d+)?)\s*(?:to|[\-\u2013\u2014])\s*([+-]?\d+(?:\.\d+)?)", _q_no_p, flags=re.IGNORECASE, ) ] if _ci_spans and not any(abs(float(_ci_lo_q) - _lo) <= 1e-6 and abs(float(_ci_hi_q) - _hi) <= 1e-6 for _lo, _hi in _ci_spans): raise ValueError(f"{eid}: 95% CI [{_ci_lo_q}, {_ci_hi_q}] does not match parsed CI span(s) {_ci_spans} in verbatim_evidence_quote") for fn in ("point_estimate", "ci_95_lower", "ci_95_upper", "treatment_mean", "control_mean", "treatment_sd_or_sem", "control_sd_or_sem", "treatment_n", "control_n", "p_value"): fval = eff.get(fn) if fval is not None and not _num_in_quote(fval, q, fn): raise ValueError(f"{eid}: numeric field {fn}={fval!r} is not grounded in verbatim_evidence_quote") p_tokens = _pvalue_tokens(re.sub(r"level of significance set at\s+[pP]\s*[<=>≤≥]\s*0?\.\d+", "", q, flags=re.IGNORECASE)) relation, bound = (p_tokens[0] if len(p_tokens) == 1 else (None, None)) if eff.get("p_value_relation") != relation or eff.get("p_value_bound") != (float(bound) if bound is not None else None): raise ValueError(f"{eid}: p-value relation/bound does not match its source token") if relation not in (None, "=") and eff.get("p_value") is not None: raise ValueError(f"{eid}: inequality p-value cannot be stored as exact p_value") if relation == "=" and (eff.get("p_value") is None or eff.get("p_value_bound") is None or abs(float(eff["p_value"]) - float(eff["p_value_bound"])) > 1e-12): raise ValueError(f"{eid}: exact p_value {eff.get('p_value')!r} disagrees with p_value_bound {eff.get('p_value_bound')!r}") if isinstance(stat_type, str) and stat_type.endswith(("_and_pvalue", "_with_pvalue")) and not q.startswith("[REDACTED_"): if relation != "=" or eff.get("p_value") is None: raise ValueError(f"{eid}: {stat_type} requires a grounded exact p-value (relation='=') and non-null exact p_value, got relation={relation!r}, p_value={eff.get('p_value')!r}") for n_fn in ("treatment_n", "control_n"): n_val = eff.get(n_fn) if n_val is not None and (not isinstance(n_val, (int, float)) or n_val <= 0 or n_val > 100000): raise ValueError(f"{eid}: implausible sample size {n_fn}={n_val!r}") def extract_atomic_effects_and_modifiers( pmid: str, dossier: dict[str, Any], study_edits: list[dict[str, Any]], cell_source: str, stage: str, transplant_site: str, tier: str, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], dict[str, Any]]: ft = _get_effective_fulltext_sections(pmid, dossier) title = dossier.get("title") or "" authors = dossier.get("authors") or [] first_author = dossier.get("first_author") or (authors[0] if authors else "") pub_year = dossier.get("pub_year") or 2020 dossier_sha = _compute_dossier_sha256(pmid, dossier) candidate_sentences: list[tuple[str, str]] = [] def _trim_quote(s: str) -> str: st = s.strip() if len(st) > 345: return st[:340].rsplit(" ", 1)[0].strip() return st for fig in ft.get("figure_legends", []): lbl = fig.get("label") or "Figure" cap = fig.get("caption") or "" for s in re.split(r"(?<=[.!])\s+", cap): if 45 <= len(s) <= 480: candidate_sentences.append((lbl, _trim_quote(s))) for idx, rpara in enumerate(ft.get("results_paragraphs", []), 1): for s in re.split(r"(?<=[.!])\s+", rpara): if 45 <= len(s) <= 480: candidate_sentences.append((f"Results para {idx}", _trim_quote(s))) abstract = dossier.get("abstract") or "" for s in re.split(r"(?<=[.!])\s+", abstract): if 40 <= len(s) <= 480: candidate_sentences.append(("Abstract", _trim_quote(s))) atomic_effects: list[dict[str, Any]] = [] modifier_interactions: list[dict[str, Any]] = [] causal_edges: list[dict[str, Any]] = [] residual_vectors: list[dict[str, Any]] = [] pleiotropic_findings: list[dict[str, Any]] = [] regime_thresholds: list[dict[str, Any]] = [] quant_pat = re.compile( r"(\b\d+\.?\d*\s*%|\b\d+\.?\d*\s*(?:-|\s)?fold|\bp\s*[=<]\s*0\.\d+|\bn\s*=\s*\d+|\b\d+\.?\d*\s*(?:±|\+/-|\+-)\s*\d+\.?\d*|" r"\bsignificant\w*\b|\bincreas\w+|\bdecreas\w+|\breduc\w+|\bprotect\w+|\bsurviv\w+|\bevad\w+|\babrogat\w+|\binhibit\w+|" r"\bdestr\w+|\bdamag\w+|\breject\w*|\bkilled\b|\bkilling\b|\bdeath\b|\bdied\b|\bfail\w*|\bnonfunction\w+|\bnecro\w+|\bdysfunction\w*|\bimpair\w+|\btoxic\w*|\blost\b|\bloss\b)", flags=re.IGNORECASE, ) modifier_pat = re.compile( r"\b(whereas|in contrast|however|unlike|only in|only when|dependent on|stage-specific|dose-dependent|failed to|in vitro versus in vivo|compared to|compared with|synerg\w+)\b", flags=re.IGNORECASE, ) seen_quotes = set() prev_sent: str | None = None candidate_sentences = [(label, clause) for label, sentence in candidate_sentences for clause in _target_bound_atomic_clauses(sentence, study_edits)] for src_label, sent in candidate_sentences: if sent in seen_quotes: prev_sent = sent continue if quant_pat.search(sent) and not is_stat_boilerplate(sent) and len(sent) != 350: seen_quotes.add(sent) pval, n_val = parse_pvalue_and_n(sent) domain = classify_outcome_domain(sent) sl = sent.lower() focal_x = identify_focal_factor(sent, study_edits, title) focal_genes = [e["gene_symbol_hgnc"] for e in study_edits if strict_gene_match(e["gene_symbol_hgnc"], focal_x)] target_gene = focal_genes[0] if len(focal_genes) == 1 else None