Spaces:
Running
Running
Download nir.js from amazeng-co/milk-nir-simulator: direct link, hf CLI and curl.
- Browser
- Download file 1.56 kB
-
https://huggingface.co/spaces/amazeng-co/milk-nir-simulator/resolve/main/nir.js
- Command line
-
hf download hf://spaces/amazeng-co/milk-nir-simulator/nir.js
-
curl -L -o nir.js https://huggingface.co/spaces/amazeng-co/milk-nir-simulator/resolve/main/nir.js
1.56 kB
| // Same math as milk_nir_pls.onnx: transmittance -> absorbance -> SNV -> Savitzky-Golay d1 -> linear. | |
| export function preprocess(t, sg) { | |
| const n = t.length, h = (sg.length - 1) / 2; | |
| const a = t.map((v) => -Math.log10(Math.max(v, 1e-6))); | |
| const mean = a.reduce((s, v) => s + v, 0) / n; | |
| const std = Math.sqrt(a.reduce((s, v) => s + (v - mean) ** 2, 0) / (n - 1)); // unbiased, like torch.std | |
| const z = a.map((v) => (v - mean) / std); | |
| // replicate padding, cross-correlation (torch conv1d) | |
| return z.map((_, i) => sg.reduce((s, k, j) => s + k * z[Math.min(n - 1, Math.max(0, i + j - h))], 0)); | |
| } | |
| export function predict(t, m) { | |
| const d = preprocess(t, m.sg); | |
| return m.w.map((row, k) => row.reduce((s, wi, i) => s + wi * d[i], m.b[k])); | |
| } | |
| // Simulated instrument effects: wavelength shift (px, linear interp), lamp intensity (gain), detector noise. | |
| export function perturb(t, { shift = 0, gain = 1, noise = 0 }, seed = 1) { | |
| const n = t.length, rand = mulberry32(seed); | |
| return t.map((_, i) => { | |
| const x = Math.min(n - 1, Math.max(0, i - shift)), i0 = Math.floor(x), i1 = Math.min(n - 1, i0 + 1), f = x - i0; | |
| return (t[i0] * (1 - f) + t[i1] * f) * gain * (1 + noise * gauss(rand)); | |
| }); | |
| } | |
| function gauss(rand) { | |
| return Math.sqrt(-2 * Math.log(1 - rand())) * Math.cos(2 * Math.PI * rand()); | |
| } | |
| function mulberry32(a) { | |
| return () => { | |
| a |= 0; a = (a + 0x6d2b79f5) | 0; | |
| let t = Math.imul(a ^ (a >>> 15), 1 | a); | |
| t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; | |
| return ((t ^ (t >>> 14)) >>> 0) / 4294967296; | |
| }; | |
| } | |