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/verify.py ADDED
@@ -0,0 +1,226 @@
1
+ """Checks that the generated C code does what the design says.
2
+
3
+ Two independent checks:
4
+
5
+ * ``check_stability``: after rounding the coefficients to float32, are all
6
+ poles still inside the unit circle?
7
+ * ``compare_with_scipy``: compile the generated header with a C compiler, run a
8
+ test signal through it, and compare with SciPy's float64 reference filter.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import shutil
13
+ import subprocess
14
+ import tempfile
15
+ from dataclasses import dataclass
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ from scipy import signal
20
+
21
+ from .design import FilterDesign
22
+
23
+ DEFAULT_TOLERANCE = 1e-4 # largest allowed error, as a fraction of the output peak
24
+
25
+
26
+ class VerificationError(RuntimeError):
27
+ """Raised when the verification could not be run (for example no compiler)."""
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Stability:
32
+ max_pole_radius: float
33
+ margin: float # 1 - max_pole_radius
34
+ stable: bool
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Comparison:
39
+ samples: int
40
+ max_abs_error: float
41
+ peak_output: float
42
+ relative_error: float
43
+ tolerance: float
44
+ passed: bool
45
+
46
+
47
+ def find_compiler() -> str | None:
48
+ """Return the path of a C compiler on this machine, or None."""
49
+ for candidate in ("gcc", "clang", "cc"):
50
+ path = shutil.which(candidate)
51
+ if path:
52
+ return path
53
+ return None
54
+
55
+
56
+ def check_stability(design: FilterDesign) -> Stability:
57
+ """Check that the float32-rounded filter is still stable."""
58
+ radius = 0.0
59
+ for _b0, _b1, _b2, _a0, a1, a2 in design.sos:
60
+ rounded = [1.0, float(np.float32(a1)), float(np.float32(a2))]
61
+ radius = max(radius, float(np.max(np.abs(np.roots(rounded)))))
62
+ return Stability(max_pole_radius=radius, margin=1.0 - radius, stable=radius < 1.0)
63
+
64
+
65
+ def make_test_signal(
66
+ fs_hz: float, samples: int = 4096, seed: int = 20261125, tones_hz: tuple[float, ...] = ()
67
+ ) -> np.ndarray:
68
+ """Three sine waves plus noise, as float32. Frequencies scale with the sampling rate.
69
+
70
+ ``tones_hz`` adds a further sine wave (amplitude 0.5) at each given frequency,
71
+ for example the frequency that a notch filter is meant to remove.
72
+ """
73
+ t = np.arange(samples) / fs_hz
74
+ rng = np.random.default_rng(seed)
75
+ x = (
76
+ np.sin(2 * np.pi * 0.005 * fs_hz * t)
77
+ + 0.5 * np.sin(2 * np.pi * 0.04 * fs_hz * t)
78
+ + 0.25 * np.sin(2 * np.pi * 0.2 * fs_hz * t)
79
+ + 0.1 * rng.standard_normal(samples)
80
+ )
81
+ for tone in tones_hz:
82
+ x = x + 0.5 * np.sin(2 * np.pi * tone * t)
83
+ return x.astype(np.float32)
84
+
85
+
86
+ _HARNESS = """#include <stdio.h>
87
+ #include "{name}.h"
88
+
89
+ int main(int argc, char **argv)
90
+ {{
91
+ FILE *in;
92
+ float x;
93
+ if (argc != 2) return 2;
94
+ in = fopen(argv[1], "r");
95
+ if (!in) return 3;
96
+ filter2c_reset(&{name});
97
+ while (fscanf(in, "%f", &x) == 1) {{
98
+ printf("%.9g\\n", filter2c_process(&{name}, x));
99
+ }}
100
+ fclose(in);
101
+ return 0;
102
+ }}
103
+ """
104
+
105
+
106
+ def run_c_filter(
107
+ header: str, runtime: str, name: str, x: np.ndarray, compiler: str | None = None
108
+ ) -> np.ndarray:
109
+ """Compile the generated header into a tiny program and filter ``x`` with it.
110
+
111
+ The input is passed as text with 9 significant digits, so the C program
112
+ reads back exactly the same float32 values that Python holds.
113
+ """
114
+ compiler = compiler or find_compiler()
115
+ if compiler is None:
116
+ raise VerificationError("no C compiler found (looked for gcc, clang, cc)")
117
+
118
+ with tempfile.TemporaryDirectory() as tmp:
119
+ folder = Path(tmp)
120
+ (folder / f"{name}.h").write_text(header, encoding="utf-8", newline="\n")
121
+ (folder / "filter2c.h").write_text(runtime, encoding="utf-8", newline="\n")
122
+ (folder / "main.c").write_text(_HARNESS.format(name=name), encoding="utf-8", newline="\n")
123
+ (folder / "input.txt").write_text(
124
+ "\n".join(f"{float(v):.9g}" for v in x), encoding="utf-8", newline="\n"
125
+ )
126
+ exe = folder / "run.exe"
127
+ try:
128
+ build = subprocess.run(
129
+ [compiler, "-std=c99", "-O2", "-Wall", "-Wextra", "-pedantic", "-Werror",
130
+ "-I", str(folder), str(folder / "main.c"), "-o", str(exe)],
131
+ capture_output=True, text=True, timeout=60,
132
+ )
133
+ except (OSError, subprocess.TimeoutExpired) as error:
134
+ raise VerificationError(f"could not run the C compiler {compiler!r}: {error}") from error
135
+ if build.returncode != 0:
136
+ raise VerificationError(f"the generated code did not compile:\n{build.stderr}")
137
+ run = subprocess.run(
138
+ [str(exe), str(folder / "input.txt")], capture_output=True, text=True, timeout=60
139
+ )
140
+ if run.returncode != 0:
141
+ raise VerificationError(f"the test program failed with code {run.returncode}")
142
+ return np.array([float(line) for line in run.stdout.split()], dtype=np.float64)
143
+
144
+
145
+ def compare_with_scipy(
146
+ design: FilterDesign,
147
+ header: str,
148
+ runtime: str,
149
+ name: str,
150
+ tolerance: float = DEFAULT_TOLERANCE,
151
+ compiler: str | None = None,
152
+ tones_hz: tuple[float, ...] = (),
153
+ ) -> Comparison:
154
+ """Run the test signal through the C code and through SciPy and compare."""
155
+ x = make_test_signal(design.fs_hz, tones_hz=tones_hz)
156
+ from_c = run_c_filter(header, runtime, name, x, compiler)
157
+ reference = signal.sosfilt(design.sos, x.astype(np.float64))
158
+ if from_c.shape != reference.shape:
159
+ raise VerificationError(
160
+ f"the C program returned {from_c.size} samples, expected {reference.size}"
161
+ )
162
+ max_abs = float(np.max(np.abs(from_c - reference)))
163
+ peak = float(np.max(np.abs(reference)))
164
+ relative = max_abs / peak
165
+ return Comparison(
166
+ samples=int(x.size),
167
+ max_abs_error=max_abs,
168
+ peak_output=peak,
169
+ relative_error=relative,
170
+ tolerance=tolerance,
171
+ passed=bool(relative <= tolerance),
172
+ )
173
+
174
+
175
+ DEFAULT_MIN_ATTENUATION_DB = 40.0
176
+
177
+
178
+ @dataclass(frozen=True)
179
+ class Attenuation:
180
+ frequency_hz: float
181
+ attenuation_db: float
182
+ minimum_db: float
183
+ samples: int
184
+ passed: bool
185
+
186
+
187
+ def _tone_amplitude(y: np.ndarray, fs_hz: float, frequency_hz: float) -> float:
188
+ """Amplitude of the sine wave at ``frequency_hz`` inside ``y`` (least squares projection)."""
189
+ n = np.arange(y.size)
190
+ w = 2 * np.pi * frequency_hz / fs_hz
191
+ return float(2.0 / y.size * np.hypot(np.sum(y * np.cos(w * n)), np.sum(y * np.sin(w * n))))
192
+
193
+
194
+ def measure_attenuation(
195
+ design: FilterDesign,
196
+ header: str,
197
+ runtime: str,
198
+ name: str,
199
+ frequency_hz: float | None = None,
200
+ minimum_db: float = DEFAULT_MIN_ATTENUATION_DB,
201
+ compiler: str | None = None,
202
+ ) -> Attenuation:
203
+ """Feed a sine wave of amplitude 1 through the compiled C code and measure what is left.
204
+
205
+ The filter needs time to settle, so the first part of the output is
206
+ ignored. How long depends on how close the poles are to the unit circle.
207
+ """
208
+ frequency = design.cutoff_hz if frequency_hz is None else frequency_hz
209
+ radius = check_stability(design).max_pole_radius
210
+ if radius >= 1.0:
211
+ raise VerificationError("the filter is not stable, so its attenuation is meaningless")
212
+ settle = int(min(max(25.0 / (1.0 - radius), 2000.0), 100_000.0))
213
+ window = int(round(50 * design.fs_hz / frequency)) # about 50 periods
214
+ window = min(max(window, 100), 100_000)
215
+ n = np.arange(settle + window)
216
+ x = np.sin(2 * np.pi * frequency * n / design.fs_hz).astype(np.float32)
217
+ y = run_c_filter(header, runtime, name, x, compiler)
218
+ residual = _tone_amplitude(y[settle:], design.fs_hz, frequency)
219
+ attenuation_db = -20.0 * float(np.log10(max(residual, 1e-12)))
220
+ return Attenuation(
221
+ frequency_hz=float(frequency),
222
+ attenuation_db=attenuation_db,
223
+ minimum_db=minimum_db,
224
+ samples=int(x.size),
225
+ passed=bool(attenuation_db >= minimum_db),
226
+ )
@@ -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,15 @@
1
+ filter2c/__init__.py,sha256=TskAEsixm8TnTaQJgv9GxwmCLS5yLjYYIp_q8poppvs,510
2
+ filter2c/__main__.py,sha256=k1ocEWawweo1qCJWNFAAvyxz3tcY13dzvCenHszij30,48
3
+ filter2c/cli.py,sha256=GbYy_zZm5xGda5lWLjZDOyFX5tDKDD1LR5OLo86XHwQ,15153
4
+ filter2c/codegen.py,sha256=rdeGKSmi-d6aOKxnCDhfhJxbpRK0gvmwXTCpHurmvA4,3202
5
+ filter2c/design.py,sha256=k3nZHDnQmK_JxhP3bDV-Q6IB7wrSBze77i_crxe0Yj0,6270
6
+ filter2c/live.py,sha256=4muf06ZQv-idYGeNSscni8BShHNuW6XfOHoVmjmAdu4,10589
7
+ filter2c/target.py,sha256=9pcg4jcOMVDUjJW1y07uHEP1EtUwjGrPtd3G6pZZqt4,11714
8
+ filter2c/verify.py,sha256=UrFIhrzY1IMTY_MlWnMq3el4BIq8kU3YR_TpBwR4qFY,7848
9
+ filter2c/runtime/filter2c.h,sha256=MKDicOh9v0cjkPkRkd5GCbchpdYMQbaIKjjH5RJMIIQ,1786
10
+ filter2c-0.1.0.dist-info/licenses/LICENSE,sha256=b8WuH6bF7NSmmRlM5t18drZtNmH2RKJCn0f3q9juQsg,1079
11
+ filter2c-0.1.0.dist-info/METADATA,sha256=l-fKGLs61NtMeRMcV-lBQhnbFz9jWhOOTxqT6krjEDE,3360
12
+ filter2c-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
13
+ filter2c-0.1.0.dist-info/entry_points.txt,sha256=xw0oWlJ5Nat2loUoL_gqqkvPMfmGU52W5zOi97JZsDY,47
14
+ filter2c-0.1.0.dist-info/top_level.txt,sha256=PkN-11q9fvrItQsEB2eTWTwC8sQob3aiMK_4CPy25l0,9
15
+ filter2c-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ filter2c = filter2c.cli:main
@@ -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 @@
1
+ filter2c