The feedback signal: three implementations of the latency budget held to each other and to the SciPy reference, the library's loop against helpers_l7 to 1e-12 on the shipped trace, three band-power derivations per block and what each costs, smoothing measured by the loopback probe on the four-channel loop, a fixed against an adaptive baseline on a planted rise, and the channels of a montage combined with the combination stated

nb-7-13-feedback Level 7 · Applied Electives ~3 min Used in L7.13 · The feedback signal: band power in a buffer

Downloads from ds-eegbci when you run it.

Download the notebook (.ipynb) Outputs below are the ones stored when it was executed — you do not need to run anything to read it.

nb-7-13-feedback · The feedback signal: band power in a buffer (L7.13)

Lesson L7.13 · Level 7 · Status draft — for expert review; uncertain points carry TODO(confirm).

"Alpha at Pz" is not a definition. A feedback signal is a band, a set of channels and how they are combined, a reference, a filter and its length, a derivation, a smoothing — and every one of those is either exact in time or it is not, and the ones that are not get measured. This notebook states the signal, then costs it.

  1. Three implementations, one budget. The course library (eegloop), the L7.3 notebook helpers (helpers_l7) and the SciPy reference shipped with the latency widget agree on every quantity of the L7.3 pipeline — the same arithmetic exists three times on purpose, and this is where that is checked.
  2. The loop, block for block. eegloop's offline loop against helpers_l7.alpha_feedback on the shipped eyes-closed trace, to a tolerance that is a fact about floating point rather than about the code.
  3. Three ways to a band-power feature per block — RMS of the filtered block, a filter-Hilbert envelope, a Welch window — and what each adds to the budget: an exact row, or a delay the loopback probe has to measure.
  4. Smoothing is latency. The four-channel loop at 256 Hz with 64-sample blocks and three smoothing constants, measured. The measured value delay with a 0.5-s smoother is a keyed number, and so are the exact rows.
  5. The baseline, fixed or adaptive, and what an adaptive threshold does to a learning claim.
  6. Combining the channels of a montage into one value, with the combination stated — on the shipped four-channel asset, where the widget's own reference numbers are reproduced.

Every number comes from the shipped assets, the synthetic stream, or a probe; no headset produced anything here.

In [1]:
# Setup: dependencies, the shared helpers, the course library, non-interactive plotting.
import importlib.util
import json
import logging
import subprocess
import sys
import time
import warnings
from pathlib import Path

_needed = ("mne", "scipy", "matplotlib", "pandas", "pooch")
_missing = [p for p in _needed if importlib.util.find_spec(p) is None]
if _missing:
    _req = next((d / "requirements.txt" for d in (Path.cwd(), *Path.cwd().parents)
                 if (d / "requirements.txt").exists()), None)
    _cmd = [sys.executable, "-m", "pip", "install", "-q"]
    _cmd += ["-r", str(_req)] if _req else ["mne==1.10.2", "pooch>=1.8"]
    subprocess.check_call(_cmd)

_shared = next((d / "_shared" for d in (Path.cwd(), *Path.cwd().parents)
                if (d / "_shared" / "helpers_l7.py").exists()), None)
if _shared is None:
    # No checkout around this notebook -- a downloaded .ipynb, or a fresh Colab kernel. Fetch the shared
    # helpers the site publishes beside it. With a checkout present the walk-up above wins and nothing
    # is downloaded; the modules land in ./_shared/ and are reused on every later run.
    import json as _json
    import urllib.request as _urllib
    _base = "https://eeg.neurokinetikz.com/notebooks/_shared/"
    _shared = Path.cwd() / "_shared"
    _shared.mkdir(exist_ok=True)
    for _name in _json.loads(_urllib.urlopen(_base + "index.json").read())["modules"]:
        if not (_shared / _name).exists():
            _urllib.urlretrieve(_base + _name, _shared / _name)
sys.path.insert(0, str(_shared))
import helpers_l7 as L7
_loop = L7.import_eegloop()   # loop/eegloop on sys.path from any directory of a checkout; returns loop/
_widget_dir = next((d / "site" / "public" / "data" / "widgets" / "w-latency-budget" for d in (Path.cwd(), *Path.cwd().parents)
                    if (d / "site" / "public" / "data" / "widgets" / "w-latency-budget" / "traces.json").exists()), None)

