class AtomicObservation: """ Deep-immutable Stage-0 evidence atom (MappingProxyType-frozen) derived strictly from ENDPOINT_REGISTRY_SPEC (forbidding caller-supplied canonical_projection or cap overrides; IIP-0024; DEC-103). """ __slots__ = ( 'endpoint_id', 'scope_type', 'scope_key', 'kind', 'value_or_k', 'se_or_n', 'sample_n', 'unit', 'controls', 'assay_version', 'campaign_id', '_campaign_explicit', 'timepoint', 'sample_unit_id', 'atom_sha256', ) def __init__( self, *, endpoint_id: str, scope_type: str, scope_key: MCBScopeKey | LotScopeKey | AssembledDeviceLotScopeKey, kind: str, value_or_k: Any, se_or_n: Any = None, sample_n: int | None = None, unit: str = 'canonical_unit', controls: dict[str, Any] | MappingProxyType | None = None, assay_version: str = 'STAGE0_IIP0024_V1', campaign_id: str | None = None, timepoint: str = 'STAGE0', sample_unit_id: str = 'SAMPLE-01', **forbidden_kwargs: Any, ) -> None: if forbidden_kwargs: raise ValueError( f'Caller-supplied projection or threshold overrides are prohibited on AtomicObservation: ' f'{sorted(forbidden_kwargs.keys())} (IIP-0024; DEC-103)' ) if not isinstance(endpoint_id, str) or not endpoint_id.strip() or endpoint_id != endpoint_id.strip(): raise ValueError('endpoint_id must be a canonical non-whitespace-padded nonempty string (IIP-0024; DEC-103)') if scope_type == 'MCB_SCOPE' and not isinstance(scope_key, MCBScopeKey): raise ValueError('MCB_SCOPE requires an MCBScopeKey instance (IIP-0024; DEC-103)') if scope_type == 'LOT_SCOPE' and not isinstance(scope_key, LotScopeKey): raise ValueError('LOT_SCOPE requires a LotScopeKey instance (IIP-0024; DEC-103)') if scope_type == 'ASSEMBLED_DEVICE_LOT_SCOPE' and not isinstance(scope_key, AssembledDeviceLotScopeKey): raise ValueError('ASSEMBLED_DEVICE_LOT_SCOPE requires an AssembledDeviceLotScopeKey instance (IIP-0024; DEC-103)') if scope_type not in ('MCB_SCOPE', 'LOT_SCOPE', 'ASSEMBLED_DEVICE_LOT_SCOPE'): raise ValueError(f'Unknown scope_type {scope_type!r} (IIP-0024; DEC-103)') if kind not in ('CONTINUOUS_STUDENT_T', 'SCALAR_EXACT', 'EXACT_INTEGER_COUNT', 'STRUCTURED_PANEL', 'METADATA_CONTROL'): raise ValueError(f'Unknown AtomicObservation kind {kind!r} (IIP-0024; DEC-103)') if kind == 'EXACT_INTEGER_COUNT': if not _is_strict_int_iip0024(value_or_k) or not _is_strict_int_iip0024(se_or_n): raise ValueError('EXACT_INTEGER_COUNT requires strict Python integers (k, n) pre-normalization (IIP-0024; DEC-103)') if se_or_n <= 0 or value_or_k < 0 or value_or_k > se_or_n: raise ValueError('EXACT_INTEGER_COUNT requires 0 <= k <= n and n > 0 (IIP-0024; DEC-103)') if kind == 'CONTINUOUS_STUDENT_T': if ( not _is_strict_finite_number_iip0024(value_or_k) or not _is_strict_finite_number_iip0024(se_or_n) or float(se_or_n) <= 0.0 or not _is_strict_int_iip0024(sample_n) or sample_n < 6 ): raise ValueError('CONTINUOUS_STUDENT_T requires finite mean, SE > 0, and integer sample_n >= 6 (IIP-0024; DEC-103)') if controls is not None and not isinstance(controls, (dict, MappingProxyType)): raise ValueError('AtomicObservation controls must be a dict or MappingProxyType (IIP-0024; DEC-103)') ctrl_dict = dict(controls) if controls is not None else {} for bad_ck in ('canonical_projection', 'canonical_projection_keys', 'override_cap', 'override_requires_k_eq_0', 'cap'): if bad_ck in ctrl_dict: raise ValueError(f'Caller-supplied {bad_ck!r} inside controls is prohibited; caps derive from ENDPOINT_REGISTRY_SPEC (IIP-0024; DEC-103)') frozen_val = _deep_freeze_iip0024(value_or_k) frozen_ctrl = _deep_freeze_iip0024(ctrl_dict) campaign_explicit = campaign_id is not None eff_campaign_id = 'CAMP-DEFAULT-01' if campaign_id is None else campaign_id for s_name, s_val in ( ('unit', unit), ('assay_version', assay_version), ('campaign_id', eff_campaign_id), ('timepoint', timepoint), ('sample_unit_id', sample_unit_id), ): if not isinstance(s_val, str) or not s_val.strip() or s_val != s_val.strip(): raise ValueError(f'{s_name} must be a canonical non-whitespace-padded nonempty string (IIP-0024; DEC-103)') canonical_doc = { 'registry_version': ENDPOINT_REGISTRY_SPEC['registry_version'], 'endpoint_id': endpoint_id, 'scope_type': scope_type, 'scope_key': list(scope_key.as_tuple()), 'kind': kind, 'value_or_k': _deep_to_jsonable_iip0024(frozen_val), 'se_or_n': se_or_n, 'sample_n': sample_n, 'unit': unit, 'controls': _deep_to_jsonable_iip0024(frozen_ctrl), 'assay_version': assay_version, 'campaign_id': eff_campaign_id, 'timepoint': timepoint, 'sample_unit_id': sample_unit_id, } digest = hashlib.sha256( json.dumps(canonical_doc, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('utf-8') ).hexdigest() object.__setattr__(self, 'endpoint_id', endpoint_id) object.__setattr__(self, 'scope_type', scope_type) object.__setattr__(self, 'scope_key', scope_key) object.__setattr__(self, 'kind', kind) object.__setattr__(self, 'value_or_k', frozen_val) object.__setattr__(self, 'se_or_n', se_or_n) object.__setattr__(self, 'sample_n', sample_n) object.__setattr__(self, 'unit', unit) object.__setattr__(self, 'controls', frozen_ctrl) object.__setattr__(self, 'assay_version', assay_version) object.__setattr__(self, 'campaign_id', eff_campaign_id) object.__setattr__(self, '_campaign_explicit', campaign_explicit) object.__setattr__(self, 'timepoint', timepoint) object.__setattr__(self, 'sample_unit_id', sample_unit_id) object.__setattr__(self, 'atom_sha256', digest) def __setattr__(self, name: str, value: Any) -> None: raise TypeError('AtomicObservation is strictly immutable (IIP-0024; DEC-103)') def __delattr__(self, name: str) -> None: raise TypeError('AtomicObservation is strictly immutable (IIP-0024; DEC-103)') def digest(self) -> str: return self.atom_sha256 def evaluate_rare_event_count_iip0024( *, gate_id: str, k: Any, n: Any, max_u95_fraction: float, require_observed_zero: bool = False, reported_rate: Any = None, rate_scale: float = 1.0, sampling_independence_model: str = 'INDEPENDENT_BIOLOGICAL_OPPORTUNITIES', clustered_sampling: bool = False, validated_clustered_estimator_id: str | None = None, eta_spike_recovery_l95: Any = None, f_clonogenic: Any = None, use_poisson_protocol_floor: bool = False, require_explicit_calibration: bool = False, ) -> dict[str, Any]: """ Fail-closed rare-event integer count validator (IIP-0024; DEC-103; hardened IIP-0031; DEC-110): - Rejects bool, float (e.g. 298.9 or 300.0), NaN, Inf, < 0, k > n with structured HOLD. - Enforces k == 0 observed-zero hard veto BEFORE calibration/recovery holds so an attributable integer k >= 1 is never downgraded to a calibration hold. - Forbids implicit 1.0 defaults on missing recovery / f_clonogenic for Tier 6B / clonogenic or explicit-calibration gates. - Computes exact independent binomial-thinning sensitivity U95 = (1 - 0.05**(1/n)) / (f_clono * eta) (holding 0/920 at eta = 0.325 where U95 = 0.01000288 > 0.01, never floor(n * eta)). - Rejects unregistered cluster estimators and naive DEFF substitution. """ is_tier6b_gate = ('TIER6B' in str(gate_id).upper()) or ('CLONOGENIC' in str(gate_id).upper()) # Latch attributable integer k >= 1 BEFORE missing/invalid n, calibration holds, recovery bounds, or clustered checks (IIP-0031; DEC-110): if require_observed_zero and _is_strict_int_iip0024(k) and k > 0: u95_nom = ( round(clopper_pearson_upper95_independent(k, n), 10) if (_is_strict_int_iip0024(n) and n >= k and n > 0) else None ) return { 'status': 'FAIL_HARD_STOP', 'reason': 'FAIL_TIER6B_OUTGROWTH_DETECTED' if is_tier6b_gate else 'OBSERVED_POSITIVE_EVENT_VIOLATES_MANDATORY_ZERO_VETO', 'gate_id': gate_id, 'k': k, 'n_nominal': n if _is_strict_int_iip0024(n) else None, 'u95_nominal': u95_nom, } if k is None or n is None: return { 'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION' if is_tier6b_gate else 'HOLD_MISSING_ATOMIC_INTEGER_K_OR_N', 'gate_id': gate_id, } if not _is_strict_int_iip0024(k) or not _is_strict_int_iip0024(n): return { 'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION' if is_tier6b_gate else 'HOLD_NON_INTEGER_COUNT_OR_DENOMINATOR_REJECTED', 'gate_id': gate_id, } if n <= 0 or k < 0 or k > n: return { 'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION' if is_tier6b_gate else 'HOLD_INVALID_COUNT_BOUNDS', 'gate_id': gate_id, } if reported_rate is not None: if not _is_strict_finite_number_iip0024(reported_rate): return {'status': 'HOLD_NONFINITE_REPORTED_RATE', 'gate_id': gate_id} expected_rate = rate_scale * (k / float(n)) if abs(float(reported_rate) - expected_rate) > 1e-9: return {'status': 'HOLD_RATE_COUNT_INCONSISTENCY_NEVER_INFER_FROM_ROUNDED_RATE', 'gate_id': gate_id} if clustered_sampling or sampling_independence_model != 'INDEPENDENT_BIOLOGICAL_OPPORTUNITIES': if ( not isinstance(validated_clustered_estimator_id, str) or validated_clustered_estimator_id.strip() not in REGISTERED_VALIDATED_CLUSTER_ESTIMATORS_IIP0024 ): return { 'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION' if is_tier6b_gate else 'HOLD_CLUSTERED_OR_UNREGISTERED_ESTIMATOR_REJECTED', 'gate_id': gate_id, } if is_tier6b_gate or require_explicit_calibration: if eta_spike_recovery_l95 is None or f_clonogenic is None: return { 'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION' if is_tier6b_gate else 'HOLD_MISSING_RECOVERY_OR_CLONOGENIC_FACTOR', 'reason': 'MISSING_RECOVERY_OR_CLONOGENIC_FACTOR_NO_IMPLICIT_1P0_DEFAULT', 'gate_id': gate_id, } else: if eta_spike_recovery_l95 is None: eta_spike_recovery_l95 = 1.0 if f_clonogenic is None: f_clonogenic = 1.0 if not _is_strict_finite_number_iip0024(eta_spike_recovery_l95) or not _is_strict_finite_number_iip0024(f_clonogenic): return { 'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION' if is_tier6b_gate else 'HOLD_NONFINITE_RECOVERY_OR_CLONOGENIC_FACTOR', 'gate_id': gate_id, } eta = float(eta_spike_recovery_l95) f_clono = float(f_clonogenic) if not (0.0 < eta <= 1.0) or not (0.0 < f_clono <= 1.0): return { 'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION' if is_tier6b_gate else 'HOLD_OUT_OF_RANGE_RECOVERY_OR_CLONOGENIC_FACTOR', 'gate_id': gate_id, } if is_tier6b_gate and (eta < 0.50 or (f_clono * eta) < 0.50): return {'status': 'HOLD_TIER6B_UNQUALIFIED_FRACTION', 'reason': 'TIER6B_DETECTION_BELOW_0P50_FLOOR', 'gate_id': gate_id} if (eta < 1.0 or f_clono < 1.0) and eta < 0.30: return {'status': 'HOLD_SPIKE_RECOVERY_BELOW_0P30_QUALIFICATION_FLOOR', 'gate_id': gate_id} eff_prob = f_clono * eta if eff_prob < 1.0 and k > 0: return { 'status': 'HOLD_NONZERO_RECOVERY_ADJUSTED_COUNT_REQUIRES_VALIDATED_JOINT_ESTIMATOR', 'gate_id': gate_id, } if k == 0: # Exact independent per-trial detection probability P(obs=0) = (1 - p * f_clono * eta)**n <= 0.05: u95_bin = min(1.0, (-math.expm1(math.log(0.05) / float(n))) / eff_prob) u95_pois = min(1.0, (-math.log(0.05) / (float(n) * eff_prob))) else: