1use core::fmt::{self, Write};
18
19use tinymind::rand::GlibcRand;
20use tinymind::{Dense, Linear, NeuralNetwork, Q16_16, Tanh};
21
22pub const WINDOW: usize = 8;
24pub const CODE: usize = 4;
26pub const TRAIN_STEPS: u32 = 3_000;
28pub const NORMAL_WINDOWS: u32 = 256;
30pub const FAULT_WINDOWS: u32 = 64;
32
33pub type Autoencoder = NeuralNetwork<(
35 Dense<Q16_16, Tanh, WINDOW, CODE>,
36 Dense<Q16_16, Linear, CODE, WINDOW>,
37)>;
38
39const SINE: [i32; 64] = [
41 0, 6424, 12785, 19024, 25080, 30893, 36410, 41576, 46341, 50660, 54491, 57798, 60547, 62714,
42 64277, 65220, 65536, 65220, 64277, 62714, 60547, 57798, 54491, 50660, 46341, 41576, 36410,
43 30893, 25080, 19024, 12785, 6424, 0, -6424, -12785, -19024, -25080, -30893, -36410, -41576,
44 -46341, -50660, -54491, -57798, -60547, -62714, -64277, -65220, -65536, -65220, -64277, -62714,
45 -60547, -57798, -54491, -50660, -46341, -41576, -36410, -30893, -25080, -19024, -12785, -6424,
46];
47
48#[derive(Clone, Copy, PartialEq, Eq)]
50pub enum Kind {
51 Normal,
52 Frequency,
54 Harmonic,
56 Spike,
58 Stall,
60}
61
62pub const FAULTS: [(Kind, &str); 4] = [
63 (Kind::Frequency, "frequency"),
64 (Kind::Harmonic, "harmonic"),
65 (Kind::Spike, "spike"),
66 (Kind::Stall, "stall"),
67];
68
69pub struct Signal(GlibcRand);
71
72impl Signal {
73 pub fn new(seed: u32) -> Self {
74 Self(GlibcRand::new(seed))
75 }
76
77 fn below(&mut self, n: u32) -> i32 {
79 (self.0.next_i32() as u32 % n) as i32
80 }
81
82 pub fn window(&mut self, kind: Kind) -> [Q16_16; WINDOW] {
84 let step = if kind == Kind::Frequency { 9 } else { 3 };
87 let amplitude = 26_214 + self.below(13_108); let phase = self.below(64);
89 let mut w = [Q16_16::ZERO; WINDOW];
90 for (n, s) in w.iter_mut().enumerate() {
91 let k = (phase + n as i32 * step) as usize % 64;
92 let mut v = Q16_16::from_raw(amplitude) * Q16_16::from_raw(SINE[k]);
93 if kind == Kind::Harmonic {
94 let k3 = (phase + 3 * n as i32 * step) as usize % 64;
95 v += Q16_16::from_raw(19_661) * Q16_16::from_raw(SINE[k3]); }
97 let noise = self.below(2_623) - 1_311; *s = v + Q16_16::from_raw(noise);
99 }
100 match kind {
101 Kind::Spike => {
102 let at = self.below(WINDOW as u32) as usize;
103 w[at] += Q16_16::from_raw(52_429); }
105 Kind::Stall => {
106 let held = w[0];
107 w = [held; WINDOW];
108 }
109 _ => {}
110 }
111 w
112 }
113}
114
115#[inline(never)]
118pub fn score(nn: &mut Autoencoder, w: &[Q16_16; WINDOW]) -> Q16_16 {
119 nn.feed_forward(w);
120 nn.calculate_error(w)
121}
122
123pub fn new_autoencoder(seed: u32) -> Autoencoder {
125 let mut rng = GlibcRand::new(seed);
126 let half = Q16_16::ONE.raw() / 2;
127 let mut nn = Autoencoder::new(|| Q16_16::from_raw(rng.next_i32() % (2 * half + 1) - half));
128 nn.set_learning_rate(Q16_16::from_raw(1 << 11)); nn.set_momentum_rate(Q16_16::from_raw(1 << 15)); nn.set_acceleration_rate(Q16_16::ZERO);
131 nn.set_gradient_clip(Some((Q16_16::from_int(-1), Q16_16::ONE)));
132 nn
133}
134
135#[inline(never)]
139pub fn train_step(nn: &mut Autoencoder, w: &[Q16_16; WINDOW]) -> Q16_16 {
140 let error = score(nn, w);
141 nn.train(w);
142 error
143}
144
145#[inline(never)]
148pub fn train(nn: &mut Autoencoder, signal: &mut Signal, steps: u32) -> i32 {
149 let mut recent = 0i32;
152 for step in 0..steps {
153 let w = signal.window(Kind::Normal);
154 let error = train_step(nn, &w);
155 if step + 500 >= steps {
156 recent = recent.saturating_add(error.raw());
157 }
158 }
159 recent / 500
160}
161
162pub struct Fnv(pub u32);
164
165impl Fnv {
166 pub fn new() -> Self {
167 Self(0x811C_9DC5)
168 }
169 pub fn add(&mut self, raw: i32) {
170 for b in raw.to_le_bytes() {
171 self.0 ^= u32::from(b);
172 self.0 = self.0.wrapping_mul(0x0100_0193);
173 }
174 }
175}
176
177#[inline(never)]
182pub fn evaluate(
183 nn: &mut Autoencoder,
184 signal: &mut Signal,
185 out: &mut dyn Write,
186 each: &mut dyn FnMut(&str, i32),
187) -> Result<u32, fmt::Error> {
188 let mut hash = Fnv::new();
189 let (l0, l1) = nn.layers();
190 for row in l0.weights() {
191 for w in row {
192 hash.add(w.raw());
193 }
194 }
195 for w in l0.bias_weights() {
196 hash.add(w.raw());
197 }
198 for row in l1.weights() {
199 for w in row {
200 hash.add(w.raw());
201 }
202 }
203 for w in l1.bias_weights() {
204 hash.add(w.raw());
205 }
206
207 let mut max_normal = 0;
209 for _ in 0..NORMAL_WINDOWS {
210 let e = score(nn, &signal.window(Kind::Normal)).raw();
211 hash.add(e);
212 max_normal = max_normal.max(e);
213 }
214 let threshold = max_normal.saturating_mul(2);
215 writeln!(
216 out,
217 "threshold={threshold} (2 x the largest error on {NORMAL_WINDOWS} normal windows, raw Q16.16)"
218 )?;
219
220 let mut flagged = |kind: Kind, name: &str, n: u32, hash: &mut Fnv| {
221 let mut count = 0;
222 for _ in 0..n {
223 let e = score(nn, &signal.window(kind)).raw();
224 hash.add(e);
225 each(name, e);
226 count += u32::from(e > threshold);
227 }
228 count
229 };
230 let fp = flagged(Kind::Normal, "normal", NORMAL_WINDOWS, &mut hash);
231 writeln!(out, "normal: flagged {fp}/{NORMAL_WINDOWS} (false alarms)")?;
232 for (kind, name) in FAULTS {
233 let tp = flagged(kind, name, FAULT_WINDOWS, &mut hash);
234 writeln!(out, "{name}: flagged {tp}/{FAULT_WINDOWS}")?;
235 }
236 writeln!(out, "hash=0x{:08X}", hash.0)?;
237 Ok(hash.0)
238}
239
240#[allow(dead_code)]
243pub fn run(out: &mut dyn Write, each: &mut dyn FnMut(&str, i32)) -> Result<u32, fmt::Error> {
244 let mut nn = new_autoencoder(1);
245 let mut signal = Signal::new(7);
246 writeln!(
247 out,
248 "autoencoder {WINDOW}-{CODE}-{WINDOW} (tanh, linear), Q16.16, {TRAIN_STEPS} training steps on normal windows"
249 )?;
250 let recent = train(&mut nn, &mut signal, TRAIN_STEPS);
251 writeln!(
252 out,
253 "training error, mean of the last 500 steps={recent} (raw Q16.16)"
254 )?;
255 evaluate(&mut nn, &mut signal, out, each)
256}