scripts/verify_iip0044_foundry_v1_3_biologics.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0044_foundry_v1_3_biologics.py · SHA-256: 1d6c53a0817f6254…
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"
)
payload: dict[str, Any] = {
"planned_analysis_looks": int(planned_analysis_looks),
"predeclared_per_donor_unit_counts": per_donor_map,
"preregistration_timestamp_utc": str(preregistration_timestamp_utc),
"roster_donor_ids": ids_list,
"roster_id": str(roster_id),
"single_look_fixed_horizon_plan_locked": bool(single_look_fixed_horizon_plan_locked),
}
if predeclared_per_donor_unit_count_n is not None:
payload["predeclared_per_donor_unit_count_n"] = int(predeclared_per_donor_unit_count_n)
raw = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(raw).hexdigest()
def _shield_build_preregistered_roster(
roster_donor_ids: list[str] | tuple[str, ...],
*,
roster_id: str = "ROSTER_SHIELD_T1D_PREREG_V1",
preregistration_timestamp_utc: str = "2026-11-28T00:00:00Z",
predeclared_per_donor_unit_count_n: int | None = _SHIELD_MIN_CYTO_N_EFF_PER_DONOR,
predeclared_per_donor_unit_counts: dict[str, int] | None = None,
planned_analysis_looks: int = 1,
single_look_fixed_horizon_plan_locked: bool = True,
) -> dict[str, Any]:
"""Construct a cryptographically hash-pinned outcome-blind pre-registered T1D donor family roster
committing donor membership, fixed per-donor cytotoxicity sample size N, and single-look fixed horizon.
"""
ids_list = [str(x) for x in roster_donor_ids]
out: dict[str, Any] = {
"roster_id": str(roster_id),
"preregistration_timestamp_utc": str(preregistration_timestamp_utc),
"outcome_blind_lock_attestation": True,
"single_look_fixed_horizon_plan_locked": bool(single_look_fixed_horizon_plan_locked),
"planned_analysis_looks": int(planned_analysis_looks),
"roster_donor_ids": ids_list,
"planned_t1d_donor_family_n": len(ids_list),
}
if predeclared_per_donor_unit_counts is not None:
counts_map = {str(did): int(predeclared_per_donor_unit_counts[did]) for did in ids_list}
out["predeclared_per_donor_unit_counts"] = counts_map
if predeclared_per_donor_unit_count_n is not None:
out["predeclared_per_donor_unit_count_n"] = int(predeclared_per_donor_unit_count_n)
out["roster_sha256"] = _shield_compute_donor_roster_sha256(
roster_id,
preregistration_timestamp_utc,
ids_list,
predeclared_per_donor_unit_count_n=predeclared_per_donor_unit_count_n,
predeclared_per_donor_unit_counts=counts_map,
planned_analysis_looks=planned_analysis_looks,
single_look_fixed_horizon_plan_locked=single_look_fixed_horizon_plan_locked,
)
else:
fixed_n = int(_SHIELD_MIN_CYTO_N_EFF_PER_DONOR if predeclared_per_donor_unit_count_n is None else predeclared_per_donor_unit_count_n)
out["predeclared_per_donor_unit_count_n"] = fixed_n
out["roster_sha256"] = _shield_compute_donor_roster_sha256(
roster_id,
preregistration_timestamp_utc,
ids_list,
predeclared_per_donor_unit_count_n=fixed_n,
planned_analysis_looks=planned_analysis_looks,
single_look_fixed_horizon_plan_locked=single_look_fixed_horizon_plan_locked,
)
return out
def _shield_descriptive_quantiles(values: list[float]) -> tuple[float, float, float, float]:
"""Return (mean, median, min, iqr) using exact linear interpolation (overflow-immune pure stdlib)."""
svals = sorted(float(v) for v in values)
n = len(svals)
scale_abs = max(abs(x) for x in svals)
mean_v = 0.0 if scale_abs == 0.0 else (sum(x / scale_abs for x in svals) / float(n)) * scale_abs
min_v = svals[0]
def _pct(p: float) -> float:
if n == 1:
return svals[0]
pos = p * float(n - 1)
lo_i = int(math.floor(pos))
hi_i = int(math.ceil(pos))
frac = pos - float(lo_i)
return (1.0 - frac) * svals[lo_i] + frac * svals[hi_i]
med_v = _pct(0.5)
q75 = _pct(0.75)
q25 = _pct(0.25)
iqr_v = q75 - q25 if math.isfinite(q75 - q25) else 0.0
return mean_v, med_v, min_v, iqr_v
def _shield_connected_clusters(
roster_ids: list[str],