dossier_blob_lower = ( str(dossier.get("title") or "") + " " + str(dossier.get("abstract") or "") + " " + " ".join(ft.get("results_paragraphs") or []) + " " + " ".join(ft.get("methods_paragraphs") or []) + " " + " ".join(str(x.get("caption") or "") for x in (ft.get("figure_legends") or [])) ).lower() immortal_or_hpsc_lines = { "HUES8", "H1", "WA01", "MEL1", "CyT49", "HEL46.11", "HEL24.3", "EndoC-βH1", "EndoC-betaH1", "EndoC-βH3", "NIT-1", "MIN6", "INS-1", "INS-1E", } for arm in doc.get("arms", []): aid = arm.get("arm_id") arm_n = arm.get("sample_size_n") if arm_n is not None: if not isinstance(arm_n, (int, float)) or isinstance(arm_n, bool) or arm_n <= 0 or arm_n > 100000: raise ValueError(f"{aid}: implausible arm sample_size_n={arm_n!r}") if dossier.get("abstract") and not _num_in_quote(arm_n, dossier_blob_lower, "sample_size_n"): raise ValueError(f"{aid}: arm sample_size_n={arm_n!r} is not grounded in source dossier") g1 = arm.get("gate1_substrate_and_differentiation") or {} sc = g1.get("cell_source_class") cl = g1.get("cell_line_id") csl_extra = str(arm.get("cell_source_or_line") or "") cl_str = f"{cl or ''} {csl_extra}".strip() cl_up = cl_str.upper() if cl == "H1": if sc != "hESC" or not re.search( r"\b(?:h1\s+hescs?|h1\s+escs?|h1\s+cells?|h1\s+line|wa01|h1/h9|h9\s+and\s+h1)\b", dossier_blob_lower, ): raise ValueError(f"{aid}: cell_line_id='H1' not supported by standalone hESC H1/WA01 context in dossier") if sc in ("Primary_Human_Islet", "NHP_Primary_Islet", "Rodent_Primary_Islet", "Unspecified_In_Source_Abstract") and ( cl in immortal_or_hpsc_lines or any(tok in cl_up for tok in ("HUES8", "WA01", "H9", "WA09", "MEL1", "CYT49", "ENDOC", "NIT-1", "MIN6", "INS-1")) or re.search(r"\bH1\b", cl_up) ): raise ValueError(f"{aid}: primary/unspecified cell_source_class {sc!r} cannot have immortalized/hPSC cell_line_id {cl_str!r}") if sc in ("iPSC_healthy_donor", "iPSC_T1D_or_LADA_patient", "CiPSC_chemically_induced") and ( cl in ("HUES8", "WA01", "H1", "MEL1", "CyT49") or (any(tok in cl_up for tok in ("HUES8", "WA01", "MEL1", "CYT49")) and "IPSC" not in cl_up) or (re.search(r"\bH1\b", cl_up) and "IPSC" not in cl_up) ): raise ValueError(f"{aid}: iPSC cell_source_class {sc!r} cannot have canonical hESC cell_line_id {cl_str!r}") if sc == "Rodent_Beta_Cell_Line_NIT1_MIN6_INS1" and ( cl in ("HUES8", "WA01", "H1", "H9", "WA09", "MEL1", "CyT49", "EndoC-βH1", "EndoC-betaH1", "EndoC-βH3") or any(tok in cl_up for tok in ("HUES8", "WA01", "WA09", "MEL1", "CYT49", "ENDOC", "HESC", "IPSC")) or re.search(r"\bH[19]\b", cl_up) ): raise ValueError(f"{aid}: rodent cell_source_class {sc!r} cannot have human hPSC/EndoC cell_line_id {cl_str!r}") if sc in ("iPSC_healthy_donor", "iPSC_T1D_or_LADA_patient", "CiPSC_chemically_induced", "hESC", "hPSC_Derived_Unspecified_Line") and ( cl in ("EndoC-βH1", "EndoC-betaH1", "EndoC-βH3", "NIT-1", "MIN6", "INS-1", "INS-1E") or any(tok in cl_up for tok in ("NIT-1", "MIN6", "INS-1")) or ("ENDOC" in cl_up and "IPSC" not in cl_up and "HESC" not in cl_up) ): raise ValueError(f"{aid}: hPSC cell_source_class {sc!r} cannot have immortalized beta-cell line {cl_str!r}") expected_polarity_map = { "Higher_Is_Better_Protective_Endpoint": 1, "Lower_Is_Better_Hazard_Endpoint": -1, "Qualitative_or_Unoriented_Endpoint": 0, } _subtrial_stop = { "pmid", "arm", "arms", "ctrl", "ref", "control", "controls", "cohort", "cohorts", "placebo", "matched", "reference", "comparator", "vehicle", "saline", "untreated", "daily", "monthly", "weekly", "systemic", "oral", "human", "murine", "mouse", "mice", "rat", "rats", "islet", "islets", "graft", "grafts", "cell", "cells", "cluster", "clusters", "group", "groups", "with", "without", "and", "the", "for", "from", "only", "alone", "overall", "primary", "adult", "wild", "type", "transgenic", "model", "models", "assay", "vitro", "vivo", "comparison", "baseline", "treated", "treatment", "therapy", "negative", "positive", "expressing", "full", "length", "table", "fig", "figure", "contrast", "blocking", "stimulated", "exposed", "variant", "variants", "fragment", "recombinant", "recombinants", "carrying", "lacking", "plus", "minus", "not", "all", "high", "low", "derived", "macrophage", "macrophages", "bone", "marrow", "c57bl", "bmdm", "porcine", "aortic", "endothelial", "paec", "liposome", "liposomes", "depleted", "intact", "autologous", "tpiat", "patients", "patient", "sequentially", "site", "sites", "supplementary", "extended", "data", "threshold", "dual", "over", "under", "after", "before", "during", "within", "between", "into", "onto", "than", "that", "this", "were", "have", "been", "showed", "overexpression", "expression", "knockout", "double", "single", } _short_domain_toks = {"wt", "ko", "ki", "tg", "c3", "c5", "5e", "6f", "d7", "o2", "h2"} def _tok_text(text: str) -> set[str]: low = (text or "").lower().replace("\u03b2", "beta") toks = set() if "primary human" in low or "primary adult human" in low: toks.add("primaryhuman") for t in re.findall(r"[a-z0-9]+", low): if t.isdigit(): continue if (len(t) >= 3 or t in _short_domain_toks) and t not in _subtrial_stop: toks.add(t) return toks def _arm_disc_tokens(arm_obj: dict[str, Any]) -> set[str]: aid_clean = re.sub(r"^pmid\d+_arm\d+_?", "", str(arm_obj.get("arm_id") or "").lower()) raw_lbl = str(arm_obj.get("arm_label") or "") if raw_lbl.startswith("[REDACTED_"): raw_lbl = "" toks = _tok_text(f"{aid_clean} {raw_lbl}") for t in list(toks): if "gtko" in t: toks.add("gtko") if "hcd64" in t: toks.add("hcd64") if "hiapp" in t: toks.add("hiapp") return toks def _tok_matches(tset_a: set[str], tset_b: set[str]) -> set[str]: hits = set() for a in tset_a: if a in tset_b: hits.add(a) continue if len(a) >= 5 and a.isalpha(): for b in tset_b: if len(b) >= 5 and b.isalpha() and (a.startswith(b) or b.startswith(a)): hits.add(a) break return hits _focal_arm_ids = [a["arm_id"] for a in doc.get("arms", []) if not a.get("is_reference_control", False)] _ref_arm_ids = [a["arm_id"] for a in doc.get("arms", []) if a.get("is_reference_control", False)] def _fig_table_refs(text: str) -> tuple[set[str], set[str]]: low = (text or "").lower() figs: set[str] = set() tabs: set[str] = set() for _m_ft in re.finditer(r"\b(figs?|figures?|tables?)\.?\s*((?:[0-9]+[a-z]?|[ivxlcdm]+)(?:\s*(?:,\s*and|,|and)\s*(?:[0-9]+[a-z]?|[ivxlcdm]+))*)", low): _dest = tabs if _m_ft.group(1).startswith("table") else figs for _tok in re.findall(r"[0-9]+[a-z]?|[ivxlcdm]+", _m_ft.group(2)): if _tok != "and": _dest.add(_tok) return figs, tabs _toks_by_arm = {aid: _arm_disc_tokens(a) for aid, a in arms_by_id.items()} _figs_by_arm = {aid: (_fig_table_refs(str(a.get("arm_label") or "")) if not str(a.get("arm_label") or "").startswith("[REDACTED_") else (set(), set())) for aid, a in arms_by_id.items()} _univ_focal = set.intersection(*(_toks_by_arm[fid] for fid in _focal_arm_ids)) if len(_focal_arm_ids) >= 2 else set() _disc_focal = {fid: _toks_by_arm[fid] - _univ_focal for fid in _focal_arm_ids} _uniq_focal = { fid: _toks_by_arm[fid] - (set().union(*(_toks_by_arm[o] for o in _focal_arm_ids if o != fid)) if len(_focal_arm_ids) > 1 else set()) for fid in _focal_arm_ids } _uniq_ref = { rid: _toks_by_arm[rid] - (set().union(*(_toks_by_arm[o] for o in _ref_arm_ids if o != rid)) if len(_ref_arm_ids) > 1 else set()) for rid in _ref_arm_ids } for eff in doc.get("atomic_effects", []): eid = eff.get("effect_id") f_id = eff.get("focal_arm_id") c_id = eff.get("comparator_arm_id") lrr = eff.get("log_response_ratio_or_smd") t_mean = eff.get("treatment_mean") c_mean = eff.get("control_mean") stat_type = eff.get("statistic_type") direction = eff.get("effect_direction") if f_id not in arms_by_id: raise ValueError(f"{eid}: focal_arm_id {f_id!r} not in arms") # Bind source identifier, bytes, digest and span as one provenance tuple. source_pmid = str(eff.get("quote_source_dossier_pmid") or "") allowed_sources = {pmid} if pmid in PEER_REVIEWED_TO_PREPRINT_MAP: allowed_sources.add(str(PEER_REVIEWED_TO_PREPRINT_MAP[pmid])) if source_pmid not in allowed_sources: raise ValueError(f"{eid}: quote_source_dossier_pmid {source_pmid!r} is not an allowed source for {pmid}") source_dossier = dossier source_raw_bytes: bytes | None = None if source_pmid != pmid: source_path = DOSSIER_DIR / f"{source_pmid}.json" if not source_path.exists(): raise ValueError(f"{eid}: declared source dossier {source_pmid} is missing") source_raw_bytes = source_path.read_bytes() source_dossier = json.loads(source_raw_bytes.decode("utf-8")) if str(source_dossier.get("pmid") or "") != source_pmid: raise ValueError(f"{eid}: declared source dossier body PMID mismatch") source_ft = source_dossier.get("fulltext_data_sections") or {} source_sha = ( hashlib.sha256(source_raw_bytes).hexdigest() if source_raw_bytes is not None else _compute_dossier_sha256(source_pmid, source_dossier) ) _f_coh = arms_by_id[f_id].get("cohort_id") _c_coh = arms_by_id[c_id].get("cohort_id") if c_id in arms_by_id else None _cm_coh = (eff.get("contrast_metadata") or {}).get("cohort_id") for _coh_val in (_f_coh, _c_coh, _cm_coh): if _coh_val is not None: _m_coh = re.fullmatch(r"pmid([1-9][0-9]{0,8})_cohort[1-9][0-9]{0,3}", str(_coh_val)) if _m_coh is None or _m_coh.group(1) != pmid: raise ValueError(f"{eid}: invalid or cross-study cohort_id {_coh_val!r} for PMID {pmid}") if c_id is not None and _f_coh and _c_coh and _f_coh != _c_coh: raise ValueError(f"{eid}: cohort_id mismatch between focal_arm {f_id!r} ({_f_coh!r}) and comparator_arm {c_id!r} ({_c_coh!r})") if _cm_coh and _f_coh and _cm_coh != _f_coh: raise ValueError(f"{eid}: contrast_metadata.cohort_id {_cm_coh!r} conflicts with focal_arm {f_id!r} ({_f_coh!r})") if _cm_coh and c_id is not None and _c_coh and _cm_coh != _c_coh: raise ValueError(f"{eid}: contrast_metadata.cohort_id {_cm_coh!r} conflicts with comparator_arm {c_id!r} ({_c_coh!r})") if eff.get("dossier_sha256") != source_sha: raise ValueError(f"{eid}: dossier_sha256 does not match declared source {source_pmid}") pol = eff.get("endpoint_polarity_registry") if not isinstance(pol, dict): raise ValueError(f"{eid}: missing endpoint_polarity_registry dict") p_class = pol.get("polarity_class") orient = pol.get("orientation_sign") if not isinstance(p_class, str) or p_class not in expected_polarity_map or type(orient) is not int or orient != expected_polarity_map[p_class]: raise ValueError( f"{eid}: orientation_sign {orient!r} does not match polarity_class {p_class!r} (expected {expected_polarity_map.get(p_class)!r})" ) if isinstance(lrr, (int, float)) and not isinstance(lrr, bool): if c_id is None or c_id not in arms_by_id: raise ValueError(f"{eid}: numeric LRR 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): raise ValueError(f"{eid}: focal_arm {f_id!r} cannot have is_reference_control=True") if not arms_by_id[c_id].get("is_reference_control", False): raise ValueError(f"{eid}: comparator_arm {c_id!r} must have is_reference_control=True") if orient not in (-1, 1): raise ValueError(f"{eid}: numeric LRR must have non-zero endpoint orientation_sign, got {orient!r}") if stat_type not in ("log_response_ratio_paired_means", "log_response_ratio_fold_change"): raise ValueError( f"{eid}: numeric LRR requires comparative statistic_type, got {stat_type!r}" ) if stat_type == "log_response_ratio_paired_means": if not (isinstance(t_mean, (int, float)) and isinstance(c_mean, (int, float)) and t_mean > 0 and c_mean > 0): raise ValueError(f"{eid}: paired-means LRR requires positive treatment_mean and control_mean") expected_lrr = _log_response_ratio(t_mean, c_mean) if abs(float(lrr) - expected_lrr) > 1e-3: raise ValueError( f"{eid}: log_response_ratio_or_smd {lrr} does not match ln({t_mean}/{c_mean}) = {expected_lrr:.4f}" ) elif stat_type == "log_response_ratio_fold_change": if not (isinstance(t_mean, (int, float)) and t_mean > 0 and t_mean != 1.0 and c_mean is None): raise ValueError(f"{eid}: fold-change LRR requires positive treatment_mean != 1.0 and control_mean=None") expected_abs = abs(math.log(float(t_mean))) if abs(abs(float(lrr)) - expected_abs) > 1e-3: raise ValueError( f"{eid}: |log_response_ratio_or_smd| {abs(float(lrr))} does not match |ln({t_mean})| = {expected_abs:.4f}" ) if direction == "Protective_or_Improved" and (float(lrr) * orient <= 0): raise ValueError(f"{eid}: Protective_or_Improved effect has non-positive oriented LRR ({lrr} * {orient})") if direction == "Deleterious_or_Impaired" and (float(lrr) * orient >= 0): raise ValueError(f"{eid}: Deleterious_or_Impaired effect has non-negative oriented LRR ({lrr} * {orient})") else: _cm_type = (eff.get("contrast_metadata") or {}).get("contrast_type") _pe = eff.get("point_estimate") _ci_lo = eff.get("ci_95_lower") _ci_hi = eff.get("ci_95_upper") _requires_ci_comp = ( stat_type == "adjusted_mean_difference_with_95ci_and_pvalue" or _cm_type == "between_arm_comparative_adjusted_difference"