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/live.py ADDED
@@ -0,0 +1,298 @@
1
+ """A live check of the filter on a real board, with a real analog input.
2
+
3
+ The self-test in ``target.py`` feeds the filter a stored signal. This check goes
4
+ one step further and uses the board's own analog-to-digital converter:
5
+
6
+ 1. ``create_live_sketch`` writes a sketch. The board drives one of its pins as a
7
+ slow square wave, reads it back through its analog input (the user connects
8
+ the two pins with one jumper wire), takes readings at the filter's sampling
9
+ rate, runs the filter, and only afterwards prints time, raw reading and
10
+ filtered value. Printing after the measurement keeps it from disturbing the
11
+ timing.
12
+ 2. ``check_live_log`` reads that output on the PC and checks three things: the
13
+ board really sampled at the expected rate, the input really changed, and the
14
+ filter output equals SciPy's filter applied to the same raw readings.
15
+
16
+ The sketch uses only ``micros``, ``millis``, ``analogRead``, ``digitalWrite`` and
17
+ ``Serial.print``, which every Arduino board has.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import re
23
+ from dataclasses import dataclass
24
+ from pathlib import Path
25
+ from string import Template
26
+
27
+ import numpy as np
28
+ from scipy import signal
29
+
30
+ from . import __version__
31
+ from .codegen import check_name, generate_header, runtime_header
32
+ from .design import FilterDesign
33
+ from .target import META_FILE, _RESERVED_NAMES, _SKETCH_FOLDER, _design_from_meta, _design_parameters
34
+ from .verify import DEFAULT_TOLERANCE, VerificationError
35
+
36
+ LIVE_SAMPLES = 2000
37
+ DEFAULT_MAX_PERIOD_ERROR = 0.005 # mean sample period may be off by 0.5 %
38
+ DEFAULT_MIN_SWING = 1000.0 # the raw reading must move by at least this many counts
39
+
40
+ _LIVE_RESERVED = _RESERVED_NAMES | {
41
+ "timeUs", "raw", "filtered", "acquire", "micros", "analogRead", "digitalWrite", "pinMode",
42
+ }
43
+
44
+ _LIVE_SKETCH = Template(
45
+ """/*
46
+ * Generated by filter2c ${version}: live check of the filter "${name}" on a real board.
47
+ *
48
+ * The board drives one of its own pins as a slow square wave (5 Hz) and reads it
49
+ * back with its analog input. Connect the two pins with ONE jumper wire, nothing
50
+ * else is needed:
51
+ * output pin OUT_PIN --- wire --- analog input pin ADC_PIN
52
+ * The pin numbers below are for ESP32-S3 boards (GPIO2 and GPIO1). On other
53
+ * boards change them.
54
+ *
55
+ * The sketch takes ${samples} readings at exactly ${fs} Hz and runs the filter on
56
+ * each one. Only afterwards it prints time, raw reading and filtered value, so
57
+ * the printing cannot disturb the timing. The block repeats every 5 seconds.
58
+ *
59
+ * What to do:
60
+ * 1. Connect the two pins with the jumper wire, select your board and upload.
61
+ * 2. Open the Serial Monitor at 921600 baud (ignored on a native USB port).
62
+ * 3. Wait for FILTER2C_LIVE_END, select all the text and save it as live.txt.
63
+ * 4. On the PC run: filter2c check-live-log <this folder> live.txt
64
+ */
65
+ #include <Arduino.h>
66
+
67
+ #include "filter2c.h"
68
+ #include "${name}.h"
69
+
70
+ #if defined(ARDUINO_ARCH_ESP32)
71
+ const int OUT_PIN = 2; // GPIO2
72
+ const int ADC_PIN = 1; // GPIO1
73
+ #else
74
+ const int OUT_PIN = 2; // D2
75
+ const int ADC_PIN = A0;
76
+ #endif
77
+
78
+ const unsigned int SAMPLES = ${samples}u;
79
+ const unsigned long PERIOD_US = ${period_us}ul; // ${fs} Hz, must match the filter design
80
+ const unsigned long HALF_CYCLE_MS = 100; // 100 ms high, 100 ms low: a 5 Hz square wave
81
+
82
+ static uint32_t timeUs[SAMPLES];
83
+ static uint16_t raw[SAMPLES];
84
+ static float filtered[SAMPLES];
85
+
86
+ static void acquire(void)
87
+ {
88
+ unsigned int i;
89
+ unsigned long next;
90
+ filter2c_reset(&${name});
91
+ next = micros();
92
+ for (i = 0; i < SAMPLES; ++i) {
93
+ // Wait for the next sample time. The subtraction also works when micros() wraps around.
94
+ while ((long)(micros() - next) < 0) {
95
+ }
96
+ next += PERIOD_US;
97
+ digitalWrite(OUT_PIN, ((millis() / HALF_CYCLE_MS) & 1) ? HIGH : LOW);
98
+ timeUs[i] = (uint32_t)micros();
99
+ raw[i] = (uint16_t)analogRead(ADC_PIN);
100
+ filtered[i] = filter2c_process(&${name}, (float)raw[i]);
101
+ }
102
+ }
103
+
104
+ void setup()
105
+ {
106
+ unsigned long start = millis();
107
+ pinMode(OUT_PIN, OUTPUT);
108
+ Serial.begin(921600);
109
+ while (!Serial && millis() - start < 5000) {
110
+ // Wait for the USB serial connection, but not forever.
111
+ }
112
+ delay(1000);
113
+ }
114
+
115
+ void loop()
116
+ {
117
+ unsigned int i;
118
+
119
+ acquire();
120
+
121
+ Serial.println("FILTER2C_LIVE_BEGIN");
122
+ for (i = 0; i < SAMPLES; ++i) {
123
+ Serial.print(timeUs[i]);
124
+ Serial.print(',');
125
+ Serial.print(raw[i]);
126
+ Serial.print(',');
127
+ Serial.println(filtered[i], 5);
128
+ }
129
+ Serial.println("FILTER2C_LIVE_END");
130
+ Serial.print("FILTER2C_LIVE_SAMPLES=");
131
+ Serial.println(SAMPLES);
132
+
133
+ delay(5000);
134
+ }
135
+ """
136
+ )
137
+
138
+
139
+ def create_live_sketch(
140
+ design: FilterDesign, name: str, folder: Path, samples: int = LIVE_SAMPLES
141
+ ) -> list[Path]:
142
+ """Write a ready-to-upload live-check sketch folder and return the files created."""
143
+ check_name(name)
144
+ if name in _LIVE_RESERVED:
145
+ raise ValueError(f"the filter name {name!r} clashes with a name used in the sketch")
146
+ if not _SKETCH_FOLDER.match(folder.name):
147
+ raise ValueError(
148
+ f"{folder.name!r} is not a usable sketch folder name "
149
+ "(letters, digits, underscores and dashes only)"
150
+ )
151
+ period_us = round(1e6 / design.fs_hz)
152
+ if period_us < 1 or abs(period_us * design.fs_hz - 1e6) > 1e-6 * 1e6:
153
+ raise ValueError(
154
+ f"a sampling rate of {design.fs_hz:g} Hz does not give a whole number of "
155
+ "microseconds per sample; use a rate such as 100, 250, 500 or 1000 Hz"
156
+ )
157
+ if samples < 100:
158
+ raise ValueError("a live check needs at least 100 samples")
159
+
160
+ meta = {
161
+ **_design_parameters(design),
162
+ "fs_hz": design.fs_hz,
163
+ "name": name,
164
+ "samples": samples,
165
+ "mode": "live",
166
+ "filter2c_version": __version__,
167
+ }
168
+ contents = {
169
+ f"{folder.name}.ino": _LIVE_SKETCH.substitute(
170
+ version=__version__, name=name, samples=samples, period_us=period_us,
171
+ fs=f"{design.fs_hz:g}",
172
+ ),
173
+ f"{name}.h": generate_header(design, name),
174
+ "filter2c.h": runtime_header(),
175
+ META_FILE: json.dumps(meta, indent=2) + "\n",
176
+ }
177
+ folder.mkdir(parents=True, exist_ok=True)
178
+ written = []
179
+ for filename, text in contents.items():
180
+ path = folder / filename
181
+ path.write_text(text, encoding="utf-8", newline="\n")
182
+ written.append(path)
183
+ return written
184
+
185
+
186
+ _LIVE_BLOCK = re.compile(r"FILTER2C_LIVE_BEGIN(.*?)FILTER2C_LIVE_END", re.DOTALL)
187
+
188
+
189
+ def parse_live_log(text: str, expected_samples: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
190
+ """Read the last complete block: time in microseconds, raw reading, filtered value.
191
+
192
+ Serial monitors may add a timestamp and ``->`` in front of each line; only
193
+ what comes after the last ``->`` is read.
194
+ """
195
+ blocks = _LIVE_BLOCK.findall(text)
196
+ if not blocks:
197
+ raise VerificationError(
198
+ "no complete result found in the log (needs FILTER2C_LIVE_BEGIN and FILTER2C_LIVE_END). "
199
+ "Wait for the block to finish printing, then copy again."
200
+ )
201
+ times, raws, outs = [], [], []
202
+ for line in blocks[-1].splitlines():
203
+ line = line.split("->")[-1].strip()
204
+ if not line:
205
+ continue
206
+ fields = line.split(",")
207
+ try:
208
+ if len(fields) != 3:
209
+ raise ValueError
210
+ times.append(int(fields[0]))
211
+ raws.append(int(fields[1]))
212
+ outs.append(float(fields[2]))
213
+ except ValueError as error:
214
+ raise VerificationError(f"unreadable line in the log: {line!r}") from error
215
+ if len(times) != expected_samples:
216
+ raise VerificationError(
217
+ f"the log has {len(times)} samples, expected {expected_samples}. "
218
+ "Copy the whole block, from FILTER2C_LIVE_BEGIN to FILTER2C_LIVE_END."
219
+ )
220
+ return (
221
+ np.array(times, dtype=np.int64),
222
+ np.array(raws, dtype=np.float64),
223
+ np.array(outs, dtype=np.float64),
224
+ )
225
+
226
+
227
+ @dataclass(frozen=True)
228
+ class LiveReport:
229
+ samples: int
230
+ expected_period_us: float
231
+ mean_period_us: float
232
+ min_period_us: float
233
+ max_period_us: float
234
+ std_period_us: float
235
+ late_fraction: float # share of sample intervals longer than 1.5 x the expected period
236
+ raw_min: float
237
+ raw_max: float
238
+ max_abs_error: float
239
+ relative_error: float
240
+ tolerance: float
241
+ timing_ok: bool
242
+ signal_ok: bool
243
+ accuracy_ok: bool
244
+
245
+ @property
246
+ def passed(self) -> bool:
247
+ return self.timing_ok and self.signal_ok and self.accuracy_ok
248
+
249
+
250
+ def check_live_log(
251
+ folder: Path,
252
+ log_text: str,
253
+ tolerance: float = DEFAULT_TOLERANCE,
254
+ max_period_error: float = DEFAULT_MAX_PERIOD_ERROR,
255
+ min_swing: float = DEFAULT_MIN_SWING,
256
+ ) -> LiveReport:
257
+ """Check a live log against the design in the sketch folder."""
258
+ meta_path = folder / META_FILE
259
+ if not meta_path.exists():
260
+ raise VerificationError(f"{meta_path} not found: is this a folder made by target-sketch?")
261
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
262
+ if meta.get("mode") != "live":
263
+ raise VerificationError(
264
+ "this folder holds a self-test sketch, not a live-check sketch. "
265
+ "Use check-board-log, or make a live sketch with: target-sketch <filter> --live"
266
+ )
267
+ design = _design_from_meta(meta)
268
+ samples = int(meta["samples"])
269
+
270
+ times, raw, filtered = parse_live_log(log_text, samples)
271
+
272
+ expected = 1e6 / design.fs_hz
273
+ periods = np.diff(times) % (2 ** 32) # micros() wraps around after about 71 minutes
274
+ mean_period = float(np.mean(periods))
275
+ swing = float(raw.max() - raw.min())
276
+
277
+ reference = signal.sosfilt(design.sos, raw)
278
+ max_abs = float(np.max(np.abs(filtered - reference)))
279
+ peak = float(np.max(np.abs(reference)))
280
+ relative = max_abs / peak if peak > 0 else float("inf")
281
+
282
+ return LiveReport(
283
+ samples=samples,
284
+ expected_period_us=expected,
285
+ mean_period_us=mean_period,
286
+ min_period_us=float(periods.min()),
287
+ max_period_us=float(periods.max()),
288
+ std_period_us=float(np.std(periods)),
289
+ late_fraction=float(np.mean(periods > 1.5 * expected)),
290
+ raw_min=float(raw.min()),
291
+ raw_max=float(raw.max()),
292
+ max_abs_error=max_abs,
293
+ relative_error=relative,
294
+ tolerance=tolerance,
295
+ timing_ok=bool(abs(mean_period - expected) / expected <= max_period_error),
296
+ signal_ok=bool(swing >= min_swing),
297
+ accuracy_ok=bool(relative <= tolerance),
298
+ )
@@ -0,0 +1,66 @@
1
+ /*
2
+ * filter2c runtime: a cascade of biquad (second-order) filter sections.
3
+ *
4
+ * Each section uses the Direct Form II Transposed structure in float:
5
+ *
6
+ * y = b0 * x + z1
7
+ * z1 = b1 * x - a1 * y + z2
8
+ * z2 = b2 * x - a2 * y
9
+ *
10
+ * The coefficients come from a header generated by the filter2c Python tool.
11
+ * This file has no dependencies, uses no dynamic memory and works in C99 and
12
+ * C++ (including Arduino sketches).
13
+ *
14
+ * Copyright (c) 2026 Abhishek Vijay Potekar. MIT licence, see LICENSE.
15
+ */
16
+ #ifndef FILTER2C_H
17
+ #define FILTER2C_H
18
+
19
+ #define FILTER2C_VERSION "0.1.0"
20
+
21
+ #ifdef __cplusplus
22
+ extern "C" {
23
+ #endif
24
+
25
+ /* One biquad section. The denominator coefficient a0 is always 1 and is not stored. */
26
+ typedef struct {
27
+ float b0, b1, b2;
28
+ float a1, a2;
29
+ } filter2c_section;
30
+
31
+ /* A filter: a list of sections plus two state values (z1, z2) per section. */
32
+ typedef struct {
33
+ const filter2c_section *sections;
34
+ float *state; /* 2 * count floats, owned by the generated header */
35
+ unsigned int count; /* number of sections */
36
+ } filter2c_sos;
37
+
38
+ /* Clear the filter memory. Call once before the first sample. */
39
+ static inline void filter2c_reset(const filter2c_sos *f)
40
+ {
41
+ unsigned int i;
42
+ for (i = 0; i < 2u * f->count; ++i) {
43
+ f->state[i] = 0.0f;
44
+ }
45
+ }
46
+
47
+ /* Filter one sample and return the filtered value. */
48
+ static inline float filter2c_process(const filter2c_sos *f, float x)
49
+ {
50
+ unsigned int i;
51
+ for (i = 0; i < f->count; ++i) {
52
+ const filter2c_section *s = &f->sections[i];
53
+ float *z = &f->state[2u * i];
54
+ float y = s->b0 * x + z[0];
55
+ z[0] = s->b1 * x - s->a1 * y + z[1];
56
+ z[1] = s->b2 * x - s->a2 * y;
57
+ x = y;
58
+ }
59
+ return x;
60
+ }
61
+
62
+ #ifdef __cplusplus
63
+ }
64
+ #endif
65
+
66
+ #endif /* FILTER2C_H */
filter2c/target.py ADDED
@@ -0,0 +1,329 @@
1
+ """Run the generated filter on a real board and check what the board says.
2
+
3
+ Workflow:
4
+
5
+ 1. ``create_sketch`` writes an Arduino sketch folder. The sketch runs the filter
6
+ on a built-in test signal, times it, and prints the result over serial.
7
+ 2. The user uploads it, copies the serial output into a text file.
8
+ 3. ``check_board_log`` compares the board's numbers with SciPy and with the same
9
+ C code compiled on the PC, and reports the speed.
10
+
11
+ The sketch uses ``ESP.getCycleCount()`` and ``getCpuFrequencyMhz()``, so it is
12
+ written for ESP32 boards.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import re
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from string import Template
21
+
22
+ import numpy as np
23
+ from scipy import signal
24
+
25
+ from . import __version__
26
+ from .codegen import check_name, float32_literal, generate_header, runtime_header
27
+ from .design import (
28
+ FilterDesign,
29
+ butterworth_bandpass,
30
+ butterworth_highpass,
31
+ butterworth_lowpass,
32
+ notch,
33
+ )
34
+ from .verify import (
35
+ DEFAULT_TOLERANCE,
36
+ VerificationError,
37
+ find_compiler,
38
+ make_test_signal,
39
+ run_c_filter,
40
+ )
41
+
42
+ SAMPLES = 1024
43
+ META_FILE = "filter2c_target.json"
44
+
45
+ # Names that would clash with files or identifiers used inside the sketch.
46
+ _RESERVED_NAMES = frozenset(
47
+ {"filter2c", "testsignal", "setup", "loop", "main", "Serial", "ESP", "delay", "millis"}
48
+ )
49
+ _SKETCH_FOLDER = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_-]{0,62}$")
50
+
51
+ _SKETCH = Template(
52
+ """/*
53
+ * Generated by filter2c ${version}: on-board self-test for ESP32 boards.
54
+ *
55
+ * The sketch runs the filter "${name}" on a built-in test signal, measures the
56
+ * time per sample and prints the result over the serial port at 115200 baud.
57
+ * The block of numbers repeats every 10 seconds.
58
+ *
59
+ * What to do:
60
+ * 1. Select your ESP32 board and upload this sketch.
61
+ * 2. Open the Serial Monitor at 115200 baud and wait until FILTER2C_END appears.
62
+ * 3. Select all the text, copy it and save it as board.txt.
63
+ * 4. On the PC run: filter2c check-board-log <this folder> board.txt
64
+ *
65
+ * No output on an ESP32-S3 when using its USB port? In the Arduino IDE set
66
+ * Tools > USB CDC On Boot > Enabled, then upload again.
67
+ */
68
+ #include <Arduino.h>
69
+
70
+ #include "filter2c.h"
71
+ #include "${name}.h"
72
+ #include "testsignal.h"
73
+
74
+ static float f2c_output[F2C_TEST_SAMPLES];
75
+
76
+ static void f2c_run(void)
77
+ {
78
+ unsigned int i;
79
+ filter2c_reset(&${name});
80
+ for (i = 0; i < F2C_TEST_SAMPLES; ++i) {
81
+ f2c_output[i] = filter2c_process(&${name}, f2c_test_input[i]);
82
+ }
83
+ }
84
+
85
+ void setup()
86
+ {
87
+ unsigned long start = millis();
88
+ Serial.begin(115200);
89
+ while (!Serial && millis() - start < 5000) {
90
+ // Wait for the USB serial connection, but not forever.
91
+ }
92
+ delay(1000);
93
+ }
94
+
95
+ void loop()
96
+ {
97
+ unsigned int i;
98
+ uint32_t t0, cycles;
99
+
100
+ f2c_run(); // first pass warms up the instruction and data caches
101
+ t0 = ESP.getCycleCount();
102
+ f2c_run(); // second pass is timed
103
+ cycles = ESP.getCycleCount() - t0;
104
+
105
+ Serial.println("FILTER2C_BEGIN");
106
+ for (i = 0; i < F2C_TEST_SAMPLES; ++i) {
107
+ Serial.printf("%.9g\\n", (double)f2c_output[i]);
108
+ }
109
+ Serial.println("FILTER2C_END");
110
+ Serial.printf("FILTER2C_SAMPLES=%u\\n", (unsigned int)F2C_TEST_SAMPLES);
111
+ Serial.printf("FILTER2C_CPU_MHZ=%u\\n", (unsigned int)getCpuFrequencyMhz());
112
+ Serial.printf("FILTER2C_CYCLES_PER_SAMPLE=%.2f\\n", (double)cycles / (double)F2C_TEST_SAMPLES);
113
+
114
+ delay(10000);
115
+ }
116
+ """
117
+ )
118
+
119
+
120
+ def test_signal_header(x: np.ndarray) -> str:
121
+ """C header holding the test signal as a float array."""
122
+ values = [float32_literal(v) for v in x]
123
+ lines = []
124
+ for start in range(0, len(values), 8):
125
+ lines.append(" " + ", ".join(values[start:start + 8]))
126
+ body = ",\n".join(lines)
127
+ return f"""/* Generated by filter2c {__version__}. Test signal for the on-board self-test. */
128
+ #ifndef FILTER2C_GENERATED_TESTSIGNAL_H
129
+ #define FILTER2C_GENERATED_TESTSIGNAL_H
130
+
131
+ #define F2C_TEST_SAMPLES {len(values)}u
132
+
133
+ static const float f2c_test_input[F2C_TEST_SAMPLES] = {{
134
+ {body}
135
+ }};
136
+
137
+ #endif /* FILTER2C_GENERATED_TESTSIGNAL_H */
138
+ """
139
+
140
+
141
+ def _design_parameters(design: FilterDesign) -> dict:
142
+ """The numbers needed to design the same filter again, for the metadata file."""
143
+ if design.q is not None:
144
+ return {"filter": "notch", "freq_hz": design.cutoff_hz, "q": design.q}
145
+ if design.high_hz is not None:
146
+ return {"filter": "butterworth-bandpass", "order": design.order,
147
+ "low_hz": design.cutoff_hz, "high_hz": design.high_hz}
148
+ if design.kind == "Butterworth high-pass":
149
+ return {"filter": "butterworth-highpass", "order": design.order,
150
+ "cutoff_hz": design.cutoff_hz}
151
+ return {"filter": "butterworth-lowpass", "order": design.order, "cutoff_hz": design.cutoff_hz}
152
+
153
+
154
+ def _design_from_meta(meta: dict) -> FilterDesign:
155
+ """Rebuild the design from a metadata file (see ``_design_parameters``)."""
156
+ kind, fs = meta.get("filter"), meta["fs_hz"]
157
+ if kind == "notch":
158
+ return notch(meta["freq_hz"], meta["q"], fs)
159
+ if kind == "butterworth-bandpass":
160
+ return butterworth_bandpass(meta["order"], meta["low_hz"], meta["high_hz"], fs)
161
+ if kind == "butterworth-highpass":
162
+ return butterworth_highpass(meta["order"], meta["cutoff_hz"], fs)
163
+ if kind == "butterworth-lowpass":
164
+ return butterworth_lowpass(meta["order"], meta["cutoff_hz"], fs)
165
+ raise VerificationError(f"unknown filter type {kind!r} in {META_FILE}")
166
+
167
+
168
+ def create_sketch(
169
+ design: FilterDesign, name: str, folder: Path, samples: int = SAMPLES
170
+ ) -> list[Path]:
171
+ """Write a ready-to-upload sketch folder and return the files created."""
172
+ check_name(name)
173
+ if name in _RESERVED_NAMES:
174
+ raise ValueError(f"the filter name {name!r} clashes with a name used in the sketch")
175
+ if not _SKETCH_FOLDER.match(folder.name):
176
+ raise ValueError(
177
+ f"{folder.name!r} is not a usable sketch folder name "
178
+ "(letters, digits, underscores and dashes only)"
179
+ )
180
+ # A notch filter gets a tone at the frequency it is meant to remove.
181
+ tones = (design.cutoff_hz,) if design.q is not None else ()
182
+ x = make_test_signal(design.fs_hz, samples, tones_hz=tones)
183
+ meta = {
184
+ **_design_parameters(design),
185
+ "fs_hz": design.fs_hz,
186
+ "name": name,
187
+ "samples": samples,
188
+ "filter2c_version": __version__,
189
+ }
190
+ contents = {
191
+ f"{folder.name}.ino": _SKETCH.substitute(version=__version__, name=name),
192
+ f"{name}.h": generate_header(design, name),
193
+ "testsignal.h": test_signal_header(x),
194
+ "filter2c.h": runtime_header(),
195
+ META_FILE: json.dumps(meta, indent=2) + "\n",
196
+ }
197
+ folder.mkdir(parents=True, exist_ok=True)
198
+ written = []
199
+ for filename, text in contents.items():
200
+ path = folder / filename
201
+ path.write_text(text, encoding="utf-8", newline="\n")
202
+ written.append(path)
203
+ return written
204
+
205
+
206
+ @dataclass(frozen=True)
207
+ class BoardLog:
208
+ outputs: np.ndarray
209
+ cpu_mhz: float
210
+ cycles_per_sample: float
211
+
212
+
213
+ @dataclass(frozen=True)
214
+ class TargetReport:
215
+ samples: int
216
+ max_abs_error: float
217
+ relative_error: float
218
+ tolerance: float
219
+ passed: bool
220
+ identical_to_pc_build: bool | None # None if no C compiler was available
221
+ max_diff_to_pc_build: float | None
222
+ cpu_mhz: float
223
+ cycles_per_sample: float
224
+
225
+ @property
226
+ def microseconds_per_sample(self) -> float:
227
+ return self.cycles_per_sample / self.cpu_mhz
228
+
229
+ @property
230
+ def max_sample_rate_hz(self) -> float:
231
+ return 1e6 / self.microseconds_per_sample
232
+
233
+
234
+ _BLOCK = re.compile(r"FILTER2C_BEGIN(.*?)FILTER2C_END(.*?)(?=FILTER2C_BEGIN|\Z)", re.DOTALL)
235
+
236
+
237
+ def parse_board_log(text: str, expected_samples: int) -> BoardLog:
238
+ """Read the last complete block of serial output.
239
+
240
+ Serial monitors may add timestamps before each line, so only the last
241
+ word of each line is read.
242
+ """
243
+ blocks = [m for m in _BLOCK.finditer(text) if "FILTER2C_CYCLES_PER_SAMPLE=" in m.group(2)]
244
+ if not blocks:
245
+ raise VerificationError(
246
+ "no complete result found in the log (needs FILTER2C_BEGIN, FILTER2C_END and the "
247
+ "FILTER2C_ lines after it). Wait for the block to finish printing, then copy again."
248
+ )
249
+ block = blocks[-1]
250
+ numbers = []
251
+ for line in block.group(1).splitlines():
252
+ words = line.split()
253
+ # A timestamp prefix ("12:00:01.123 ->") can be left over in front of a marker.
254
+ if not words or words[-1] == "->":
255
+ continue
256
+ try:
257
+ numbers.append(float(words[-1]))
258
+ except ValueError as error:
259
+ raise VerificationError(f"unreadable line in the log: {line!r}") from error
260
+ if len(numbers) != expected_samples:
261
+ raise VerificationError(
262
+ f"the log has {len(numbers)} samples, expected {expected_samples}. "
263
+ "Copy the whole block, from FILTER2C_BEGIN to the last FILTER2C_ line."
264
+ )
265
+
266
+ def stat(key: str) -> float:
267
+ match = re.search(rf"{key}=([0-9.eE+-]+)", block.group(2))
268
+ if not match:
269
+ raise VerificationError(f"{key} is missing from the log")
270
+ return float(match.group(1))
271
+
272
+ cpu = stat("FILTER2C_CPU_MHZ")
273
+ cycles = stat("FILTER2C_CYCLES_PER_SAMPLE")
274
+ if cpu <= 0 or cycles <= 0:
275
+ raise VerificationError("the clock speed and cycle count in the log must be positive")
276
+ return BoardLog(np.array(numbers, dtype=np.float64), cpu, cycles)
277
+
278
+
279
+ def read_test_signal(folder: Path) -> np.ndarray:
280
+ """Read the test signal back from the sketch folder, exactly as the board sees it."""
281
+ text = (folder / "testsignal.h").read_text(encoding="utf-8")
282
+ match = re.search(r"=\s*\{(.*?)\}\s*;", text, re.DOTALL)
283
+ if not match:
284
+ raise VerificationError("could not read the test signal from testsignal.h")
285
+ values = re.findall(r"[-+]?\d[\d.]*(?:[eE][-+]?\d+)?(?=f)", match.group(1))
286
+ return np.array([np.float32(v) for v in values], dtype=np.float32)
287
+
288
+
289
+ def check_board_log(
290
+ folder: Path, log_text: str, tolerance: float = DEFAULT_TOLERANCE
291
+ ) -> TargetReport:
292
+ """Compare what the board printed with SciPy and with the PC build."""
293
+ meta_path = folder / META_FILE
294
+ if not meta_path.exists():
295
+ raise VerificationError(f"{meta_path} not found: is this a folder made by target-sketch?")
296
+ meta = json.loads(meta_path.read_text(encoding="utf-8"))
297
+ if meta.get("mode") == "live":
298
+ raise VerificationError(
299
+ "this folder holds a live-check sketch. Use check-live-log for its output."
300
+ )
301
+ design = _design_from_meta(meta)
302
+ name, samples = meta["name"], int(meta["samples"])
303
+
304
+ x = read_test_signal(folder)
305
+ if x.size != samples:
306
+ raise VerificationError(f"testsignal.h has {x.size} samples, expected {samples}")
307
+ board = parse_board_log(log_text, samples)
308
+
309
+ reference = signal.sosfilt(design.sos, x.astype(np.float64))
310
+ max_abs = float(np.max(np.abs(board.outputs - reference)))
311
+ relative = max_abs / float(np.max(np.abs(reference)))
312
+
313
+ identical = diff = None
314
+ if find_compiler() is not None:
315
+ pc = run_c_filter(generate_header(design, name), runtime_header(), name, x)
316
+ diff = float(np.max(np.abs(board.outputs - pc)))
317
+ identical = bool(np.array_equal(board.outputs.astype(np.float32), pc.astype(np.float32)))
318
+
319
+ return TargetReport(
320
+ samples=samples,
321
+ max_abs_error=max_abs,
322
+ relative_error=relative,
323
+ tolerance=tolerance,
324
+ passed=bool(relative <= tolerance),
325
+ identical_to_pc_build=identical,
326
+ max_diff_to_pc_build=diff,
327
+ cpu_mhz=board.cpu_mhz,
328
+ cycles_per_sample=board.cycles_per_sample,
329
+ )