clutgen 0.0.1__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.
clutgen-0.0.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
clutgen-0.0.1/PKG-INFO ADDED
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: clutgen
3
+ Version: 0.0.1
4
+ Summary: CLUTGen, an ADC LUT generator for fast aquisition and calibration.
5
+ Author-email: Paulo Santos <pauloxrms@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/wkhadgar/clutgen
8
+ Project-URL: Issues, https://github.com/wkhadgar/clutgen/issues
9
+ Keywords: ADC,LUT,Look-up table,generator
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Embedded Systems
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: PyYAML
17
+ Requires-Dist: pandas
18
+ Requires-Dist: numpy
19
+ Requires-Dist: matplotlib
20
+ Dynamic: license-file
21
+
22
+ ---
23
+ # C Lookup Table (LUT) Generator
24
+
25
+ CLUTGen automates the creation of **Look-Up Tables** for embedded systems, specifically for converting raw ADC (Analog-to-Digital Converter) readings into calibrated physical units (like temperature, pressure, or distance).
26
+
27
+ ### Features
28
+
29
+ * **Curve Fitting:** Automatically find your fit from many algorithms.
30
+ * Linear Interpolation
31
+ * Cubic Splines
32
+ * Polynomial Interpolation (up to 7th degree)
33
+ * Piecewise Interpolation
34
+ * **Visual Preview:** Generates plots to compare calibration data against the calculated LUT.
35
+ * **C Code Generation:** Outputs production-ready `.c` and `.h` files with Doxygen-style comments.
36
+
37
+ ### Requirements
38
+
39
+ * Python 3.10+
40
+ * `numpy`, `pandas`, `matplotlib`, `pyyaml`, `openpyxl` (for Excel support)
41
+
42
+ ### Usage
43
+
44
+ ```bash
45
+ # From the root of the repository
46
+ pip install .
47
+ # Generate LUTs with cubic splines fit for every configuration yaml in the given paths.
48
+ clutgen -s -i ./examples/calibration/*.y*ml ./examples/temperature_copy.yml
49
+ ```
50
+
51
+ ### YAML Configuration Template
52
+
53
+ Create a table mapping your POIs with the given schema, where `raw` is the measured ADC raw value, and `calibration` is the desired output for the LUT at that given `raw` value:
54
+ ```csv
55
+ raw,calibration
56
+ ```
57
+
58
+ With your CSV table done (or Excel one), create a configuration YAML:
59
+
60
+ ```yaml
61
+ # temperature.yaml
62
+
63
+ name: "temp_sensor" # Used for variable names (e.g., temp_sensor_lut)
64
+ description: "ambient temperature" # Used for documentation and plot titles
65
+ table_resolution_bits: 12 # Resolution (e.g., 12 bits = 4096 entries)
66
+ lut_type: "int16_t" # C type (int8_t, uint16_t, etc.)
67
+
68
+ generator: "./data/calibration.csv" # Path to CSV/Excel with 'raw' and 'calibration' columns. Global or relative to this file.
69
+
70
+ ```
@@ -0,0 +1,49 @@
1
+ ---
2
+ # C Lookup Table (LUT) Generator
3
+
4
+ CLUTGen automates the creation of **Look-Up Tables** for embedded systems, specifically for converting raw ADC (Analog-to-Digital Converter) readings into calibrated physical units (like temperature, pressure, or distance).
5
+
6
+ ### Features
7
+
8
+ * **Curve Fitting:** Automatically find your fit from many algorithms.
9
+ * Linear Interpolation
10
+ * Cubic Splines
11
+ * Polynomial Interpolation (up to 7th degree)
12
+ * Piecewise Interpolation
13
+ * **Visual Preview:** Generates plots to compare calibration data against the calculated LUT.
14
+ * **C Code Generation:** Outputs production-ready `.c` and `.h` files with Doxygen-style comments.
15
+
16
+ ### Requirements
17
+
18
+ * Python 3.10+
19
+ * `numpy`, `pandas`, `matplotlib`, `pyyaml`, `openpyxl` (for Excel support)
20
+
21
+ ### Usage
22
+
23
+ ```bash
24
+ # From the root of the repository
25
+ pip install .
26
+ # Generate LUTs with cubic splines fit for every configuration yaml in the given paths.
27
+ clutgen -s -i ./examples/calibration/*.y*ml ./examples/temperature_copy.yml
28
+ ```
29
+
30
+ ### YAML Configuration Template
31
+
32
+ Create a table mapping your POIs with the given schema, where `raw` is the measured ADC raw value, and `calibration` is the desired output for the LUT at that given `raw` value:
33
+ ```csv
34
+ raw,calibration
35
+ ```
36
+
37
+ With your CSV table done (or Excel one), create a configuration YAML:
38
+
39
+ ```yaml
40
+ # temperature.yaml
41
+
42
+ name: "temp_sensor" # Used for variable names (e.g., temp_sensor_lut)
43
+ description: "ambient temperature" # Used for documentation and plot titles
44
+ table_resolution_bits: 12 # Resolution (e.g., 12 bits = 4096 entries)
45
+ lut_type: "int16_t" # C type (int8_t, uint16_t, etc.)
46
+
47
+ generator: "./data/calibration.csv" # Path to CSV/Excel with 'raw' and 'calibration' columns. Global or relative to this file.
48
+
49
+ ```
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: clutgen
3
+ Version: 0.0.1
4
+ Summary: CLUTGen, an ADC LUT generator for fast aquisition and calibration.
5
+ Author-email: Paulo Santos <pauloxrms@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/wkhadgar/clutgen
8
+ Project-URL: Issues, https://github.com/wkhadgar/clutgen/issues
9
+ Keywords: ADC,LUT,Look-up table,generator
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Software Development :: Embedded Systems
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: PyYAML
17
+ Requires-Dist: pandas
18
+ Requires-Dist: numpy
19
+ Requires-Dist: matplotlib
20
+ Dynamic: license-file
21
+
22
+ ---
23
+ # C Lookup Table (LUT) Generator
24
+
25
+ CLUTGen automates the creation of **Look-Up Tables** for embedded systems, specifically for converting raw ADC (Analog-to-Digital Converter) readings into calibrated physical units (like temperature, pressure, or distance).
26
+
27
+ ### Features
28
+
29
+ * **Curve Fitting:** Automatically find your fit from many algorithms.
30
+ * Linear Interpolation
31
+ * Cubic Splines
32
+ * Polynomial Interpolation (up to 7th degree)
33
+ * Piecewise Interpolation
34
+ * **Visual Preview:** Generates plots to compare calibration data against the calculated LUT.
35
+ * **C Code Generation:** Outputs production-ready `.c` and `.h` files with Doxygen-style comments.
36
+
37
+ ### Requirements
38
+
39
+ * Python 3.10+
40
+ * `numpy`, `pandas`, `matplotlib`, `pyyaml`, `openpyxl` (for Excel support)
41
+
42
+ ### Usage
43
+
44
+ ```bash
45
+ # From the root of the repository
46
+ pip install .
47
+ # Generate LUTs with cubic splines fit for every configuration yaml in the given paths.
48
+ clutgen -s -i ./examples/calibration/*.y*ml ./examples/temperature_copy.yml
49
+ ```
50
+
51
+ ### YAML Configuration Template
52
+
53
+ Create a table mapping your POIs with the given schema, where `raw` is the measured ADC raw value, and `calibration` is the desired output for the LUT at that given `raw` value:
54
+ ```csv
55
+ raw,calibration
56
+ ```
57
+
58
+ With your CSV table done (or Excel one), create a configuration YAML:
59
+
60
+ ```yaml
61
+ # temperature.yaml
62
+
63
+ name: "temp_sensor" # Used for variable names (e.g., temp_sensor_lut)
64
+ description: "ambient temperature" # Used for documentation and plot titles
65
+ table_resolution_bits: 12 # Resolution (e.g., 12 bits = 4096 entries)
66
+ lut_type: "int16_t" # C type (int8_t, uint16_t, etc.)
67
+
68
+ generator: "./data/calibration.csv" # Path to CSV/Excel with 'raw' and 'calibration' columns. Global or relative to this file.
69
+
70
+ ```
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ clutgen.egg-info/PKG-INFO
5
+ clutgen.egg-info/SOURCES.txt
6
+ clutgen.egg-info/dependency_links.txt
7
+ clutgen.egg-info/entry_points.txt
8
+ clutgen.egg-info/requires.txt
9
+ clutgen.egg-info/top_level.txt
10
+ src/__init__.py
11
+ src/cli.py
12
+ src/generator.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ clutgen = src.cli:main
@@ -0,0 +1,4 @@
1
+ PyYAML
2
+ pandas
3
+ numpy
4
+ matplotlib
@@ -0,0 +1 @@
1
+ src
@@ -0,0 +1,54 @@
1
+ [project]
2
+ name = "clutgen"
3
+ version = "0.0.1"
4
+ authors = [{ name = "Paulo Santos", email = "pauloxrms@gmail.com" }]
5
+ description = "CLUTGen, an ADC LUT generator for fast aquisition and calibration."
6
+ dependencies = ["PyYAML", "pandas", "numpy", "matplotlib"]
7
+ classifiers = [
8
+ "Development Status :: 3 - Alpha",
9
+ "Intended Audience :: Developers",
10
+ "Programming Language :: Python :: 3",
11
+ "Topic :: Software Development :: Embedded Systems",
12
+ ]
13
+ readme = "README.md"
14
+ license = "Apache-2.0"
15
+ license-files = ["LICENSE"]
16
+ keywords = ["ADC", "LUT", "Look-up table", "generator"]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/wkhadgar/clutgen"
20
+ Issues = "https://github.com/wkhadgar/clutgen/issues"
21
+
22
+ [project.scripts]
23
+ clutgen = "src.cli:main"
24
+
25
+ [build-system]
26
+ requires = ["setuptools>=61.0"]
27
+ build-backend = "setuptools.build_meta"
28
+
29
+ [tool.setuptools]
30
+ py-modules = ["src.cli"]
31
+ packages = ["src"]
32
+
33
+ [tool.ruff]
34
+ target-version = "py310"
35
+ line-length = 100
36
+
37
+ [tool.ruff.lint]
38
+ select = [
39
+ "B", # flake8-bugbear
40
+ "E", # pycodestyle
41
+ "F", # pyflakes
42
+ "I", # isort
43
+ "SIM", # flake8-simplify
44
+ "UP", # pyupgrade
45
+ "W", # pycodestyle warnings
46
+ ]
47
+ ignore = [
48
+ "SIM108", # Allow if-else blocks instead of forcing ternary operator
49
+ "E402", # Allow module-level import outside top of file
50
+ ]
51
+
52
+ [tool.ruff.format]
53
+ quote-style = "preserve"
54
+ line-ending = "lf"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,82 @@
1
+ import argparse
2
+
3
+ from src import generator as gen
4
+ from src.generator import GenMethod
5
+
6
+
7
+ def build_parser(parser: argparse.ArgumentParser) -> argparse.ArgumentParser:
8
+ parser.add_argument(
9
+ "-i",
10
+ metavar="path/to/yaml.yml",
11
+ help="Configuration YAMLs for the LUT generation.",
12
+ type=str,
13
+ nargs="+",
14
+ required=True,
15
+ )
16
+ parser.add_argument(
17
+ "-n",
18
+ "--name",
19
+ metavar="name",
20
+ help="Name of the generated LUT files.",
21
+ default="lookup_tables",
22
+ )
23
+
24
+ method_group = parser.add_mutually_exclusive_group()
25
+ parser.set_defaults(method=GenMethod.LINEAR)
26
+
27
+ method_group.add_argument(
28
+ "-l",
29
+ "--linear",
30
+ action="store_const",
31
+ const=GenMethod.LINEAR,
32
+ dest="method",
33
+ help="Linear Interpolation generation method. [default]",
34
+ )
35
+ method_group.add_argument(
36
+ "-s",
37
+ "--spline",
38
+ action="store_const",
39
+ const=GenMethod.SPLINE,
40
+ dest="method",
41
+ help="Cubic Splines Interpolation generation method.",
42
+ )
43
+ method_group.add_argument(
44
+ "-p",
45
+ "--polinomial",
46
+ action="store_const",
47
+ const=GenMethod.POLINOMIAL,
48
+ dest="method",
49
+ help="Polinomial Interpolation generation method.",
50
+ )
51
+ method_group.add_argument(
52
+ "-w",
53
+ "--piecewise",
54
+ action="store_const",
55
+ const=GenMethod.PIECEWISE,
56
+ dest="method",
57
+ help="Piecewise Interpolation generation method.",
58
+ )
59
+ method_group.add_argument(
60
+ "-d",
61
+ "--idw",
62
+ action="store_const",
63
+ const=GenMethod.IDW,
64
+ dest="method",
65
+ help="Inverse Distance Weighting generation method.",
66
+ )
67
+
68
+ return parser
69
+
70
+
71
+ def main():
72
+ parser = build_parser(argparse.ArgumentParser())
73
+
74
+ gen.generate(
75
+ parser.parse_args().i,
76
+ parser.parse_args().name,
77
+ parser.parse_args().method,
78
+ )
79
+
80
+
81
+ if __name__ == "__main__":
82
+ main()
@@ -0,0 +1,373 @@
1
+ """
2
+ :file: generator.py
3
+ :author: Paulo Santos (@wkhadgar)
4
+ :brief: Look-up Table generation base.
5
+ :version: 0.1
6
+ :date: 23-02-2026
7
+
8
+ :copyright: Copyright (c) 2026
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import datetime
14
+ import math
15
+ import sys
16
+ from enum import Enum
17
+ from pathlib import Path
18
+
19
+ import matplotlib.pyplot as plt
20
+ import numpy as np
21
+ import pandas as pd
22
+ import yaml
23
+
24
+
25
+ class GenMethod(Enum):
26
+ LINEAR = "linear"
27
+ SPLINE = "spline"
28
+ POLINOMIAL = "polynomial"
29
+ PIECEWISE = "piecewise"
30
+ IDW = "IDW"
31
+
32
+
33
+ class VirtualSensor:
34
+ def __init__(
35
+ self,
36
+ measure_dict: dict[int, int | float] | None = None,
37
+ *,
38
+ resolution: int,
39
+ ):
40
+ """
41
+ Creates a virtual sensor for simulation.
42
+
43
+ :param measure_dict: Calibration measurement dictionary in the form [adc_raw:calibration].
44
+ :param resolution: Resolution of the measurements made, in bits of precision.
45
+ :param generator: Optional data generator of type `foo(raw, resolution) -> val`
46
+ """
47
+ self.resolution: int = resolution
48
+
49
+ if measure_dict is not None:
50
+ self.x = np.array(list(measure_dict.keys()))
51
+ self.y = np.array(list(measure_dict.values()))
52
+ return
53
+
54
+ raise ValueError(f"Unable to create virtual sensor with given data: {measure_dict}")
55
+
56
+ def __get_best_fit_lms(self) -> list:
57
+ """
58
+ Generates a list of polynomial coefficients that best approximate the measurements.
59
+
60
+ :return: List of polynomial coefficients, ordered from highest degree to lowest.
61
+ """
62
+ c, [residuals, _, _, _] = np.polynomial.polynomial.polyfit(self.x, self.y, 1, full=True)
63
+ minimal_dev = residuals
64
+ best_coefficients: np.ndarray = c
65
+ for deg in range(2, 8):
66
+ if (len(self.x) <= deg + 1) or minimal_dev < 1e-10:
67
+ break
68
+
69
+ c, [residuals, _, _, _] = np.polynomial.polynomial.polyfit(
70
+ self.x, self.y, deg, full=True
71
+ )
72
+ if residuals < minimal_dev:
73
+ minimal_dev = residuals
74
+ best_coefficients = c
75
+
76
+ return list(reversed(best_coefficients))
77
+
78
+ def data_gen(self, method: GenMethod, *, max_val: int, min_val: int) -> dict[int, int]:
79
+ max_raw = 2**self.resolution
80
+ virtual_measures_span = range(0, max_raw)
81
+
82
+ match method:
83
+ case GenMethod.POLINOMIAL:
84
+ virtual_measures: dict[int, int] = {}
85
+ coefficients = self.__get_best_fit_lms()
86
+ degree = len(coefficients)
87
+ for virtual_reading in virtual_measures_span:
88
+ out = (virtual_reading * coefficients[0]) + coefficients[1]
89
+ i = 2
90
+ while i < degree:
91
+ out = (out * virtual_reading) + coefficients[i]
92
+ i += 1
93
+ virtual_measures[virtual_reading] = int(
94
+ max(min(math.trunc(out), max_val), min_val)
95
+ )
96
+ return virtual_measures
97
+ case GenMethod.LINEAR:
98
+ if self.x[0] != 0:
99
+ self.x = np.append([0], self.x)
100
+ self.y = np.append(self.y[0], self.y)
101
+ if self.x[-1] != max_raw:
102
+ self.x = np.append(self.x, [max_raw])
103
+ self.y = np.append(self.y, self.y[-1])
104
+
105
+ y_interp = np.interp(virtual_measures_span, self.x, self.y)
106
+ return {
107
+ xi: int(max(min(math.trunc(yi), max_val), min_val))
108
+ for xi, yi in zip(virtual_measures_span, y_interp, strict=False)
109
+ }
110
+ case GenMethod.SPLINE:
111
+ x, y = self.x, self.y
112
+ n = len(x)
113
+ h = np.diff(x)
114
+
115
+ A = np.zeros((n, n))
116
+ B = np.zeros(n)
117
+ A[0, 0] = 1
118
+ A[-1, -1] = 1
119
+
120
+ for i in range(1, n - 1):
121
+ A[i, i - 1] = h[i - 1] / 6
122
+ A[i, i] = (h[i - 1] + h[i]) / 3
123
+ A[i, i + 1] = h[i] / 6
124
+ B[i] = (y[i + 1] - y[i]) / h[i] - (y[i] - y[i - 1]) / h[i - 1]
125
+
126
+ M = np.linalg.solve(A, B)
127
+
128
+ def interpolate(xi):
129
+ idx = np.searchsorted(x, xi, side='right') - 1
130
+ idx = np.clip(idx, 0, n - 2)
131
+
132
+ dx = x[idx + 1] - x[idx]
133
+ t = (xi - x[idx]) / dx
134
+
135
+ val = (
136
+ (M[idx] * (1 - t) ** 3 / 6 + M[idx + 1] * t**3 / 6) * dx**2
137
+ + (y[idx] - M[idx] * dx**2 / 6) * (1 - t)
138
+ + (y[idx + 1] - M[idx + 1] * dx**2 / 6) * t
139
+ )
140
+ return val
141
+
142
+ return {
143
+ xi: int(max(min(math.trunc(interpolate(xi)), max_val), min_val))
144
+ for xi in virtual_measures_span
145
+ }
146
+ case GenMethod.PIECEWISE:
147
+ indices = np.searchsorted(self.x, virtual_measures_span, side='right') - 1
148
+ indices = np.clip(indices, 0, len(self.y) - 1)
149
+ y_interp = self.y[indices]
150
+
151
+ return {
152
+ xi: int(max(min(yi, max_val), min_val))
153
+ for xi, yi in zip(virtual_measures_span, y_interp, strict=True)
154
+ }
155
+ case GenMethod.IDW:
156
+ virtual_measures: dict[int, int] = {}
157
+ power = 2
158
+
159
+ for xi in virtual_measures_span:
160
+ distances = np.abs(self.x - xi)
161
+
162
+ if np.any(distances == 0):
163
+ yi = self.y[np.argmin(distances)]
164
+ else:
165
+ weights = 1.0 / (distances**power)
166
+ yi = np.sum(weights * self.y) / np.sum(weights)
167
+
168
+ virtual_measures[xi] = int(max(min(int(yi), max_val), min_val))
169
+
170
+ return virtual_measures
171
+
172
+
173
+ class LUTStringify:
174
+ def __init__(
175
+ self,
176
+ out_path: Path,
177
+ sensor: VirtualSensor,
178
+ *,
179
+ output_type: str,
180
+ method: GenMethod,
181
+ ):
182
+ """
183
+ Creates an instance of a calibrated data generator based on a virtual sensor.
184
+
185
+ :param sensor: Virtual sensor to be used or generation function.
186
+ :param output_type: Type used in the generated output.
187
+ """
188
+
189
+ self.sensor = sensor
190
+ self.var_size_bits: int = int(
191
+ output_type.removeprefix("u").removeprefix("int").removesuffix("_t")
192
+ )
193
+ self.type_str = f"const {output_type}"
194
+ self.preview_out_dir = out_path / "preview"
195
+ self.preview_out_path = None
196
+ self.method: GenMethod = method
197
+
198
+ out_path.mkdir(exist_ok=True)
199
+ self.preview_out_dir.mkdir(exist_ok=True)
200
+
201
+ if output_type.startswith("u"):
202
+ self.max_int = (2**self.var_size_bits) - 1
203
+ self.min_int = 0
204
+ else:
205
+ self.max_int = (2 ** (self.var_size_bits - 1)) - 1
206
+ self.min_int = -self.max_int
207
+
208
+ def __get_lut_values_str(self):
209
+ """
210
+ Generates calibrated values based on previous measurements.
211
+
212
+ :return: String representing the values the sensor read.
213
+ """
214
+ line_dim = 0
215
+ output_str = ""
216
+
217
+ table = self.sensor.data_gen(self.method, max_val=self.max_int, min_val=self.min_int)
218
+
219
+ plt.figure(figsize=(15, 10), dpi=250)
220
+ plt.scatter(self.sensor.x, self.sensor.y, c="r", s=10, zorder=3)
221
+ plt.grid(visible=True, which="both")
222
+ plt.plot(range(len(table)), list(table.values()), c="b")
223
+ plt.legend(["Calibration values", "Calculated LUT"])
224
+ plt.savefig(self.preview_out_path, bbox_inches='tight')
225
+
226
+ for v in list(table.values()):
227
+ current_temp_str = f"{v}, "
228
+
229
+ if (line_dim + len(current_temp_str)) >= 95:
230
+ current_temp_str = "\n\t" + current_temp_str
231
+ line_dim = 0
232
+
233
+ output_str += current_temp_str
234
+ line_dim += len(current_temp_str)
235
+
236
+ return "{\n\t" + output_str + "\n};\n\n"
237
+
238
+ def get_lut_definition(self, code_name: str, doc_name: str):
239
+ """
240
+ Generates a syntactically correct C string for header assignment.
241
+
242
+ :param code_name: Name used in the code for the generated LUT.
243
+ :param doc_name: Natural language name for the generated LUT.
244
+ :return: Formatted string for use in headers.
245
+ """
246
+
247
+ self.preview_out_path = self.preview_out_dir / code_name
248
+ plt.close()
249
+ plt.title(f"{doc_name.capitalize()}")
250
+ plt.xlabel(f"ADC Value (scaled to {self.sensor.resolution} bits)")
251
+ plt.ylabel("LUT Value (in calibration unit)")
252
+ return (
253
+ f"{self.type_str} {code_name}_lut[{2**self.sensor.resolution}] = "
254
+ + self.__get_lut_values_str()
255
+ )
256
+
257
+ def get_lut_declaration(self, code_name: str, doc_name: str):
258
+ docs = (
259
+ "/**\n"
260
+ f" * @brief LUT for {doc_name} measurements.\n"
261
+ " *\n"
262
+ f" * @note The value read by the ADC is scaled to {self.sensor.resolution} bits "
263
+ f"(0 to {(2**self.sensor.resolution) - 1}), and used as an index for this LUT.\n"
264
+ " */"
265
+ )
266
+
267
+ return docs + f"\nextern {self.type_str} {code_name}_lut[{2**self.sensor.resolution}];\n\n"
268
+
269
+
270
+ def generate(in_files: list[str], filename: str, method: GenMethod):
271
+ out_dir = Path("./generated_luts")
272
+ out_include_dir = Path("./include")
273
+ out_path_c = out_dir / (filename + ".c")
274
+ out_path_h = out_include_dir / (filename + ".h")
275
+
276
+ header_h = (
277
+ "/**\n"
278
+ f" * @file {filename}.h\n"
279
+ " * @brief Organizes lookup tables to speed up sensor readings.\n"
280
+ " * @note The code in this file is generated and should not be modified.\n"
281
+ " * @version 0.1\n"
282
+ f" * @date {datetime.datetime.now().strftime('%d-%m-%Y')}\n"
283
+ " *\n"
284
+ " */\n"
285
+ "\n"
286
+ f"#ifndef {filename.upper()}_H\n"
287
+ f"#define {filename.upper()}_H\n"
288
+ "\n"
289
+ "#include <stdint.h>\n\n"
290
+ )
291
+
292
+ footer = f"\n#endif /* {filename.upper()}_H */\n"
293
+
294
+ header_c = (
295
+ "/**\n"
296
+ f" * @file {filename}.c\n"
297
+ " * @brief Defines lookup tables to speed up sensor readings.\n"
298
+ " * @note The code in this file is generated and should not be modified.\n"
299
+ " * @version 0.1\n"
300
+ f" * @date {datetime.datetime.now().strftime('%d-%m-%Y')}\n"
301
+ " *\n"
302
+ " */\n"
303
+ "\n"
304
+ f'#include "{filename}.h"\n\n'
305
+ )
306
+
307
+ print("-- Running scripts to generate LUTs")
308
+
309
+ luts_c = []
310
+ luts_h = []
311
+
312
+ calibration_data_yamls: list[Path] = []
313
+ for file in in_files:
314
+ abs_file_path = Path(file).resolve()
315
+ if file.endswith(".yml") or file.endswith(".yaml"):
316
+ calibration_data_yamls.append(abs_file_path.resolve())
317
+
318
+ if len(calibration_data_yamls) == 0:
319
+ print("-- No configuration YAMLs found.")
320
+ return
321
+
322
+ for gen_yaml in calibration_data_yamls:
323
+ with open(gen_yaml, encoding="utf8") as stream:
324
+ lut_descriptor = yaml.safe_load(stream)
325
+
326
+ code_name: str = lut_descriptor["name"]
327
+ doc_name: str = lut_descriptor["description"]
328
+ resolution: int = int(lut_descriptor["table_resolution_bits"])
329
+ output_size_bits: str = lut_descriptor["lut_type"]
330
+ generator: Path = Path(lut_descriptor["generator"])
331
+
332
+ try:
333
+ path = (gen_yaml.parent / generator).resolve(strict=True)
334
+ except FileNotFoundError:
335
+ path = generator.resolve(strict=True)
336
+
337
+ if generator.suffix == ".csv":
338
+ gen_data = pd.read_csv(path)
339
+ elif generator.suffix in (".xls", ".xlsx", ".xlsm", ".xlsb", ".odf", ".ods", ".odt"):
340
+ gen_data = pd.read_excel(path)
341
+ else:
342
+ print(f"Could not obtain generator for {code_name}\nCheck the table format.")
343
+ sys.exit(1)
344
+
345
+ sensor = VirtualSensor(
346
+ {
347
+ int(raw): int(val)
348
+ for raw, val in zip(gen_data["raw"], gen_data["calibration"], strict=False)
349
+ },
350
+ resolution=resolution,
351
+ )
352
+ print(f"-- Generating {code_name} LUT based on '{path}'...")
353
+ printer = LUTStringify(out_dir, sensor, output_type=output_size_bits, method=method)
354
+ luts_c.append(printer.get_lut_definition(code_name=code_name, doc_name=doc_name))
355
+ luts_h.append(printer.get_lut_declaration(code_name=code_name, doc_name=doc_name))
356
+
357
+ out_dir.mkdir(exist_ok=True)
358
+ out_include_dir.mkdir(exist_ok=True)
359
+
360
+ with open(out_path_c, "w", encoding="utf8") as out:
361
+ print(f"-- Generating source {filename}.c...")
362
+ out.write(header_c)
363
+ for lut in luts_c:
364
+ out.write(lut)
365
+
366
+ with open(out_path_h, "w", encoding="utf8") as out:
367
+ print(f"-- Generating header {filename}.h...")
368
+ out.write(header_h)
369
+ for lut in luts_h:
370
+ out.write(lut)
371
+ out.write(footer)
372
+
373
+ print("-- LUTs generated successfully.")