Episode 7: Closing a Loop
Hold a stream back with a Delay, then use its second form to close a feedback loop, the shape of every neurofeedback application.
A delay holds a stream back by a whole number of samples. On its own that is bookkeeping. Its second form is what makes feedback possible: a node whose output flows back into its own input. The script runs three small pipelines in turn.
Delay(num_samples=25) shifts every sample by 25 and fills the first 25 with initial_value, 0 unless you give one. It takes its channel count, rate and frame size from its input. Two Collector nodes keep the original and the delayed stream, and a helper reads the one channel each kept.
22 # 1. Delay a stream: every sample arrives LAG later, the first LAG are 0
23 p = gp.Pipeline()
24 source = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
25 signal_frequency=2, signal_amplitude=1.0)
26 delay = gp.Delay(num_samples=LAG)
27 original = gp.Collector(name="original")
28 delayed = gp.Collector(name="delayed")
29 p.connect(source, original)
30 p.connect(source, delay)
31 p.connect(delay, delayed)
32 p.start()
33 time.sleep(SECONDS)
34 p.stop()
35 p.close()
Run the script. The first lines confirm the shift: the first 25 delayed samples are zero, and from then on every delayed sample equals the original 25 samples earlier:
Delay(num_samples=25)
first 25 delayed samples are zero: True
largest |delayed[n] - original[n - 25]|: 0
The loop is y[n] = x[n] + 0.5 * y[n - 1]: an Equation whose output comes back into its own y input one sample later. The plain Delay cannot close it. It takes its context from its input, and here its input is the loop’s own output, which does not exist until the loop has run. The pipeline refuses the connection that closes the loop, and names the form that works.
48 p = gp.Pipeline()
49 source = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
50 frame_size=1, signal_frequency=0.1,
51 signal_shape="rect", signal_amplitude=1.0)
52 feedback = gp.Equation("x + 0.5*y", name="Feedback")
53 plain = gp.Delay(num_samples=1, name="Plain")
54 p.connect(source, feedback["x"])
55 p.connect(feedback, plain)
56 print()
57 print("closing the loop with Delay(num_samples=1)")
58 try:
59 p.connect(plain, feedback["y"])
60 except ValueError as refusal:
61 print(textwrap.fill(f"ValueError: {refusal}", width=72,
62 initial_indent=" ", subsequent_indent=" "))
63 p.close()
closing the loop with Delay(num_samples=1)
ValueError: the connection closes a feedback loop: Feedback -> Plain
-> Feedback. [...] Insert a gp.Delay that declares its own context --
gp.Delay(num_samples=1, channel_count=..., sampling_rate=...) -- into
this loop [...]
Declaring channel_count and sampling_rate gives the Delay the context it cannot derive. It then pushes one frame of initial_value before it has seen any input, which is the y[-1] the first sample needs, and reports BREAKS_CYCLES, which is what the pipeline checks for.
69 p = gp.Pipeline()
70 source = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
71 frame_size=1, signal_frequency=0.1,
72 signal_shape="rect", signal_amplitude=1.0)
73 feedback = gp.Equation("x + 0.5*y", name="Feedback")
74 breaker = gp.Delay(num_samples=1, channel_count=1,
75 sampling_rate=SAMPLING_RATE, name="Breaker")
76 output = gp.Collector(name="output")
77 p.connect(source, feedback["x"])
78 p.connect(feedback, breaker)
79 p.connect(breaker, feedback["y"])
80 p.connect(feedback, output)
The input is 0 at the first sample and 1 from then on, so each sample adds 1 to half the one before, and the loop settles at 2, where x + 0.5 * y equals y:
closing it with Delay(num_samples=1, channel_count=1, sampling_rate=250)
BREAKS_CYCLES: plain False, declaring True
first samples: [0.0, 1.0, 1.5, 1.75, 1.875, 1.9375]
after 1 s: 2.0000
Two rules come with the declaring form. The loop delay is exactly num_samples, and it must be at least one frame, because a node pushes a whole frame at a time. And every loop needs a breaker of its own: a Delay in another loop does not cover this one, even where the two share nodes.
In this episode, you learned how to:
shift a stream by whole samples with Delay
read the refusal a loop with nothing in it gets
close a loop with a Delay that declares its own context
Proceed to Episode 8, where the MainApp gets a caption, a grid and a theme.
Nodes in this episode: Generator, Delay, Equation, Collector
File s2e7_closing_a_loop.py – View file on GitHub
1"""Season 2, Episode 7: a Delay shifts a stream, or closes a loop."""
2
3import textwrap
4import time
5
6import numpy as np
7
8import gpype as gp
9
10SAMPLING_RATE = 250
11SECONDS = 1.0
12LAG = 25 # samples: a tenth of a second at 250 Hz
13
14
15def samples(collector):
16 """The one channel a Collector kept, as float64."""
17 return np.asarray(collector.result.data, dtype=np.float64)[:, 0]
18
19
20if __name__ == "__main__":
21
22 # 1. Delay a stream: every sample arrives LAG later, the first LAG are 0
23 p = gp.Pipeline()
24 source = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
25 signal_frequency=2, signal_amplitude=1.0)
26 delay = gp.Delay(num_samples=LAG)
27 original = gp.Collector(name="original")
28 delayed = gp.Collector(name="delayed")
29 p.connect(source, original)
30 p.connect(source, delay)
31 p.connect(delay, delayed)
32 p.start()
33 time.sleep(SECONDS)
34 p.stop()
35 p.close()
36
37 x, y = samples(original), samples(delayed)
38 n = min(len(x), len(y))
39 print(f"Delay(num_samples={LAG})")
40 print(f" first {LAG} delayed samples are zero: "
41 f"{bool(np.all(y[:LAG] == 0))}")
42 print(f" largest |delayed[n] - original[n - {LAG}]|: "
43 f"{np.max(np.abs(y[LAG:n] - x[:n - LAG])):g}")
44
45 # 2. Try to close a loop with it: y[n] = x[n] + 0.5 * y[n - 1]. The
46 # plain Delay takes its context from its input, and its input is the
47 # loop's own output, so the pipeline refuses the closing connection
48 p = gp.Pipeline()
49 source = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
50 frame_size=1, signal_frequency=0.1,
51 signal_shape="rect", signal_amplitude=1.0)
52 feedback = gp.Equation("x + 0.5*y", name="Feedback")
53 plain = gp.Delay(num_samples=1, name="Plain")
54 p.connect(source, feedback["x"])
55 p.connect(feedback, plain)
56 print()
57 print("closing the loop with Delay(num_samples=1)")
58 try:
59 p.connect(plain, feedback["y"])
60 except ValueError as refusal:
61 print(textwrap.fill(f"ValueError: {refusal}", width=72,
62 initial_indent=" ", subsequent_indent=" "))
63 p.close()
64
65 # 3. Close it with the declaring form. Given channel_count and
66 # sampling_rate, the Delay pushes one frame of initial_value before
67 # any input arrives (the y[-1] the first sample needs) and reports
68 # BREAKS_CYCLES, which is what the pipeline checks for
69 p = gp.Pipeline()
70 source = gp.Generator(sampling_rate=SAMPLING_RATE, channel_count=1,
71 frame_size=1, signal_frequency=0.1,
72 signal_shape="rect", signal_amplitude=1.0)
73 feedback = gp.Equation("x + 0.5*y", name="Feedback")
74 breaker = gp.Delay(num_samples=1, channel_count=1,
75 sampling_rate=SAMPLING_RATE, name="Breaker")
76 output = gp.Collector(name="output")
77 p.connect(source, feedback["x"])
78 p.connect(feedback, breaker)
79 p.connect(breaker, feedback["y"])
80 p.connect(feedback, output)
81 print()
82 print("closing it with Delay(num_samples=1, channel_count=1, "
83 f"sampling_rate={SAMPLING_RATE})")
84 print(f" BREAKS_CYCLES: plain {plain.BREAKS_CYCLES}, "
85 f"declaring {breaker.BREAKS_CYCLES}")
86 p.start()
87 time.sleep(SECONDS)
88 p.stop()
89 p.close()
90
91 y = samples(output)
92 print(f" first samples: {np.round(y[:6], 4).tolist()}")
93 print(f" after {SECONDS:g} s: {y[-1]:.4f}")