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…
Fraction(mult_f64) >= target_ratio
and Fraction(eff_ocr) >= target_ocr
and base_float_frac * Fraction(mult_f64) >= target_ocr
and (not (target_ocr > base_dec_frac) or mult_f64 > 1.0)
):
return mult_f64, eff_ocr
mult_f64 = math.nextafter(mult_f64, math.inf)
if not math.isfinite(mult_f64):
raise ValueError("Computed vascular voxel scale factor overflowed IEEE-754 float64 range")
@lru_cache(maxsize=256)
def exact_student_t_one_sided_95(df: int) -> float:
"""
R14-B2 + R16-M1 Provably outward-conservative upper-enclosed one-sided 95% Student-t critical
value t_{0.95, df} >= exact_quantile for ALL integer degrees of freedom df in [1, 10**9]:
- df == 1: exact algebraic Cauchy identity cot(pi/20) = sqrt(5 + 2*sqrt(5)) + sqrt(5) + 1
evaluated in 80-digit Decimal and rounded UP to IEEE-754 float64 (`>= cot(pi/20)`).
- df == 2: exact closed form sqrt(162 / 19) evaluated in 80-digit Decimal and rounded UP.
- 3 <= df <= 2000: safeguarded high-precision Decimal inversion of the exact finite-sum
Student-t CDF with outward margin + upward float64 enclosure (e.g. df = 5 -> 2.0150483733330247,
displaying exact 7-dp `2.0150484` with ZERO inward rounding error).
- df > 2000: 4-term high-precision Decimal Cornish-Fisher expansion from upper-enclosed z_{0.95}
plus provably positive conservative O(1/df^5) remainder `10 / df^5`, rounded UP to float64.
Guarantees BOTH `Decimal.from_float(res) >= exact_quantile` AND `Decimal(str(res)) >= exact_quantile`.
"""
if isinstance(df, bool) or not isinstance(df, int) or df < 1 or df > MAX_NW08_STUDENT_T_DF:
raise ValueError(f"HOLD_NW08_OCR_INVALID_DEGREES_OF_FREEDOM:df must be int in [1, {MAX_NW08_STUDENT_T_DF}]; got {df!r}")
def _cf_upper_dec(d_int: int) -> Decimal:
with _clean_dec_ctx(60, ROUND_HALF_EVEN):
z = _EXACT_Z95_UPPER_40D
z2 = z * z
z3 = z2 * z
z5 = z3 * z2
z7 = z5 * z2
z9 = z7 * z2
d = Decimal(d_int)
g1 = (z3 + z) / Decimal(4)
g2 = (Decimal(5) * z5 + Decimal(16) * z3 + Decimal(3) * z) / Decimal(96)
g3 = (Decimal(3) * z7 + Decimal(19) * z5 + Decimal(17) * z3 - Decimal(15) * z) / Decimal(384)
g4 = (
Decimal(79) * z9
+ Decimal(776) * z7
+ Decimal(1482) * z5
- Decimal(1920) * z3
- Decimal(945) * z
) / Decimal(92160)
# Conservative strictly positive O(1/df^5) remainder (>60x true g5 ~ 0.145 at p=0.95)
rem = Decimal(10) / (d ** 5)
return z + g1 / d + g2 / (d * d) + g3 / (d ** 3) + g4 / (d ** 4) + rem
if df == 1:
with _clean_dec_ctx(80, ROUND_HALF_EVEN):
s5 = Decimal(5).sqrt()
exact_u = (Decimal(5) + Decimal(2) * s5).sqrt() + s5 + Decimal(1) + Decimal("1e-60")
elif df == 2:
with _clean_dec_ctx(80, ROUND_HALF_EVEN):
exact_u = (Decimal(162) / Decimal(19)).sqrt() + Decimal("1e-60")
elif df <= 2000:
with _clean_dec_ctx(60, ROUND_HALF_EVEN):
p95 = Decimal("0.95")
t_est = _cf_upper_dec(df)
step = Decimal("0.01") if df >= 10 else Decimal("0.2")
lo = max(_EXACT_Z95_UPPER_40D, t_est - step)
hi = t_est + step
while _exact_student_t_cdf_dec(lo, df, 52) >= p95:
hi = lo
lo = max(Decimal("1.6448536"), lo - step)
while _exact_student_t_cdf_dec(hi, df, 52) < p95:
lo = hi
hi = hi + step
f_lo = _exact_student_t_cdf_dec(lo, df, 52) - p95
f_hi = _exact_student_t_cdf_dec(hi, df, 52) - p95
for it in range(100):
if hi - lo <= Decimal("1e-35"):
break
if it % 3 != 2 and f_hi != f_lo:
cand = lo - f_lo * (hi - lo) / (f_hi - f_lo)
if not (lo < cand < hi):
cand = (lo + hi) / Decimal(2)
else:
cand = (lo + hi) / Decimal(2)
f_c = _exact_student_t_cdf_dec(cand, df, 52) - p95
if f_c < Decimal(0):
lo, f_lo = cand, f_c
else:
hi, f_hi = cand, f_c
exact_u = hi + Decimal("1e-32")
else:
with _clean_dec_ctx(60, ROUND_HALF_EVEN):
exact_u = _cf_upper_dec(df) + Decimal("1e-50")
f_val = max(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95, float(exact_u))
with _clean_dec_ctx(80, ROUND_HALF_EVEN):
while Decimal.from_float(f_val) < exact_u or Decimal(str(f_val)) < exact_u:
f_val = math.nextafter(f_val, math.inf)
return f_val
def _resolve_nw08_ocr_uncertainty_bound(
*,
f_measured_ocr: float,
dec_measured_ocr: Decimal,
f_uncertainty_se: float,
dec_uncertainty_se: Decimal,
z_one_sided_95: Any = None,
ocr_uncertainty_model: Any = None,
ocr_replicates_n: Any = None,
ocr_degrees_of_freedom: Any = None,
ocr_uncertainty_provenance: Any = None,
measured_ocr_u95_override: Any = None,
require_explicit_model_for_positive_se: bool = False,
) -> Dict[str, Any]:
"""
R14-B2 + R17-B2 Canonical NW-08 measured-OCR inferential uncertainty validator and upper-bound
resolver (NIST §8.6 compliant). Rejects undeclared bare positive `uncertainty_se` without an
explicit inferential model / degrees of freedom / independently justified upper bound, computes
exact upward-enclosed one-sided 95% Student-t critical values for `STUDENT_T_ESTIMATED_SE`,
strictly scopes the provably upper-enclosed normal quantile `z_{0.95} > Phi^{-1}(0.95)`
(`MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC`, upward float64 `1.6448536269514729`) to declared
`KNOWN_SIGMA_NORMAL` models with provenance, and rounds float64 upper OCR strictly upward.
"""
# 1. Validate explicit z_one_sided_95 first whenever supplied (preserves R04-B5 / R12-B2 error codes)
f_z95_sup: float | None = None
dec_z95_sup: Decimal | None = None
if z_one_sided_95 is not None:
if _is_negative_zero(z_one_sided_95):
raise ValueError(
f"INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:Require conservative one-sided >=95% "
f"confidence quantile z_one_sided_95 >= {MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC}; got {z_one_sided_95!r}"
)
f_z95_sup, dec_z95_sup = _parse_nw08_boundary_scalar(
z_one_sided_95, "z_one_sided_95", non_negative=False, strictly_positive=False
)
with _clean_dec_ctx(120, ROUND_HALF_EVEN):
min_z95_dec = MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC
float_undercuts_z95 = isinstance(z_one_sided_95, float) and (Decimal.from_float(f_z95_sup) < min_z95_dec)
if dec_z95_sup < min_z95_dec or float_undercuts_z95:
z_prefix = "INVALID_NEGATIVE_OR_SIGNED_ZERO_BOUNDARY_VALUE:" if dec_z95_sup <= Decimal(0) else ""
raise ValueError(
f"{z_prefix}Require conservative one-sided >=95% confidence quantile "
f"z_one_sided_95 >= {MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95_DEC}; got {z_one_sided_95!r}"
)
# 2. Validate replicates_n and degrees_of_freedom strictly as positive integers (no bool/float/str)
rep_n: int | None = None
if ocr_replicates_n is not None:
if (
isinstance(ocr_replicates_n, bool)
or not isinstance(ocr_replicates_n, int)
or ocr_replicates_n < 2
or ocr_replicates_n > MAX_NW08_STUDENT_T_DF + 1
):
raise ValueError(
f"HOLD_NW08_OCR_INVALID_REPLICATES_N:ocr_replicates_n must be int >= 2; got {ocr_replicates_n!r}"
)
rep_n = ocr_replicates_n
df_sup: int | None = None
if ocr_degrees_of_freedom is not None:
if (
isinstance(ocr_degrees_of_freedom, bool)
or not isinstance(ocr_degrees_of_freedom, int)
or ocr_degrees_of_freedom < 1
or ocr_degrees_of_freedom > MAX_NW08_STUDENT_T_DF
):
raise ValueError(
f"HOLD_NW08_OCR_INVALID_DEGREES_OF_FREEDOM:ocr_degrees_of_freedom must be int >= 1; got {ocr_degrees_of_freedom!r}"
)
df_sup = ocr_degrees_of_freedom
if rep_n is not None and df_sup is not None and df_sup > (rep_n - 1):
raise ValueError(
f"HOLD_NW08_OCR_INCONSISTENT_REPLICATES_AND_DF:ocr_degrees_of_freedom ({df_sup}) exceeds "
f"ocr_replicates_n - 1 ({rep_n - 1})"
)
eff_df: int | None = df_sup if df_sup is not None else ((rep_n - 1) if rep_n is not None else None)
# 3. Validate provenance string whenever supplied (clean, non-empty, zero placeholder tokens)
prov_clean: str | None = None
if ocr_uncertainty_provenance is not None:
if (
not _is_clean_nonempty_str(ocr_uncertainty_provenance)
or _FORBIDDEN_ID_CHARS_RE.search(ocr_uncertainty_provenance)
or _PLACEHOLDER_TOKEN_RE.search(ocr_uncertainty_provenance)
):
raise ValueError(
f"HOLD_NW08_OCR_INVALID_UNCERTAINTY_PROVENANCE:ocr_uncertainty_provenance must be a clean "
f"non-placeholder string; got {ocr_uncertainty_provenance!r}"
)
prov_clean = ocr_uncertainty_provenance
# 4. Validate measured_ocr_u95_override whenever supplied
f_u95_ov: float | None = None
dec_u95_ov: Decimal | None = None
if measured_ocr_u95_override is not None:
f_u95_ov, dec_u95_ov = _parse_nw08_boundary_scalar(
measured_ocr_u95_override, "measured_ocr_u95_override", strictly_positive=True
)
# 5. Determine canonical inferential model (fail-closed on undeclared bare positive SE!)
with _clean_dec_ctx(120, ROUND_HALF_EVEN):
has_positive_se = bool(dec_uncertainty_se > Decimal(0))
if ocr_uncertainty_model is not None:
if not isinstance(ocr_uncertainty_model, str) or ocr_uncertainty_model not in NW08_ALLOWED_OCR_UNCERTAINTY_MODELS:
raise ValueError(
f"HOLD_NW08_OCR_INVALID_UNCERTAINTY_MODEL:Unrecognized ocr_uncertainty_model={ocr_uncertainty_model!r}; "
f"expected one of {sorted(NW08_ALLOWED_OCR_UNCERTAINTY_MODELS)}"
)
eff_model = ocr_uncertainty_model
elif (not has_positive_se) and (f_u95_ov is None) and (eff_df is None):
eff_model = NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT
elif require_explicit_model_for_positive_se:
raise ValueError(
"HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF:NW-08 OCR records with uncertainty_se > 0 "
"(or df/upper-bound specifications) require explicit ocr_uncertainty_model "
"('STUDENT_T_ESTIMATED_SE', 'KNOWN_SIGMA_NORMAL', or 'INDEPENDENT_JUSTIFIED_UPPER_BOUND')"
)
elif f_u95_ov is not None:
eff_model = NW08_OCR_UNCERTAINTY_MODEL_INDEPENDENT_UPPER
elif eff_df is not None:
eff_model = NW08_OCR_UNCERTAINTY_MODEL_STUDENT_T
else:
raise ValueError(
"HOLD_NW08_OCR_MISSING_UNCERTAINTY_MODEL_OR_DF:Positive uncertainty_se requires explicit inferential "
"model provenance: specify ocr_uncertainty_model='STUDENT_T_ESTIMATED_SE' with ocr_replicates_n>=2 "
"or ocr_degrees_of_freedom>=1, 'KNOWN_SIGMA_NORMAL' with ocr_uncertainty_provenance, or "
"'INDEPENDENT_JUSTIFIED_UPPER_BOUND' with measured_ocr_u95_override + ocr_uncertainty_provenance"
)
# 6. Resolve conservative upper bound under the validated inferential model
normal_z_cov_at_df: float | None = (
exact_student_t_cdf(MIN_NW08_CONSERVATIVE_Z_ONE_SIDED_95, eff_df) if eff_df is not None else None
)
req_min_mult: float | None = None
req_min_mult_dec: Decimal | None = None
applied_mult: float | None = None
applied_mult_dec: Decimal | None = None
assumptions_text: str
if eff_model == NW08_OCR_UNCERTAINTY_MODEL_ZERO_POINT:
if has_positive_se:
raise ValueError(
"HOLD_NW08_OCR_ZERO_MODEL_WITH_POSITIVE_SE:ZERO_UNCERTAINTY_DETERMINISTIC_POINT requires uncertainty_se == 0"
)
if f_u95_ov is not None:
raise ValueError(
"HOLD_NW08_OCR_UNEXPECTED_UPPER_BOUND_OVERRIDE:measured_ocr_u95_override is only valid with INDEPENDENT_JUSTIFIED_UPPER_BOUND"