import helpers
import helpers_l7 as L7
import eegloop
from eegloop import Block
from eegloop.feedback import AdaptiveBaseline, ContinuousMapping, FixedBaseline, SignalSpec, build_chain, combine
from eegloop.latency import BUFFER_CONVENTIONS, iir_group_delay_samples, latency_budget, latency_budget_for, print_budget, zero_phase_lookahead_samples
from eegloop.probe import energy_centroid, make_probe, measure_loop_delay, run_offline
from eegloop.sources import ReplaySource, SyntheticSource, blocks
from eegloop.sources.replay import read_recording
from eegloop.steps import Chain
from eegloop.steps.causal_filter import CausalFIR, CausalSOS, butter_sos, fir_taps
from eegloop.steps.envelope import BandPower, BlockRMS, Smoother

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import mne
from scipy import signal as sps

mne.set_log_level("WARNING")
logging.getLogger("pooch").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", category=RuntimeWarning)
plt.rcParams["figure.dpi"] = 72

SOURCE = "replay"
LOCAL_RECORDING = None      # a path to a recording of your own: a second pass on it, never shipped

# L7.3's pipeline, the one every implementation is checked on (helpers_l7.LATENCY_SPEC)
SPEC = dict(fs=float(L7.LATENCY_SPEC["sfreq_hz"]), band=tuple(L7.LATENCY_SPEC["band_hz"]), n_taps=int(L7.LATENCY_SPEC["fir_taps"]),
            block_samples=int(L7.LATENCY_SPEC["block_samples"]), processing_ms=float(L7.LATENCY_SPEC["processing_ms"]),
            ref_hz=float(L7.LATENCY_SPEC.get("ref_hz", 10.0)))
print("LATENCY_SPEC:", SPEC)
print(f"eegloop {eegloop.__version__} · mne {mne.__version__}; widget assets {'found' if _widget_dir else 'not found (fallback)'}")
_edf_before = set(Path(mne.get_config("MNE_DATA", str(Path.home() / "mne_data"))).rglob("*.edf"))
LATENCY_SPEC: {'fs': 160.0, 'band': (8.0, 12.0), 'n_taps': 129, 'block_samples': 32, 'processing_ms': 10.0, 'ref_hz': 10.0}
eegloop 0.1.0 · mne 1.10.2; widget assets found

1 · Three implementations, one budget

The same latency arithmetic exists three times on this site on purpose: in the course library, in the L7.3 notebook helpers it was ported from, and as a SciPy-computed reference shipped beside the widget's traces so the widget's TypeScript can be checked rather than trusted. Three copies are a liability unless something holds them together; this is that something. Every quantity site/notes/widget-latency.md lists for the L7.3 pipeline is computed by all three and the largest disagreement is printed.

In [2]:
ref = json.loads((_widget_dir / "traces.json").read_text())["reference"] if _widget_dir else None
kw = dict(fs=SPEC["fs"], n_taps=SPEC["n_taps"], block_samples=SPEC["block_samples"], processing_ms=SPEC["processing_ms"])
rows = []
def row(quantity, ours, theirs, scipy_ref=None):
    vals = [v for v in (ours, theirs, scipy_ref) if v is not None]
    rows.append({"quantity": quantity, "eegloop": ours, "helpers_l7": theirs, "SciPy reference": scipy_ref,
                 "max |Δ|": float(max(vals) - min(vals))})

for conv in ("block-period", "first-to-last"):
    a, b = latency_budget(convention=conv, **kw), L7.latency_budget(convention=conv, **kw)
    row(f"total, worst case, {conv} (ms)", a["total_ms"], b["total_ms"],
        None if ref is None else next(d["group_delay_ms"] for d in ref["designs"] if d["id"] == "fir-129") + (32 if conv == "block-period" else 31) / SPEC["fs"] * 1000 + SPEC["processing_ms"])
    if conv == "block-period":
        row("total, mean over block position (ms)", a["mean_ms"], b["mean_ms"])
        row("filter row (ms)", a["rows"][0]["ms"], b["rows"][0]["ms"], None if ref is None else next(d["group_delay_ms"] for d in ref["designs"] if d["id"] == "fir-129"))
a, b = latency_budget(phase="zero-phase-live", **kw), L7.latency_budget(phase="zero-phase-live", **kw)
row("zero-phase live, worst case (ms)", a["total_ms"], b["total_ms"])
taps = fir_taps(SPEC["n_taps"], SPEC["band"], SPEC["fs"])
row("zero-phase look-ahead, 129 taps (samples)", zero_phase_lookahead_samples(taps, fir=True), L7.zero_phase_lookahead_samples(taps, fir=True),
    None if ref is None else next((d.get("lookahead_samples_zero_phase_live", d.get("lookahead_samples_live")) for d in ref["designs"] if d["id"] == "fir-129"), None))
sos = butter_sos(4, SPEC["band"], SPEC["fs"])
row("Butterworth order 4, group delay at 10 Hz (samples)", iir_group_delay_samples(sos, 10.0, SPEC["fs"]), L7.iir_group_delay_samples(sos, 10.0, SPEC["fs"]),
    None if ref is None else next(d["group_delay_samples"] for d in ref["designs"] if d["id"] == "iir-butter-4"))
probe_ours = measure_loop_delay(lambda: Chain([CausalFIR(taps, 1)]), fs=SPEC["fs"], block_samples=SPEC["block_samples"], centre_hz=float(np.mean(SPEC["band"])), alignments=8)
probe_theirs = L7.measure_loop_delay(fs=SPEC["fs"], taps=taps, block_samples=SPEC["block_samples"], alignments=8)
row("probe: filter delay (ms)", probe_ours["filter_ms"], probe_theirs["filter_ms"],
    None if ref is None else next(d["measured_lag_samples"] for d in ref["designs"] if d["id"] == "fir-129") / SPEC["fs"] * 1000)
row("probe: value delay (ms)", probe_ours["value_ms"], probe_theirs["value_ms"])
tab = pd.DataFrame(rows)
pd.set_option("display.float_format", lambda v: f"{v:.6f}")
print(tab.to_string(index=False))
worst = float(tab["max |Δ|"].max())
print(f"\nlargest disagreement across the three: {worst:.2e}")
assert worst < 5e-3, "the three implementations disagree beyond the probe's stated accuracy"
                                           quantity     eegloop  helpers_l7  SciPy reference  max |Δ|
               total, worst case, block-period (ms)  610.000000  610.000000       610.000000 0.000000
               total, mean over block position (ms)  510.000000  510.000000              NaN 0.000000
                                    filter row (ms)  400.000000  400.000000       400.000000 0.000000
              total, worst case, first-to-last (ms)  603.750000  603.750000       603.750000 0.000000
                   zero-phase live, worst case (ms) 1010.000000 1010.000000              NaN 0.000000
          zero-phase look-ahead, 129 taps (samples)  128.000000  128.000000              NaN 0.000000
Butterworth order 4, group delay at 10 Hz (samples)   32.727137   32.727137        32.727137 0.000000
                           probe: filter delay (ms)  399.999544  399.999544       400.000000 0.000456
                            probe: value delay (ms)  503.123959  503.123959              NaN 0.000000

largest disagreement across the three: 4.56e-04

The SciPy reference column is derived where the reference ships only the filter row (the buffer and processing rows are arithmetic on top of it) and blank where it ships nothing. The probe's filter delay is measured by the energy centroid of a packet, which times a causal FIR to within 5 × 10⁻⁴ samples (site/notes/widget-latency.md §2.2) — the tolerance above is that number in milliseconds, not a looser one that would hide a disagreement.

2 · The loop, block for block

