Episode 17: Zero-Phase Filtering

Filter a recording with no delay at all, which only an offline run can do, and see the same filter refused against the clock.

Every filter in the training so far ran forwards, one frame at a time, and every one of them delays the signal a little. Offline there is another way: filter forwards and backwards, and the delays cancel. Bandpass and the other three Butterworth filters take a phase for it.

A symmetric burst

A short 10 Hz burst, symmetric about its centre sample, written to a CSV file. Symmetry is what makes a delay measurable: a filtered trace that is still symmetric about the same sample was not shifted.

16def write_recording(path=RECORDING):
17    """Write a burst that is symmetric about its centre sample."""
18    index = np.arange(SAMPLES)
19    signal = np.exp(-(((index - CENTRE) / 8.0) ** 2)) * np.cos(
20        2 * np.pi * 10.0 * (index - CENTRE) / RATE)
21    with open(path, "w", encoding="utf-8", newline="") as handle:
22        handle.write("Time, Ch01\n")
23        for i in range(SAMPLES):
24            handle.write(f"{i / RATE:g}, {signal[i]:.10f}\n")
25    return signal
The same coefficients, both ways

A batch pipeline as in Episode 16, with the Bandpass taking phase. "causal" is the default, the same state machine as a live run. "zero" runs the same coefficients forwards and then backwards: no phase shift at any frequency, at the price of the magnitude response applied twice, so the attenuation at the cutoffs doubles, and the first and last few samples carry the padding’s transient.

28def filtered(path, phase):
29    """Bandpass the recording offline, causal or zero-phase."""
30    with gp.Pipeline() as p:
31        reader = gp.CsvReader(file_name=path, mode="batch")
32        bandpass = gp.Bandpass(f_lo=1, f_hi=30, phase=phase)
33        collector = gp.Collector()
34        p.connect(reader, bandpass)
35        p.connect(bandpass, collector)
36        return p.run().data[:, 0].astype(np.float64)
Result

Run the script. Two helpers measure each trace: how far it is from symmetric about the centre, and the whole-sample lag of the carrier that best aligns it with the input, the filter’s delay at 10 Hz rounded to samples rather than its group delay:

causal : asymmetry 0.626   lag +1 samples (+4.0 ms)
zero   : asymmetry 0.000   lag +0 samples (+0.0 ms)
realtime: Bandpass could not set up, so the pipeline is not running:
  ValueError: phase='zero' filters forwards and backwards [...]

The last lines are the same filter in a realtime pipeline, refused at start(): a zero-phase filter would have to know the future, which is exactly why the option exists offline and nowhere else.

Summary

In this episode, you learned how to:

  • choose phase="zero" for an offline filter

  • measure a delay by symmetry and lag rather than by eye

  • read the refusal the same filter gets against the clock

That closes Season 2. Proceed to Season 3, where real amplifiers come on board.

Nodes in this episode: CsvReader, Bandpass, Collector, Generator

File s2e17_zero_phase_filtering.py – View file on GitHub

 1"""Season 2, Episode 17: a bandpass causal and zero-phase, offline only."""
 2
 3import os
 4import tempfile
 5
 6import numpy as np
 7
 8import gpype as gp
 9
10RECORDING = os.path.join(tempfile.gettempdir(), "s2e17_burst.csv")
11RATE = 250.0
12SAMPLES = 1000
13CENTRE = 500
14
15
16def write_recording(path=RECORDING):
17    """Write a burst that is symmetric about its centre sample."""
18    index = np.arange(SAMPLES)
19    signal = np.exp(-(((index - CENTRE) / 8.0) ** 2)) * np.cos(
20        2 * np.pi * 10.0 * (index - CENTRE) / RATE)
21    with open(path, "w", encoding="utf-8", newline="") as handle:
22        handle.write("Time, Ch01\n")
23        for i in range(SAMPLES):
24            handle.write(f"{i / RATE:g}, {signal[i]:.10f}\n")
25    return signal
26
27
28def filtered(path, phase):
29    """Bandpass the recording offline, causal or zero-phase."""
30    with gp.Pipeline() as p:
31        reader = gp.CsvReader(file_name=path, mode="batch")
32        bandpass = gp.Bandpass(f_lo=1, f_hi=30, phase=phase)
33        collector = gp.Collector()
34        p.connect(reader, bandpass)
35        p.connect(bandpass, collector)
36        return p.run().data[:, 0].astype(np.float64)
37
38
39def asymmetry(trace):
40    """How far a trace is from symmetric about the centre, 0 to 1."""
41    window = trace[CENTRE - 200:CENTRE + 201]
42    scale = np.max(np.abs(window)) or 1.0
43    return float(np.max(np.abs(window - window[::-1])) / scale)
44
45
46def lag(trace, reference):
47    """The lag in samples that best aligns a trace with the input."""
48    a = trace - trace.mean()
49    b = reference - reference.mean()
50    return int(np.argmax(np.correlate(a, b, mode="full")) - (len(b) - 1))
51
52
53if __name__ == "__main__":
54
55    signal = write_recording()
56    for phase in ("causal", "zero"):
57        trace = filtered(RECORDING, phase)
58        shift = lag(trace, signal)
59        print(f"{phase:7}: asymmetry {asymmetry(trace):.3f}   "
60              f"lag {shift:+d} samples ({shift / RATE * 1000:+.1f} ms)")
61
62    # Against the clock the zero-phase form is refused: it would need
63    # samples that have not arrived yet
64    with gp.Pipeline() as p:
65        source = gp.Generator(sampling_rate=RATE, channel_count=1)
66        p.connect(source, gp.Bandpass(f_lo=1, f_hi=30, phase="zero"))
67        try:
68            p.start()
69        except RuntimeError as refusal:
70            print(f"realtime: {refusal}")
71        else:
72            p.stop()