"""Fixed Mold 9974ae27 objective; original regression plus unique-query E[d].""" import numpy as np import torch from phase2_h2_model import weighted_loss THETA = .03 COEFFICIENT = .001 def candidates(full_ids, query_ids, counts, coordinates, truth_seconds): """Exact original hard-peak reference; multiplicities do not vote in softmax. Keep original query records separately. Repeated IDs must have identical coordinates/truth; malformed data is an error, never an undefined waiver. """ full = np.asarray(full_ids) ids = np.asarray(query_ids) counts = np.asarray(counts) xyz = np.asarray(coordinates, dtype=np.float64) truth = np.asarray(truth_seconds, dtype=np.float64) if (full.ndim != 1 or ids.ndim != 1 or not len(ids) or full.dtype.kind not in 'iu' or ids.dtype.kind not in 'iu' or np.any(np.diff(full) <= 0) or counts.shape != ids.shape or counts.dtype.kind not in 'iu' or np.any(counts <= 0) or xyz.shape != (len(ids), 3) or truth.shape != ids.shape or not np.isfinite(xyz).all() or not np.isfinite(truth).all()): raise ValueError('Invalid frozen query identity or truth') unique, first, inverse = np.unique(ids, return_index=True, return_inverse=True) if not np.array_equal(xyz, xyz[first][inverse]) or not np.array_equal(truth, truth[first][inverse]): raise ValueError('Repeated raw ID has inconsistent coordinate/truth') index = np.searchsorted(full, unique) if np.any(index >= len(full)) or not np.array_equal(full[index], unique): raise ValueError('Query ID absent from full-node geometry') # np.unique orders raw IDs; the first true maximum implements the old tie. t = truth[first] peak = int(np.flatnonzero(t == t.max())[0]) distances = np.linalg.norm(xyz[first] - xyz[first][peak], axis=1) return dict(indices=index.astype(np.int64), distances=distances, unique_raw_ids=unique, true_peak_raw_id=int(unique[peak]), true_peak_ties=int(np.sum(t == t.max()))) def location_loss(residual, prior64, indices, distances): if prior64.dtype != torch.float64 or distances.dtype != torch.float64: raise ValueError('Location prior and distances must stay FP64') if residual.ndim != 1 or prior64.shape != residual.shape or indices.ndim != 1 or not indices.numel(): raise ValueError('Invalid location shapes') if indices.dtype != torch.int64 or distances.shape != indices.shape or torch.unique(indices).numel() != indices.numel(): raise ValueError('Exactly one equal-weight vote per candidate') s = prior64[indices] + residual[indices].to(torch.float64) if not bool(torch.isfinite(s).all()) or not bool(torch.isfinite(distances).all()) or bool((distances < 0).any()): raise ValueError('Nonfinite location data') return torch.sum(torch.softmax((s - s.max()) / THETA, dim=0) * distances) def objective(prediction, target, parts, nodes, total, prior64, indices, distances): regression = weighted_loss(prediction, target, parts, nodes, total) location = location_loss(prediction, prior64, indices, distances) return regression + COEFFICIENT * location, regression, location