File size: 2,273 Bytes
cfe4144
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""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)