"""An auditable morphology encoder for HHDC photon-return cubes.""" import numpy as np SHAPE = (128, 48, 48) DIMENSIONS = 64 def morphology(cubes): """Return 128 morphology features and three physical summary statistics per cube.""" array = np.asarray(cubes, dtype=np.float32).reshape(-1, 128, 48 * 48) count = len(array) profiles = array.sum(axis=2, dtype=np.float64) present = array > 0 footprints = present.any(axis=1) top = 127 - present[:, ::-1, :].argmax(axis=1) density = array.sum(axis=1, dtype=np.float64) def distribution(matrix): total = matrix.sum(axis=1, keepdims=True) normalized = np.divide(matrix, total, out=np.zeros(matrix.shape, dtype=np.float64), where=total > 0) return np.sqrt(normalized) def histogram(values, valid): block = np.arange(count, dtype=np.int64)[:, None] * 16 return np.bincount((values + block)[valid], minlength=count * 16).reshape(count, 16) return_profile = profiles.reshape(count, 64, 2).sum(axis=2) footprint_profile = present.reshape(count, 32, 4, -1).any(axis=2).sum(axis=2) top_histogram = histogram(top // 8, footprints) density_band = np.minimum(np.floor(np.log2(1 + density)).astype(np.int64), 15) density_histogram = histogram(density_band, np.ones_like(footprints)) descriptor = np.concatenate([distribution(part) for part in (return_profile, footprint_profile, top_histogram, density_histogram)], axis=1) cumulative = profiles.cumsum(axis=1) total = cumulative[:, -1] p95_bin = (cumulative >= total[:, None] * 0.95).argmax(axis=1) upper_fraction = (footprints & (top >= 4)).mean(axis=1) mean_returns = density.mean(axis=1) return descriptor.astype(np.float32), np.column_stack((p95_bin, upper_fraction, mean_returns)).astype(np.float32) def embed(descriptor, model): """Apply the saved training-only scaler and PCA and normalize for cosine search.""" features = (descriptor - model['mean']) / model['scale'] projected = (features - model['pca_mean']) @ model['components'].T norm = np.linalg.norm(projected, axis=-1, keepdims=True) return np.divide(projected, norm, out=np.zeros_like(projected), where=norm > 0).astype(np.float32)