filter2c 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abhishek Vijay Potekar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.4
2
+ Name: filter2c
3
+ Version: 0.1.0
4
+ Summary: Design digital filters with SciPy and generate verified, dependency-free C code for microcontrollers.
5
+ Author: Abhishek Vijay Potekar
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Madmaxcoder2612/filter2c
8
+ Project-URL: Issues, https://github.com/Madmaxcoder2612/filter2c/issues
9
+ Keywords: dsp,filter,butterworth,biquad,embedded,code generation,microcontroller
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: C
15
+ Classifier: Topic :: Scientific/Engineering
16
+ Classifier: Topic :: Software Development :: Code Generators
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: numpy>=1.24
21
+ Requires-Dist: scipy>=1.10
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=7; extra == "test"
24
+ Dynamic: license-file
25
+
26
+ # filter2c
27
+
28
+ Design digital filters in Python with SciPy, and get C code that runs the same filter on a microcontroller, together with proof that the C code does what the design says.
29
+
30
+ The code generation is the easy part. The point of this project is the **check**: the generated code is compiled, run on a test signal and compared with SciPy, and the tool tells you when 32-bit float is not precise enough for your filter.
31
+
32
+ > **Early alpha.** Tested on one ESP32-S3 board. Do not use the output in a safety-relevant system without your own verification. The full list of results and limitations is in the [project README on GitHub](https://github.com/Madmaxcoder2612/filter2c#readme).
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install filter2c
38
+ ```
39
+
40
+ Needs Python 3.10 or newer. For `--verify` you also need a C compiler (gcc or clang).
41
+
42
+ ## Use it
43
+
44
+ Make an ECG band-pass filter (0.5 to 40 Hz at 250 Hz sampling), write the C header and check it:
45
+
46
+ ```bash
47
+ filter2c butter-bandpass --order 2 --low 0.5 --high 40 --fs 250 --name ecg -o ecg.h --write-runtime --verify
48
+ ```
49
+
50
+ Other filters: `butter-lowpass`, `butter-highpass` and `notch` (for example to remove 50 Hz mains hum).
51
+
52
+ From Python:
53
+
54
+ ```python
55
+ from filter2c import butterworth_lowpass, notch, generate_header
56
+
57
+ design = butterworth_lowpass(order=4, cutoff_hz=40, fs_hz=1000)
58
+ header_text = generate_header(design, "lp40")
59
+ hum_filter = notch(freq_hz=50, q=30, fs_hz=1000)
60
+ ```
61
+
62
+ On the microcontroller, add the two generated headers to your project:
63
+
64
+ ```c
65
+ #include "lp40.h"
66
+
67
+ filter2c_reset(&lp40); /* once, before the first sample */
68
+ float y = filter2c_process(&lp40, x); /* once per sample, at exactly 1000 Hz */
69
+ ```
70
+
71
+ ## What it checks
72
+
73
+ - The filter stays stable after its coefficients are rounded to 32-bit float.
74
+ - The compiled C code matches SciPy on a test signal. For a notch filter it also measures how much of a tone at the notch frequency is removed.
75
+ - On a real ESP32 board, `filter2c target-sketch` writes a sketch that runs the filter on the board, and `filter2c check-board-log` checks what the board printed. `--live` does the same with the board's own analog input and one jumper wire.
76
+
77
+ ## Links
78
+
79
+ - Project page with results, figures and the Arduino library: <https://github.com/Madmaxcoder2612/filter2c>
80
+ - Changelog: <https://github.com/Madmaxcoder2612/filter2c/blob/main/CHANGELOG.md>
81
+ - Licence: MIT
@@ -0,0 +1,56 @@
1
+ # filter2c
2
+
3
+ Design digital filters in Python with SciPy, and get C code that runs the same filter on a microcontroller, together with proof that the C code does what the design says.
4
+
5
+ The code generation is the easy part. The point of this project is the **check**: the generated code is compiled, run on a test signal and compared with SciPy, and the tool tells you when 32-bit float is not precise enough for your filter.
6
+
7
+ > **Early alpha.** Tested on one ESP32-S3 board. Do not use the output in a safety-relevant system without your own verification. The full list of results and limitations is in the [project README on GitHub](https://github.com/Madmaxcoder2612/filter2c#readme).
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install filter2c
13
+ ```
14
+
15
+ Needs Python 3.10 or newer. For `--verify` you also need a C compiler (gcc or clang).
16
+
17
+ ## Use it
18
+
19
+ Make an ECG band-pass filter (0.5 to 40 Hz at 250 Hz sampling), write the C header and check it:
20
+
21
+ ```bash
22
+ filter2c butter-bandpass --order 2 --low 0.5 --high 40 --fs 250 --name ecg -o ecg.h --write-runtime --verify
23
+ ```
24
+
25
+ Other filters: `butter-lowpass`, `butter-highpass` and `notch` (for example to remove 50 Hz mains hum).
26
+
27
+ From Python:
28
+
29
+ ```python
30
+ from filter2c import butterworth_lowpass, notch, generate_header
31
+
32
+ design = butterworth_lowpass(order=4, cutoff_hz=40, fs_hz=1000)
33
+ header_text = generate_header(design, "lp40")
34
+ hum_filter = notch(freq_hz=50, q=30, fs_hz=1000)
35
+ ```
36
+
37
+ On the microcontroller, add the two generated headers to your project:
38
+
39
+ ```c
40
+ #include "lp40.h"
41
+
42
+ filter2c_reset(&lp40); /* once, before the first sample */
43
+ float y = filter2c_process(&lp40, x); /* once per sample, at exactly 1000 Hz */
44
+ ```
45
+
46
+ ## What it checks
47
+
48
+ - The filter stays stable after its coefficients are rounded to 32-bit float.
49
+ - The compiled C code matches SciPy on a test signal. For a notch filter it also measures how much of a tone at the notch frequency is removed.
50
+ - On a real ESP32 board, `filter2c target-sketch` writes a sketch that runs the filter on the board, and `filter2c check-board-log` checks what the board printed. `--live` does the same with the board's own analog input and one jumper wire.
51
+
52
+ ## Links
53
+
54
+ - Project page with results, figures and the Arduino library: <https://github.com/Madmaxcoder2612/filter2c>
55
+ - Changelog: <https://github.com/Madmaxcoder2612/filter2c/blob/main/CHANGELOG.md>
56
+ - Licence: MIT
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "filter2c"
7
+ version = "0.1.0"
8
+ description = "Design digital filters with SciPy and generate verified, dependency-free C code for microcontrollers."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Abhishek Vijay Potekar" }]
14
+ keywords = ["dsp", "filter", "butterworth", "biquad", "embedded", "code generation", "microcontroller"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Intended Audience :: Science/Research",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: C",
21
+ "Topic :: Scientific/Engineering",
22
+ "Topic :: Software Development :: Code Generators",
23
+ ]
24
+ dependencies = ["numpy>=1.24", "scipy>=1.10"]
25
+
26
+ [project.optional-dependencies]
27
+ test = ["pytest>=7"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/Madmaxcoder2612/filter2c"
31
+ Issues = "https://github.com/Madmaxcoder2612/filter2c/issues"
32
+
33
+ [project.scripts]
34
+ filter2c = "filter2c.cli:main"
35
+
36
+ [tool.setuptools.packages.find]
37
+ where = ["src"]
38
+
39
+ [tool.setuptools.package-data]
40
+ filter2c = ["runtime/filter2c.h"]
41
+
42
+ [tool.pytest.ini_options]
43
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -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())