zeechimp commited on
Commit
e17d34f
·
verified ·
1 Parent(s): 968c754

Create liar_detector/signals.py

Browse files
Files changed (1) hide show
  1. liar_detector/signals.py +61 -0
liar_detector/signals.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Signal synthesis and lie injection. Pure numpy, no torch."""
2
+ from __future__ import annotations
3
+ import numpy as np
4
+
5
+ T_LEN = 400
6
+ ID_FAMILIES = ("offset", "scale", "saturation",
7
+ "quantization", "lag", "harmonic")
8
+ OOD_FAMILIES = ("deadzone", "dropout", "drift", "inversion")
9
+ ALL_FAMILIES = ID_FAMILIES + OOD_FAMILIES
10
+ FAMILY_INDEX = {f: i for i, f in enumerate(ID_FAMILIES)}
11
+
12
+
13
+ def synth_true(rng: np.random.Generator, t_len: int = T_LEN) -> np.ndarray:
14
+ t = np.arange(t_len)
15
+ x = np.zeros(t_len)
16
+ for _ in range(3):
17
+ f = rng.uniform(0.01, 0.15)
18
+ a = rng.uniform(0.5, 2.0)
19
+ p = rng.uniform(0.0, 2.0 * np.pi)
20
+ x += a * np.sin(2.0 * np.pi * f * t + p)
21
+ return x
22
+
23
+
24
+ def apply_lie(x: np.ndarray, rng: np.random.Generator, family: str) -> np.ndarray:
25
+ sx = float(np.std(x)) + 1e-9
26
+ if family == "offset":
27
+ return x + rng.uniform(-0.5, 0.5) * sx
28
+ if family == "scale":
29
+ return x * rng.uniform(0.85, 1.15)
30
+ if family == "saturation":
31
+ M = sx * rng.uniform(0.7, 1.5)
32
+ return np.clip(x, -M, M)
33
+ if family == "quantization":
34
+ q = sx * rng.uniform(0.05, 0.3)
35
+ return np.round(x / q) * q
36
+ if family == "lag":
37
+ d = int(rng.integers(1, 5))
38
+ return np.concatenate([np.full(d, x[0]), x[:-d]])
39
+ if family == "harmonic":
40
+ beta = rng.uniform(0.05, 0.15)
41
+ return x + beta * x * x / sx
42
+ if family == "deadzone":
43
+ eps = sx * rng.uniform(0.2, 0.5)
44
+ return np.where(np.abs(x) < eps, 0.0, x)
45
+ if family == "dropout":
46
+ mask = rng.random(len(x)) < 0.15
47
+ out = x.copy()
48
+ last = x[0]
49
+ for i in range(len(x)):
50
+ if mask[i]:
51
+ out[i] = last
52
+ else:
53
+ last = x[i]
54
+ return out
55
+ if family == "drift":
56
+ d = np.cumsum(rng.standard_normal(len(x))) * 0.03 * sx
57
+ return x + d
58
+ if family == "inversion":
59
+ eps = sx * rng.uniform(0.1, 0.3)
60
+ return np.where(np.abs(x) < eps, -x, x)
61
+ return x