scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…
"""R12-B2 Strictly convert non-negative boundary scalar to finite Decimal, rejecting signed negative zero (`-0.0`)."""
if _is_negative_zero(val):
return None
d = _to_exact_decimal(val)
if d is None:
return None
with localcontext(
Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
):
if d < Decimal(0):
return None
return d
def _is_strict_int(val: Any) -> bool:
return isinstance(val, int) and not isinstance(val, bool)
def _is_strict_bool(val: Any) -> bool:
return type(val) is bool
def _is_valid_sha256_hex(val: Any) -> bool:
return isinstance(val, str) and bool(_HEX64_RE.fullmatch(val)) and len(set(val)) > 1
def _is_valid_identifier(val: Any) -> bool:
if not isinstance(val, str):
return False
s = val.strip()
if not s or s != val:
return False
if _PLACEHOLDER_TOKEN_RE.search(s) or _FORBIDDEN_ID_CHARS_RE.search(s):
return False
return True
def _is_clean_nonempty_str(val: Any) -> bool:
return isinstance(val, str) and bool(val.strip()) and val == val.strip()
def _dec_to_float_pct(val: Decimal, ndigits: int = 6) -> float:
"""Convert Decimal fraction to percentage float completely inside an isolated untrapped context."""
with _clean_dec_ctx(80, ROUND_HALF_EVEN):
return round(float(val * Decimal(100)), ndigits)
def _dec_to_float(val: Decimal, ndigits: int = 6) -> float:
"""Convert Decimal to float completely inside an isolated untrapped context."""
with _clean_dec_ctx(80, ROUND_HALF_EVEN):
return round(float(+val), ndigits)
def _canonical_json_dumps(obj: Any) -> str:
"""
R12-B2 Canonical compact RFC-8259 JSON serializer (`sort_keys=True`, `separators=(',', ':')`,
`ensure_ascii=False`, `allow_nan=False`) supporting preserved exact `Decimal` boundary values
deterministically without lossy float64 rounding or `TypeError`:
- Losslessly float64-representable Decimals (`Decimal('1.097')`, `Decimal('1.0')`, `Decimal('0.0')`)
emit the identical token to `json.dumps(float(d))` so existing canonical hashes remain invariant.
- Signed negative zero (`Decimal('-0.0')`) emits `"-0.0"`.
- Higher-precision Decimals (e.g. `Decimal('1.00000000000000001')`) emit exact finite JSON number
literals (`1.00000000000000001`).
"""
if isinstance(obj, dict):
items: List[str] = []
for k in sorted(obj.keys()):
if not isinstance(k, str):
raise TypeError(f"Canonical JSON object keys must be str, got {type(k).__name__}")
items.append(f"{json.dumps(k, ensure_ascii=False)}:{_canonical_json_dumps(obj[k])}")
return "{" + ",".join(items) + "}"
if isinstance(obj, (list, tuple)):
return "[" + ",".join(_canonical_json_dumps(x) for x in obj) + "]"
if isinstance(obj, Decimal):
with localcontext(
Context(prec=120, rounding=ROUND_HALF_EVEN, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN, traps=[])
):
if not obj.is_finite():
raise ValueError(f"Non-finite Decimal rejected in canonical JSON: {obj!r}")
if obj == Decimal(0):
return "-0.0" if obj.is_signed() else "0.0"
try:
fval = float(obj)
except (OverflowError, ValueError):
fval = math.nan
if math.isfinite(fval) and fval != 0.0:
f_str = json.dumps(fval, allow_nan=False)
if Decimal(f_str) == obj:
return f_str
return str(obj)
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
def compute_canonical_lot_sha256(payload: Dict[str, Any]) -> str:
"""Compute canonical SHA-256 digest of a measured-lot Gate 0V payload (excluding payload_sha256)."""
body = {k: v for k, v in payload.items() if k != "payload_sha256"}
canonical = _canonical_json_dumps(body)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def _safe_canonical_lot_sha256(payload: Dict[str, Any]) -> str | None:
"""Return canonical SHA-256 or None if payload contains non-finite floats (NaN/Infinity), excessive depth, or non-JSON values."""
try:
return compute_canonical_lot_sha256(payload)
except (TypeError, ValueError, OverflowError, RecursionError):
return None
def build_reconciled_unit_partition(
k: int,
n: int,
units_n: int = MIN_INDEPENDENT_BIOLOGICAL_UNITS_N,
*,
unit_prefix: str = "WELL",
) -> List[Dict[str, Any]]:
"""
R12-B1 Deterministic balanced partition of binomial integer counts `(k, n)` across `units_n`
independent biological units (`len == units_n`, each `n_u > 0`, `0 <= k_u <= n_u`, `sum(n_u) == n`,
`sum(k_u) == k`). Used strictly for reference/test fixture generation; NEVER used by the evaluator
to backfill omitted or mismatched operator partitions!
"""
if not (_is_strict_int(units_n) and units_n >= 1):
raise ValueError(f"units_n must be a positive int, got {units_n!r}")
if not (_is_strict_int(n) and n >= units_n and _is_strict_int(k) and 0 <= k <= n):
raise ValueError(f"Cannot partition (k={k!r}, n={n!r}) across {units_n} positive-denominator units")
base_n, rem_n = divmod(n, units_n)
n_parts = [base_n + (1 if idx < rem_n else 0) for idx in range(units_n)]
k_parts = [0] * units_n
rem_k = k
for idx in range(units_n):
if rem_k <= 0:
break
share = min(n_parts[idx], (rem_k + (units_n - idx) - 1) // (units_n - idx))
k_parts[idx] = share
rem_k -= share
for idx in range(units_n):
if rem_k <= 0:
break
room = n_parts[idx] - k_parts[idx]
if room > 0:
add = min(room, rem_k)
k_parts[idx] += add
rem_k -= add
return [
{"unit_id": f"{unit_prefix}-{idx + 1:02d}", "k": k_parts[idx], "n": n_parts[idx]}
for idx in range(units_n)
]
def _build_subset_unit_partition(
k_sub: int,
parent_part: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""
R13-B2 Deterministic synchronized subset partition of integer `k_sub` across the exact same
`unit_id`s and `n_u` denominators as `parent_part`, guaranteeing `0 <= k_sub_u <= parent_k_u <= n_u`
on EVERY individual unit and `sum(k_sub_u) == k_sub`. Used strictly by test/fixture generation.
"""
cap_list = [int(p["k"]) for p in parent_part]
cap_tot = sum(cap_list)
if not (_is_strict_int(k_sub) and 0 <= k_sub <= cap_tot):
raise ValueError(f"Cannot partition subset k_sub={k_sub!r} within parent capacity {cap_tot!r}")
if k_sub == 0 or cap_tot == 0:
return [
{"unit_id": p["unit_id"], "k": 0, "n": int(p["n"])}
for p in parent_part
]
k_parts = [(k_sub * c) // cap_tot for c in cap_list]
rem = k_sub - sum(k_parts)
if rem > 0:
order = sorted(
range(len(parent_part)),
key=lambda i: (-((k_sub * cap_list[i]) % cap_tot), i),
)
for idx in order:
if rem <= 0:
break
if k_parts[idx] < cap_list[idx]:
k_parts[idx] += 1
rem -= 1
return [
{"unit_id": parent_part[i]["unit_id"], "k": k_parts[i], "n": int(parent_part[i]["n"])}
for i in range(len(parent_part))
]
def reconcile_fixture_per_unit_counts(
payload: Dict[str, Any],
units_n: int | None = None,
) -> Dict[str, Any]:
"""
R12-B1 + R13-B2 Test/fixture utility that rebuilds matching `per_unit_counts` across valid
integer count fields on a mutated synthetic Gate-0V fixture (NEVER invoked by the production
evaluator!), guaranteeing synchronized same-unit IDs and within-unit subset inequalities
(`direct_infected_veh_72h <= veh_72h` and `infected_viral_pos_72h <= ap1903_72h`).
"""
if not isinstance(payload, dict):
return payload
clust = payload.get("clustering_and_independence_spec")
u_n = units_n
if u_n is None and isinstance(clust, dict) and _is_strict_int(clust.get("independent_biological_units_n")):
u_n = int(clust["independent_biological_units_n"])
if not (_is_strict_int(u_n) and u_n >= 1):
u_n = MIN_INDEPENDENT_BIOLOGICAL_UNITS_N
def _try_part(k_val: Any, n_val: Any) -> List[Dict[str, Any]] | None:
if _is_strict_int(k_val) and _is_strict_int(n_val) and n_val >= u_n and 0 <= k_val <= n_val:
return build_reconciled_unit_partition(k_val, n_val, u_n)
return None
inf = payload.get("gate0v_b_infectious_challenge")
if isinstance(inf, dict) and isinstance(inf.get("pathogens"), dict):
for pb in inf["pathogens"].values():
if not isinstance(pb, dict):
continue
lat = pb.get("day28_latent_and_defective_genome_arm")
if isinstance(lat, dict):
lp = _try_part(lat.get("ddpcr_positive_events_k"), lat.get("ddpcr_cell_equivalents_screened_n"))
if lp is not None:
lat["per_unit_counts"] = lp
tgts = lat.get("ddpcr_targets")
if isinstance(tgts, dict):
for te in tgts.values():
if isinstance(te, dict):
tp = _try_part(te.get("k"), te.get("n"))
if tp is not None:
te["per_unit_counts"] = tp
lin_map = pb.get("day28_persistence_by_lineage")
if isinstance(lin_map, dict):
for le in lin_map.values():
if isinstance(le, dict):
ep = _try_part(le.get("stage2_confirmed_infectious_k"), le.get("cells_scored_n"))
if ep is not None:
le["per_unit_counts"] = ep
uc_p = _try_part(le.get("uninfected_ctrl_fp_k"), le.get("uninfected_ctrl_scored_n"))
if uc_p is not None:
le["uninfected_ctrl_per_unit_counts"] = uc_p
sc_p = _try_part(le.get("spike_calibrant_detected_k"), le.get("spike_calibrant_total_n"))
if sc_p is not None:
le["spike_calibrant_per_unit_counts"] = sc_p
fsc_p = _try_part(
le.get("fragile_infected_spike_detected_k"),
le.get("fragile_infected_spike_total_n"),
)
if fsc_p is not None:
le["fragile_infected_spike_per_unit_counts"] = fsc_p
cd46 = payload.get("cd46_tropic_viral_addendum")
if isinstance(cd46, dict):
for vid in CD46_ADDENDUM_VIRUSES: