File size: 7,319 Bytes
0b2d8e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/env python3
"""
reference_frontend.py -- numpy-only reimplementation of the ANIMAL-SPOT inference
preprocessing used by predict.py (StridedAudioDataset) for the BatSpot m09
call classifier, for ONE analysis window.

    PCM float32 @ 250 kHz (one window)  ->  model input float32 [1, 1, T, 256]

Port target: Go. Everything you need is in this header and the ~40 lines below.

---------------------------------------------------------------------------
STAGE 0  Audio loading / windowing (done by the caller, NOT in this file)
---------------------------------------------------------------------------
  * predict.py loads the file with soundfile (dtype float32, i.e. s16 / 32768),
    down-mixes to mono by averaging channels, and if the file rate != 250000
    resamples the WHOLE file with resampy.resample(filter="kaiser_best").
  * sequence_len = ceil(0.020 * 250000) = 5000 samples
    hop          = ceil(0.005 * 250000) = 1250 samples
  * window k = audio[k*1250 : min(k*1250 + 5000, n)]   (k = 0 .. N-1)
    N = max(ceil((n + 1 - 5000) / 1250), 1)
  * NO zero padding: a final window shorter than 5000 samples is processed
    as-is and yields fewer STFT frames (T < 38). The ONNX graph accepts a
    dynamic T, but such windows were never seen in training.
  * Each window is processed independently (pre-emphasis restarts per window).

---------------------------------------------------------------------------
STAGE 1  Pre-emphasis (factor 0.98), per window
---------------------------------------------------------------------------
  y[0] = x[0]                     (first sample passed through unchanged)
  y[i] = x[i] - 0.98 * x[i-1]     for i >= 1

---------------------------------------------------------------------------
STAGE 2  STFT power spectrogram (torch.stft semantics)
---------------------------------------------------------------------------
  n_fft = 256, hop = 128, win_length = 256
  window  : PERIODIC Hann, w[n] = 0.5 - 0.5*cos(2*pi*n/256), n = 0..255
            (torch.hann_window default; w[0] = 0, w[128] = 1)
  center  : False -> no padding at all; frame t covers y[t*128 : t*128+256]
  frames  : T = 1 + floor((len(y) - 256) / 128)   -> 38 for 5000 samples
            (samples 4992..4999 are never used). len(y) < 256 is an error.
  FFT     : one-sided, bins 0..128 (129 bins), unnormalised forward DFT
            X[t,k] = sum_n y[t*128+n] * w[n] * exp(-2j*pi*k*n/256)
  power   : P[t,k] = |X[t,k]|^2 / sum(w^2)       with sum(w^2) = 96.0 exactly
            (ANIMAL-SPOT divides re/im by sqrt(sum w^2) then squares)
  layout  : [T, 129]  (time-major, frequency is the LAST / fastest axis)

---------------------------------------------------------------------------
STAGE 3  Linear frequency compression ("Interpolate", freq_compression=linear)
---------------------------------------------------------------------------
  n_fft'  = (129 - 1) * 2 = 256
  min_bin = floor(256 * 10000 / 250000) = floor(10.24) = 10
  max_bin = min(255, ceil(256 * 125000 / 250000))     = 128
  crop    : P[:, 10:128]  -> 118 bins (bins 10..127; Nyquist bin 128 EXCLUDED)
            (bin k centre = k * 976.5625 Hz -> 9.77 kHz .. 124.0 kHz)
  resize  : NEAREST-neighbour (torch F.interpolate mode="nearest") 118 -> 256:
            out[:, j] = crop[:, floor(j * 118 / 256)]     j = 0..255
            (scale 118/256 = 0.4609375 is exact in float32; time axis untouched)

---------------------------------------------------------------------------
STAGE 4  Amplitude -> dB  (Amp2Db, stype="power", min_level_db = -100)
---------------------------------------------------------------------------
  D = 10 * log10( max(P, 1e-10) )        (floor 1e-10 == -100 dB; no ref, no top_db)

---------------------------------------------------------------------------
STAGE 5  Normalisation: MinMaxNormalize (predict --min_max_norm, as configured)
---------------------------------------------------------------------------
  D = D - min(D)                         (min over the whole [T,256] window)
  if max(D) == 0:  return D              (constant window, e.g. digital silence
                                          -> all-zero tensor, NO NaN)
  D = D / max(D)                         -> range [0, 1], exactly 0 and 1 present
  (Alternative path, NOT used here: Normalize = clip((D - 20 + 100)/100, 0, 1),
   i.e. ref_level_db = 20, min_level_db = -100; this is what training used
   unless training also had min-max enabled -- see NOTES.md.)

---------------------------------------------------------------------------
STAGE 6  Tensor layout
---------------------------------------------------------------------------
  model input  : float32 [B, 1, T, 256]  (NCHW; H = time frames, W = freq bins,
                 freq index 0 = lowest frequency), T = 38 for a full window.
  model output : logits [B, 15]; predict.py applies softmax over dim 1, takes
                 argmax as the class and reports a detection if max prob >= 0.5.

All arithmetic in torch is float32. This file computes in float64 and casts to
float32 at the end; observed max abs diff vs. the torch path is reported in
NOTES.md (~1e-6 order, dominated by FFT rounding near the dB floor).
"""
import numpy as np

SR = 250000
N_FFT = 256
HOP = 128
N_FREQ_BINS = 256
F_MIN = 10000
F_MAX = 125000
PREEMPH = 0.98
MIN_LEVEL_DB = -100.0
SEQ_LEN = 5000      # ceil(0.020 * SR)
WIN_HOP = 1250      # ceil(0.005 * SR)


def hann_periodic(n=N_FFT):
    i = np.arange(n, dtype=np.float64)
    return 0.5 - 0.5 * np.cos(2.0 * np.pi * i / n)


def frontend(pcm):
    """pcm: 1-D float32 window at 250 kHz (normally 5000 samples).
    Returns float32 array [1, 1, T, 256]."""
    x = np.asarray(pcm, dtype=np.float64)
    if x.ndim != 1 or x.shape[0] < N_FFT:
        raise ValueError("need a 1-D window with >= 256 samples")
    # 1. pre-emphasis
    y = np.empty_like(x)
    y[0] = x[0]
    y[1:] = x[1:] - PREEMPH * x[:-1]
    # 2. STFT, center=False, periodic Hann, power / sum(w^2)
    w = hann_periodic()
    T = 1 + (y.shape[0] - N_FFT) // HOP
    frames = np.stack([y[t * HOP:t * HOP + N_FFT] for t in range(T)]) * w
    X = np.fft.rfft(frames, n=N_FFT, axis=1)                    # [T, 129]
    P = (X.real ** 2 + X.imag ** 2) / np.sum(w * w)             # sum(w^2) = 96
    # 3. crop 10..127 and nearest-resize 118 -> 256
    n_fft = (P.shape[1] - 1) * 2
    min_bin = int(max(0, np.floor(n_fft * F_MIN / SR)))
    max_bin = int(min(n_fft - 1, np.ceil(n_fft * F_MAX / SR)))
    C = P[:, min_bin:max_bin]
    n_in = C.shape[1]
    idx = np.minimum((np.arange(N_FREQ_BINS) * n_in) // N_FREQ_BINS, n_in - 1)
    S = C[:, idx]                                               # [T, 256]
    # 4. power -> dB with -100 dB floor
    D = 10.0 * np.log10(np.maximum(S, 10.0 ** (MIN_LEVEL_DB / 10.0)))
    # 5. min-max normalisation (silence -> zeros, never NaN)
    D = D - D.min()
    m = D.max()
    if m != 0.0:
        D = D / m
    return D.astype(np.float32)[None, None, :, :]


def softmax(logits):
    z = np.asarray(logits, dtype=np.float64)
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)


if __name__ == "__main__":
    import sys
    pcm = np.fromfile(sys.argv[1], dtype="<f4")
    out = frontend(pcm)
    print(out.shape, float(out.min()), float(out.max()))