pymetrology 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.
@@ -0,0 +1,44 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ jobs:
8
+ test:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v4
12
+ - uses: actions/setup-python@v5
13
+ with:
14
+ python-version: "3.12"
15
+ - run: pip install -e ".[dev]"
16
+ - run: pytest -q
17
+
18
+ build:
19
+ needs: test
20
+ runs-on: ubuntu-latest
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ - uses: actions/setup-python@v5
24
+ with:
25
+ python-version: "3.12"
26
+ - run: pip install build
27
+ - run: python -m build
28
+ - uses: actions/upload-artifact@v4
29
+ with:
30
+ name: dist
31
+ path: dist/
32
+
33
+ publish:
34
+ needs: build
35
+ runs-on: ubuntu-latest
36
+ environment: pypi
37
+ permissions:
38
+ id-token: write
39
+ steps:
40
+ - uses: actions/download-artifact@v4
41
+ with:
42
+ name: dist
43
+ path: dist/
44
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .venv/
7
+ .pytest_cache/
8
+ .ipynb_checkpoints/
@@ -0,0 +1,18 @@
1
+ cff-version: 1.2.0
2
+ message: "If you use this software, please cite it as below."
3
+ title: "pymetrology: GUM-compliant metrological characterisation of low-cost data acquisition chains"
4
+ version: 0.1.0
5
+ date-released: 2026-12-04
6
+ license: MIT
7
+ repository-code: "https://github.com/ThermalProjects/pymetrology"
8
+ authors:
9
+ - family-names: "Ferrer Pareja"
10
+ given-names: "Miguel F."
11
+ orcid: "https://orcid.org/0009-0000-7518-3583"
12
+ affiliation: "SIANI, Universidad de Las Palmas de Gran Canaria"
13
+ keywords:
14
+ - metrology
15
+ - measurement uncertainty
16
+ - GUM
17
+ - ADC
18
+ - data acquisition
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Miguel F. Ferrer Pareja
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,91 @@
1
+ Metadata-Version: 2.5
2
+ Name: pymetrology
3
+ Version: 0.1.0
4
+ Summary: GUM-compliant metrological characterisation of low-cost data acquisition chains: ADC noise, calibration, sampling and drift.
5
+ Project-URL: Homepage, https://github.com/ThermalProjects/pymetrology
6
+ Project-URL: Issues, https://github.com/ThermalProjects/pymetrology/issues
7
+ Author: Miguel F. Ferrer Pareja
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: ADC,ENOB,GUM,calibration,data acquisition,instrumentation,measurement uncertainty,metrology,sensors
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering
16
+ Classifier: Topic :: Scientific/Engineering :: Physics
17
+ Requires-Python: >=3.9
18
+ Requires-Dist: numpy>=1.22
19
+ Provides-Extra: dev
20
+ Requires-Dist: matplotlib; extra == 'dev'
21
+ Requires-Dist: pytest>=7; extra == 'dev'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # pymetrology
25
+
26
+ **GUM-compliant metrological characterisation of low-cost data acquisition chains.**
27
+
28
+ `pymetrology` turns raw readings from a sensor + microcontroller + ADC chain
29
+ (Arduino, ESP32, Raspberry Pi Pico, ...) into the figures a measurement needs
30
+ before it can be trusted: resolution, noise, effective number of bits,
31
+ calibration, sampling adequacy, drift and a GUM uncertainty budget.
32
+
33
+ > Status: alpha (v0.1). Only the `adc` module is available.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install pymetrology
39
+ ```
40
+
41
+ From source:
42
+
43
+ ```bash
44
+ git clone https://github.com/ThermalProjects/pymetrology
45
+ cd pymetrology
46
+ pip install -e ".[dev]"
47
+ pytest
48
+ ```
49
+
50
+ ## Quick start
51
+
52
+ ```python
53
+ import numpy as np
54
+ from pymetrology import characterize_noise, enob_sine, lsb
55
+
56
+ codes = np.loadtxt("static_codes.csv", dtype=int) # constant input
57
+ print(characterize_noise(codes, bits=12, vref=3.3).summary())
58
+
59
+ v = np.loadtxt("sine_codes.csv") * lsb(3.3, 12) # near full-scale sine
60
+ print(enob_sine(v, fs=5000, bits=12, vref=3.3).summary())
61
+ ```
62
+
63
+ ## Features (v0.1)
64
+
65
+ | Function | What it gives | Reference |
66
+ |---|---|---|
67
+ | `lsb`, `quantization_uncertainty` | LSB size; type B quantisation uncertainty (LSB/√12) | GUM 4.3.7 |
68
+ | `characterize_noise` | RMS and peak-to-peak noise, effective and noise-free resolution, type A uncertainty of the mean corrected for autocorrelation | GUM 4.2 |
69
+ | `code_histogram` | Code histogram and missing codes | IEEE 1241 |
70
+ | `enob_sine` | Four-parameter sine fit, SINAD and ENOB | IEEE 1057, IEEE 1241 |
71
+
72
+ ## Roadmap
73
+
74
+ - `calibration`: calibration against a certified reference, with uncertainty in both axes
75
+ - `sampling`: minimum sampling rate and anti-aliasing filter from the system dynamics
76
+ - `drift`: long-term drift and Allan deviation
77
+ - `uncertainty`: full GUM uncertainty budget per measurand
78
+ - `report`: Markdown/HTML report for supplementary material
79
+
80
+ ## Citation
81
+
82
+ If you use `pymetrology` in your research, please cite it using the metadata
83
+ in [`CITATION.cff`](CITATION.cff).
84
+
85
+ ## Acknowledgements
86
+
87
+ Developed at SIANI, Universidad de Las Palmas de Gran Canaria.
88
+
89
+ ## License
90
+
91
+ MIT
@@ -0,0 +1,68 @@
1
+ # pymetrology
2
+
3
+ **GUM-compliant metrological characterisation of low-cost data acquisition chains.**
4
+
5
+ `pymetrology` turns raw readings from a sensor + microcontroller + ADC chain
6
+ (Arduino, ESP32, Raspberry Pi Pico, ...) into the figures a measurement needs
7
+ before it can be trusted: resolution, noise, effective number of bits,
8
+ calibration, sampling adequacy, drift and a GUM uncertainty budget.
9
+
10
+ > Status: alpha (v0.1). Only the `adc` module is available.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pip install pymetrology
16
+ ```
17
+
18
+ From source:
19
+
20
+ ```bash
21
+ git clone https://github.com/ThermalProjects/pymetrology
22
+ cd pymetrology
23
+ pip install -e ".[dev]"
24
+ pytest
25
+ ```
26
+
27
+ ## Quick start
28
+
29
+ ```python
30
+ import numpy as np
31
+ from pymetrology import characterize_noise, enob_sine, lsb
32
+
33
+ codes = np.loadtxt("static_codes.csv", dtype=int) # constant input
34
+ print(characterize_noise(codes, bits=12, vref=3.3).summary())
35
+
36
+ v = np.loadtxt("sine_codes.csv") * lsb(3.3, 12) # near full-scale sine
37
+ print(enob_sine(v, fs=5000, bits=12, vref=3.3).summary())
38
+ ```
39
+
40
+ ## Features (v0.1)
41
+
42
+ | Function | What it gives | Reference |
43
+ |---|---|---|
44
+ | `lsb`, `quantization_uncertainty` | LSB size; type B quantisation uncertainty (LSB/√12) | GUM 4.3.7 |
45
+ | `characterize_noise` | RMS and peak-to-peak noise, effective and noise-free resolution, type A uncertainty of the mean corrected for autocorrelation | GUM 4.2 |
46
+ | `code_histogram` | Code histogram and missing codes | IEEE 1241 |
47
+ | `enob_sine` | Four-parameter sine fit, SINAD and ENOB | IEEE 1057, IEEE 1241 |
48
+
49
+ ## Roadmap
50
+
51
+ - `calibration`: calibration against a certified reference, with uncertainty in both axes
52
+ - `sampling`: minimum sampling rate and anti-aliasing filter from the system dynamics
53
+ - `drift`: long-term drift and Allan deviation
54
+ - `uncertainty`: full GUM uncertainty budget per measurand
55
+ - `report`: Markdown/HTML report for supplementary material
56
+
57
+ ## Citation
58
+
59
+ If you use `pymetrology` in your research, please cite it using the metadata
60
+ in [`CITATION.cff`](CITATION.cff).
61
+
62
+ ## Acknowledgements
63
+
64
+ Developed at SIANI, Universidad de Las Palmas de Gran Canaria.
65
+
66
+ ## License
67
+
68
+ MIT
@@ -0,0 +1,33 @@
1
+ """Example: static noise and ENOB of a 12-bit ADC (e.g. Arduino Nano 33 IoT).
2
+
3
+ Replace the synthetic data with your own readings:
4
+
5
+ * Static test: short the analogue input (or connect a stable reference)
6
+ and log a few thousand raw codes with analogReadResolution(12).
7
+ * Dynamic test: feed a near full-scale sine from a function generator
8
+ and log the codes together with the sampling frequency.
9
+ """
10
+
11
+ import numpy as np
12
+
13
+ from pymetrology import characterize_noise, enob_sine, lsb
14
+
15
+ BITS = 12
16
+ VREF = 3.3
17
+ FS = 5_000.0
18
+
19
+ rng = np.random.default_rng(0)
20
+ q = lsb(VREF, BITS)
21
+
22
+ # --- Static test (replace with np.loadtxt("static_codes.csv")) -------------
23
+ v_static = 1.20 + rng.normal(0, 2.5 * q, 5000)
24
+ codes_static = np.clip(np.round(v_static / q), 0, 2**BITS - 1).astype(int)
25
+ print(characterize_noise(codes_static, BITS, VREF).summary())
26
+ print()
27
+
28
+ # --- Dynamic test (replace with your logged sine) --------------------------
29
+ t = np.arange(10000) / FS
30
+ v_sine = VREF / 2 + 0.48 * VREF * np.sin(2 * np.pi * 23.17 * t)
31
+ v_sine += rng.normal(0, 2.5 * q, t.size)
32
+ codes_sine = np.clip(np.round(v_sine / q), 0, 2**BITS - 1).astype(int)
33
+ print(enob_sine(codes_sine * q, FS, BITS, VREF).summary())
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pymetrology"
7
+ version = "0.1.0"
8
+ description = "GUM-compliant metrological characterisation of low-cost data acquisition chains: ADC noise, calibration, sampling and drift."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [
14
+ { name = "Miguel F. Ferrer Pareja" },
15
+ ]
16
+ keywords = [
17
+ "metrology", "measurement uncertainty", "GUM", "ADC", "ENOB",
18
+ "data acquisition", "calibration", "sensors", "instrumentation",
19
+ ]
20
+ classifiers = [
21
+ "Development Status :: 3 - Alpha",
22
+ "Intended Audience :: Science/Research",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3",
25
+ "Topic :: Scientific/Engineering",
26
+ "Topic :: Scientific/Engineering :: Physics",
27
+ ]
28
+ dependencies = ["numpy>=1.22"]
29
+
30
+ [project.optional-dependencies]
31
+ dev = ["pytest>=7", "matplotlib"]
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/ThermalProjects/pymetrology"
35
+ Issues = "https://github.com/ThermalProjects/pymetrology/issues"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/pymetrology"]
39
+
40
+ [tool.pytest.ini_options]
41
+ testpaths = ["tests"]
@@ -0,0 +1,36 @@
1
+ """pymetrology: GUM-compliant metrological characterisation of low-cost
2
+ data acquisition chains.
3
+
4
+ Modules
5
+ -------
6
+ adc
7
+ Resolution, quantisation uncertainty, static noise and dynamic (sine-fit)
8
+ ENOB of analogue-to-digital converters.
9
+
10
+ Planned: calibration, sampling, drift, uncertainty, report.
11
+ """
12
+
13
+ from .adc import (
14
+ NoiseReport,
15
+ SineFitReport,
16
+ characterize_noise,
17
+ code_histogram,
18
+ effective_sample_size,
19
+ enob_sine,
20
+ lsb,
21
+ quantization_uncertainty,
22
+ )
23
+
24
+ __version__ = "0.1.0"
25
+
26
+ __all__ = [
27
+ "NoiseReport",
28
+ "SineFitReport",
29
+ "characterize_noise",
30
+ "code_histogram",
31
+ "effective_sample_size",
32
+ "enob_sine",
33
+ "lsb",
34
+ "quantization_uncertainty",
35
+ "__version__",
36
+ ]
@@ -0,0 +1,358 @@
1
+ """Characterisation of analogue-to-digital converters (ADC).
2
+
3
+ Static tests use repeated readings with a constant input (shorted input or
4
+ stable reference). Dynamic tests use a sampled sine wave and the four-parameter
5
+ sine fit of IEEE Std 1057 / IEEE Std 1241.
6
+
7
+ Conventions
8
+ -----------
9
+ * ``codes`` are raw integer ADC outputs (0 ... 2**bits - 1).
10
+ * ``vref`` is the full-scale span in volts, so 1 LSB = vref / 2**bits.
11
+ * Standard uncertainties follow the GUM (JCGM 100:2008): type B for
12
+ quantisation (rectangular distribution), type A for repeated readings.
13
+
14
+ References
15
+ ----------
16
+ JCGM 100:2008, Evaluation of measurement data - Guide to the expression of
17
+ uncertainty in measurement.
18
+ IEEE Std 1241-2010, Terminology and Test Methods for Analog-to-Digital
19
+ Converters.
20
+ IEEE Std 1057-2017, Standard for Digitizing Waveform Recorders.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass, field
26
+
27
+ import numpy as np
28
+
29
+ __all__ = [
30
+ "lsb",
31
+ "quantization_uncertainty",
32
+ "effective_sample_size",
33
+ "NoiseReport",
34
+ "characterize_noise",
35
+ "code_histogram",
36
+ "SineFitReport",
37
+ "enob_sine",
38
+ ]
39
+
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # Resolution and quantisation
43
+ # ---------------------------------------------------------------------------
44
+ def lsb(vref: float, bits: int) -> float:
45
+ """Size of one least significant bit, in volts: ``vref / 2**bits``."""
46
+ if bits <= 0:
47
+ raise ValueError("bits must be a positive integer")
48
+ if vref <= 0:
49
+ raise ValueError("vref must be positive")
50
+ return vref / 2**bits
51
+
52
+
53
+ def quantization_uncertainty(vref: float, bits: int) -> float:
54
+ """Standard uncertainty due to quantisation, in volts.
55
+
56
+ Type B evaluation with a rectangular distribution of full width 1 LSB
57
+ (GUM 4.3.7): ``u = LSB / sqrt(12)``.
58
+ """
59
+ return lsb(vref, bits) / np.sqrt(12.0)
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Static noise
64
+ # ---------------------------------------------------------------------------
65
+ def effective_sample_size(x: np.ndarray) -> float:
66
+ """Effective number of independent samples under an AR(1) model.
67
+
68
+ Consecutive readings of a real acquisition chain are often correlated
69
+ (filtering, slow drift, mains pickup). Using ``n`` instead of ``n_eff``
70
+ in ``s / sqrt(n)`` underestimates the type A uncertainty of the mean.
71
+
72
+ ``n_eff = n * (1 - r1) / (1 + r1)``, with ``r1`` the lag-1
73
+ autocorrelation, clipped to ``[1, n]``.
74
+ """
75
+ x = np.asarray(x, dtype=float)
76
+ n = x.size
77
+ if n < 3:
78
+ return float(n)
79
+ d = x - x.mean()
80
+ denom = np.dot(d, d)
81
+ if denom == 0.0:
82
+ return float(n)
83
+ r1 = np.dot(d[:-1], d[1:]) / denom
84
+ n_eff = n * (1.0 - r1) / (1.0 + r1)
85
+ return float(np.clip(n_eff, 1.0, n))
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class NoiseReport:
90
+ """Result of :func:`characterize_noise`. Voltages in volts, codes in LSB."""
91
+
92
+ n: int
93
+ bits: int
94
+ vref: float
95
+ lsb: float
96
+ mean_code: float
97
+ std_code: float
98
+ peak_to_peak_code: int
99
+ mean_voltage: float
100
+ rms_noise_voltage: float
101
+ effective_resolution_bits: float
102
+ noise_free_bits: float
103
+ n_eff: float
104
+ u_mean_voltage: float
105
+ u_quantization_voltage: float
106
+ warnings: tuple = field(default_factory=tuple)
107
+
108
+ def summary(self) -> str:
109
+ """Human-readable summary of the report."""
110
+ lines = [
111
+ f"ADC static noise ({self.bits}-bit, Vref = {self.vref:g} V, n = {self.n})",
112
+ f" LSB : {self.lsb * 1e3:.4f} mV",
113
+ f" Mean : {self.mean_code:.3f} LSB = {self.mean_voltage:.6f} V",
114
+ f" RMS noise : {self.std_code:.3f} LSB = {self.rms_noise_voltage * 1e3:.4f} mV",
115
+ f" Peak-to-peak noise : {self.peak_to_peak_code} LSB",
116
+ f" Effective resolution : {self.effective_resolution_bits:.2f} bits",
117
+ f" Noise-free resolution : {self.noise_free_bits:.2f} bits",
118
+ f" Effective sample size : {self.n_eff:.1f} of {self.n}",
119
+ f" u(mean), type A : {self.u_mean_voltage * 1e3:.4f} mV",
120
+ f" u(quantisation), type B : {self.u_quantization_voltage * 1e3:.4f} mV",
121
+ ]
122
+ lines += [f" WARNING: {w}" for w in self.warnings]
123
+ return "\n".join(lines)
124
+
125
+
126
+ def characterize_noise(codes, bits: int, vref: float) -> NoiseReport:
127
+ """Static noise of an ADC channel from repeated readings at constant input.
128
+
129
+ Parameters
130
+ ----------
131
+ codes : array_like of int
132
+ Raw ADC codes acquired with a constant input (shorted input, stable
133
+ voltage reference or sensor in a thermally stable bath).
134
+ bits : int
135
+ Nominal resolution of the converter.
136
+ vref : float
137
+ Full-scale span in volts.
138
+
139
+ Returns
140
+ -------
141
+ NoiseReport
142
+
143
+ Notes
144
+ -----
145
+ * Effective resolution: ``bits - log2(sigma_LSB)`` (based on RMS noise).
146
+ * Noise-free resolution: ``bits - log2(peak_to_peak_LSB)``; when the
147
+ peak-to-peak value is 0 LSB it is reported as ``bits``.
148
+ * When the RMS noise is below about 0.5 LSB, quantisation dominates and
149
+ the RMS-based figures are not meaningful; a warning is added.
150
+ """
151
+ c = np.asarray(codes)
152
+ if c.ndim != 1 or c.size < 2:
153
+ raise ValueError("codes must be a 1-D array with at least 2 readings")
154
+ if not np.issubdtype(c.dtype, np.integer):
155
+ if not np.allclose(c, np.round(c)):
156
+ raise ValueError("codes must be integer ADC outputs")
157
+ c = np.round(c).astype(np.int64)
158
+ full = 2**bits
159
+ warnings = []
160
+ if c.min() < 0 or c.max() > full - 1:
161
+ raise ValueError(f"codes outside the range 0..{full - 1} for a {bits}-bit ADC")
162
+ if c.min() == 0 or c.max() == full - 1:
163
+ warnings.append("readings reach the ADC limits (possible clipping)")
164
+
165
+ q = lsb(vref, bits)
166
+ n = c.size
167
+ cf = c.astype(float)
168
+ mean_code = float(cf.mean())
169
+ std_code = float(cf.std(ddof=1))
170
+ p2p = int(c.max() - c.min())
171
+
172
+ if std_code < 0.5:
173
+ warnings.append(
174
+ "RMS noise below 0.5 LSB: quantisation dominates; "
175
+ "RMS-based resolution is not meaningful"
176
+ )
177
+ eff_bits = float(bits - np.log2(std_code)) if std_code > 0 else float(bits)
178
+ eff_bits = min(eff_bits, float(bits))
179
+ nf_bits = float(bits - np.log2(p2p)) if p2p > 0 else float(bits)
180
+
181
+ n_eff = effective_sample_size(cf)
182
+ if n_eff < 0.5 * n:
183
+ warnings.append(
184
+ f"readings are autocorrelated (n_eff = {n_eff:.0f} of {n}); "
185
+ "u(mean) uses n_eff"
186
+ )
187
+ u_mean = std_code * q / np.sqrt(n_eff)
188
+
189
+ return NoiseReport(
190
+ n=n,
191
+ bits=bits,
192
+ vref=vref,
193
+ lsb=q,
194
+ mean_code=mean_code,
195
+ std_code=std_code,
196
+ peak_to_peak_code=p2p,
197
+ mean_voltage=mean_code * q,
198
+ rms_noise_voltage=std_code * q,
199
+ effective_resolution_bits=eff_bits,
200
+ noise_free_bits=nf_bits,
201
+ n_eff=n_eff,
202
+ u_mean_voltage=float(u_mean),
203
+ u_quantization_voltage=quantization_uncertainty(vref, bits),
204
+ warnings=tuple(warnings),
205
+ )
206
+
207
+
208
+ def code_histogram(codes, bits: int):
209
+ """Histogram of output codes and list of missing codes.
210
+
211
+ Returns
212
+ -------
213
+ code_values : ndarray
214
+ Codes from ``min(codes)`` to ``max(codes)``.
215
+ counts : ndarray
216
+ Occurrences of each code.
217
+ missing : ndarray
218
+ Codes inside the observed range that never occurred. With a slowly
219
+ varying or noisy input covering the range, missing codes indicate
220
+ large differential non-linearity (DNL).
221
+ """
222
+ c = np.asarray(codes).astype(np.int64)
223
+ full = 2**bits
224
+ if c.min() < 0 or c.max() > full - 1:
225
+ raise ValueError(f"codes outside the range 0..{full - 1}")
226
+ lo, hi = int(c.min()), int(c.max())
227
+ counts = np.bincount(c - lo, minlength=hi - lo + 1)
228
+ values = np.arange(lo, hi + 1)
229
+ return values, counts, values[counts == 0]
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # Dynamic test: four-parameter sine fit and ENOB
234
+ # ---------------------------------------------------------------------------
235
+ @dataclass(frozen=True)
236
+ class SineFitReport:
237
+ """Result of :func:`enob_sine`. Amplitude and residuals in volts."""
238
+
239
+ frequency: float
240
+ amplitude: float
241
+ phase: float
242
+ offset: float
243
+ rms_residual: float
244
+ sinad_db: float
245
+ enob: float
246
+ iterations: int
247
+ converged: bool
248
+
249
+ def summary(self) -> str:
250
+ """Human-readable summary of the report."""
251
+ return "\n".join([
252
+ "ADC dynamic test (IEEE 1057 four-parameter sine fit)",
253
+ f" Frequency : {self.frequency:.6g} Hz",
254
+ f" Amplitude : {self.amplitude:.6g} V",
255
+ f" Offset : {self.offset:.6g} V",
256
+ f" RMS residual : {self.rms_residual * 1e3:.4f} mV",
257
+ f" SINAD : {self.sinad_db:.2f} dB",
258
+ f" ENOB : {self.enob:.2f} bits",
259
+ f" Converged : {self.converged} ({self.iterations} iterations)",
260
+ ])
261
+
262
+
263
+ def _initial_frequency(y: np.ndarray, fs: float) -> float:
264
+ """Frequency estimate from the FFT peak with parabolic interpolation."""
265
+ n = y.size
266
+ w = np.hanning(n)
267
+ spec = np.abs(np.fft.rfft((y - y.mean()) * w))
268
+ k = int(np.argmax(spec[1:]) + 1)
269
+ if 1 <= k < spec.size - 1:
270
+ a, b, c = np.log(spec[k - 1 : k + 2] + 1e-300)
271
+ delta = 0.5 * (a - c) / (a - 2 * b + c)
272
+ else:
273
+ delta = 0.0
274
+ return (k + delta) * fs / n
275
+
276
+
277
+ def enob_sine(
278
+ signal,
279
+ fs: float,
280
+ bits: int,
281
+ vref: float,
282
+ frequency: float | None = None,
283
+ max_iter: int = 50,
284
+ tol: float = 1e-10,
285
+ ) -> SineFitReport:
286
+ """Effective number of bits from a sampled sine wave.
287
+
288
+ Fits ``A cos(2 pi f t) + B sin(2 pi f t) + C`` with the frequency as a
289
+ fourth parameter (IEEE Std 1057, Gauss-Newton), then computes
290
+
291
+ * ``ENOB = bits - log2(rms_residual / (LSB / sqrt(12)))`` (IEEE 1241),
292
+ * ``SINAD = 20 log10((amplitude / sqrt(2)) / rms_residual)``.
293
+
294
+ Parameters
295
+ ----------
296
+ signal : array_like
297
+ Samples in volts (convert codes with ``codes * lsb(vref, bits)``).
298
+ fs : float
299
+ Sampling frequency in Hz.
300
+ bits, vref :
301
+ Nominal resolution and full-scale span of the converter.
302
+ frequency : float, optional
303
+ Initial frequency estimate in Hz. If omitted, estimated by FFT.
304
+
305
+ Notes
306
+ -----
307
+ The IEEE 1241 ENOB assumes a sine close to full scale without clipping.
308
+ Record several (ideally non-integer, co-prime) periods so that all codes
309
+ are exercised.
310
+ """
311
+ y = np.asarray(signal, dtype=float)
312
+ if y.ndim != 1 or y.size < 16:
313
+ raise ValueError("signal must be a 1-D array with at least 16 samples")
314
+ t = np.arange(y.size) / fs
315
+ f = float(frequency) if frequency is not None else _initial_frequency(y, fs)
316
+
317
+ # Three-parameter fit at the initial frequency (linear least squares)
318
+ def three_param(freq):
319
+ w = 2 * np.pi * freq * t
320
+ m = np.column_stack([np.cos(w), np.sin(w), np.ones_like(t)])
321
+ p, *_ = np.linalg.lstsq(m, y, rcond=None)
322
+ return p
323
+
324
+ a, b, c = three_param(f)
325
+ converged = False
326
+ it = 0
327
+ for it in range(1, max_iter + 1):
328
+ w = 2 * np.pi * f * t
329
+ cw, sw = np.cos(w), np.sin(w)
330
+ d_f = 2 * np.pi * t * (-a * sw + b * cw)
331
+ m = np.column_stack([cw, sw, np.ones_like(t), d_f])
332
+ p, *_ = np.linalg.lstsq(m, y, rcond=None)
333
+ a, b, c, df = p
334
+ f += df
335
+ if abs(df) <= tol * max(abs(f), 1.0):
336
+ converged = True
337
+ break
338
+
339
+ w = 2 * np.pi * f * t
340
+ resid = y - (a * np.cos(w) + b * np.sin(w) + c)
341
+ rms_res = float(np.sqrt(np.mean(resid**2)))
342
+ amp = float(np.hypot(a, b))
343
+ phase = float(np.arctan2(-b, a))
344
+ eq = quantization_uncertainty(vref, bits)
345
+ enob = float(bits - np.log2(rms_res / eq)) if rms_res > 0 else float("inf")
346
+ sinad = float(20 * np.log10((amp / np.sqrt(2)) / rms_res)) if rms_res > 0 else float("inf")
347
+
348
+ return SineFitReport(
349
+ frequency=float(f),
350
+ amplitude=amp,
351
+ phase=phase,
352
+ offset=float(c),
353
+ rms_residual=rms_res,
354
+ sinad_db=sinad,
355
+ enob=enob,
356
+ iterations=it,
357
+ converged=converged,
358
+ )
@@ -0,0 +1,94 @@
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pymetrology import (
5
+ characterize_noise,
6
+ code_histogram,
7
+ effective_sample_size,
8
+ enob_sine,
9
+ lsb,
10
+ quantization_uncertainty,
11
+ )
12
+
13
+
14
+ def ideal_adc(v, bits, vref):
15
+ """Ideal mid-tread quantiser with clipping."""
16
+ q = vref / 2**bits
17
+ return np.clip(np.round(v / q), 0, 2**bits - 1).astype(np.int64)
18
+
19
+
20
+ def test_lsb_and_quantization():
21
+ assert lsb(3.3, 12) == pytest.approx(3.3 / 4096)
22
+ assert quantization_uncertainty(3.3, 12) == pytest.approx(3.3 / 4096 / np.sqrt(12))
23
+ with pytest.raises(ValueError):
24
+ lsb(3.3, 0)
25
+
26
+
27
+ def test_noise_recovers_known_sigma():
28
+ rng = np.random.default_rng(1)
29
+ bits, vref = 12, 3.3
30
+ q = lsb(vref, bits)
31
+ sigma_lsb = 3.0
32
+ v = 1.65 + rng.normal(0, sigma_lsb * q, 20000)
33
+ rep = characterize_noise(ideal_adc(v, bits, vref), bits, vref)
34
+ expected = np.sqrt(sigma_lsb**2 + 1 / 12) # Gaussian + quantisation
35
+ assert rep.std_code == pytest.approx(expected, rel=0.03)
36
+ assert rep.effective_resolution_bits == pytest.approx(bits - np.log2(expected), abs=0.05)
37
+ assert rep.n_eff == pytest.approx(rep.n, rel=0.05)
38
+ assert not rep.warnings
39
+
40
+
41
+ def test_noise_warns_on_autocorrelation():
42
+ rng = np.random.default_rng(2)
43
+ e = rng.normal(0, 5, 5000)
44
+ x = np.empty_like(e)
45
+ x[0] = e[0]
46
+ for i in range(1, e.size):
47
+ x[i] = 0.95 * x[i - 1] + e[i]
48
+ codes = np.round(2000 + x).astype(int)
49
+ rep = characterize_noise(codes, 12, 3.3)
50
+ assert rep.n_eff < 0.1 * rep.n
51
+ assert any("autocorrelated" in w for w in rep.warnings)
52
+
53
+
54
+ def test_noise_rejects_out_of_range():
55
+ with pytest.raises(ValueError):
56
+ characterize_noise([0, 5000], 12, 3.3)
57
+
58
+
59
+ def test_effective_sample_size_white():
60
+ rng = np.random.default_rng(3)
61
+ assert effective_sample_size(rng.normal(size=10000)) == pytest.approx(10000, rel=0.05)
62
+
63
+
64
+ def test_code_histogram_missing_codes():
65
+ values, counts, missing = code_histogram([10, 10, 11, 13, 13], 12)
66
+ assert list(values) == [10, 11, 12, 13]
67
+ assert list(counts) == [2, 1, 0, 2]
68
+ assert list(missing) == [12]
69
+
70
+
71
+ @pytest.mark.parametrize("bits", [10, 12, 14])
72
+ def test_enob_ideal_adc_close_to_nominal(bits):
73
+ vref, fs, f0, n = 3.3, 10_000.0, 97.3, 20000
74
+ t = np.arange(n) / fs
75
+ amp = 0.49 * vref
76
+ v = vref / 2 + amp * np.sin(2 * np.pi * f0 * t + 0.3)
77
+ signal = ideal_adc(v, bits, vref) * lsb(vref, bits)
78
+ rep = enob_sine(signal, fs, bits, vref)
79
+ assert rep.converged
80
+ assert rep.frequency == pytest.approx(f0, rel=1e-6)
81
+ assert rep.amplitude == pytest.approx(amp, rel=1e-3)
82
+ assert rep.enob == pytest.approx(bits, abs=0.1)
83
+
84
+
85
+ def test_enob_drops_with_noise():
86
+ rng = np.random.default_rng(4)
87
+ bits, vref, fs, f0, n = 12, 3.3, 10_000.0, 51.7, 20000
88
+ q = lsb(vref, bits)
89
+ t = np.arange(n) / fs
90
+ v = vref / 2 + 0.49 * vref * np.sin(2 * np.pi * f0 * t)
91
+ v += rng.normal(0, 4 * q, n)
92
+ rep = enob_sine(ideal_adc(v, bits, vref) * q, fs, bits, vref)
93
+ expected = bits - np.log2(np.sqrt(16 + 1 / 12) / np.sqrt(1 / 12))
94
+ assert rep.enob == pytest.approx(expected, abs=0.1)