eegloop.probe.run_offline replays a recording through a chain in fixed blocks and returns what a participant would see; helpers_l7.alpha_feedback is the single-channel function it was ported from. On the shipped eyes-closed trace (ds-eegbci S001 R02, O1, 10 s at 160 Hz — the latency widget's own replay trace) the two agree to a tolerance that is a fact about floating point, with and without smoothing. Not "bit for bit": a 1-D and a (1 × B) reduction can differ in the last unit of precision, and the honest tolerance says so.

In [3]:
if _widget_dir is not None:
    x_ec, fs_ec, names_ec, _, nom_ec = read_recording(_widget_dir / "alpha-ec.bin")
    src_note = f"shipped asset alpha-ec ({nom_ec.get('dataset')}, {nom_ec.get('subject')} {nom_ec.get('run')}, {names_ec}, {fs_ec:g} Hz, {x_ec.shape[1] / fs_ec:.0f} s)"
else:
    raw_ec = helpers.load_spine("ds-eegbci", 1, run=2).pick(["O1"]).crop(20.0, 30.0)
    x_ec = raw_ec.get_data() * 1e6; x_ec = x_ec - x_ec.mean(axis=1, keepdims=True); fs_ec = float(raw_ec.info["sfreq"]); names_ec = ("O1",)
    src_note = "ds-eegbci S001 R02 O1, 20–30 s (the widget assets were not found; the same recording)"
print("trace:", src_note)
taps_ec = fir_taps(SPEC["n_taps"], SPEC["band"], fs_ec)
for smooth in (0.0, 0.5):
    ours = run_offline(Chain([CausalFIR(taps_ec, 1)]), x_ec, fs=fs_ec, block_samples=SPEC["block_samples"], smooth_s=smooth)
    theirs = L7.alpha_feedback(x_ec[0], fs=fs_ec, taps=taps_ec, block_samples=SPEC["block_samples"], smooth_s=smooth)
    d_val = float(np.max(np.abs(ours["values"] - theirs["values"])))
    d_held = float(np.max(np.abs(ours["held"] - theirs["held"])))
    d_filt = float(np.max(np.abs(ours["filtered"][0] - theirs["filtered"])))
    print(f"smooth_s = {smooth:<4g} max |Δ| values {d_val:.1e}  held {d_held:.1e}  filtered {d_filt:.1e}  ({len(ours['values'])} blocks; times equal: {np.array_equal(ours['times_s'], theirs['times_s'])})")
    assert max(d_val, d_held, d_filt) <= 1e-12
print("\nthe library and the notebook helpers compute the same loop to 1e-12 on a real trace")
trace: shipped asset alpha-ec (ds-eegbci, S001 R02, ('O1',), 160 Hz, 10 s)
smooth_s = 0    max |Δ| values 0.0e+00  held 0.0e+00  filtered 0.0e+00  (50 blocks; times equal: True)
smooth_s = 0.5  max |Δ| values 0.0e+00  held 0.0e+00  filtered 0.0e+00  (50 blocks; times equal: True)

the library and the notebook helpers compute the same loop to 1e-12 on a real trace

3 · Three ways to a band-power feature per block, and what each costs

Time-frequency was taught in Level 4; a feedback signal needs only as much of it as fits in a buffer. Three derivations, one probe, and for each the honest statement of its delay:

  • RMS of the filtered block — the block is the delay, already the buffer row; the step adds an exact 0.
  • Filter-Hilbert envelope of the block — the analytic amplitude over the block, averaged; the block is still the delay, but the Hilbert transform of a finite block is not the Hilbert transform of the stream, and the probe says what that costs.
  • Welch band power over a window — a two-second window whose centroid sits near half its length; not a row, a measured delay.
In [4]:
def value_delay(chain_factory, value_fn, *, fs, B, centre_hz=10.0, alignments=None):
    # eegloop.probe.measure_loop_delay, generalised to any per-block value: the probe packet at every alignment
    # of the block grid, the filtered stream and the per-block values timed by their energy centroids.
    A = B if alignments is None else int(alignments)
    lag_filt, lag_val = [], []
    for off in range(A):
        t, x = make_probe(fs, centre_hz=centre_hz, offset_samples=off)
        chain = chain_factory()
        n = x.size - x.size % B
        filt = np.zeros(n); vals, times = [], []
        for k, i in enumerate(range(0, n, B)):
            out = chain.process(Block(x[None, i:i + B], fs, seq=k, sample_index=i, t_start_s=i / fs))
            filt[i:i + B] = out.data[0]
            vals.append(value_fn(out)); times.append((i + B) / fs)
        t_in = energy_centroid(t, x)
        lag_filt.append((energy_centroid(t[:n], filt) - t_in) * 1000)
        lag_val.append((energy_centroid(np.asarray(times), np.asarray(vals)) - t_in) * 1000)
    return {"filter_ms": float(np.mean(lag_filt)), "value_ms": float(np.mean(lag_val)),
            "value_min_ms": float(np.min(lag_val)), "value_max_ms": float(np.max(lag_val)), "alignments": A}

fs, B, N = SPEC["fs"], SPEC["block_samples"], SPEC["n_taps"]
taps = fir_taps(N, SPEC["band"], fs)
exact_filter_ms = (N - 1) / 2 / fs * 1000
exact_value_ms = ((N - 1) / 2 + (B + 1) / 2) / fs * 1000
methods = {
    "RMS of the filtered block": (lambda: Chain([CausalFIR(taps, 1), BlockRMS()]), lambda out: float(out.flags["envelope"][0]), "exact: 0 on top of the buffer row"),
    "filter-Hilbert envelope of the block": (lambda: Chain([CausalFIR(taps, 1)]), lambda out: float(np.mean(np.abs(sps.hilbert(out.data[0])))), "measured: the block's Hilbert is not the stream's"),
    "Welch band power, 2-s window": (lambda: Chain([CausalFIR(taps, 1), BandPower(fs, 1, {"alpha": SPEC["band"]}, window_s=2.0)]), lambda out: float(out.flags["envelope"][0]), "measured: a window's centroid is a criterion"),
}
rows = []
for name, (factory, fn, note) in methods.items():
    r = value_delay(factory, fn, fs=fs, B=B)
    rows.append({"method": name, "filter delay (ms)": round(r["filter_ms"], 2), "value delay (ms)": round(r["value_ms"], 1),
                 "range over the block grid (ms)": f"{r['value_min_ms']:.1f}–{r['value_max_ms']:.1f}", "exact expectation (ms)": round(exact_value_ms, 2) if name.startswith("RMS") else None, "how the budget lists it": note})
methods_tab = pd.DataFrame(rows)
print(f"L7.3 pipeline: {fs:g} Hz, {N} taps, {B}-sample blocks; exact filter delay {exact_filter_ms:.2f} ms; exact RMS value delay {exact_value_ms:.2f} ms")
print(methods_tab.to_string(index=False))
L7.3 pipeline: 160 Hz, 129 taps, 32-sample blocks; exact filter delay 400.00 ms; exact RMS value delay 503.13 ms
                              method  filter delay (ms)  value delay (ms) range over the block grid (ms)  exact expectation (ms)                           how the budget lists it
           RMS of the filtered block         400.000000        503.100000                    495.6–510.7              503.130000                 exact: 0 on top of the buffer row
filter-Hilbert envelope of the block         400.000000        503.100000                    495.6–510.7                     NaN measured: the block's Hilbert is not the stream's
        Welch band power, 2-s window         400.000000       1400.000000                  1400.0–1400.0                     NaN      measured: a window's centroid is a criterion

The RMS row lands on its exact expectation to the probe's accuracy, which is why the budget can list it as a row. The Hilbert row lands close — the block is still the delay — and the Welch row lands about a second late, which is not a defect but a definition: a two-second window says what it means. None of the three is "the" band power; the one you choose is part of the signal's statement.

4 · Smoothing is latency, measured

The four-channel loop of the consumer path runs at 256 Hz with 64-sample blocks and the same 129-tap filter. A one-pole smoother on the per-block value buys a steadier bar and costs time, and there is no single number for that cost — the impulse response never ends — so the budget lists the smoother under measured and the probe fills it in. The value delay with a 0.5-s smoother is the lesson's keyed number; the exact rows are the other.

In [5]:
fs4, B4 = 256.0, 64
taps4 = fir_taps(N, SPEC["band"], fs4)
budget4 = latency_budget(fs=fs4, n_taps=N, block_samples=B4, processing_ms=SPEC["processing_ms"])
print_budget(budget4, title=f"the four-channel loop: {fs4:g} Hz, {N} taps, {B4}-sample blocks, {SPEC['processing_ms']:g} ms stated")
print()
rows = []
for tau in (0.0, 0.25, 0.5):
    r = measure_loop_delay(lambda: Chain([CausalFIR(taps4, 1)]), fs=fs4, block_samples=B4, centre_hz=float(np.mean(SPEC["band"])), smooth_s=tau)
    rows.append({"smooth_s": tau, "filter delay (ms)": round(r["filter_ms"], 2), "value delay (ms)": round(r["value_ms"], 1),
                 "range over the block grid (ms)": f"{r['value_min_ms']:.1f}–{r['value_max_ms']:.1f}",
                 "expected without smoothing (ms)": round(r["expected_value_ms"], 2), "smoothing cost (ms)": round(r["value_ms"] - r["expected_value_ms"], 1)})
smooth_tab = pd.DataFrame(rows)
print(smooth_tab.to_string(index=False))
delay_05 = float(smooth_tab.loc[smooth_tab.smooth_s == 0.5, "value delay (ms)"].iloc[0])
chain_s = Chain([CausalFIR(taps4, 1), BlockRMS(), Smoother(0.5, fs4, B4)])
b_for = latency_budget_for(chain_s, fs=fs4, block_samples=B4, processing_ms=SPEC["processing_ms"])
print(f"\nlatency_budget_for(chain with the smoother): total of the exact rows {b_for['total_ms']:.2f} ms; listed as measured: {[m['name'] for m in b_for['measured']]}")
print("the smoother's cost is never added into that total; it sits beside it, from the probe")
the four-channel loop: 256 Hz, 129 taps, 64-sample blocks, 10 ms stated
row          detail                                           samples        ms
--------------------------------------------------------------------------------
filter       FIR group delay (N - 1) / 2, 129 taps              64.00    250.00
buffer       64 samples, block-period                           64.00    250.00
processing   stated, not measured                                2.56     10.00
--------------------------------------------------------------------------------
TOTAL        worst case, block-period                          130.56    510.00
             worst case, first-to-last                                   506.09
             mean over block position                                    385.00

loop update rate 4.00 Hz (64 samples at 256 Hz)

 smooth_s  filter delay (ms)  value delay (ms) range over the block grid (ms)  expected without smoothing (ms)  smoothing cost (ms)
 0.000000         250.000000        377.000000                    368.9–385.0                       376.950000            -0.000000
 0.250000         250.000000        477.800000                    469.7–485.8                       376.950000           100.800000
 0.500000         250.000000        615.900000                    607.8–623.9                       376.950000           239.000000

latency_budget_for(chain with the smoother): total of the exact rows 510.00 ms; listed as measured: ['smoother']
the smoother's cost is never added into that total; it sits beside it, from the probe

5 · The baseline: fixed, or adaptive

Decision 3 of L7.3. A fixed baseline is set from a calibration block and does not move, so a later change in the signal is a change relative to something and "improvement" has a definition. An adaptive baseline follows the participant, keeps the display responsive, and makes the reward rate a property of the rule. Both are in the library, each with a note on what it does to a learning claim; run them on the same synthetic signal with a planted rise (the figure of pf-adaptive-threshold-moving-target, recomputed here).

In [6]:
src = SyntheticSource("alpha-schedule", duration_s=300.0, alpha_uv=6.0, alpha_bursts=(), pace="fast")
spec = SignalSpec(band=SPEC["band"], channels=("TP9", "TP10"), n_taps=N)
chain = build_chain(spec, src.info, 32, quality=None)
picks = spec.picks(src.info.ch_names)
t, v = [], []
for blk in blocks(src, 32):
    o = chain.process(blk); t.append(blk.t_end_s); v.append(combine(o.flags["envelope"], picks, "rms"))
t, v = np.asarray(t), np.asarray(v)
v = v * (1.0 + 0.6 * np.clip((t - 30.0) / 270.0, 0, 1))          # the planted rise: +60 % over the session
n_cal = int(round(20.0 * src.info.fs / 32))
fixed = FixedBaseline.from_values(v[:n_cal])
adaptive = AdaptiveBaseline(30.0, src.info.fs, 32)
z_fixed, z_adapt = np.empty_like(v), np.full_like(v, np.nan)
for k in range(v.size):
    z_fixed[k] = fixed.z(v[k])
    adaptive.update(v[k]); z_adapt[k] = adaptive.z(v[k])
rate = lambda z, lo, hi: float(np.nanmean((z[(t > lo) & (t < hi)] >= 1.0)))  # noqa: E731
print("fixed:   ", fixed.note)
print("adaptive:", adaptive.note)
print(f"\nreward rate (fraction of blocks with z ≥ +1), early (30–90 s) → late (240–300 s):  fixed {rate(z_fixed, 30, 90):.2f} → {rate(z_fixed, 240, 300):.2f};  "
      f"adaptive {rate(z_adapt, 60, 120):.2f} → {rate(z_adapt, 240, 300):.2f}")
print("the signal rose 60 %; one rule shows it and the other, by construction, cannot")
fixed:    fixed from 160 calibration values (median 2.74, mad 0.593): the threshold does not move, so a change in the signal is a change relative to the calibration and 'improvement' has a definition
adaptive: adaptive: the 50th percentile of the last 30 s (240 blocks). The participant is always near threshold by construction, which makes the feedback feel responsive and makes 'improvement' much harder to define; the raw value is logged beside the threshold so the outcome can still be pre-specified on the signal

reward rate (fraction of blocks with z ≥ +1), early (30–90 s) → late (240–300 s):  fixed 0.23 → 0.81;  adaptive 0.24 → 0.21
the signal rose 60 %; one rule shows it and the other, by construction, cannot

6 · Combining the channels of a montage into one value

Decision 1 again: the channels and how they are combined are part of the signal's definition. On the shipped four-channel asset (ds-eegbci S001 R02 on O1, O2, T7, T8 — the occipitotemporal-4 replica, 60 s at 160 Hz) the same chain gives a different feedback value for the occipital pair, the temporal pair and all four, and a different calibration baseline. The widget's feedback mode carries a reference the library computed on this asset; it is recomputed here, which is the check that the reference is reproducible.

In [7]:
if _widget_dir is not None:
    x4, fs_4, names4, _, nom4 = read_recording(_widget_dir / "oc4-ec.bin")
    fb_ref = json.loads((_widget_dir / "feedback.json").read_text())
    info4 = ReplaySource(x4, fs=fs_4, ch_names=names4, pace="fast", block_samples=32).info
    p = fb_ref["params"]
    rows = []
    for label, chs in (("occipital pair", ("O1", "O2")), ("temporal pair", ("T7", "T8")), ("all four", tuple(names4))):
        spec4 = SignalSpec(band=tuple(p["band_hz"]), channels=chs, n_taps=int(p["n_taps"]))
        chain4 = build_chain(spec4, info4, int(p["block_samples"]), quality=None)
        picks4 = spec4.picks(tuple(names4))
        vals = []
        s4 = ReplaySource(x4, fs=fs_4, ch_names=names4, pace="fast", block_samples=int(p["block_samples"]))
        for blk in blocks(s4, int(p["block_samples"])):
            vals.append(combine(chain4.process(blk).flags["envelope"], picks4, "rms"))
        vals = np.asarray(vals)
        n_cal = int(round(p["calibration_s"] * fs_4 / p["block_samples"]))
        base = FixedBaseline.from_values(vals[:n_cal])
        z = (vals - base.centre) / base.spread
        rows.append({"channels": label, "calibration median (µV)": round(base.centre, 2), "robust spread (µV)": round(base.spread, 2),
                     "blocks above z = +1 after calibration": round(float(np.mean(z[n_cal:] >= 1.0)), 3), "definition": spec4.describe(fs_4, int(p["block_samples"]))[:90] + "…"})
        if chs == ("O1", "O2"):
            d_ref = float(np.max(np.abs(vals - np.asarray(fb_ref["reference"]["values"]))))
    print(pd.DataFrame(rows).to_string(index=False))
    print(f"\nthe widget's reference values for the occipital pair reproduce to {d_ref:.1e} µV (rounded to 6 decimals in feedback.json)")
    assert d_ref < 1e-5
    print("\nthe signal, stated in full (CRED-nf item 4):")
    print("  " + SignalSpec(band=tuple(p["band_hz"]), channels=("O1", "O2"), n_taps=int(p["n_taps"])).describe(fs_4, int(p["block_samples"])))
else:
    print("the widget assets were not found in this checkout; section 6 needs site/public/data/widgets/w-latency-budget/oc4-ec.bin")
      channels  calibration median (µV)  robust spread (µV)  blocks above z = +1 after calibration                                                                                  definition
occipital pair                38.570000           18.230000                               0.400000 8–12 Hz at O1, O2 with no re-referencing, a causal linear-phase FIR of 129 taps (group del…
 temporal pair                 6.630000            2.560000                               0.680000 8–12 Hz at T7, T8 with no re-referencing, a causal linear-phase FIR of 129 taps (group del…
      all four                23.110000            8.320000                               0.516000 8–12 Hz at O1, O2, T7, T8 with no re-referencing, a causal linear-phase FIR of 129 taps (g…

the widget's reference values for the occipital pair reproduce to 2.1e-06 µV (rounded to 6 decimals in feedback.json)

the signal, stated in full (CRED-nf item 4):
  8–12 Hz at O1, O2 with no re-referencing, a causal linear-phase FIR of 129 taps (group delay 400.0 ms), the root-mean-square per block averaged over those channels, updated every 200 ms (5.0 Hz), unsmoothed.

Your own recording, if you have one

When LOCAL_RECORDING names a file — a .bin with its sidecar as eegloop run --record-raw writes it, or an .npz — the cell below runs this notebook's measurement on it and prints the result titled as yours; when it is None the cell is skipped entirely, so nothing empty ships. Nothing from your recording is written into this notebook's outputs on the site: it is a second pass, never shipped (CONTRACTS, Phase 5).

In [8]:
if LOCAL_RECORDING is not None:
    mine = ReplaySource(LOCAL_RECORDING, pace="fast", block_samples=32)
    x_mine = np.concatenate([b.data for b in blocks(mine, 32)], axis=1)
    spec_mine = SignalSpec(band=(8.0, 12.0), channels=(), n_taps=129)          # every channel, combined by the mean
    chain_mine = build_chain(spec_mine, mine.info, 32, quality=None)
    print_budget(latency_budget_for(chain_mine, fs=mine.info.fs, block_samples=32, processing_ms=10.0), title="your recording — declared budget")
    r_mine = run_offline(build_chain(spec_mine, mine.info, 32, quality=None, include_smoother=False), x_mine, fs=mine.info.fs, block_samples=32)
    print(f"your recording — not shipped: {r_mine['values'].size} per-block values; median {np.median(r_mine['values']):.2f} µV RMS, "
          f"MAD-spread {1.4826 * np.median(np.abs(r_mine['values'] - np.median(r_mine['values']))):.2f} µV over {mine.info.n_channels} channels")
else:
    print("LOCAL_RECORDING is None: skipped (set it to a .bin with its sidecar, or an .npz, to state and cost the feedback signal on your own file)")
LOCAL_RECORDING is None: skipped (set it to a .bin with its sidecar, or an .npz, to state and cost the feedback signal on your own file)

7 · The numbers the lesson's exercises ask for

In [9]:
print("nb-7-13-feedback — L7.13 numbers (draft; TODO(confirm) at author review)")
print()
r0 = smooth_tab.loc[smooth_tab.smooth_s == 0.0].iloc[0]; r5 = smooth_tab.loc[smooth_tab.smooth_s == 0.5].iloc[0]
print(f"(a) Measured value delay with a 0.5-s smoother at {fs4:g} Hz, {N} taps, {B4}-sample blocks: {delay_05:.1f} ms "
      f"(range {r5['range over the block grid (ms)']} over the block grid; {r0['value delay (ms)']:.1f} ms without smoothing, expected {r0['expected without smoothing (ms)']:.2f}).")
rows4 = budget4["rows"]
print(f"(b) Exact rows for that pipeline, block-period convention: filter {rows4[0]['ms']:.2f} + buffer {rows4[1]['ms']:.2f} + processing {rows4[2]['ms']:.2f} "
      f"= {budget4['total_ms']:.2f} ms worst case; {budget4['total_other_convention_ms']:.2f} ms first-to-last; {budget4['mean_ms']:.2f} ms mean over block position.")
print(f"(c) Adaptive threshold: the reward rate stays near its early value while the signal rises 60 % (fixed {rate(z_fixed, 30, 90):.2f} → {rate(z_fixed, 240, 300):.2f}; "
      f"adaptive {rate(z_adapt, 60, 120):.2f} → {rate(z_adapt, 240, 300):.2f}).")
print()
print(f"Three-implementation cross-check on the L7.3 pipeline: largest disagreement {worst:.2e} over {len(tab)} quantities.")
print(f"Three derivations at 160 Hz / 32-sample blocks — value delays: " + "; ".join(f"{r['method']} {r['value delay (ms)']} ms" for _, r in methods_tab.iterrows()))
nb-7-13-feedback — L7.13 numbers (draft; TODO(confirm) at author review)

(a) Measured value delay with a 0.5-s smoother at 256 Hz, 129 taps, 64-sample blocks: 615.9 ms (range 607.8–623.9 over the block grid; 377.0 ms without smoothing, expected 376.95).
(b) Exact rows for that pipeline, block-period convention: filter 250.00 + buffer 250.00 + processing 10.00 = 510.00 ms worst case; 506.09 ms first-to-last; 385.00 ms mean over block position.
(c) Adaptive threshold: the reward rate stays near its early value while the signal rises 60 % (fixed 0.23 → 0.81; adaptive 0.24 → 0.21).

Three-implementation cross-check on the L7.3 pipeline: largest disagreement 4.56e-04 over 9 quantities.
Three derivations at 160 Hz / 32-sample blocks — value delays: RMS of the filtered block 503.1 ms; filter-Hilbert envelope of the block 503.1 ms; Welch band power, 2-s window 1400.0 ms

Cleanup

Nothing was downloaded unless the widget assets were absent; in that case only the fetched run is deleted.

In [10]:
_edf_after = set(Path(mne.get_config("MNE_DATA", str(Path.home() / "mne_data"))).rglob("*.edf"))
_new = sorted(_edf_after - _edf_before)
for p_ in _new:
    p_.unlink(missing_ok=True)
print(f"deleted {len(_new)} EDF file(s) this run fetched; kept everything that was already cached")
deleted 0 EDF file(s) this run fetched; kept everything that was already cached