tdmread 0.2.1__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.
tdmread/__init__.py ADDED
@@ -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
+ ]
tdmread/__main__.py ADDED
@@ -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())
tdmread/_binary.py ADDED
@@ -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])
tdmread/_cli.py ADDED
@@ -0,0 +1,142 @@
1
+ """Command-line interface for reading NI TDM/TDX files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import io
8
+ import json
9
+ import sys
10
+ from collections.abc import Sequence
11
+
12
+ from . import __version__
13
+ from ._errors import TdmError
14
+ from ._model import Channel, TdmFile
15
+ from ._reader import read_tdm
16
+
17
+ _EXAMPLES = """\
18
+ examples:
19
+ tdmread info measurement.tdm
20
+ tdmread channels measurement.tdm
21
+ tdmread dump measurement.tdm --group Amplitudes --channel "A = 1" --format csv
22
+ tdmread dump measurement.tdm -g Amplitudes -c "A = 1" -f json -o values.json
23
+ """
24
+
25
+
26
+ def main(argv: Sequence[str] | None = None) -> int:
27
+ """Entry point for the `tdmread` console script. Returns a process exit code."""
28
+ parser = _build_parser()
29
+ args = parser.parse_args(argv)
30
+ if args.command is None:
31
+ parser.print_help()
32
+ return 0
33
+ try:
34
+ exit_code: int = args.handler(args)
35
+ return exit_code
36
+ except TdmError as exc:
37
+ print(f"tdmread: error: {exc}", file=sys.stderr)
38
+ return 1
39
+ except OSError as exc:
40
+ print(f"tdmread: error: {exc}", file=sys.stderr)
41
+ return 1
42
+
43
+
44
+ def _build_parser() -> argparse.ArgumentParser:
45
+ parser = argparse.ArgumentParser(
46
+ prog="tdmread",
47
+ description="Read NI TDM/TDX measurement files (XML .tdm header plus binary .tdx).",
48
+ epilog=_EXAMPLES,
49
+ formatter_class=argparse.RawDescriptionHelpFormatter,
50
+ )
51
+ parser.add_argument("--version", action="version", version=f"tdmread {__version__}")
52
+ sub = parser.add_subparsers(dest="command", metavar="command")
53
+
54
+ info = sub.add_parser("info", help="print dataset metadata and a group summary")
55
+ info.add_argument("tdm", help="path to the .tdm header file")
56
+ info.add_argument("--tdx", help="path to the .tdx data file (default: from the header)")
57
+ info.set_defaults(handler=_cmd_info)
58
+
59
+ channels = sub.add_parser("channels", help="list every channel with its type and length")
60
+ channels.add_argument("tdm", help="path to the .tdm header file")
61
+ channels.add_argument("--tdx", help="path to the .tdx data file (default: from the header)")
62
+ channels.set_defaults(handler=_cmd_channels)
63
+
64
+ dump = sub.add_parser("dump", help="dump one channel's values to CSV or JSON")
65
+ dump.add_argument("tdm", help="path to the .tdm header file")
66
+ dump.add_argument("-g", "--group", required=True, help="group name")
67
+ dump.add_argument("-c", "--channel", required=True, help="channel name")
68
+ dump.add_argument(
69
+ "-f", "--format", choices=("csv", "json"), default="csv", help="output format"
70
+ )
71
+ dump.add_argument("-o", "--output", help="write to this file instead of standard output")
72
+ dump.add_argument("--tdx", help="path to the .tdx data file (default: from the header)")
73
+ dump.set_defaults(handler=_cmd_dump)
74
+ return parser
75
+
76
+
77
+ def _load(args: argparse.Namespace) -> TdmFile:
78
+ return read_tdm(args.tdm, args.tdx)
79
+
80
+
81
+ def _cmd_info(args: argparse.Namespace) -> int:
82
+ dataset = _load(args)
83
+ meta = dataset.metadata
84
+ for label, value in (
85
+ ("name", meta.name),
86
+ ("title", meta.title),
87
+ ("author", meta.author),
88
+ ("datetime", meta.datetime),
89
+ ("description", meta.description),
90
+ ):
91
+ if value:
92
+ print(f"{label}: {value}")
93
+ print(f"groups: {len(dataset.groups)}")
94
+ for group in dataset.groups:
95
+ print(f" {group.name} ({len(group.channels)} channels)")
96
+ return 0
97
+
98
+
99
+ def _cmd_channels(args: argparse.Namespace) -> int:
100
+ dataset = _load(args)
101
+ for group, channel in dataset.channels():
102
+ kind = channel.value_type or channel.representation or "?"
103
+ unit = f" [{channel.unit}]" if channel.unit else ""
104
+ print(f"{group.name}\t{channel.name}{unit}\t{kind}\t{len(channel)}")
105
+ return 0
106
+
107
+
108
+ def _cmd_dump(args: argparse.Namespace) -> int:
109
+ dataset = _load(args)
110
+ channel = dataset.group(args.group).channel(args.channel)
111
+ text = _as_csv(channel) if args.format == "csv" else _as_json(channel)
112
+ if args.output:
113
+ with open(args.output, "w", encoding="utf-8", newline="") as handle:
114
+ handle.write(text)
115
+ else:
116
+ sys.stdout.write(text)
117
+ return 0
118
+
119
+
120
+ def _as_csv(channel: Channel) -> str:
121
+ buffer = io.StringIO()
122
+ writer = csv.writer(buffer)
123
+ writer.writerow(["index", channel.name or "value"])
124
+ for index, value in enumerate(channel.data):
125
+ writer.writerow([index, repr(value)])
126
+ return buffer.getvalue()
127
+
128
+
129
+ def _as_json(channel: Channel) -> str:
130
+ payload = {
131
+ "name": channel.name,
132
+ "unit": channel.unit,
133
+ "value_type": channel.value_type,
134
+ "representation": channel.representation,
135
+ "length": len(channel),
136
+ "data": list(channel.data),
137
+ }
138
+ return json.dumps(payload, indent=2) + "\n"
139
+
140
+
141
+ if __name__ == "__main__":
142
+ raise SystemExit(main())
tdmread/_errors.py ADDED
@@ -0,0 +1,15 @@
1
+ """Exceptions raised while reading TDM/TDX files."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class TdmError(Exception):
7
+ """A TDM dataset is malformed or cannot be read."""
8
+
9
+
10
+ class TdmFileNotFoundError(TdmError, FileNotFoundError):
11
+ """The .tdm header or its referenced .tdx data file is missing."""
12
+
13
+
14
+ class UnsupportedTdmError(TdmError):
15
+ """The dataset uses a TDM feature outside the supported subset."""
tdmread/_model.py ADDED
@@ -0,0 +1,127 @@
1
+ """Structured result types returned by :func:`tdmread.read_tdm`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from dataclasses import dataclass, field
7
+ from typing import Any
8
+
9
+ from ._errors import TdmError
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Channel:
14
+ """One channel: its metadata and the values decoded from the .tdx.
15
+
16
+ `data` holds the decoded numbers as a plain tuple. For `explicit` channels the
17
+ values come straight from the .tdx; for `implicit_linear` channels they are the
18
+ generated linear axis `offset + index * increment`. `value_type` is the TDM
19
+ valueType of an explicit block (empty for a generated axis), and `representation`
20
+ is the sequence representation (`explicit` or `implicit_linear`).
21
+ """
22
+
23
+ name: str
24
+ unit: str
25
+ description: str
26
+ value_type: str
27
+ data: tuple[float, ...]
28
+ representation: str = ""
29
+ minimum: float | None = None
30
+ maximum: float | None = None
31
+ datatype: str = ""
32
+
33
+ def __len__(self) -> int:
34
+ """Number of samples in the channel."""
35
+ return len(self.data)
36
+
37
+ def to_list(self) -> list[float]:
38
+ """Return the channel values as a new list."""
39
+ return list(self.data)
40
+
41
+ def to_numpy(self) -> Any:
42
+ """Return the values as a NumPy array.
43
+
44
+ NumPy is an optional extra: the core library never imports it. This raises
45
+ :class:`TdmError` with an actionable message when NumPy is not installed.
46
+ """
47
+ try:
48
+ import numpy as np
49
+ except ModuleNotFoundError as exc:
50
+ raise TdmError(
51
+ "NumPy is not installed; run 'pip install numpy' to use Channel.to_numpy()"
52
+ ) from exc
53
+ return np.asarray(self.data)
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class Group:
58
+ """A channel group holding an ordered set of channels."""
59
+
60
+ name: str
61
+ channels: tuple[Channel, ...]
62
+ description: str = ""
63
+
64
+ def __len__(self) -> int:
65
+ """Number of channels in the group."""
66
+ return len(self.channels)
67
+
68
+ def __iter__(self) -> Iterator[Channel]:
69
+ """Iterate over the group's channels in order."""
70
+ return iter(self.channels)
71
+
72
+ @property
73
+ def channel_names(self) -> tuple[str, ...]:
74
+ """The names of the channels in this group, in order."""
75
+ return tuple(channel.name for channel in self.channels)
76
+
77
+ def channel(self, name: str) -> Channel:
78
+ """Return the channel with `name`, or raise :class:`TdmError`."""
79
+ for channel in self.channels:
80
+ if channel.name == name:
81
+ return channel
82
+ raise TdmError(f"no channel named {name!r} in group {self.name!r}")
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class FileMetadata:
87
+ """Dataset-level metadata read from the .tdm `tdm_root` block."""
88
+
89
+ name: str = ""
90
+ title: str = ""
91
+ description: str = ""
92
+ author: str = ""
93
+ datetime: str = ""
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class TdmFile:
98
+ """A parsed TDM dataset: its groups, each with its channels and data."""
99
+
100
+ groups: tuple[Group, ...]
101
+ metadata: FileMetadata = field(default_factory=FileMetadata)
102
+
103
+ def __len__(self) -> int:
104
+ """Number of groups in the dataset."""
105
+ return len(self.groups)
106
+
107
+ def __iter__(self) -> Iterator[Group]:
108
+ """Iterate over the dataset's groups in order."""
109
+ return iter(self.groups)
110
+
111
+ @property
112
+ def group_names(self) -> tuple[str, ...]:
113
+ """The names of the groups in this dataset, in order."""
114
+ return tuple(group.name for group in self.groups)
115
+
116
+ def group(self, name: str) -> Group:
117
+ """Return the group with `name`, or raise :class:`TdmError`."""
118
+ for group in self.groups:
119
+ if group.name == name:
120
+ return group
121
+ raise TdmError(f"no group named {name!r}")
122
+
123
+ def channels(self) -> Iterator[tuple[Group, Channel]]:
124
+ """Iterate over every `(group, channel)` pair in the dataset."""
125
+ for group in self.groups:
126
+ for channel in group.channels:
127
+ yield group, channel
tdmread/_reader.py ADDED
@@ -0,0 +1,121 @@
1
+ """Parse a .tdm XML header and read its channel data from the .tdx binary."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import xml.etree.ElementTree as ET
6
+ from pathlib import Path
7
+
8
+ from ._binary import byte_order_prefix
9
+ from ._errors import TdmError, TdmFileNotFoundError
10
+ from ._model import Channel, Group, TdmFile
11
+ from ._sequence import Sequence, read_sequence
12
+ from ._xml import child_text, one_ref, read_metadata, refs
13
+
14
+ StrPath = str | Path
15
+
16
+ _ElementMap = dict[str | None, ET.Element]
17
+
18
+
19
+ def read_tdm(tdm_path: StrPath, tdx_path: StrPath | None = None) -> TdmFile:
20
+ """Read a TDM dataset from `tdm_path`, locating the .tdx by the header reference.
21
+
22
+ Pass `tdx_path` to override the data file the header points to. Explicit channels
23
+ are decoded from the .tdx; implicit-linear channels are generated and need no .tdx,
24
+ so the data file is only read when at least one explicit block refers to it.
25
+
26
+ Raises :class:`TdmFileNotFoundError` when a required file is missing and
27
+ :class:`UnsupportedTdmError` for features outside the supported subset.
28
+ """
29
+ header = Path(tdm_path)
30
+ if not header.is_file():
31
+ raise TdmFileNotFoundError(f"TDM header not found: {header}")
32
+
33
+ root = ET.parse(header).getroot()
34
+ # A purely implicit dataset generates every axis and has no binary file descriptor.
35
+ file_el = root.find(".//{*}file")
36
+ byte_order = file_el.get("byteOrder", "littleEndian") if file_el is not None else "littleEndian"
37
+ prefix = byte_order_prefix(byte_order)
38
+
39
+ blocks: _ElementMap = {b.get("id"): b for b in root.findall(".//{*}file/{*}block")}
40
+ by_id: _ElementMap = {el.get("id"): el for el in root.iter() if el.get("id")}
41
+ data = _read_tdx(header, file_el, tdx_path) if (blocks and file_el is not None) else b""
42
+
43
+ groups = tuple(_read_groups(root, by_id, blocks, data, prefix))
44
+ return TdmFile(groups=groups, metadata=read_metadata(root))
45
+
46
+
47
+ def _read_tdx(header: Path, file_el: ET.Element, override: StrPath | None) -> bytes:
48
+ if override is not None:
49
+ tdx = Path(override)
50
+ else:
51
+ url = file_el.get("url")
52
+ if not url:
53
+ raise TdmError("the .tdm header does not reference a .tdx file")
54
+ tdx = header.parent / url
55
+ try:
56
+ return tdx.read_bytes()
57
+ except FileNotFoundError as exc:
58
+ raise TdmFileNotFoundError(f"TDX data not found: {tdx}") from exc
59
+
60
+
61
+ def _read_groups(
62
+ root: ET.Element,
63
+ by_id: _ElementMap,
64
+ blocks: _ElementMap,
65
+ data: bytes,
66
+ prefix: str,
67
+ ) -> list[Group]:
68
+ tdm_root = root.find(".//{*}tdm_root")
69
+ group_ids = refs(child_text(tdm_root, "channelgroups")) if tdm_root is not None else []
70
+ groups = []
71
+ for gid in group_ids:
72
+ group_el = by_id.get(gid)
73
+ if group_el is None:
74
+ continue
75
+ channels = [
76
+ _read_channel(by_id[cid], by_id, blocks, data, prefix)
77
+ for cid in refs(child_text(group_el, "channels"))
78
+ if cid in by_id
79
+ ]
80
+ groups.append(
81
+ Group(
82
+ name=child_text(group_el, "name"),
83
+ channels=tuple(channels),
84
+ description=child_text(group_el, "description"),
85
+ )
86
+ )
87
+ return groups
88
+
89
+
90
+ def _read_channel(
91
+ channel_el: ET.Element,
92
+ by_id: _ElementMap,
93
+ blocks: _ElementMap,
94
+ data: bytes,
95
+ prefix: str,
96
+ ) -> Channel:
97
+ column = by_id.get(one_ref(child_text(channel_el, "local_columns")))
98
+ if column is None:
99
+ sequence = Sequence("", "", ())
100
+ else:
101
+ sequence = read_sequence(channel_el, column, by_id, blocks, data, prefix)
102
+ return Channel(
103
+ name=child_text(channel_el, "name"),
104
+ unit=child_text(channel_el, "unit_string"),
105
+ description=child_text(channel_el, "description"),
106
+ value_type=sequence.value_type,
107
+ data=sequence.values,
108
+ representation=sequence.representation,
109
+ minimum=_optional_float(child_text(channel_el, "minimum")),
110
+ maximum=_optional_float(child_text(channel_el, "maximum")),
111
+ datatype=child_text(channel_el, "datatype"),
112
+ )
113
+
114
+
115
+ def _optional_float(text: str) -> float | None:
116
+ if not text:
117
+ return None
118
+ try:
119
+ return float(text)
120
+ except ValueError:
121
+ return None
tdmread/_sequence.py ADDED
@@ -0,0 +1,119 @@
1
+ """Turn a localcolumn into decoded values, explicit or implicit-linear."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import xml.etree.ElementTree as ET
6
+ from typing import NamedTuple
7
+
8
+ from ._binary import decode_block
9
+ from ._errors import TdmError, UnsupportedTdmError
10
+ from ._xml import child_text, long_attribute, one_ref
11
+
12
+ _ElementMap = dict[str | None, ET.Element]
13
+
14
+ # Representations that generate a linear axis instead of storing samples.
15
+ _IMPLICIT = frozenset({"implicit_linear", "implicit"})
16
+
17
+
18
+ class Sequence(NamedTuple):
19
+ """Decoded samples plus the TDM value type and representation they came from."""
20
+
21
+ value_type: str
22
+ representation: str
23
+ values: tuple[float, ...]
24
+
25
+
26
+ def read_sequence(
27
+ channel_el: ET.Element,
28
+ column: ET.Element,
29
+ by_id: _ElementMap,
30
+ blocks: _ElementMap,
31
+ data: bytes,
32
+ prefix: str,
33
+ ) -> Sequence:
34
+ """Decode the values a localcolumn describes.
35
+
36
+ `explicit` columns are read from the .tdx block they point at. `implicit_linear`
37
+ columns are generated as `offset + index * increment` from their generation
38
+ parameters, with the length taken from the owning channel. Any other
39
+ representation raises :class:`UnsupportedTdmError`.
40
+ """
41
+ representation = child_text(column, "sequence_representation") or "explicit"
42
+ if representation == "explicit":
43
+ return _read_explicit(column, by_id, blocks, data, prefix)
44
+ if representation in _IMPLICIT:
45
+ return _read_implicit(channel_el, column, by_id)
46
+ raise UnsupportedTdmError(
47
+ f"unsupported sequence representation {representation!r}; "
48
+ "only 'explicit' and 'implicit_linear' channels are read"
49
+ )
50
+
51
+
52
+ def _read_explicit(
53
+ column: ET.Element,
54
+ by_id: _ElementMap,
55
+ blocks: _ElementMap,
56
+ data: bytes,
57
+ prefix: str,
58
+ ) -> Sequence:
59
+ sequence = by_id.get(one_ref(child_text(column, "values")))
60
+ if sequence is None:
61
+ return Sequence("", "explicit", ())
62
+ values_el = sequence.find("{*}values")
63
+ block = blocks.get(values_el.get("external")) if values_el is not None else None
64
+ if block is None:
65
+ return Sequence("", "explicit", ())
66
+ value_type = block.get("valueType", "")
67
+ byte_offset = int(block.get("byteOffset", "0"))
68
+ length = int(block.get("length", "0"))
69
+ values = decode_block(data, prefix, value_type, byte_offset, length)
70
+ return Sequence(value_type, "explicit", values)
71
+
72
+
73
+ def _read_implicit(
74
+ channel_el: ET.Element,
75
+ column: ET.Element,
76
+ by_id: _ElementMap,
77
+ ) -> Sequence:
78
+ offset, increment = _generation_parameters(child_text(column, "generation_parameters"))
79
+ count = long_attribute(channel_el, "NI_ChannelLength")
80
+ if count is None:
81
+ count = _count_from_submatrix(column, by_id)
82
+ if count is None:
83
+ raise TdmError("implicit channel has no known length (no NI_ChannelLength or submatrix)")
84
+ if count < 0:
85
+ raise TdmError(f"implicit channel reports a negative length: {count}")
86
+ values = tuple(offset + index * increment for index in range(count))
87
+ return Sequence("", "implicit_linear", values)
88
+
89
+
90
+ def _generation_parameters(text: str) -> tuple[float, float]:
91
+ """Return `(offset, increment)` from a generation_parameters string.
92
+
93
+ A missing or partial value defaults the offset to 0.0 and the increment to 1.0,
94
+ which yields the natural sample-index axis.
95
+ """
96
+ parts = text.split()
97
+ offset = _as_float(parts[0]) if parts else 0.0
98
+ increment = _as_float(parts[1]) if len(parts) > 1 else 1.0
99
+ return offset, increment
100
+
101
+
102
+ def _as_float(token: str) -> float:
103
+ try:
104
+ return float(token)
105
+ except ValueError as exc:
106
+ raise TdmError(f"invalid generation parameter {token!r}") from exc
107
+
108
+
109
+ def _count_from_submatrix(column: ET.Element, by_id: _ElementMap) -> int | None:
110
+ submatrix = by_id.get(one_ref(child_text(column, "submatrix")))
111
+ if submatrix is None:
112
+ return None
113
+ rows = child_text(submatrix, "number_of_rows")
114
+ if not rows:
115
+ return None
116
+ try:
117
+ return int(rows)
118
+ except ValueError:
119
+ return None
tdmread/_xml.py ADDED
@@ -0,0 +1,62 @@
1
+ """Namespace-agnostic helpers for reading the USI `.tdm` XML header."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import xml.etree.ElementTree as ET
7
+
8
+ from ._model import FileMetadata
9
+
10
+ # References appear as `id("usi12")`, optionally wrapped as
11
+ # `#xpointer(id("usi12") id("usi13"))`. This matches every id token in either form.
12
+ _REF = re.compile(r'id\("([^"]+)"\)')
13
+
14
+
15
+ def child_text(element: ET.Element | None, name: str) -> str:
16
+ """Return the stripped text of the first `name` child, or an empty string."""
17
+ if element is None:
18
+ return ""
19
+ child = element.find(f"{{*}}{name}")
20
+ return (child.text or "").strip() if child is not None else ""
21
+
22
+
23
+ def refs(text: str) -> list[str]:
24
+ """Return every referenced id found in `text`, in order."""
25
+ return _REF.findall(text)
26
+
27
+
28
+ def one_ref(text: str) -> str | None:
29
+ """Return the first referenced id in `text`, or None when there is none."""
30
+ found = _REF.findall(text)
31
+ return found[0] if found else None
32
+
33
+
34
+ def long_attribute(element: ET.Element, name: str) -> int | None:
35
+ """Return the integer value of a `long_attribute` named `name`, or None.
36
+
37
+ Channel lengths and similar scalars live in `instance_attributes` as
38
+ `<long_attribute name="NI_ChannelLength">1000</long_attribute>` entries.
39
+ """
40
+ for attr in element.findall(".//{*}long_attribute"):
41
+ if attr.get("name") == name:
42
+ text = (attr.text or "").strip()
43
+ if text:
44
+ try:
45
+ return int(text)
46
+ except ValueError:
47
+ return None
48
+ return None
49
+
50
+
51
+ def read_metadata(root: ET.Element) -> FileMetadata:
52
+ """Extract dataset-level metadata from the `tdm_root` block."""
53
+ tdm_root = root.find(".//{*}tdm_root")
54
+ if tdm_root is None:
55
+ return FileMetadata()
56
+ return FileMetadata(
57
+ name=child_text(tdm_root, "name"),
58
+ title=child_text(tdm_root, "title"),
59
+ description=child_text(tdm_root, "description"),
60
+ author=child_text(tdm_root, "author"),
61
+ datetime=child_text(tdm_root, "datetime"),
62
+ )
tdmread/py.typed ADDED
File without changes
@@ -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,15 @@
1
+ tdmread/__init__.py,sha256=Qdt-Bj1LdD-pcM5IyW6MppEMXI6IYzDysq_aSqPe9E4,549
2
+ tdmread/__main__.py,sha256=TISOozsFVLPqbtrjrlTDt9k1PK4Z489Y6MHtDYSPDEY,186
3
+ tdmread/_binary.py,sha256=kMmkg2D4d7fssnwn_ZIGuRj2PqU1-nB1KyARAKU-MC8,1802
4
+ tdmread/_cli.py,sha256=fQQX2udUMlxWehtI7QItaq_1WveebixSQzQqFI5IGLI,4866
5
+ tdmread/_errors.py,sha256=W0Yr9WWLf-U3ekULB0orRLflOAQVgpghUUhuWgI72WI,414
6
+ tdmread/_model.py,sha256=OA_sZ4h6GYEaw_1TveITOJH5gvtoxmk0wzSZPD2E3g0,4035
7
+ tdmread/_reader.py,sha256=1WgQw9Wm-ZDsivrwwcLk5ckvOWtWjXTOLKWyaR6p21o,4233
8
+ tdmread/_sequence.py,sha256=hmnCxRqzFL1ar8gCurWc9530LLHqcg5fUbC6Yoys1os,4057
9
+ tdmread/_xml.py,sha256=StJ85UxWmL5AUEIYRJQFkqGllTClTWThERp5aIRI6HY,2087
10
+ tdmread/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
+ tdmread-0.2.1.dist-info/METADATA,sha256=d1VsRdeLbDVDtSaZlQyPmVORiNFt99T6S-vdVtQSuEw,4646
12
+ tdmread-0.2.1.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
13
+ tdmread-0.2.1.dist-info/entry_points.txt,sha256=DPblv_vYHUqmnRSf2uDSSRUy5yQxrw-KwHHhK0U6Q68,46
14
+ tdmread-0.2.1.dist-info/licenses/LICENSE,sha256=wirD5nCA2aQa5UusK_1YHLBogI3CGcw23xAnulp3L_U,1091
15
+ tdmread-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tdmread = tdmread._cli:main
@@ -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.