mustafaabdullahk's picture
Add milk NIR simulator
d5891f7 verified
Raw History Blame Contribute Delete
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;
};
}