Episode 15: An Envelope
Measure the size of an oscillation with a RollingStatistic, and put Episode 12’s Threshold on that instead of on the oscillation itself.
Episode 12 put a threshold on a slow swing. Most signals worth a decision are not slow: alpha is a 10 Hz oscillation whose size changes, and a threshold on the oscillation itself fires on every cycle. What the decision needs is the size. The RMS over a sliding window estimates the signal’s envelope: for a sinusoid it reads the amplitude over the square root of two, with the noise added in quadrature.
Three generators and an Equation make a 10 Hz carrier that switches on and off once a second, in noise that is there all the time. frame_size=1 keeps every node at 250 Hz: RollingStatistic emits one value per input frame.
28 # A 10 Hz carrier switched on and off once a second, plus noise that
29 # is there all the time. frame_size=1 keeps every node at 250 Hz:
30 # RollingStatistic emits one value per input frame
31 carrier = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
32 frame_size=1, signal_frequency=10,
33 signal_amplitude=1.0, name="carrier")
34 gate = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
35 frame_size=1, signal_frequency=0.5,
36 signal_shape="rect", signal_amplitude=1.0,
37 name="gate")
38 noise = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
39 frame_size=1, noise_amplitude=0.3, name="noise")
40 bursts = gp.Equation("a * (1 + g) / 2 + n")
41 p.connect(carrier, bursts["a"])
42 p.connect(gate, bursts["g"])
43 p.connect(noise, bursts["n"])
RollingStatistic(statistic="rms", window_size=50) emits, for every sample, the RMS of the last 50: 0.2 s, two cycles of the carrier. It offers mean, var, std, min, max, peak_to_peak and median the same way, and takes window_seconds= instead of a sample count if you prefer.
45 # The envelope: the RMS over the last WINDOW samples, one per sample
46 envelope = gp.RollingStatistic(statistic="rms", window_size=WINDOW)
47 p.connect(bursts, envelope)
The same threshold on the signal and on its envelope, and a third on the envelope, at 0.55 with release and dwell as Episode 12 taught.
49 # Three decisions: on the signal, on its envelope, and on the envelope
50 # debounced as Episode 12 taught
51 on_signal = gp.Threshold(level=0.5)
52 on_envelope = gp.Threshold(level=0.5)
53 debounced = gp.Threshold(level=0.55, release=0.45, dwell=25)
54 p.connect(bursts, on_signal)
55 p.connect(envelope, on_envelope)
56 p.connect(envelope, debounced)
Run the script. The envelope is read inside the first burst and the first pause, well away from the edges, and each decision’s state changes are counted:
4 s: a 10 Hz burst every other second, amplitude 1, noise of standard deviation 0.3
envelope during a burst 0.77
envelope between bursts 0.32
Threshold(level=0.5) on the signal ... transitions
Threshold(level=0.5) on the envelope ... transitions
... with release=0.45, dwell=25 4 transitions
Four is the answer: two bursts, each switched on and off. On the signal the threshold fires twice per cycle of the carrier and on every noise spike between bursts. On the envelope it sees the size of the oscillation: a sine of amplitude 1 has an RMS of 0.71, the noise alone about 0.3, and the two add in quadrature, which is the 0.77 during a burst. The envelope still wobbles as it crosses the level, which is what release and dwell are for. The noise is random, so the first counts vary from run to run.
A shorter window follows the bursts faster and wobbles more; a longer one is smoother and later. Either way the envelope lags the burst by about half a window.
In this episode, you learned how to:
measure an envelope with RollingStatistic
decide on the size of an oscillation, not on the oscillation
keep every node at the signal’s rate with
frame_size=1
Proceed to Episode 16, where a whole recording goes through a pipeline in one call.
Nodes in this episode: Generator, Equation, RollingStatistic, Threshold, Collector
File s2e15_an_envelope.py – View file on GitHub
1"""Season 2, Episode 15: a RollingStatistic reads an envelope."""
2
3import time
4
5import numpy as np
6
7import gpype as gp
8
9SAMPLING_RATE = 250
10SECONDS = 4.0
11WINDOW = 50 # samples: 0.2 s, two cycles of 10 Hz
12
13
14def collected(collector):
15 """The one channel a Collector kept, as float64."""
16 return np.asarray(collector.result.data, dtype=np.float64)[:, 0]
17
18
19def transitions(collector):
20 """How many times a Threshold's output changed state."""
21 return int(np.count_nonzero(np.diff(collected(collector))))
22
23
24if __name__ == "__main__":
25
26 p = gp.Pipeline()
27
28 # A 10 Hz carrier switched on and off once a second, plus noise that
29 # is there all the time. frame_size=1 keeps every node at 250 Hz:
30 # RollingStatistic emits one value per input frame
31 carrier = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
32 frame_size=1, signal_frequency=10,
33 signal_amplitude=1.0, name="carrier")
34 gate = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
35 frame_size=1, signal_frequency=0.5,
36 signal_shape="rect", signal_amplitude=1.0,
37 name="gate")
38 noise = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
39 frame_size=1, noise_amplitude=0.3, name="noise")
40 bursts = gp.Equation("a * (1 + g) / 2 + n")
41 p.connect(carrier, bursts["a"])
42 p.connect(gate, bursts["g"])
43 p.connect(noise, bursts["n"])
44
45 # The envelope: the RMS over the last WINDOW samples, one per sample
46 envelope = gp.RollingStatistic(statistic="rms", window_size=WINDOW)
47 p.connect(bursts, envelope)
48
49 # Three decisions: on the signal, on its envelope, and on the envelope
50 # debounced as Episode 12 taught
51 on_signal = gp.Threshold(level=0.5)
52 on_envelope = gp.Threshold(level=0.5)
53 debounced = gp.Threshold(level=0.55, release=0.45, dwell=25)
54 p.connect(bursts, on_signal)
55 p.connect(envelope, on_envelope)
56 p.connect(envelope, debounced)
57
58 kept = {name: gp.Collector(name=name)
59 for name in ("envelope", "on_signal", "on_envelope",
60 "debounced")}
61 p.connect(envelope, kept["envelope"])
62 p.connect(on_signal, kept["on_signal"])
63 p.connect(on_envelope, kept["on_envelope"])
64 p.connect(debounced, kept["debounced"])
65
66 p.start()
67 time.sleep(SECONDS)
68 p.stop()
69 p.close()
70
71 # The first burst is samples 0-249, the first pause 250-499: read
72 # each well away from its edges, once the window has filled
73 rms = collected(kept["envelope"])
74 print(f"{SECONDS:.0f} s: a 10 Hz burst every other second, amplitude 1, "
75 "noise of standard deviation 0.3")
76 print(f" envelope during a burst {np.median(rms[100:240]):.2f}")
77 print(f" envelope between bursts {np.median(rms[350:490]):.2f}")
78 print(f" Threshold(level=0.5) on the signal "
79 f"{transitions(kept['on_signal']):5d} transitions")
80 print(f" Threshold(level=0.5) on the envelope "
81 f"{transitions(kept['on_envelope']):5d} transitions")
82 print(f" ... with release=0.45, dwell=25 "
83 f"{transitions(kept['debounced']):5d} transitions")