if val == Decimal("1"): return 1.0, None return ( None, f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required " f"(got exact Decimal({str(val)!r}) != 1; zero tolerance)", ) if type(val) is int: if val == 1: return 1.0, None return ( None, f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required " f"(got {val!r} != 1; zero tolerance)", ) if isinstance(val, float): if math.isfinite(val) and val == 1.0: return 1.0, None return ( None, f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required " f"(got {val!r} != 1.0; zero tolerance)", ) return None, f"{label} must be a finite non-bool numeric value (got {val!r})" def _shield_canonicalize_construct_id(raw_cid: str) -> str: clean = raw_cid.strip() return _SHIELD_CONSTRUCT_CANONICAL_MAP.get(clean, clean) def _shield_parse_batch_construct_ids( batch_obj: dict[str, Any], batch_id: str, ) -> tuple[frozenset[str] | None, str | None]: """Parse & validate non-empty construct_ids (or alias constructs) on a declared expression batch.""" has_cids = "construct_ids" in batch_obj and batch_obj["construct_ids"] is not None has_cons = "constructs" in batch_obj and batch_obj["constructs"] is not None if not has_cids and not has_cons: return None, f"Expression batch {batch_id!r} missing non-empty construct_ids (or constructs) list" def _parse_one(raw_list: Any, field_name: str) -> tuple[frozenset[str] | None, str | None]: if not isinstance(raw_list, list) or len(raw_list) == 0: return None, f"Expression batch {batch_id!r} {field_name} must be a non-empty list of construct IDs" seen_c: set[str] = set() for c_idx, c_item in enumerate(raw_list): if type(c_item) is not str or not c_item.strip(): return None, f"Expression batch {batch_id!r}.{field_name}[{c_idx}] must be a non-empty string (got {c_item!r})" canon = _shield_canonicalize_construct_id(c_item) if canon in seen_c: return None, f"Expression batch {batch_id!r}.{field_name} contains duplicate construct ID {canon!r}" seen_c.add(canon) return frozenset(seen_c), None cset_primary: frozenset[str] | None = None cset_alias: frozenset[str] | None = None if has_cids: cset_primary, err_p = _parse_one(batch_obj["construct_ids"], "construct_ids") if err_p is not None: return None, err_p if has_cons: cset_alias, err_a = _parse_one(batch_obj["constructs"], "constructs") if err_a is not None: return None, err_a if cset_primary is not None and cset_alias is not None and cset_primary != cset_alias: return None, ( f"Expression batch {batch_id!r} construct_ids={sorted(cset_primary)} " f"disagrees with constructs={sorted(cset_alias)}" ) final_set = cset_primary if cset_primary is not None else cset_alias return final_set, None def _shield_validate_batch_ids( raw_ids: Any, label: str, passing_batch_constructs: dict[str, frozenset[str]], referenced_batches: set[str], *, required_construct_all: str | None = None, require_cocktail_both_leads: bool = False, role_comp1_batches: set[str] | None = None, role_comp2_batches: set[str] | None = None, ) -> str | None: if not isinstance(raw_ids, list) or len(raw_ids) == 0: return f"{label} missing non-empty expression_batch_ids linkage list" local_seen: set[str] = set() for idx, bid in enumerate(raw_ids): if type(bid) is not str or not bid.strip(): return f"{label}.expression_batch_ids[{idx}] must be a non-empty string (got {bid!r})" bid_c = bid.strip() if bid_c in local_seen: return f"{label}.expression_batch_ids contains duplicate batch_id {bid_c!r}" local_seen.add(bid_c) if bid_c not in passing_batch_constructs: return f"{label}.expression_batch_ids references undeclared, empty-construct, or non-passing batch_id {bid_c!r}" if required_construct_all is not None: req_c = _shield_canonicalize_construct_id(required_construct_all) for bid_c in sorted(local_seen): if req_c not in passing_batch_constructs[bid_c]: return ( f"{label}.expression_batch_ids batch {bid_c!r} does not contain required construct " f"{req_c!r} (batch construct_ids={sorted(passing_batch_constructs[bid_c])})" ) if require_cocktail_both_leads: has_comp1 = False has_comp2 = False for bid_c in sorted(local_seen): bcons = passing_batch_constructs[bid_c] in_c1 = _SHIELD_COMP1_LEAD in bcons in_c2 = _SHIELD_COMP2_LEAD in bcons if not (in_c1 or in_c2): return ( f"{label}.expression_batch_ids cocktail assay references non-lead batch {bid_c!r} " f"(batch construct_ids={sorted(bcons)})" ) if in_c1: has_comp1 = True if in_c2: has_comp2 = True if not (has_comp1 and has_comp2): return ( f"{label}.expression_batch_ids cocktail assay must link BOTH {_SHIELD_COMP1_LEAD!r} " f"and {_SHIELD_COMP2_LEAD!r} passing batches (has_comp1={has_comp1}, has_comp2={has_comp2})" ) referenced_batches.update(local_seen) for bid_c in local_seen: bcons = passing_batch_constructs[bid_c] if role_comp1_batches is not None and _SHIELD_COMP1_LEAD in bcons: role_comp1_batches.add(bid_c) if role_comp2_batches is not None and _SHIELD_COMP2_LEAD in bcons: role_comp2_batches.add(bid_c) return None def _shield_parse_qualifying_hla_genotype(raw_gt: Any, label: str) -> tuple[list[str] | None, str | None]: if type(raw_gt) is not str or not raw_gt.strip(): return None, f"{label} missing non-empty qualifying T1D hla_genotype" norm = re.sub(r"\s*([/;,+|])\s*", r"\1", raw_gt.strip().upper()) if norm in _SHIELD_QUALIFYING_HLA_DQ_TOKENS: return [norm], None raw_parts = [p.strip() for p in re.split(r"[;,+|]+", norm) if p.strip()] tokens: list[str] = [] for part in raw_parts: if part in _SHIELD_QUALIFYING_HLA_DQ_TOKENS: tokens.append(part) elif "DQA1*" in part or "DQB1*" in part: return None, f"{label} has non-qualifying HLA-DQ allele pair {part!r}" else: sub = [s.strip() for s in part.split("/") if s.strip()] if not sub: return None, f"{label} has empty HLA-DQ token in {raw_gt!r}" for tok in sub: if tok not in _SHIELD_QUALIFYING_HLA_DQ_TOKENS: return None, f"{label} contains non-qualifying HLA-DQ genotype token {tok!r} (from {raw_gt!r})" tokens.append(tok) if not tokens: return None, f"{label} contains no qualifying HLA-DQ tokens" return tokens, None def _shield_student_t_ci_pct( values: list[float], *, lo_bound: float = _SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MIN_PCT, hi_bound: float = _SHIELD_SUPPRESSION_ASSAY_ACCEPTANCE_MAX_PCT, ) -> tuple[float, float, float]: """Overflow-immune non-authorizing descriptive Student-t summary over finite float inputs. Clamps endpoints symmetrically to [lo_bound, hi_bound] (default [-1000.0, 100.0]% signed suppression scale) while guaranteeing non-inverted ordering L <= U (and L <= mean <= U whenever mean lies in [lo_bound, hi_bound]). """ n = len(values) if n < 1: raise ValueError("Student-t diagnostic requires >= 1 value") if lo_bound > hi_bound: raise ValueError(f"Invalid Student-t clamp bounds: lo_bound={lo_bound} > hi_bound={hi_bound}") fvals = [float(x) for x in values] scale_abs = max(abs(x) for x in fvals) if not math.isfinite(scale_abs): return 0.0, lo_bound, hi_bound if scale_abs == 0.0: z_clamp = min(hi_bound, max(lo_bound, 0.0)) return 0.0, z_clamp, z_clamp mean_scaled = sum(x / scale_abs for x in fvals) / float(n) mean_v = mean_scaled * scale_abs if not math.isfinite(mean_v): mean_v = 0.0 if n == 1: m_clamp = min(hi_bound, max(lo_bound, mean_v)) return mean_v, m_clamp, m_clamp devs_scaled = [(x / scale_abs) - mean_scaled for x in fvals] max_dev = max(abs(d) for d in devs_scaled) if max_dev == 0.0: m_clamp = min(hi_bound, max(lo_bound, mean_v)) return mean_v, m_clamp, m_clamp norm_devs = [d / max_dev for d in devs_scaled] sd_unit = math.sqrt(sum(d * d for d in norm_devs) / float(n - 1)) se_unit = sd_unit / math.sqrt(float(n)) half_scaled = _shield_t95_critical(n - 1) * se_unit * max_dev lo_scaled = mean_scaled - half_scaled hi_scaled = mean_scaled + half_scaled lo_raw = lo_scaled * scale_abs hi_raw = hi_scaled * scale_abs lo_val = (lo_bound if lo_scaled <= 0.0 else hi_bound) if not math.isfinite(lo_raw) else min(hi_bound, max(lo_bound, lo_raw)) hi_val = (hi_bound if hi_scaled >= 0.0 else lo_bound) if not math.isfinite(hi_raw) else min(hi_bound, max(lo_bound, hi_raw)) if lo_val > hi_val: lo_val, hi_val = hi_val, lo_val return mean_v, lo_val, hi_val def _shield_parse_iso8601_utc(raw_ts: Any, label: str) -> tuple[datetime | None, str | None]: """Validate strict unpadded ISO-8601 UTC timestamp (YYYY-MM-DDTHH:MM:SS[.ffffff]Z) compatible with Python 3.9+.""" if type(raw_ts) is not str or not raw_ts or raw_ts != raw_ts.strip(): return None, f"{label} must be a non-empty unpadded ISO-8601 UTC string (got {raw_ts!r})" if not _SHIELD_ISO8601_UTC_RE.match(raw_ts): return None, f"{label}={raw_ts!r} must match strict ISO-8601 UTC format YYYY-MM-DDTHH:MM:SS[.ffffff]Z" try: dt_val = datetime.fromisoformat(raw_ts[:-1] + "+00:00") except ValueError as exc: return None, f"{label}={raw_ts!r} is not a valid calendar UTC timestamp: {exc}" return dt_val, None def _shield_compute_donor_roster_sha256( roster_id: str, preregistration_timestamp_utc: str, roster_donor_ids: list[str] | tuple[str, ...], *, predeclared_per_donor_unit_count_n: int | None = None, predeclared_per_donor_unit_counts: dict[str, int] | None = None, planned_analysis_looks: int = 1, single_look_fixed_horizon_plan_locked: bool = True, ) -> str: """Canonical lowercase 64-hex SHA-256 over UTF-8 compact sorted JSON committing the full outcome-blind pre-readout analysis plan: {planned_analysis_looks, predeclared_per_donor_unit_counts, preregistration_timestamp_utc, roster_donor_ids, roster_id, single_look_fixed_horizon_plan_locked[, predeclared_per_donor_unit_count_n]}. """ ids_list = [str(x) for x in roster_donor_ids] if predeclared_per_donor_unit_counts is not None: per_donor_map = {str(did): int(predeclared_per_donor_unit_counts[did]) for did in ids_list} elif predeclared_per_donor_unit_count_n is not None: per_donor_map = {str(did): int(predeclared_per_donor_unit_count_n) for did in ids_list} else: raise ValueError( "Fixed per-donor sample size commitment (predeclared_per_donor_unit_count_n or " "predeclared_per_donor_unit_counts) is mandatory for roster_sha256"