Files
MeltMind/tools/phase2_residual_math.py
T

66 lines
2.9 KiB
Python

"""Array-only residual interface; no I/O, model, labels, or clock fitting policy.
The caller supplies a frozen, training-only clock. It also fixes the F precision
in the reviewed contract. Passing F explicitly avoids a hidden extra feature.
"""
import numpy as np
def learning_clock(end_ratios, component_ids):
"""Mean over components of mean retained-tet-end/t_set per learning part.
For the random v4 protocol each part can be its own unit, if the final
specification chooses part weighting. Caller enforces training roles.
"""
ratios = np.asarray(end_ratios, dtype=np.float64)
if ratios.ndim != 1 or not len(ratios) or len(component_ids) != len(ratios):
raise ValueError('Clock row count mismatch')
if not np.isfinite(ratios).all() or np.any(ratios <= 0):
raise ValueError('Invalid retained-tet endpoint ratio')
groups = {}
for group, ratio in zip(component_ids, ratios):
if not isinstance(group, str) or not group:
raise ValueError('Missing clock group identity')
groups.setdefault(group, []).append(float(ratio))
return float(np.mean([np.mean(v) for v in groups.values()]))
def prior(cdf, clock):
f = np.asarray(cdf)
if f.ndim != 1 or f.dtype.kind != 'f' or not len(f):
raise ValueError('Expected nonempty floating-point CDF vector')
if not np.isfinite(f).all() or np.any(f < 0) or np.any(f > 1):
raise ValueError('CDF outside [0,1] or nonfinite')
if not np.isscalar(clock) or not np.isfinite(clock) or clock <= 0:
raise ValueError('Clock must be a finite positive frozen scalar')
return np.asarray(f, dtype=np.float64)*float(clock)
def residual_target(target_star, cdf, clock, *, fit_dtype):
y = np.asarray(target_star, dtype=np.float64)
base = prior(cdf, clock)
if y.shape != base.shape or not np.isfinite(y).all() or np.any(y < 0):
raise ValueError('Invalid original normalized arrival target')
dtype = np.dtype(fit_dtype)
if dtype not in (np.dtype('float32'), np.dtype('float64')):
raise ValueError('Fit precision must be explicitly float32 or float64')
out = np.asarray(y-base, dtype=dtype)
if not np.isfinite(out).all():
raise ValueError('Residual overflow at fit precision')
# Negative residuals are valid. Never clip or impose a positivity loss here.
return out
def decode_seconds(predicted_residual, cdf, clock, t_set):
residual = np.asarray(predicted_residual, dtype=np.float64)
base = prior(cdf, clock)
if residual.shape != base.shape or not np.isfinite(residual).all():
raise ValueError('Invalid predicted residual')
if not np.isscalar(t_set) or not np.isfinite(t_set) or t_set <= 0:
raise ValueError('Invalid pre-solve seconds scale')
out = (base+residual)*float(t_set)
if not np.isfinite(out).all():
raise ValueError('Decoded prediction overflow')
# Keep negative predictions visible to scoring/diagnostics; no silent clamp.
return out