tdmread 0.2.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.
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ build/
6
+ dist/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
13
+
14
+ # Third-party sample files, fetched locally by scripts/fetch_upstream.py; only the manifest is tracked.
15
+ tests/upstream/*
16
+ !tests/upstream/MANIFEST.json
@@ -0,0 +1,44 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.2.1]
10
+
11
+ ### Changed
12
+
13
+ - The NI `SineData` samples are no longer tracked or shipped in the sdist.
14
+ `scripts/fetch_upstream.py` downloads them from the recorded TDMtermite revision into
15
+ `tests/upstream` (checked against the tracked manifest), and their tests skip when absent.
16
+ The always-on tests use a small TDM/TDX set generated by `scripts/make_synthetic_tdm.py`.
17
+
18
+ ## [0.2.0]
19
+
20
+ - Added decoding of `implicit_linear` channels: a generated `offset + index * increment`
21
+ axis sized from `NI_ChannelLength` (or the submatrix row count), with a `0, 1, 2, ...`
22
+ default when generation parameters are absent. These channels need no `.tdx`.
23
+ - Added a `tdmread` command-line interface (`info`, `channels`, `dump` to CSV or JSON),
24
+ with `--version`, example-rich help, and errors on stderr with exit code 1.
25
+ `python -m tdmread` works as an alias.
26
+ - `read_tdm` now returns dataset metadata (`TdmFile.metadata`: name, title, description,
27
+ author, datetime) and each `Channel` carries its `representation`, `minimum`,
28
+ `maximum`, and `datatype`; groups carry their `description`.
29
+ - Added convenience helpers: `Channel.__len__`, `Channel.to_list`, optional
30
+ `Channel.to_numpy`, `Group` iteration and `channel_names`, and `TdmFile` iteration,
31
+ `group_names`, and `channels()`.
32
+ - Exported `FileMetadata` and `supported_value_types`.
33
+ - Committed the real `SineData` sample files as golden fixtures and added end-to-end
34
+ tests, including one that installs the package and drives the installed console script.
35
+
36
+ ## [0.1.0]
37
+
38
+ - First release.
39
+ - `read_tdm` parses a `.tdm` XML header, locates the `.tdx` by its reference, and returns
40
+ groups and channels with decoded numeric data.
41
+ - Supports numeric channels with the `explicit` sequence representation, signed and
42
+ unsigned 8/16/32/64-bit integers, 32/64-bit floats, and both byte orders.
43
+ - Unsupported value types, sequence representations, and byte orders raise
44
+ `UnsupportedTdmError`; missing files raise `TdmFileNotFoundError`.
@@ -0,0 +1,24 @@
1
+ # Contributing
2
+
3
+ Thanks for taking the time. This project keeps a small, predictable shape.
4
+
5
+ ## Setup
6
+
7
+ ```
8
+ pip install -r requirements-dev.txt
9
+ ```
10
+
11
+ ## Before you open a pull request
12
+
13
+ - Keep public API in `src/tdmread/__init__.py`; internals live in `_`-prefixed modules.
14
+ - Add a test for the behaviour you change. Tests inject time, disk and network; they
15
+ never touch the real thing.
16
+ - The always-on fixtures in `tests/fixtures/synthetic` are generated by
17
+ `python scripts/make_synthetic_tdm.py`; regenerate them rather than editing them. The NI
18
+ `SineData` samples are never committed: `python scripts/fetch_upstream.py` downloads them
19
+ into `tests/upstream` (checked against `tests/upstream/MANIFEST.json`) and their tests
20
+ skip until then.
21
+ - Run `scripts/check.ps1` (format, lint, types, tests) and make sure it passes.
22
+ - One logical change per commit, imperative subject line.
23
+
24
+ Open an issue first if the change is large or shifts the public API.
tdmread-0.2.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Javier Lianes
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.
tdmread-0.2.1/PKG-INFO ADDED
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.5
2
+ Name: tdmread
3
+ Version: 0.2.1
4
+ Summary: Zero-dependency, typed reader for NI TDM/TDX files (XML .tdm header plus binary .tdx), using only the Python standard library
5
+ Project-URL: Homepage, https://lianes8studio.com
6
+ Project-URL: Repository, https://github.com/JaviLianes8/tdmread
7
+ Project-URL: Issues, https://github.com/JaviLianes8/tdmread/issues
8
+ Project-URL: Changelog, https://github.com/JaviLianes8/tdmread/blob/main/CHANGELOG.md
9
+ Project-URL: LinkedIn, https://www.linkedin.com/in/jlianes/
10
+ Project-URL: Funding, https://buymeacoffee.com/jlianesglrs
11
+ Author-email: Javier Lianes <javier@lianes8studio.com>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: diadem,labview,measurement,ni,parser,tdm,tdx
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.10
20
+ Provides-Extra: dev
21
+ Requires-Dist: build; extra == 'dev'
22
+ Requires-Dist: mypy; extra == 'dev'
23
+ Requires-Dist: pytest; extra == 'dev'
24
+ Requires-Dist: ruff; extra == 'dev'
25
+ Requires-Dist: twine; extra == 'dev'
26
+ Provides-Extra: numpy
27
+ Requires-Dist: numpy; extra == 'numpy'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # tdmread
31
+
32
+ Zero-dependency, typed reader for NI TDM/TDX files (an XML `.tdm` header paired with a
33
+ binary `.tdx` data file), using only the Python standard library.
34
+
35
+ ## Install
36
+
37
+ ```
38
+ pip install tdmread
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ```python
44
+ from tdmread import read_tdm
45
+
46
+ dataset = read_tdm("measurement.tdm") # the .tdx is found via the header reference
47
+
48
+ for group in dataset.groups:
49
+ print(group.name)
50
+ for channel in group.channels:
51
+ print(f" {channel.name} [{channel.unit}]: {channel.data[:5]}")
52
+
53
+ # Direct lookup by name.
54
+ voltage = dataset.group("Measurements").channel("voltage")
55
+ print(voltage.value_type, len(voltage.data))
56
+ ```
57
+
58
+ Each `Channel` carries its `name`, `unit`, `description`, the TDM `value_type`, the
59
+ `representation` (`explicit` or `implicit_linear`), the header `minimum`/`maximum` and
60
+ `datatype`, and the decoded `data` as a plain tuple of numbers. `read_tdm` also returns
61
+ dataset metadata on `dataset.metadata` (name, title, description, author, datetime).
62
+ Pass a second argument to point at a `.tdx` in a non-default location:
63
+ `read_tdm("m.tdm", "elsewhere/m.tdx")`.
64
+
65
+ ```python
66
+ # Convenience helpers.
67
+ for group, channel in dataset.channels():
68
+ print(group.name, channel.name, len(channel))
69
+
70
+ values = dataset.group("Amplitudes").channel("A = 1").to_list()
71
+ array = dataset.group("Amplitudes").channel("A = 1").to_numpy() # needs numpy installed
72
+ ```
73
+
74
+ ## Command line
75
+
76
+ Installing the package also installs a `tdmread` console script:
77
+
78
+ ```
79
+ tdmread info measurement.tdm
80
+ tdmread channels measurement.tdm
81
+ tdmread dump measurement.tdm --group Amplitudes --channel "A = 1" --format csv
82
+ tdmread dump measurement.tdm -g Amplitudes -c "A = 1" -f json -o values.json
83
+ ```
84
+
85
+ `info` prints the dataset metadata and a group summary, `channels` lists every channel
86
+ with its type and length, and `dump` writes one channel to CSV or JSON (to standard
87
+ output, or to a file with `-o`). Errors go to standard error with exit code 1.
88
+
89
+ ## Why
90
+
91
+ [npTDMS](https://pypi.org/project/npTDMS/) reads the newer `.tdms` format but not the
92
+ older `.tdm`/`.tdx` pair, so it is no help to anyone holding `.tdm` data. Two packages do
93
+ read `.tdm`/`.tdx`, but each pulls in weight: [tdm-loader](https://pypi.org/project/tdm-loader/)
94
+ depends on NumPy, and [TDMtermite](https://pypi.org/project/TDMtermite/) ships a compiled
95
+ C++ extension. `tdmread` fills the remaining gap: a small, fully typed reader with no
96
+ runtime dependencies and nothing to build, for scripts and environments where adding
97
+ NumPy or a native extension is unwelcome.
98
+
99
+ ## Supported subset
100
+
101
+ `tdmread` targets the common documented TDM layout and is honest about its limits:
102
+
103
+ - Numeric channels with the `explicit` sequence representation.
104
+ - Numeric channels with the `implicit_linear` representation, generated as
105
+ `offset + index * increment` from the header (no `.tdx` needed for those).
106
+ - Value types `eInt8`/`16`/`32`/`64`, their unsigned variants, `eFloat32`, and `eFloat64`,
107
+ in both `littleEndian` and `bigEndian` byte order.
108
+
109
+ It does not yet decode string, timestamp, or extended-precision channels, `raw_linear`
110
+ scaled sequences, or per-sample flags; those raise `UnsupportedTdmError` rather than
111
+ returning wrong numbers. Issues and sample files that broaden the coverage are welcome.
112
+
113
+ ## License
114
+
115
+ MIT. See [LICENSE](LICENSE).
116
+
117
+ ## Links
118
+
119
+ - Website: https://lianes8studio.com
120
+ - GitHub: https://github.com/JaviLianes8
121
+ - LinkedIn: https://www.linkedin.com/in/jlianes/
@@ -0,0 +1,92 @@
1
+ # tdmread
2
+
3
+ Zero-dependency, typed reader for NI TDM/TDX files (an XML `.tdm` header paired with a
4
+ binary `.tdx` data file), using only the Python standard library.
5
+
6
+ ## Install
7
+
8
+ ```
9
+ pip install tdmread
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```python
15
+ from tdmread import read_tdm
16
+
17
+ dataset = read_tdm("measurement.tdm") # the .tdx is found via the header reference
18
+
19
+ for group in dataset.groups:
20
+ print(group.name)
21
+ for channel in group.channels:
22
+ print(f" {channel.name} [{channel.unit}]: {channel.data[:5]}")
23
+
24
+ # Direct lookup by name.
25
+ voltage = dataset.group("Measurements").channel("voltage")
26
+ print(voltage.value_type, len(voltage.data))
27
+ ```
28
+
29
+ Each `Channel` carries its `name`, `unit`, `description`, the TDM `value_type`, the
30
+ `representation` (`explicit` or `implicit_linear`), the header `minimum`/`maximum` and
31
+ `datatype`, and the decoded `data` as a plain tuple of numbers. `read_tdm` also returns
32
+ dataset metadata on `dataset.metadata` (name, title, description, author, datetime).
33
+ Pass a second argument to point at a `.tdx` in a non-default location:
34
+ `read_tdm("m.tdm", "elsewhere/m.tdx")`.
35
+
36
+ ```python
37
+ # Convenience helpers.
38
+ for group, channel in dataset.channels():
39
+ print(group.name, channel.name, len(channel))
40
+
41
+ values = dataset.group("Amplitudes").channel("A = 1").to_list()
42
+ array = dataset.group("Amplitudes").channel("A = 1").to_numpy() # needs numpy installed
43
+ ```
44
+
45
+ ## Command line
46
+
47
+ Installing the package also installs a `tdmread` console script:
48
+
49
+ ```
50
+ tdmread info measurement.tdm
51
+ tdmread channels measurement.tdm
52
+ tdmread dump measurement.tdm --group Amplitudes --channel "A = 1" --format csv
53
+ tdmread dump measurement.tdm -g Amplitudes -c "A = 1" -f json -o values.json
54
+ ```
55
+
56
+ `info` prints the dataset metadata and a group summary, `channels` lists every channel
57
+ with its type and length, and `dump` writes one channel to CSV or JSON (to standard
58
+ output, or to a file with `-o`). Errors go to standard error with exit code 1.
59
+
60
+ ## Why
61
+
62
+ [npTDMS](https://pypi.org/project/npTDMS/) reads the newer `.tdms` format but not the
63
+ older `.tdm`/`.tdx` pair, so it is no help to anyone holding `.tdm` data. Two packages do
64
+ read `.tdm`/`.tdx`, but each pulls in weight: [tdm-loader](https://pypi.org/project/tdm-loader/)
65
+ depends on NumPy, and [TDMtermite](https://pypi.org/project/TDMtermite/) ships a compiled
66
+ C++ extension. `tdmread` fills the remaining gap: a small, fully typed reader with no
67
+ runtime dependencies and nothing to build, for scripts and environments where adding
68
+ NumPy or a native extension is unwelcome.
69
+
70
+ ## Supported subset
71
+
72
+ `tdmread` targets the common documented TDM layout and is honest about its limits:
73
+
74
+ - Numeric channels with the `explicit` sequence representation.
75
+ - Numeric channels with the `implicit_linear` representation, generated as
76
+ `offset + index * increment` from the header (no `.tdx` needed for those).
77
+ - Value types `eInt8`/`16`/`32`/`64`, their unsigned variants, `eFloat32`, and `eFloat64`,
78
+ in both `littleEndian` and `bigEndian` byte order.
79
+
80
+ It does not yet decode string, timestamp, or extended-precision channels, `raw_linear`
81
+ scaled sequences, or per-sample flags; those raise `UnsupportedTdmError` rather than
82
+ returning wrong numbers. Issues and sample files that broaden the coverage are welcome.
83
+
84
+ ## License
85
+
86
+ MIT. See [LICENSE](LICENSE).
87
+
88
+ ## Links
89
+
90
+ - Website: https://lianes8studio.com
91
+ - GitHub: https://github.com/JaviLianes8
92
+ - LinkedIn: https://www.linkedin.com/in/jlianes/
@@ -0,0 +1,74 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "tdmread"
7
+ version = "0.2.1"
8
+ description = "Zero-dependency, typed reader for NI TDM/TDX files (XML .tdm header plus binary .tdx), using only the Python standard library"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Javier Lianes", email = "javier@lianes8studio.com" }]
14
+ keywords = ["tdm", "tdx", "ni", "labview", "diadem", "measurement", "parser"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.optional-dependencies]
24
+ dev = ["ruff", "mypy", "pytest", "build", "twine"]
25
+ numpy = ["numpy"]
26
+
27
+ [project.scripts]
28
+ tdmread = "tdmread._cli:main"
29
+
30
+ [project.urls]
31
+ Homepage = "https://lianes8studio.com"
32
+ Repository = "https://github.com/JaviLianes8/tdmread"
33
+ Issues = "https://github.com/JaviLianes8/tdmread/issues"
34
+ Changelog = "https://github.com/JaviLianes8/tdmread/blob/main/CHANGELOG.md"
35
+ LinkedIn = "https://www.linkedin.com/in/jlianes/"
36
+ Funding = "https://buymeacoffee.com/jlianesglrs"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/tdmread"]
40
+
41
+ [tool.hatch.build.targets.sdist]
42
+ only-include = [
43
+ "src/tdmread",
44
+ "tests",
45
+ "scripts/fetch_upstream.py",
46
+ "scripts/make_synthetic_tdm.py",
47
+ "README.md",
48
+ "CHANGELOG.md",
49
+ "CONTRIBUTING.md",
50
+ "LICENSE",
51
+ "pyproject.toml",
52
+ ]
53
+ # Third-party samples are fetched locally for the tests and never shipped; only their manifest is.
54
+ exclude = ["**/__pycache__", "**/*.pyc", "tests/upstream/*.tdm", "tests/upstream/*.tdx"]
55
+
56
+ [tool.ruff]
57
+ line-length = 100
58
+ target-version = "py310"
59
+
60
+ [tool.ruff.lint]
61
+ select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
62
+
63
+ [tool.mypy]
64
+ python_version = "3.10"
65
+ strict = true
66
+
67
+ [[tool.mypy.overrides]]
68
+ module = ["numpy", "numpy.*"]
69
+ ignore_missing_imports = true
70
+
71
+ [tool.pytest.ini_options]
72
+ testpaths = ["tests"]
73
+ pythonpath = ["src"]
74
+ addopts = "-q"
@@ -0,0 +1,37 @@
1
+ """Fetch the third-party test files listed in tests/upstream/MANIFEST.json.
2
+
3
+ The files are not part of the repository. Their tests skip until this script has fetched
4
+ them; each download is checked against the size and sha256 in the manifest.
5
+
6
+ python scripts/fetch_upstream.py
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ import sys
14
+ import urllib.request
15
+ from pathlib import Path
16
+
17
+ FOLDER = Path(__file__).resolve().parents[1] / "tests" / "upstream"
18
+
19
+
20
+ def main() -> int:
21
+ manifest = json.loads((FOLDER / "MANIFEST.json").read_text(encoding="utf-8"))
22
+ failed = 0
23
+ for name, entry in manifest.items():
24
+ with urllib.request.urlopen(entry["url"], timeout=60) as response:
25
+ body = response.read()
26
+ digest = hashlib.sha256(body).hexdigest()
27
+ if len(body) != entry["size"] or digest != entry["sha256"]:
28
+ print(f"{name}: got {len(body)} bytes, sha256 {digest}; manifest differs")
29
+ failed += 1
30
+ continue
31
+ (FOLDER / name).write_bytes(body)
32
+ print(f"{name}: ok")
33
+ return 1 if failed else 0
34
+
35
+
36
+ if __name__ == "__main__":
37
+ sys.exit(main())
@@ -0,0 +1,128 @@
1
+ """Write the hand-made TDM/TDX fixtures in tests/fixtures/synthetic.
2
+
3
+ The always-on tests run against these files. Every value is generated here from a
4
+ formula, so the files copy nothing from any third-party sample:
5
+
6
+ * ``Synthetic.tdm`` + ``.tdx``: little-endian. Group ``Amplitudes`` holds ``A = k`` with
7
+ ``k * sin(STEP * i)``; group ``Frequencies`` holds ``F = k`` with ``sin(k * STEP * i)``.
8
+ * ``Synthetic-be.tdm`` + ``.tdx``: the same values stored big-endian.
9
+ * ``Synthetic_implicit.tdm``: the ``Amplitudes`` channels are implicit_linear
10
+ (``OFFSET + INCREMENT * i``), lengths from ``NI_ChannelLength`` or the submatrix row
11
+ count; the ``Frequencies`` channels stay explicit and read ``Synthetic.tdx``.
12
+
13
+ python scripts/make_synthetic_tdm.py
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ import struct
20
+ from pathlib import Path
21
+
22
+ OUT = Path(__file__).resolve().parents[1] / "tests" / "fixtures" / "synthetic"
23
+ LENGTH = 100
24
+ STEP = 0.05
25
+ OFFSET, INCREMENT = 0.25, 0.5
26
+ SCALES = (1, 2, 4, 8, 16)
27
+ GROUPS = (("Amplitudes", "A"), ("Frequencies", "F"))
28
+
29
+
30
+ def _values(group: str, k: int) -> list[float]:
31
+ if group == "Amplitudes":
32
+ return [k * math.sin(STEP * i) for i in range(LENGTH)]
33
+ return [math.sin(k * STEP * i) for i in range(LENGTH)]
34
+
35
+
36
+ def _channels() -> list[tuple[str, str, list[float]]]:
37
+ return [(g, f"{p} = {k}", _values(g, k)) for g, p in GROUPS for k in SCALES]
38
+
39
+
40
+ def _tdx(order: str) -> bytes:
41
+ fmt = ("<" if order == "littleEndian" else ">") + f"{LENGTH}d"
42
+ return b"".join(struct.pack(fmt, *values) for _, _, values in _channels())
43
+
44
+
45
+ def _refs(ids: list[str]) -> str:
46
+ return "#xpointer(" + " ".join(f'id("{i}")' for i in ids) + ")"
47
+
48
+
49
+ def _channel_xml(n: int, group_id: str, name: str, values: list[float], implicit: bool) -> str:
50
+ length_attr = (
51
+ ""
52
+ if implicit and n % 2
53
+ else (f' <long_attribute name="NI_ChannelLength">{LENGTH}</long_attribute>\n')
54
+ )
55
+ if implicit:
56
+ column = (
57
+ " <sequence_representation>implicit_linear</sequence_representation>\n"
58
+ f" <generation_parameters>{OFFSET} {INCREMENT}</generation_parameters>\n"
59
+ )
60
+ else:
61
+ column = (
62
+ " <sequence_representation>explicit</sequence_representation>\n"
63
+ f" <values>{_refs([f'seq{n}'])}</values>\n"
64
+ )
65
+ sequence = (
66
+ ""
67
+ if implicit
68
+ else (f' <double_sequence id="seq{n}"><values external="inc{n}"/></double_sequence>\n')
69
+ )
70
+ return (
71
+ f' <tdm_channel id="ch{n}">\n <name>{name}</name>\n'
72
+ f" <group>{_refs([group_id])}</group>\n <datatype>DT_DOUBLE</datatype>\n"
73
+ f" <minimum>{min(values)!r}</minimum>\n <maximum>{max(values)!r}</maximum>\n"
74
+ f" <instance_attributes>\n{length_attr} </instance_attributes>\n"
75
+ f" <local_columns>{_refs([f'lc{n}'])}</local_columns>\n </tdm_channel>\n"
76
+ f' <submatrix id="sm{n}">\n <number_of_rows>{LENGTH}</number_of_rows>\n'
77
+ f" <local_columns>{_refs([f'lc{n}'])}</local_columns>\n </submatrix>\n"
78
+ f' <localcolumn id="lc{n}">\n <measurement_quantity>{_refs([f"ch{n}"])}'
79
+ f"</measurement_quantity>\n <submatrix>{_refs([f'sm{n}'])}</submatrix>\n"
80
+ f"{column} </localcolumn>\n{sequence}"
81
+ )
82
+
83
+
84
+ def _tdm(name: str, tdx: str, order: str, implicit: bool) -> str:
85
+ channels = _channels()
86
+ blocks = "".join(
87
+ f' <block id="inc{n}" valueType="eFloat64Usi" byteOffset="{n * LENGTH * 8}"'
88
+ f' length="{LENGTH}"/>\n'
89
+ for n in range(len(channels))
90
+ )
91
+ group_ids = {g: f"grp{gi}" for gi, (g, _) in enumerate(GROUPS)}
92
+ body = "".join(
93
+ _channel_xml(n, group_ids[g], c, v, implicit and g == "Amplitudes")
94
+ for n, (g, c, v) in enumerate(channels)
95
+ )
96
+ groups = "".join(
97
+ f' <tdm_channelgroup id="grp{gi}">\n <name>{g}</name>\n'
98
+ f" <root>{_refs(['root'])}</root>\n <channels>"
99
+ f"{_refs([f'ch{n}' for n, (cg, _, _) in enumerate(channels) if cg == g])}</channels>\n"
100
+ f" </tdm_channelgroup>\n"
101
+ for gi, (g, _) in enumerate(GROUPS)
102
+ )
103
+ return (
104
+ '<?xml version="1.0" encoding="UTF-8"?>\n'
105
+ "<!-- Hand-made tdmread test fixture, written by scripts/make_synthetic_tdm.py. -->\n"
106
+ '<usi:tdm xmlns:usi="http://www.ni.com/Schemas/USI/1_0" version="1.0">\n'
107
+ f' <usi:include>\n <file url="{tdx}" byteOrder="{order}">\n{blocks}'
108
+ " </file>\n </usi:include>\n <usi:data>\n"
109
+ f' <tdm_root id="root">\n <name>{name}</name>\n'
110
+ " <description>Generated sine signals for the tdmread tests.</description>\n"
111
+ " <author>tdmread test suite</author>\n"
112
+ f" <channelgroups>{_refs(['grp0', 'grp1'])}</channelgroups>\n </tdm_root>\n"
113
+ f"{groups}{body} </usi:data>\n</usi:tdm>\n"
114
+ )
115
+
116
+
117
+ def main() -> None:
118
+ OUT.mkdir(parents=True, exist_ok=True)
119
+ for stem, order in (("Synthetic", "littleEndian"), ("Synthetic-be", "bigEndian")):
120
+ (OUT / f"{stem}.tdx").write_bytes(_tdx(order))
121
+ tdm = _tdm(f"{stem}.TDM", f"{stem}.tdx", order, implicit=False)
122
+ (OUT / f"{stem}.tdm").write_bytes(tdm.encode("utf-8"))
123
+ implicit = _tdm("Synthetic_implicit.TDM", "Synthetic.tdx", "littleEndian", implicit=True)
124
+ (OUT / "Synthetic_implicit.tdm").write_bytes(implicit.encode("utf-8"))
125
+
126
+
127
+ if __name__ == "__main__":
128
+ main()
@@ -0,0 +1,22 @@
1
+ """Zero-dependency, typed reader for NI TDM/TDX files, using only the standard library."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._binary import supported_value_types
6
+ from ._errors import TdmError, TdmFileNotFoundError, UnsupportedTdmError
7
+ from ._model import Channel, FileMetadata, Group, TdmFile
8
+ from ._reader import read_tdm
9
+
10
+ __version__ = "0.2.1"
11
+
12
+ __all__ = [
13
+ "Channel",
14
+ "FileMetadata",
15
+ "Group",
16
+ "TdmError",
17
+ "TdmFile",
18
+ "TdmFileNotFoundError",
19
+ "UnsupportedTdmError",
20
+ "read_tdm",
21
+ "supported_value_types",
22
+ ]
@@ -0,0 +1,8 @@
1
+ """Enable `python -m tdmread` as an alias for the console script."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ._cli import main
6
+
7
+ if __name__ == "__main__":
8
+ raise SystemExit(main())
@@ -0,0 +1,58 @@
1
+ """Decode numeric value blocks out of a binary .tdx file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import struct
6
+
7
+ from ._errors import TdmError, UnsupportedTdmError
8
+
9
+ # TDM valueType names mapped to standard-size struct format codes. The byte-order
10
+ # prefix is applied separately, so every code here reads a fixed width.
11
+ _STRUCT_CODE: dict[str, str] = {
12
+ "eInt8Usi": "b",
13
+ "eUInt8Usi": "B",
14
+ "eInt16Usi": "h",
15
+ "eUInt16Usi": "H",
16
+ "eInt32Usi": "i",
17
+ "eUInt32Usi": "I",
18
+ "eInt64Usi": "q",
19
+ "eUInt64Usi": "Q",
20
+ "eFloat32Usi": "f",
21
+ "eFloat64Usi": "d",
22
+ }
23
+
24
+ _BYTE_ORDER: dict[str, str] = {"littleEndian": "<", "bigEndian": ">"}
25
+
26
+
27
+ def byte_order_prefix(byte_order: str) -> str:
28
+ """Return the struct prefix ('<' or '>') for a TDM byteOrder attribute."""
29
+ try:
30
+ return _BYTE_ORDER[byte_order]
31
+ except KeyError:
32
+ raise UnsupportedTdmError(f"unknown byte order {byte_order!r}") from None
33
+
34
+
35
+ def supported_value_types() -> frozenset[str]:
36
+ """The set of TDM valueType names this reader can decode."""
37
+ return frozenset(_STRUCT_CODE)
38
+
39
+
40
+ def decode_block(
41
+ data: bytes,
42
+ prefix: str,
43
+ value_type: str,
44
+ byte_offset: int,
45
+ length: int,
46
+ ) -> tuple[float, ...]:
47
+ """Decode `length` values of `value_type` starting at `byte_offset` in `data`."""
48
+ code = _STRUCT_CODE.get(value_type)
49
+ if code is None:
50
+ raise UnsupportedTdmError(f"unsupported value type {value_type!r}")
51
+ item = struct.calcsize(prefix + code)
52
+ end = byte_offset + length * item
53
+ if byte_offset < 0 or end > len(data):
54
+ raise TdmError(
55
+ f"block of {length} {value_type} at offset {byte_offset} "
56
+ f"runs past the .tdx data ({len(data)} bytes)"
57
+ )
58
+ return struct.unpack(f"{prefix}{length}{code}", data[byte_offset:end])