filter2c 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
filter2c/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """filter2c: design digital filters with SciPy and generate verified C code."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .codegen import generate_header, runtime_header # noqa: E402
6
+ from .design import ( # noqa: E402
7
+ FilterDesign,
8
+ butterworth_bandpass,
9
+ butterworth_highpass,
10
+ butterworth_lowpass,
11
+ notch,
12
+ )
13
+
14
+ __all__ = [
15
+ "FilterDesign",
16
+ "butterworth_bandpass",
17
+ "butterworth_highpass",
18
+ "butterworth_lowpass",
19
+ "notch",
20
+ "generate_header",
21
+ "runtime_header",
22
+ "__version__",
23
+ ]
filter2c/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
filter2c/cli.py ADDED
@@ -0,0 +1,356 @@
1
+ """Command line interface.
2
+
3
+ filter2c butter-lowpass ... write C code for a Butterworth low-pass filter
4
+ filter2c butter-highpass ... write C code for a Butterworth high-pass filter
5
+ filter2c butter-bandpass ... write C code for a Butterworth band-pass filter
6
+ filter2c notch ... write C code for a notch filter
7
+ filter2c target-sketch <filter> write an ESP32 self-test sketch
8
+ filter2c check-board-log ... check what the board printed
9
+ filter2c check-live-log ... check a live run with the board's analog input
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from . import __version__
18
+ from .codegen import check_name, generate_header, runtime_header
19
+ from .design import (
20
+ FilterDesign,
21
+ butterworth_bandpass,
22
+ butterworth_highpass,
23
+ butterworth_lowpass,
24
+ notch,
25
+ )
26
+ from .live import (
27
+ DEFAULT_MAX_PERIOD_ERROR,
28
+ DEFAULT_MIN_SWING,
29
+ check_live_log,
30
+ create_live_sketch,
31
+ )
32
+ from .target import check_board_log, create_sketch
33
+ from .verify import (
34
+ DEFAULT_MIN_ATTENUATION_DB,
35
+ DEFAULT_TOLERANCE,
36
+ VerificationError,
37
+ check_stability,
38
+ compare_with_scipy,
39
+ measure_attenuation,
40
+ )
41
+
42
+ _FLOAT_HINT = (
43
+ "hint: 32-bit float loses precision when the cutoff is a very small fraction "
44
+ "of the sampling rate. Lower the sampling rate (filter fewer samples per "
45
+ "second), raise the cutoff, or accept a larger --tolerance if your "
46
+ "application allows it."
47
+ )
48
+
49
+
50
+ def _add_lowpass_arguments(parser: argparse.ArgumentParser) -> None:
51
+ parser.add_argument("--order", type=int, required=True, help="filter order (1 to 16)")
52
+ parser.add_argument("--cutoff", type=float, required=True, help="-3 dB frequency in Hz")
53
+ parser.add_argument("--fs", type=float, required=True, help="sampling rate in Hz")
54
+ parser.add_argument("--name", default="filter", help="C name of the filter (default: filter)")
55
+ parser.set_defaults(filter="butter-lowpass")
56
+
57
+
58
+ def _add_highpass_arguments(parser: argparse.ArgumentParser) -> None:
59
+ parser.add_argument("--order", type=int, required=True, help="filter order (1 to 16)")
60
+ parser.add_argument("--cutoff", type=float, required=True, help="-3 dB frequency in Hz")
61
+ parser.add_argument("--fs", type=float, required=True, help="sampling rate in Hz")
62
+ parser.add_argument("--name", default="filter", help="C name of the filter (default: filter)")
63
+ parser.set_defaults(filter="butter-highpass")
64
+
65
+
66
+ def _add_bandpass_arguments(parser: argparse.ArgumentParser) -> None:
67
+ parser.add_argument(
68
+ "--order", type=int, required=True,
69
+ help="order of each band edge (1 to 16); the filter as a whole has twice this order",
70
+ )
71
+ parser.add_argument("--low", type=float, required=True, help="lower -3 dB edge in Hz")
72
+ parser.add_argument("--high", type=float, required=True, help="upper -3 dB edge in Hz")
73
+ parser.add_argument("--fs", type=float, required=True, help="sampling rate in Hz")
74
+ parser.add_argument("--name", default="filter", help="C name of the filter (default: filter)")
75
+ parser.set_defaults(filter="butter-bandpass")
76
+
77
+
78
+ def _add_notch_arguments(parser: argparse.ArgumentParser) -> None:
79
+ parser.add_argument("--freq", type=float, required=True, help="frequency to remove, in Hz")
80
+ parser.add_argument("--q", type=float, required=True, help="quality factor, 0.5 to 100")
81
+ parser.add_argument("--fs", type=float, required=True, help="sampling rate in Hz")
82
+ parser.add_argument("--name", default="filter", help="C name of the filter (default: filter)")
83
+ parser.set_defaults(filter="notch")
84
+
85
+
86
+ def _add_tolerance_argument(parser: argparse.ArgumentParser) -> None:
87
+ parser.add_argument(
88
+ "--tolerance", type=float, default=DEFAULT_TOLERANCE,
89
+ help=f"allowed error as a fraction of the output peak (default: {DEFAULT_TOLERANCE:g})",
90
+ )
91
+
92
+
93
+ def _add_generate_arguments(parser: argparse.ArgumentParser) -> None:
94
+ parser.add_argument("-o", "--output", type=Path, required=True, help="header file to write")
95
+ parser.add_argument(
96
+ "--write-runtime", action="store_true",
97
+ help="also write filter2c.h next to the output file",
98
+ )
99
+ parser.add_argument(
100
+ "--verify", action="store_true",
101
+ help="compile the result and compare it with SciPy (needs a C compiler)",
102
+ )
103
+ _add_tolerance_argument(parser)
104
+
105
+
106
+ def build_parser() -> argparse.ArgumentParser:
107
+ parser = argparse.ArgumentParser(
108
+ prog="filter2c",
109
+ description="Design a digital filter with SciPy and generate C code for it.",
110
+ )
111
+ parser.add_argument("--version", action="version", version=f"filter2c {__version__}")
112
+ sub = parser.add_subparsers(dest="command", required=True)
113
+
114
+ low = sub.add_parser("butter-lowpass", help="Butterworth low-pass filter")
115
+ _add_lowpass_arguments(low)
116
+ _add_generate_arguments(low)
117
+
118
+ high = sub.add_parser("butter-highpass", help="Butterworth high-pass filter")
119
+ _add_highpass_arguments(high)
120
+ _add_generate_arguments(high)
121
+
122
+ band = sub.add_parser("butter-bandpass", help="Butterworth band-pass filter")
123
+ _add_bandpass_arguments(band)
124
+ _add_generate_arguments(band)
125
+
126
+ notch_parser = sub.add_parser("notch", help="notch filter that removes one frequency")
127
+ _add_notch_arguments(notch_parser)
128
+ _add_generate_arguments(notch_parser)
129
+ notch_parser.add_argument(
130
+ "--min-attenuation-db", type=float, default=DEFAULT_MIN_ATTENUATION_DB,
131
+ help=f"with --verify: required attenuation at the notch frequency "
132
+ f"(default: {DEFAULT_MIN_ATTENUATION_DB:g} dB)",
133
+ )
134
+
135
+ sketch = sub.add_parser(
136
+ "target-sketch",
137
+ help="write an ESP32 sketch that runs the filter on the board and prints the result",
138
+ )
139
+ sketch_sub = sketch.add_subparsers(dest="sketch_filter", required=True)
140
+ for filter_name, add_arguments, help_text in (
141
+ ("butter-lowpass", _add_lowpass_arguments, "Butterworth low-pass filter"),
142
+ ("butter-highpass", _add_highpass_arguments, "Butterworth high-pass filter"),
143
+ ("butter-bandpass", _add_bandpass_arguments, "Butterworth band-pass filter"),
144
+ ("notch", _add_notch_arguments, "notch filter"),
145
+ ):
146
+ p = sketch_sub.add_parser(filter_name, help=help_text)
147
+ add_arguments(p)
148
+ p.add_argument(
149
+ "-o", "--output", type=Path, required=True,
150
+ help="sketch folder to create (its name becomes the sketch name)",
151
+ )
152
+ p.add_argument(
153
+ "--live", action="store_true",
154
+ help="write a live-check sketch that uses the board's analog input, with one "
155
+ "jumper wire between two pins, instead of the stored-signal self-test",
156
+ )
157
+
158
+ log = sub.add_parser(
159
+ "check-board-log",
160
+ help="compare the text the board printed with SciPy and the PC build",
161
+ )
162
+ log.add_argument("sketch", type=Path, help="the sketch folder made by target-sketch")
163
+ log.add_argument("log", type=Path, help="text file with the copied serial output")
164
+ _add_tolerance_argument(log)
165
+
166
+ live = sub.add_parser(
167
+ "check-live-log",
168
+ help="check the output of a live-check sketch: sampling rate, input activity, filter",
169
+ )
170
+ live.add_argument("sketch", type=Path, help="the live-check sketch folder")
171
+ live.add_argument("log", type=Path, help="text file with the copied serial output")
172
+ _add_tolerance_argument(live)
173
+ live.add_argument(
174
+ "--max-period-error", type=float, default=DEFAULT_MAX_PERIOD_ERROR,
175
+ help="allowed error of the mean sample period, as a fraction "
176
+ f"(default: {DEFAULT_MAX_PERIOD_ERROR:g})",
177
+ )
178
+ live.add_argument(
179
+ "--min-swing", type=float, default=DEFAULT_MIN_SWING,
180
+ help="the raw reading must change by at least this many counts "
181
+ f"(default: {DEFAULT_MIN_SWING:g})",
182
+ )
183
+ return parser
184
+
185
+
186
+ def _design_from_args(args: argparse.Namespace) -> FilterDesign:
187
+ if args.filter == "notch":
188
+ return notch(args.freq, args.q, args.fs)
189
+ if args.filter == "butter-highpass":
190
+ return butterworth_highpass(args.order, args.cutoff, args.fs)
191
+ if args.filter == "butter-bandpass":
192
+ return butterworth_bandpass(args.order, args.low, args.high, args.fs)
193
+ return butterworth_lowpass(args.order, args.cutoff, args.fs)
194
+
195
+
196
+ def _run_generate(args: argparse.Namespace) -> int:
197
+ check_name(args.name)
198
+ design = _design_from_args(args)
199
+
200
+ header = generate_header(design, args.name)
201
+ runtime = runtime_header()
202
+ args.output.parent.mkdir(parents=True, exist_ok=True)
203
+ args.output.write_text(header, encoding="utf-8", newline="\n")
204
+ print(f"Wrote {args.output} ({design.describe()}, {design.sections} section(s))")
205
+
206
+ if args.write_runtime:
207
+ target = args.output.parent / "filter2c.h"
208
+ target.write_text(runtime, encoding="utf-8", newline="\n")
209
+ print(f"Wrote {target}")
210
+
211
+ stability = check_stability(design)
212
+ verdict = "stable" if stability.stable else "UNSTABLE"
213
+ print(
214
+ f"Stability after rounding to float: {verdict} "
215
+ f"(largest pole radius {stability.max_pole_radius:.9f})"
216
+ )
217
+ if not stability.stable:
218
+ return 1
219
+
220
+ if args.verify:
221
+ is_notch = args.filter == "notch"
222
+ tones = (design.cutoff_hz,) if is_notch else ()
223
+ result = compare_with_scipy(
224
+ design, header, runtime, args.name, args.tolerance, tones_hz=tones
225
+ )
226
+ status = "PASS" if result.passed else "FAIL"
227
+ print(
228
+ f"C code against SciPy: {status} "
229
+ f"(max error {result.max_abs_error:.2e} = {result.relative_error:.2e} of the peak, "
230
+ f"tolerance {result.tolerance:.0e}, {result.samples} samples)"
231
+ )
232
+ failed = not result.passed
233
+ if is_notch:
234
+ att = measure_attenuation(
235
+ design, header, runtime, args.name, minimum_db=args.min_attenuation_db
236
+ )
237
+ att_status = "PASS" if att.passed else "FAIL"
238
+ print(
239
+ f"Attenuation of a {att.frequency_hz:g} Hz tone by the C code: "
240
+ f"{att.attenuation_db:.0f} dB {att_status} (required: at least {att.minimum_db:g} dB)"
241
+ )
242
+ failed = failed or not att.passed
243
+ if failed:
244
+ print(_FLOAT_HINT, file=sys.stderr)
245
+ return 1
246
+ return 0
247
+
248
+
249
+ def _run_target_sketch(args: argparse.Namespace) -> int:
250
+ design = _design_from_args(args)
251
+ if args.live:
252
+ files = create_live_sketch(design, args.name, args.output)
253
+ print(f"Wrote live-check sketch folder {args.output} ({design.describe()}):")
254
+ for path in files:
255
+ print(f" {path.name}")
256
+ print(
257
+ "Next: connect pin 2 and the analog pin (GPIO2 and GPIO1 on ESP32-S3) with one jumper "
258
+ f"wire, open {args.output / (args.output.name + '.ino')} in the Arduino IDE, upload, "
259
+ "open the Serial Monitor at 921600 baud, copy all of its text into a file and run: "
260
+ f"filter2c check-live-log {args.output} <that file>"
261
+ )
262
+ return 0
263
+ files = create_sketch(design, args.name, args.output)
264
+ print(f"Wrote sketch folder {args.output} ({design.describe()}):")
265
+ for path in files:
266
+ print(f" {path.name}")
267
+ print(
268
+ f"Next: open {args.output / (args.output.name + '.ino')} in the Arduino IDE, select your "
269
+ "ESP32 board, upload, open the Serial Monitor at 115200 baud, then copy all of its text "
270
+ f"into a file and run: filter2c check-board-log {args.output} <that file>"
271
+ )
272
+ return 0
273
+
274
+
275
+ def _run_check_board_log(args: argparse.Namespace) -> int:
276
+ report = check_board_log(args.sketch, args.log.read_text(encoding="utf-8", errors="replace"),
277
+ args.tolerance)
278
+ status = "PASS" if report.passed else "FAIL"
279
+ print(
280
+ f"Board output against SciPy: {status} "
281
+ f"(max error {report.max_abs_error:.2e} = {report.relative_error:.2e} of the peak, "
282
+ f"tolerance {report.tolerance:.0e}, {report.samples} samples)"
283
+ )
284
+ if report.identical_to_pc_build is None:
285
+ print("Board against the PC build: not compared (no C compiler found)")
286
+ elif report.identical_to_pc_build:
287
+ print("Board against the PC build: identical, every sample matches exactly")
288
+ else:
289
+ print(
290
+ "Board against the PC build: tiny differences, "
291
+ f"largest {report.max_diff_to_pc_build:.2e} (different compilers round differently)"
292
+ )
293
+ print(
294
+ f"Speed: {report.cpu_mhz:g} MHz, {report.cycles_per_sample:.1f} cycles per sample = "
295
+ f"{report.microseconds_per_sample:.2f} us per sample "
296
+ f"(this filter alone could keep up with up to {report.max_sample_rate_hz / 1000:.0f} kHz)"
297
+ )
298
+ if not report.passed:
299
+ print(_FLOAT_HINT, file=sys.stderr)
300
+ return 1
301
+ return 0
302
+
303
+
304
+ def _run_check_live_log(args: argparse.Namespace) -> int:
305
+ report = check_live_log(
306
+ args.sketch, args.log.read_text(encoding="utf-8", errors="replace"),
307
+ args.tolerance, args.max_period_error, args.min_swing,
308
+ )
309
+
310
+ def word(ok: bool) -> str:
311
+ return "PASS" if ok else "FAIL"
312
+
313
+ print(f"Live readings: {report.samples}")
314
+ print(
315
+ f"Timing: mean sample period {report.mean_period_us:.1f} us (expected "
316
+ f"{report.expected_period_us:.1f}), shortest {report.min_period_us:.0f}, longest "
317
+ f"{report.max_period_us:.0f}, spread (std) {report.std_period_us:.1f} us, "
318
+ f"{report.late_fraction * 100:.1f} % of intervals late: {word(report.timing_ok)}"
319
+ )
320
+ print(
321
+ f"Input activity: raw reading from {report.raw_min:.0f} to {report.raw_max:.0f} counts "
322
+ f"(swing {report.raw_max - report.raw_min:.0f}): {word(report.signal_ok)}"
323
+ )
324
+ print(
325
+ "Filter output against SciPy applied to the same raw readings: "
326
+ f"{word(report.accuracy_ok)} (max error {report.max_abs_error:.2e} = "
327
+ f"{report.relative_error:.2e} of the peak, tolerance {report.tolerance:.0e})"
328
+ )
329
+ if not report.signal_ok:
330
+ print("hint: the input barely changed. Check the jumper wire between the two pins.",
331
+ file=sys.stderr)
332
+ if not report.timing_ok:
333
+ print("hint: the board did not sample at the expected rate. Is the loop too slow "
334
+ "for this sampling rate?", file=sys.stderr)
335
+ if not report.accuracy_ok:
336
+ print(_FLOAT_HINT, file=sys.stderr)
337
+ return 0 if report.passed else 1
338
+
339
+
340
+ def main(argv: list[str] | None = None) -> int:
341
+ args = build_parser().parse_args(argv)
342
+ try:
343
+ if args.command in ("butter-lowpass", "butter-highpass", "butter-bandpass", "notch"):
344
+ return _run_generate(args)
345
+ if args.command == "target-sketch":
346
+ return _run_target_sketch(args)
347
+ if args.command == "check-live-log":
348
+ return _run_check_live_log(args)
349
+ return _run_check_board_log(args)
350
+ except (ValueError, VerificationError, OSError) as error:
351
+ print(f"error: {error}", file=sys.stderr)
352
+ return 2
353
+
354
+
355
+ if __name__ == "__main__":
356
+ raise SystemExit(main())
filter2c/codegen.py ADDED
@@ -0,0 +1,97 @@
1
+ """Turn a FilterDesign into a C header."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from importlib import resources
6
+
7
+ import numpy as np
8
+
9
+ from . import __version__
10
+ from .design import FilterDesign
11
+
12
+ _IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
13
+
14
+ # Reserved words of C99 and C++, so the generated names compile in both.
15
+ _RESERVED = frozenset(
16
+ """auto break case char const continue default do double else enum extern
17
+ float for goto if inline int long register restrict return short signed
18
+ sizeof static struct switch typedef union unsigned void volatile while
19
+ bool class namespace new delete template this try catch throw true false
20
+ public private protected virtual operator friend using""".split()
21
+ )
22
+
23
+
24
+ def check_name(name: str) -> str:
25
+ """Return ``name`` if it can be used as a C identifier, else raise ValueError."""
26
+ if not _IDENTIFIER.match(name) or name in _RESERVED:
27
+ raise ValueError(
28
+ f"{name!r} is not a usable C identifier "
29
+ "(letters, digits and underscores, not starting with a digit, not a keyword)"
30
+ )
31
+ return name
32
+
33
+
34
+ def float32_literal(value: float) -> str:
35
+ """Write a value as a C float literal that reads back as the same float32."""
36
+ with np.errstate(over="ignore"):
37
+ as_f32 = np.float32(value)
38
+ if not np.isfinite(as_f32):
39
+ raise ValueError(f"coefficient {value!r} does not fit in a float")
40
+ # 9 significant digits are enough to identify any float32 exactly.
41
+ text = f"{float(as_f32):.9g}"
42
+ if not any(c in text for c in ".eE"):
43
+ text += ".0"
44
+ return text + "f"
45
+
46
+
47
+ def runtime_header() -> str:
48
+ """Return the text of filter2c.h that ships inside this package."""
49
+ return (resources.files("filter2c") / "runtime" / "filter2c.h").read_text(encoding="utf-8")
50
+
51
+
52
+ def generate_header(design: FilterDesign, name: str) -> str:
53
+ """Generate the C header for a design.
54
+
55
+ The header includes ``filter2c.h`` and defines a ready-to-use filter called
56
+ ``name``. It is meant to be included from one source file.
57
+ """
58
+ check_name(name)
59
+ upper = name.upper()
60
+ count = design.sections
61
+ rows = []
62
+ for b0, b1, b2, a0, a1, a2 in design.sos:
63
+ if a0 != 1.0:
64
+ raise ValueError("expected sections normalised to a0 == 1")
65
+ coefficients = ", ".join(float32_literal(v) for v in (b0, b1, b2, a1, a2))
66
+ rows.append(f" {{ {coefficients} }}")
67
+ table = ",\n".join(rows)
68
+
69
+ return f"""/* Generated by filter2c {__version__}. Do not edit by hand.
70
+ *
71
+ * {design.describe()}
72
+ * {count} biquad section(s), Direct Form II Transposed, float (32 bit).
73
+ *
74
+ * Usage:
75
+ * #include "{name}.h"
76
+ * filter2c_reset(&{name});
77
+ * float y = filter2c_process(&{name}, x);
78
+ *
79
+ * Include this header from one source file only.
80
+ */
81
+ #ifndef FILTER2C_GENERATED_{upper}_H
82
+ #define FILTER2C_GENERATED_{upper}_H
83
+
84
+ #include "filter2c.h"
85
+
86
+ #define {upper}_SECTIONS {count}u
87
+
88
+ static const filter2c_section {name}_sections[{upper}_SECTIONS] = {{
89
+ {table}
90
+ }};
91
+
92
+ static float {name}_state[2u * {upper}_SECTIONS];
93
+
94
+ static const filter2c_sos {name} = {{ {name}_sections, {name}_state, {upper}_SECTIONS }};
95
+
96
+ #endif /* FILTER2C_GENERATED_{upper}_H */
97
+ """
filter2c/design.py ADDED
@@ -0,0 +1,188 @@
1
+ """Filter design: a small, validated layer on top of SciPy.
2
+
3
+ A filter is stored as second-order sections (biquads), which stay numerically
4
+ well behaved at higher orders. A single high-order polynomial does not.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass
9
+
10
+ import numpy as np
11
+ from scipy import signal
12
+
13
+ MAX_ORDER = 16
14
+ MIN_Q = 0.5
15
+ MAX_Q = 100.0
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class FilterDesign:
20
+ """A designed filter.
21
+
22
+ ``sos`` has one row per biquad section: ``[b0, b1, b2, a0, a1, a2]``,
23
+ normalised so that ``a0 == 1``.
24
+
25
+ ``cutoff_hz`` is the -3 dB frequency of a low-pass or high-pass filter, the
26
+ lower -3 dB edge of a band-pass filter, or the centre frequency of a notch
27
+ filter. ``high_hz`` is the upper edge of a band-pass filter. ``q`` is only
28
+ set for a notch.
29
+ """
30
+
31
+ kind: str
32
+ order: int
33
+ fs_hz: float
34
+ cutoff_hz: float
35
+ sos: np.ndarray
36
+ q: float | None = None
37
+ high_hz: float | None = None
38
+
39
+ @property
40
+ def sections(self) -> int:
41
+ return int(self.sos.shape[0])
42
+
43
+ def describe(self) -> str:
44
+ if self.q is not None:
45
+ return (
46
+ f"{self.kind}, frequency {self.cutoff_hz:g} Hz, Q {self.q:g}, "
47
+ f"sampling {self.fs_hz:g} Hz"
48
+ )
49
+ if self.high_hz is not None:
50
+ return (
51
+ f"{self.kind}, order {self.order} per edge, passband "
52
+ f"{self.cutoff_hz:g} to {self.high_hz:g} Hz, sampling {self.fs_hz:g} Hz"
53
+ )
54
+ return (
55
+ f"{self.kind}, order {self.order}, cutoff {self.cutoff_hz:g} Hz, "
56
+ f"sampling {self.fs_hz:g} Hz"
57
+ )
58
+
59
+
60
+ def _check_order(order: int) -> int:
61
+ if isinstance(order, bool) or not isinstance(order, (int, np.integer)):
62
+ raise ValueError(f"order must be an integer, got {order!r}")
63
+ if not 1 <= order <= MAX_ORDER:
64
+ raise ValueError(f"order must be between 1 and {MAX_ORDER}, got {order}")
65
+ return int(order)
66
+
67
+
68
+ def _check_fs(fs_hz: float) -> float:
69
+ if not np.isfinite(fs_hz) or fs_hz <= 0:
70
+ raise ValueError(f"fs_hz must be a positive number, got {fs_hz!r}")
71
+ return float(fs_hz)
72
+
73
+
74
+ def _check_frequency(name: str, frequency_hz: float, fs_hz: float) -> float:
75
+ if not np.isfinite(frequency_hz) or not 0 < frequency_hz < fs_hz / 2:
76
+ raise ValueError(
77
+ f"{name} must be between 0 and fs_hz / 2 = {fs_hz / 2:g}, got {frequency_hz!r}"
78
+ )
79
+ return float(frequency_hz)
80
+
81
+
82
+ def butterworth_lowpass(order: int, cutoff_hz: float, fs_hz: float) -> FilterDesign:
83
+ """Design a digital Butterworth low-pass filter.
84
+
85
+ Args:
86
+ order: filter order, 1 to 16.
87
+ cutoff_hz: -3 dB frequency in Hz. Must lie between 0 and fs_hz / 2.
88
+ fs_hz: sampling rate in Hz.
89
+ """
90
+ order = _check_order(order)
91
+ fs_hz = _check_fs(fs_hz)
92
+ cutoff_hz = _check_frequency("cutoff_hz", cutoff_hz, fs_hz)
93
+
94
+ sos = signal.butter(order, cutoff_hz, btype="low", fs=fs_hz, output="sos")
95
+ return FilterDesign(
96
+ kind="Butterworth low-pass",
97
+ order=order,
98
+ fs_hz=fs_hz,
99
+ cutoff_hz=cutoff_hz,
100
+ sos=np.asarray(sos, dtype=np.float64),
101
+ )
102
+
103
+
104
+ def butterworth_highpass(order: int, cutoff_hz: float, fs_hz: float) -> FilterDesign:
105
+ """Design a digital Butterworth high-pass filter.
106
+
107
+ A high-pass removes slow drift (such as the wandering baseline of an ECG)
108
+ and lets faster changes through.
109
+
110
+ Args:
111
+ order: filter order, 1 to 16.
112
+ cutoff_hz: -3 dB frequency in Hz. Must lie between 0 and fs_hz / 2.
113
+ fs_hz: sampling rate in Hz.
114
+ """
115
+ order = _check_order(order)
116
+ fs_hz = _check_fs(fs_hz)
117
+ cutoff_hz = _check_frequency("cutoff_hz", cutoff_hz, fs_hz)
118
+
119
+ sos = signal.butter(order, cutoff_hz, btype="high", fs=fs_hz, output="sos")
120
+ return FilterDesign(
121
+ kind="Butterworth high-pass",
122
+ order=order,
123
+ fs_hz=fs_hz,
124
+ cutoff_hz=cutoff_hz,
125
+ sos=np.asarray(sos, dtype=np.float64),
126
+ )
127
+
128
+
129
+ def butterworth_bandpass(order: int, low_hz: float, high_hz: float, fs_hz: float) -> FilterDesign:
130
+ """Design a digital Butterworth band-pass filter.
131
+
132
+ A band-pass keeps the frequencies between ``low_hz`` and ``high_hz``. For
133
+ example 0.5 to 40 Hz is a common band for an ECG.
134
+
135
+ ``order`` is the order of each band edge, as in SciPy: the filter as a whole
136
+ has twice this order and ``order`` biquad sections.
137
+
138
+ Args:
139
+ order: order of each band edge, 1 to 16.
140
+ low_hz: lower -3 dB edge in Hz.
141
+ high_hz: upper -3 dB edge in Hz. Must be above ``low_hz`` and below fs_hz / 2.
142
+ fs_hz: sampling rate in Hz.
143
+ """
144
+ order = _check_order(order)
145
+ fs_hz = _check_fs(fs_hz)
146
+ low_hz = _check_frequency("low_hz", low_hz, fs_hz)
147
+ high_hz = _check_frequency("high_hz", high_hz, fs_hz)
148
+ if not low_hz < high_hz:
149
+ raise ValueError(f"low_hz must be below high_hz, got {low_hz:g} and {high_hz:g}")
150
+
151
+ sos = signal.butter(order, [low_hz, high_hz], btype="band", fs=fs_hz, output="sos")
152
+ return FilterDesign(
153
+ kind="Butterworth band-pass",
154
+ order=order,
155
+ fs_hz=fs_hz,
156
+ cutoff_hz=low_hz,
157
+ sos=np.asarray(sos, dtype=np.float64),
158
+ high_hz=high_hz,
159
+ )
160
+
161
+
162
+ def notch(freq_hz: float, q: float, fs_hz: float) -> FilterDesign:
163
+ """Design a digital notch filter that removes one frequency, such as 50 Hz mains hum.
164
+
165
+ A notch passes everything except a narrow band around ``freq_hz``. The
166
+ higher the quality factor ``q``, the narrower the band that is removed
167
+ (its width at -3 dB is about ``freq_hz / q``).
168
+
169
+ Args:
170
+ freq_hz: centre frequency to remove. Must lie between 0 and fs_hz / 2.
171
+ q: quality factor, 0.5 to 100.
172
+ fs_hz: sampling rate in Hz.
173
+ """
174
+ fs_hz = _check_fs(fs_hz)
175
+ freq_hz = _check_frequency("freq_hz", freq_hz, fs_hz)
176
+ if not np.isfinite(q) or not MIN_Q <= q <= MAX_Q:
177
+ raise ValueError(f"q must be between {MIN_Q:g} and {MAX_Q:g}, got {q!r}")
178
+
179
+ b, a = signal.iirnotch(freq_hz, q, fs=fs_hz)
180
+ sos = signal.tf2sos(b, a)
181
+ return FilterDesign(
182
+ kind="Notch",
183
+ order=2,
184
+ fs_hz=fs_hz,
185
+ cutoff_hz=freq_hz,
186
+ sos=np.asarray(sos, dtype=np.float64),
187
+ q=float(q),
188
+ )