instro-pymeasure 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,19 @@
1
+ """Publish pymeasure instrument traffic through any instro publisher (Nominal, files, ...).
2
+
3
+ Wrap a pymeasure instrument with `PymeasureInstrument` (instro-first code) or `attach` (existing
4
+ pymeasure code): every property write publishes a ``.cmd`` command channel and every property read
5
+ publishes a measurement channel. `ChannelMap` (or ``instro pymeasure map``) controls the names.
6
+ """
7
+
8
+ from instro.pymeasure.channel_map import ChannelMap
9
+ from instro.pymeasure.inspection import ChannelSpec, default_channel_name, describe
10
+ from instro.pymeasure.wrapper import PymeasureInstrument, attach
11
+
12
+ __all__ = [
13
+ "ChannelMap",
14
+ "ChannelSpec",
15
+ "PymeasureInstrument",
16
+ "attach",
17
+ "default_channel_name",
18
+ "describe",
19
+ ]
@@ -0,0 +1,296 @@
1
+ """Editable mapping from pymeasure attribute paths to instro channel names."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import json
7
+ import re
8
+ from collections import Counter
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from pymeasure.instruments.common_base import CommonBase
14
+
15
+ from instro.pymeasure.inspection import ChannelSpec, describe, original_class
16
+
17
+ MAP_FORMAT = "instro-pymeasure-channel-map/1"
18
+
19
+ _ENTRY_KEYS = {"channel", "kind", "get", "set", "doc"}
20
+ _INDEXED_NAME = re.compile(r"^(.+)\.\d+$")
21
+ _VALID_NAME = re.compile(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$")
22
+
23
+
24
+ @dataclass
25
+ class ChannelMap:
26
+ """Which pymeasure properties publish, and under which channel names.
27
+
28
+ Generate one from an instrument, save it, edit the ``channel`` of each entry (or set it to
29
+ ``null`` to stop publishing that property), and pass the file or object to
30
+ `PymeasureInstrument` or `attach`.
31
+
32
+ A command channel is the mapped name plus ``.cmd``; a measurement channel is the mapped name.
33
+ Both sit under the instrument name: ``<instrument name>.<mapped name>[.cmd]``.
34
+
35
+ Attributes:
36
+ channels: Attribute path (``"ch_1.voltage_setpoint"``) to channel name (``"ch1.vset"``), or
37
+ ``None`` to leave that property unpublished.
38
+ include_unmapped: Publish properties missing from ``channels`` under their default names.
39
+ instrument: ``module.Class`` of the instrument the map was generated from; informational.
40
+ """
41
+
42
+ channels: dict[str, str | None] = field(default_factory=dict)
43
+ include_unmapped: bool = False
44
+ instrument: str | None = None
45
+
46
+ @classmethod
47
+ def defaults(cls) -> ChannelMap:
48
+ """Return the map used when none is given: every property under its default name."""
49
+ return cls(channels={}, include_unmapped=True)
50
+
51
+ @classmethod
52
+ def generate(cls, target: CommonBase | type[CommonBase]) -> ChannelMap:
53
+ """Build a map listing every publishable property of ``target`` under its default name.
54
+
55
+ Args:
56
+ target: A pymeasure instrument instance (preferred: it sees channels added in
57
+ ``__init__``) or class.
58
+
59
+ Returns:
60
+ A `ChannelMap` with one entry per property and ``include_unmapped=False``.
61
+ """
62
+ return cls(
63
+ channels={spec.path: spec.default_name for spec in describe(target)},
64
+ include_unmapped=False,
65
+ instrument=_qualified_name(target),
66
+ )
67
+
68
+ @classmethod
69
+ def from_dict(cls, data: dict[str, Any]) -> ChannelMap:
70
+ """Parse the JSON-compatible form written by `to_dict`.
71
+
72
+ Each ``channels`` value may be a channel-name string, ``null``, or an object whose
73
+ ``channel`` key holds either; its ``kind``/``get``/``set``/``doc`` keys are informational.
74
+
75
+ Raises:
76
+ ValueError: The format tag is unknown or an entry is malformed.
77
+ """
78
+ fmt = data.get("format", MAP_FORMAT)
79
+ if fmt != MAP_FORMAT:
80
+ raise ValueError(f"Unsupported channel map format {fmt!r}; expected {MAP_FORMAT!r}")
81
+ channels: dict[str, str | None] = {}
82
+ for path, entry in data.get("channels", {}).items():
83
+ if isinstance(entry, dict):
84
+ unknown = set(entry) - _ENTRY_KEYS
85
+ if unknown:
86
+ raise ValueError(f"Channel map entry {path!r} has unknown keys {sorted(unknown)}")
87
+ entry = entry.get("channel")
88
+ if entry is not None and not isinstance(entry, str):
89
+ raise ValueError(f"Channel map entry {path!r} must be a string or null, got {entry!r}")
90
+ channels[path] = entry
91
+ return cls(
92
+ channels=channels,
93
+ include_unmapped=bool(data.get("include_unmapped", False)),
94
+ instrument=data.get("instrument"),
95
+ )
96
+
97
+ @classmethod
98
+ def load(cls, path: str | Path) -> ChannelMap:
99
+ """Read a map from a JSON file written by `save` (or the ``instro pymeasure map`` command)."""
100
+ return cls.from_dict(json.loads(Path(path).read_text()))
101
+
102
+ def to_dict(self, specs: list[ChannelSpec] | None = None) -> dict[str, Any]:
103
+ """Return the JSON-compatible form.
104
+
105
+ Args:
106
+ specs: Inspection results for the instrument. When given, each entry also records the
107
+ property's kind, SCPI commands, and docstring to make the file easier to edit.
108
+ """
109
+ by_path = {spec.path: spec for spec in specs or []}
110
+ channels: dict[str, Any] = {}
111
+ for path, name in self.channels.items():
112
+ spec = by_path.get(path)
113
+ if spec is None:
114
+ channels[path] = name
115
+ continue
116
+ entry: dict[str, Any] = {"channel": name, "kind": spec.kind}
117
+ if spec.get_command:
118
+ entry["get"] = spec.get_command
119
+ if spec.set_command:
120
+ entry["set"] = spec.set_command
121
+ if spec.doc:
122
+ entry["doc"] = spec.doc
123
+ channels[path] = entry
124
+ data: dict[str, Any] = {"format": MAP_FORMAT}
125
+ if self.instrument:
126
+ data["instrument"] = self.instrument
127
+ data["include_unmapped"] = self.include_unmapped
128
+ data["channels"] = channels
129
+ return data
130
+
131
+ def save(self, path: str | Path, target: CommonBase | type[CommonBase] | None = None) -> None:
132
+ """Write the map as JSON.
133
+
134
+ Args:
135
+ path: Destination file.
136
+ target: Instrument the map belongs to; when given, entries carry each property's kind,
137
+ SCPI commands, and docstring.
138
+ """
139
+ specs = describe(target) if target is not None else None
140
+ Path(path).write_text(json.dumps(self.to_dict(specs), indent=2) + "\n")
141
+
142
+ def rename(self, names: dict[str, str | None]) -> ChannelMap:
143
+ """Set the channel name of each attribute path in ``names`` (``None`` stops publishing it).
144
+
145
+ Example::
146
+
147
+ channel_map.rename({"ch_1.voltage_setpoint": "out1.v_set", "ch_1.current": "out1.i"})
148
+
149
+ Returns:
150
+ This map, so calls can be chained.
151
+
152
+ Raises:
153
+ KeyError: A path is not in the map.
154
+ """
155
+ missing = sorted(set(names) - set(self.channels))
156
+ if missing:
157
+ raise KeyError(f"Not in the channel map: {missing}")
158
+ self.channels.update(names)
159
+ return self
160
+
161
+ def exclude(self, *patterns: str) -> ChannelMap:
162
+ """Stop publishing every attribute path that matches one of the glob ``patterns``.
163
+
164
+ Example::
165
+
166
+ channel_map.exclude("ch_2.*", "ch_3.*")
167
+
168
+ Returns:
169
+ This map, so calls can be chained.
170
+
171
+ Raises:
172
+ KeyError: A pattern matches no path, which is usually a typo.
173
+ """
174
+ for path in self._matching(patterns):
175
+ self.channels[path] = None
176
+ return self
177
+
178
+ def select(self, *patterns: str) -> ChannelMap:
179
+ """Stop publishing every attribute path that matches none of the glob ``patterns``.
180
+
181
+ Example::
182
+
183
+ channel_map.select("ch_1.*") # publish output 1 only
184
+
185
+ Returns:
186
+ This map, so calls can be chained.
187
+
188
+ Raises:
189
+ KeyError: A pattern matches no path, which is usually a typo.
190
+ """
191
+ keep = self._matching(patterns)
192
+ for path in self.channels:
193
+ if path not in keep:
194
+ self.channels[path] = None
195
+ return self
196
+
197
+ def preview(self, target: CommonBase | type[CommonBase], name: str | None = None) -> list[dict[str, str | None]]:
198
+ """Show exactly which channels each property publishes, separately for commands and measurements.
199
+
200
+ Writing a property publishes a :class:`~instro.lib.types.Command` on the ``command`` channel; reading it
201
+ publishes a :class:`~instro.lib.types.Measurement` on the ``measurement`` channel. A control has both,
202
+ a measurement only the second, a setting only the first.
203
+
204
+ Example::
205
+
206
+ import pandas as pd
207
+ pd.DataFrame(channel_map.preview(supply, "psu"))
208
+
209
+ Args:
210
+ target: The instrument (instance or class) the map is for.
211
+ name: Instrument name to prefix, as passed to `attach` or `PymeasureInstrument`.
212
+
213
+ Returns:
214
+ One row per property with keys ``property``, ``kind``, ``command``, and ``measurement``;
215
+ a channel is ``None`` when the property doesn't publish in that direction.
216
+
217
+ Raises:
218
+ ValueError: The map does not fit ``target`` (see `resolve`).
219
+ """
220
+ specs = describe(target)
221
+ resolved = self.resolve(specs)
222
+ prefix = f"{name}." if name else ""
223
+ rows: list[dict[str, str | None]] = []
224
+ for spec in specs:
225
+ channel = resolved.get(spec.path)
226
+ rows.append(
227
+ {
228
+ "property": spec.path,
229
+ "kind": spec.kind,
230
+ "command": f"{prefix}{channel}.cmd" if channel and spec.writable else None,
231
+ "measurement": f"{prefix}{channel}" if channel and spec.readable else None,
232
+ }
233
+ )
234
+ return rows
235
+
236
+ def _matching(self, patterns: tuple[str, ...]) -> set[str]:
237
+ matched: set[str] = set()
238
+ for pattern in patterns:
239
+ paths = fnmatch.filter(self.channels, pattern)
240
+ if not paths:
241
+ raise KeyError(f"No channel map entry matches {pattern!r}")
242
+ matched.update(paths)
243
+ return matched
244
+
245
+ def resolve(self, specs: list[ChannelSpec]) -> dict[str, str]:
246
+ """Return attribute path to channel name for every property that publishes.
247
+
248
+ Args:
249
+ specs: Inspection results for the instrument the map is applied to.
250
+
251
+ Raises:
252
+ ValueError: The map names a path the instrument does not have (a typo, or a pymeasure
253
+ upgrade renamed it), a channel name is invalid or ends in ``.cmd``, or two
254
+ properties map to the same channel name.
255
+ """
256
+ known = {spec.path: spec for spec in specs}
257
+ unknown = sorted(set(self.channels) - set(known))
258
+ if unknown:
259
+ raise ValueError(
260
+ f"Channel map names properties the instrument does not have: {unknown}. "
261
+ "Regenerate the map with `instro pymeasure map` if pymeasure renamed them."
262
+ )
263
+
264
+ resolved: dict[str, str] = {}
265
+ for path, spec in known.items():
266
+ if path in self.channels:
267
+ name = self.channels[path]
268
+ elif self.include_unmapped:
269
+ name = spec.default_name
270
+ else:
271
+ continue
272
+ if name is None:
273
+ continue
274
+ if not _VALID_NAME.match(name):
275
+ raise ValueError(f"Channel name {name!r} for {path!r} must be dot-separated [A-Za-z0-9_] segments")
276
+ if name == "cmd" or name.endswith(".cmd"):
277
+ raise ValueError(f"Channel name {name!r} for {path!r} must not end in '.cmd'; it is added to commands")
278
+ resolved[path] = name
279
+
280
+ duplicates = sorted(name for name, count in Counter(resolved.values()).items() if count > 1)
281
+ if duplicates:
282
+ raise ValueError(f"Channel map gives several properties the same channel name: {duplicates}")
283
+ # A list-valued property publishes <name>.0, <name>.1, …, so those names can't belong to another property.
284
+ names = set(resolved.values())
285
+ overlaps = sorted(name for name in names if (m := _INDEXED_NAME.match(name)) and m.group(1) in names)
286
+ if overlaps:
287
+ raise ValueError(
288
+ f"Channel names {overlaps} collide with the numbered channels that a list value of another "
289
+ "property publishes; rename one of them"
290
+ )
291
+ return resolved
292
+
293
+
294
+ def _qualified_name(target: Any) -> str:
295
+ cls = original_class(target if isinstance(target, type) else type(target))
296
+ return f"{cls.__module__}.{cls.__qualname__}"
@@ -0,0 +1,107 @@
1
+ """``instro pymeasure`` commands: inspect a pymeasure instrument and generate its channel map."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Annotated, Any
9
+
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.table import Table
13
+
14
+ from instro.pymeasure.channel_map import ChannelMap
15
+ from instro.pymeasure.inspection import describe
16
+
17
+ app = typer.Typer(help="Publish pymeasure instruments through instro.", no_args_is_help=True)
18
+
19
+ _INSTRUMENT_HELP = (
20
+ "pymeasure instrument class, as a full dotted path (pymeasure.instruments.keithley.Keithley2400) "
21
+ "or relative to pymeasure.instruments (keithley.Keithley2400)."
22
+ )
23
+ _RESOURCE_HELP = (
24
+ "Connect to this VISA resource and inspect the live instance. Needed for drivers that add "
25
+ "channels in __init__ rather than with ChannelCreator."
26
+ )
27
+
28
+
29
+ def load_instrument_class(dotted: str) -> type:
30
+ """Import a pymeasure instrument class from ``pkg.module.Class`` or ``vendor.Class``.
31
+
32
+ Raises:
33
+ typer.BadParameter: The class can't be imported.
34
+ """
35
+ module_name, _, class_name = dotted.rpartition(".")
36
+ if not module_name:
37
+ raise typer.BadParameter(f"{dotted!r} is not a dotted path to a class")
38
+ for candidate in (module_name, f"pymeasure.instruments.{module_name}"):
39
+ try:
40
+ module = importlib.import_module(candidate)
41
+ except ImportError:
42
+ continue
43
+ cls = getattr(module, class_name, None)
44
+ if isinstance(cls, type):
45
+ return cls
46
+ raise typer.BadParameter(f"Could not import pymeasure instrument class {dotted!r}")
47
+
48
+
49
+ def _target(instrument: str, resource: str | None) -> Any:
50
+ cls = load_instrument_class(instrument)
51
+ return cls(resource) if resource else cls
52
+
53
+
54
+ def _close(target: Any) -> None:
55
+ if not isinstance(target, type):
56
+ target.adapter.close()
57
+
58
+
59
+ @app.command("map")
60
+ def map_cmd(
61
+ instrument: Annotated[str, typer.Argument(help=_INSTRUMENT_HELP)],
62
+ output: Annotated[Path | None, typer.Option("--output", "-o", help="Write the map here instead of stdout.")] = None,
63
+ resource: Annotated[str | None, typer.Option(help=_RESOURCE_HELP)] = None,
64
+ ) -> None:
65
+ """Generate an editable JSON channel map for a pymeasure instrument.
66
+
67
+ Edit each entry's "channel" to rename it, or set it to null to stop publishing it, then pass
68
+ the file as channel_map= to PymeasureInstrument or attach().
69
+ """
70
+ target = _target(instrument, resource)
71
+ try:
72
+ channel_map = ChannelMap.generate(target)
73
+ text = json.dumps(channel_map.to_dict(describe(target)), indent=2) + "\n"
74
+ finally:
75
+ _close(target)
76
+ if output is None:
77
+ typer.echo(text, nl=False)
78
+ else:
79
+ output.write_text(text)
80
+ typer.echo(f"Wrote {len(channel_map.channels)} channels to {output}", err=True)
81
+
82
+
83
+ @app.command("describe")
84
+ def describe_cmd(
85
+ instrument: Annotated[str, typer.Argument(help=_INSTRUMENT_HELP)],
86
+ resource: Annotated[str | None, typer.Option(help=_RESOURCE_HELP)] = None,
87
+ ) -> None:
88
+ """Print each publishable property with its SCPI commands and its default command/measurement channels."""
89
+ target = _target(instrument, resource)
90
+ try:
91
+ specs = describe(target)
92
+ rows = ChannelMap.defaults().preview(target)
93
+ finally:
94
+ _close(target)
95
+ table = Table(title=instrument)
96
+ for column in ("property", "kind", "get", "set", "command channel", "measurement channel"):
97
+ table.add_column(column)
98
+ for spec, row in zip(specs, rows):
99
+ table.add_row(
100
+ spec.path,
101
+ spec.kind,
102
+ spec.get_command or "",
103
+ spec.set_command or "",
104
+ row["command"] or "",
105
+ row["measurement"] or "",
106
+ )
107
+ Console().print(table)
@@ -0,0 +1,182 @@
1
+ """Discover the publishable properties of a pymeasure instrument and name their channels."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import re
7
+ from dataclasses import dataclass
8
+ from typing import Any, Literal
9
+
10
+ from pymeasure.instruments import Channel, Instrument
11
+ from pymeasure.instruments.common_base import CommonBase
12
+
13
+ try:
14
+ from pymeasure.instruments.generic_types import SCPIMixin
15
+
16
+ _BASE_CLASSES: tuple[type, ...] = (CommonBase, Instrument, Channel, SCPIMixin)
17
+ except ImportError: # pymeasure < 0.14 has no SCPIMixin
18
+ _BASE_CLASSES = (CommonBase, Instrument, Channel)
19
+
20
+ PropertyKind = Literal["control", "measurement", "setting", "property"]
21
+
22
+ _MISSING = object()
23
+
24
+ # Housekeeping properties (`id`, `status`, `next_error`, …) that every pymeasure instrument inherits.
25
+ BASE_NAMES = frozenset(name for base in _BASE_CLASSES for name in dir(base))
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class ChannelSpec:
30
+ """One publishable property of a pymeasure instrument.
31
+
32
+ Attributes:
33
+ path: Attribute path from the root instrument, e.g. ``"ch_1.voltage_setpoint"``.
34
+ kind: ``"control"`` (read and write), ``"measurement"`` (read only), ``"setting"``
35
+ (write only), or ``"property"`` (a hand-written Python property).
36
+ readable: Reading the property queries the instrument.
37
+ writable: Assigning the property sends a command.
38
+ get_command: SCPI query template, or ``None``.
39
+ set_command: SCPI command template, or ``None``.
40
+ doc: First line of the property's docstring.
41
+ default_name: Channel name the inspection rules give this property, without the
42
+ instrument-name prefix or ``.cmd`` suffix.
43
+ """
44
+
45
+ path: str
46
+ kind: PropertyKind
47
+ readable: bool
48
+ writable: bool
49
+ get_command: str | None
50
+ set_command: str | None
51
+ doc: str
52
+ default_name: str
53
+
54
+
55
+ def default_channel_name(path: str) -> str:
56
+ """Return the channel name the inspection rules give an attribute path.
57
+
58
+ pymeasure channel attributes ``ch_<id>`` become ``ch<id>`` to match instro's naming, and any
59
+ character outside ``[A-Za-z0-9_]`` becomes ``_``.
60
+
61
+ Args:
62
+ path: Attribute path, e.g. ``"ch_1.voltage_setpoint"``.
63
+
64
+ Returns:
65
+ Dotted channel name, e.g. ``"ch1.voltage_setpoint"``.
66
+ """
67
+ segments = []
68
+ for segment in path.split("."):
69
+ segment = re.sub(r"^ch_(\w+)$", r"ch\1", segment)
70
+ segments.append(re.sub(r"\W", "_", segment))
71
+ return ".".join(segments)
72
+
73
+
74
+ def original_class(cls: type) -> type:
75
+ """Return the pymeasure class behind a class the wrapper generated, or ``cls`` itself."""
76
+ return getattr(cls, "_instro_original_class", cls)
77
+
78
+
79
+ def describe(target: CommonBase | type[CommonBase]) -> list[ChannelSpec]:
80
+ """List every publishable property of a pymeasure instrument, including its channels.
81
+
82
+ Pass an instance where possible: channels a driver adds in ``__init__`` (rather than with
83
+ ``ChannelCreator``/``MultiChannelCreator`` at class level) only exist on an instance.
84
+
85
+ Properties inherited from pymeasure's base classes (``id``, ``status``, ``next_error``, …)
86
+ are left out.
87
+
88
+ Args:
89
+ target: A pymeasure instrument instance or class.
90
+
91
+ Returns:
92
+ One `ChannelSpec` per property, instrument properties first, then each channel's.
93
+ """
94
+ specs: list[ChannelSpec] = []
95
+ _walk(target, "", specs, set())
96
+ return specs
97
+
98
+
99
+ def _walk(target: Any, prefix: str, specs: list[ChannelSpec], seen: set[int]) -> None:
100
+ is_class = inspect.isclass(target)
101
+ # Only instances can form cycles; classes repeat legitimately (ch_1..ch_3 sharing one channel class).
102
+ if not is_class:
103
+ if id(target) in seen:
104
+ return
105
+ seen.add(id(target))
106
+ cls = original_class(target if is_class else type(target))
107
+
108
+ for name in sorted(dir(cls)):
109
+ if name.startswith("_") or name in BASE_NAMES:
110
+ continue
111
+ attr = inspect.getattr_static(cls, name)
112
+ if isinstance(attr, property):
113
+ spec = _spec_for(prefix + name, attr)
114
+ if spec is not None:
115
+ specs.append(spec)
116
+
117
+ for child_name, child in _children(target, cls):
118
+ _walk(child, f"{prefix}{child_name}.", specs, seen)
119
+
120
+
121
+ def child_attributes(obj: CommonBase) -> list[tuple[str, CommonBase]]:
122
+ """Return ``(attribute name, child)`` for each channel or other child object of a pymeasure instance."""
123
+ return [
124
+ (name, value)
125
+ for name, value in list(vars(obj).items())
126
+ if isinstance(value, CommonBase) and name != "parent" and not name.startswith("_")
127
+ ]
128
+
129
+
130
+ def _children(target: Any, cls: type) -> list[tuple[str, Any]]:
131
+ """Return ``(attribute name, child)`` pairs: instances from ``vars``, classes from channel creators."""
132
+ if not inspect.isclass(target):
133
+ return list(child_attributes(target))
134
+
135
+ children: list[tuple[str, Any]] = []
136
+ for name, creator in CommonBase.get_channels(cls):
137
+ for child_cls, child_id in creator.pairs:
138
+ prefix = creator.kwargs.get("prefix")
139
+ if isinstance(creator, CommonBase.MultiChannelCreator) and prefix and child_id is not None:
140
+ children.append((f"{prefix}{child_id}", child_cls))
141
+ else:
142
+ children.append((name, child_cls))
143
+ return children
144
+
145
+
146
+ def _command(fn: Any, param: str) -> Any:
147
+ if fn is None:
148
+ return _MISSING
149
+ try:
150
+ parameter = inspect.signature(fn).parameters.get(param)
151
+ except (TypeError, ValueError):
152
+ return _MISSING
153
+ return _MISSING if parameter is None else parameter.default
154
+
155
+
156
+ def _spec_for(path: str, prop: property) -> ChannelSpec | None:
157
+ get_command = _command(prop.fget, "get_command")
158
+ set_command = _command(prop.fset, "set_command")
159
+ kind: PropertyKind
160
+ if get_command is _MISSING and set_command is _MISSING:
161
+ readable, writable = prop.fget is not None, prop.fset is not None
162
+ get_command = set_command = None
163
+ kind = "property"
164
+ else:
165
+ get_command = None if get_command is _MISSING else get_command
166
+ set_command = None if set_command is _MISSING else set_command
167
+ readable, writable = get_command is not None, set_command is not None
168
+ kind = "control" if readable and writable else "measurement" if readable else "setting"
169
+ if not (readable or writable):
170
+ return None
171
+ # pymeasure appends "(dynamic)" to dynamic properties' docstrings.
172
+ doc = (inspect.getdoc(prop) or "").removesuffix("(dynamic)").strip().splitlines()
173
+ return ChannelSpec(
174
+ path=path,
175
+ kind=kind,
176
+ readable=readable,
177
+ writable=writable,
178
+ get_command=get_command if isinstance(get_command, str) else None,
179
+ set_command=set_command if isinstance(set_command, str) else None,
180
+ doc=doc[0] if doc else "",
181
+ default_name=default_channel_name(path),
182
+ )
@@ -0,0 +1,413 @@
1
+ """Publish every command sent to, and every value read from, a pymeasure instrument."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import inspect
7
+ import logging
8
+ import threading
9
+ import time
10
+ from enum import Enum
11
+ from importlib.metadata import PackageNotFoundError, version
12
+ from pathlib import Path
13
+ from types import FunctionType
14
+ from typing import Any, Callable, Generic, TypeVar
15
+
16
+ from pymeasure.instruments.common_base import CommonBase
17
+
18
+ from instro.lib.instrument import Instrument
19
+ from instro.lib.publishers import Publisher
20
+ from instro.lib.types import BackgroundDaemonConfig, Command, Measurement
21
+ from instro.pymeasure.channel_map import ChannelMap
22
+ from instro.pymeasure.inspection import BASE_NAMES, child_attributes, describe, original_class
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ T = TypeVar("T", bound=CommonBase)
27
+
28
+ _SINK_ATTR = "_instro_sink"
29
+ # Longer lists/arrays are traces or buffers with no timebase to attach; they are skipped.
30
+ _MAX_SPLIT = 16
31
+
32
+ _published_classes: dict[type, type] = {}
33
+ _published_classes_lock = threading.Lock()
34
+
35
+
36
+ class _Sink:
37
+ """Per-object link from a wrapped pymeasure object back to its `PymeasureInstrument`."""
38
+
39
+ def __init__(self, owner: PymeasureInstrument, prefix: str):
40
+ self.owner = owner
41
+ self.prefix = prefix
42
+
43
+
44
+ class _PublishingProperty:
45
+ """Delegates to the original pymeasure property, then publishes what was read or written."""
46
+
47
+ def __init__(self, original: property, attr: str):
48
+ self.original = original
49
+ self.attr = attr
50
+ self.__doc__ = original.__doc__
51
+
52
+ def __get__(self, obj: Any, objtype: type | None = None) -> Any:
53
+ # Class access returns the original so pymeasure's own scans (DynamicProperty setup) still see it.
54
+ if obj is None:
55
+ return self.original
56
+ sink = obj.__dict__.get(_SINK_ATTR)
57
+ if sink is None:
58
+ return self.original.__get__(obj, objtype)
59
+ return sink.owner._on_read(sink.prefix + self.attr, lambda: self.original.__get__(obj, objtype))
60
+
61
+ def __set__(self, obj: Any, value: Any) -> None:
62
+ sink = obj.__dict__.get(_SINK_ATTR)
63
+ if sink is None:
64
+ self.original.__set__(obj, value)
65
+ return
66
+ sink.owner._on_write(sink.prefix + self.attr, value, lambda: self.original.__set__(obj, value))
67
+
68
+ def __delete__(self, obj: Any) -> None:
69
+ self.original.__delete__(obj)
70
+
71
+
72
+ def _locked(method: FunctionType) -> Callable:
73
+ @functools.wraps(method)
74
+ def wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
75
+ sink = self.__dict__.get(_SINK_ATTR)
76
+ if sink is None:
77
+ return method(self, *args, **kwargs)
78
+ with sink.owner._lock:
79
+ return method(self, *args, **kwargs)
80
+
81
+ return wrapper
82
+
83
+
84
+ def _published_class(cls: type) -> type:
85
+ """Return (and cache) a subclass of ``cls`` whose properties publish and whose methods hold the lock."""
86
+ with _published_classes_lock:
87
+ cached = _published_classes.get(cls)
88
+ if cached is not None:
89
+ return cached
90
+ namespace: dict[str, Any] = {
91
+ "_instro_original_class": cls,
92
+ "__module__": cls.__module__,
93
+ "__qualname__": cls.__qualname__,
94
+ "__doc__": cls.__doc__,
95
+ }
96
+ for name in dir(cls):
97
+ if name.startswith("_"):
98
+ continue
99
+ attr = inspect.getattr_static(cls, name)
100
+ if isinstance(attr, property):
101
+ # Base-class properties (id, status, …) never publish; their I/O goes through the locked methods.
102
+ if name not in BASE_NAMES:
103
+ namespace[name] = _PublishingProperty(attr, name)
104
+ elif isinstance(attr, FunctionType):
105
+ # Includes the base write/read/ask/values, so direct I/O is serialized with background polling.
106
+ namespace[name] = _locked(attr)
107
+ published = type(cls.__name__, (cls,), namespace)
108
+ _published_classes[cls] = published
109
+ return published
110
+
111
+
112
+ def _scalar(value: Any) -> float | str | None:
113
+ if isinstance(value, Enum):
114
+ value = value.value
115
+ if not isinstance(value, (int, float, str)) and hasattr(value, "magnitude"): # pint Quantity
116
+ value = value.magnitude
117
+ if getattr(value, "ndim", None) == 0 and hasattr(value, "item"): # numpy scalar
118
+ value = value.item()
119
+ if isinstance(value, (bool, int, float)):
120
+ return float(value)
121
+ if isinstance(value, str):
122
+ return value
123
+ return None
124
+
125
+
126
+ def _flatten(value: Any) -> list[tuple[str, float | str]] | None:
127
+ """Return ``(channel suffix, value)`` pairs to publish, or ``None`` if the value can't be published."""
128
+ scalar = _scalar(value)
129
+ if scalar is not None:
130
+ return [("", scalar)]
131
+ if not (isinstance(value, (list, tuple)) or getattr(value, "ndim", None) == 1):
132
+ return None
133
+ # Check the length first so long traces are skipped without converting every sample.
134
+ if not 0 < len(value) <= _MAX_SPLIT:
135
+ return None
136
+ pairs: list[tuple[str, float | str]] = []
137
+ for index, item in enumerate(value):
138
+ converted = _scalar(item)
139
+ if converted is None:
140
+ return None
141
+ pairs.append((f".{index}", converted))
142
+ return pairs
143
+
144
+
145
+ class PymeasureInstrument(Instrument, Generic[T]):
146
+ """An instro `Instrument` that publishes the traffic of a pymeasure instrument.
147
+
148
+ Every property assignment on the wrapped instrument (and its channels) publishes a
149
+ :class:`~instro.lib.types.Command` on ``<name>.<channel>.cmd``; every property read publishes a
150
+ :class:`~instro.lib.types.Measurement` on ``<name>.<channel>``. This includes property access
151
+ inside the driver's own methods, such as ``apply_voltage()``.
152
+
153
+ The pymeasure object keeps working exactly as before and stays an instance of its class: the
154
+ wrapper swaps in a generated subclass, and `close` (or `detach`) swaps the original back.
155
+ """
156
+
157
+ def __init__(
158
+ self,
159
+ name: str,
160
+ instrument: T,
161
+ publishers: list[Publisher] | None = None,
162
+ *,
163
+ channel_map: ChannelMap | dict[str, Any] | str | Path | None = None,
164
+ poll: list[str] | None = None,
165
+ device_attr: str = "device",
166
+ close_device: bool = True,
167
+ background_config: BackgroundDaemonConfig | None = None,
168
+ **kwargs: Any,
169
+ ):
170
+ """Wrap ``instrument`` so its commands and readings reach ``publishers``.
171
+
172
+ Example::
173
+
174
+ from pymeasure.instruments.keysight import KeysightE36312A
175
+ from instro.lib import FilePublisher
176
+ from instro.pymeasure import PymeasureInstrument
177
+
178
+ with PymeasureInstrument(
179
+ name="psu",
180
+ instrument=KeysightE36312A("USB0::0x2A8D::0x1102::MY123::INSTR"),
181
+ publishers=[FilePublisher(format="jsonl")],
182
+ channel_map="psu_map.json",
183
+ poll=["ch_1.voltage", "ch_1.current"],
184
+ ) as psu:
185
+ psu.device.ch_1.voltage_setpoint = 5 # publishes psu.ch1.voltage_setpoint.cmd
186
+ psu.start() # polls ch_1.voltage/current every second
187
+ print(psu.get_channel("ch1.current", wait_for_new_samples=True).latest)
188
+
189
+ Args:
190
+ name: Channel-name prefix for everything published.
191
+ instrument: The pymeasure instrument, already constructed (connected).
192
+ publishers: Publishers that receive the commands and measurements.
193
+ channel_map: Which properties publish and under which names: a `ChannelMap`, its dict
194
+ form, or the path of a JSON file from ``instro pymeasure map``. ``None`` publishes
195
+ every property under the names the inspection rules give it.
196
+ poll: Attribute paths (``"ch_1.voltage"``) the background daemon reads every
197
+ ``background_interval`` seconds once `start` is called.
198
+ device_attr: Extra attribute name for the pymeasure instrument, in addition to
199
+ ``device``; e.g. ``"smu"`` makes ``wrapper.smu`` work.
200
+ close_device: Close the pymeasure instrument's adapter in `close`. `close` doesn't call the
201
+ driver's ``shutdown()``, which on many drivers turns outputs off; call
202
+ ``device.shutdown()`` first if you want the instrument left in its safe state.
203
+ background_config: Background-daemon settings.
204
+ **kwargs: Default tags, or ``dataset_rid=`` (see `Instrument`).
205
+
206
+ Raises:
207
+ RuntimeError: ``instrument`` is already attached to another `PymeasureInstrument`.
208
+ ValueError: The channel map does not fit ``instrument``, a ``poll`` path is unknown or
209
+ not readable, or ``device_attr`` collides with an existing attribute.
210
+ """
211
+ existing = instrument.__dict__.get(_SINK_ATTR)
212
+ if existing is not None:
213
+ raise RuntimeError(
214
+ f"{type(instrument).__name__} is already attached to instro instrument '{existing.owner.name}'"
215
+ )
216
+ super().__init__(name, publishers=publishers, background_config=background_config, **kwargs)
217
+ self._device: T = instrument
218
+ self._lock = threading.RLock()
219
+ self._close_device = close_device
220
+ self._attached: list[tuple[Any, type]] = []
221
+ self._warned: set[str] = set()
222
+
223
+ specs = describe(instrument)
224
+ self._channel_names = self._load_map(channel_map).resolve(specs)
225
+ self._add_pymeasure_tags(instrument)
226
+
227
+ if device_attr != "device":
228
+ if not device_attr.isidentifier() or hasattr(self, device_attr):
229
+ raise ValueError(f"device_attr {device_attr!r} is not a free attribute name on {type(self).__name__}")
230
+ setattr(self, device_attr, instrument)
231
+
232
+ readable = {spec.path for spec in specs if spec.readable}
233
+ self._poll = list(poll or [])
234
+ for path in self._poll:
235
+ if path not in readable:
236
+ raise ValueError(f"poll path {path!r} is not a readable property of {type(instrument).__name__}")
237
+ if path not in self._channel_names:
238
+ logger.warning("poll path %r is read but not published: the channel map excludes it", path)
239
+ if self._poll:
240
+ self.add_background_daemon_function(self._poll_once)
241
+
242
+ try:
243
+ self._attach(instrument, "")
244
+ except Exception:
245
+ self.detach()
246
+ raise
247
+ logger.info(
248
+ "Attached pymeasure %s as '%s' (%d published properties)",
249
+ type(instrument).__name__,
250
+ name,
251
+ len(self._channel_names),
252
+ )
253
+
254
+ @property
255
+ def device(self) -> T:
256
+ """The wrapped pymeasure instrument; use it exactly as without instro."""
257
+ return self._device
258
+
259
+ def __enter__(self) -> PymeasureInstrument[T]:
260
+ """Return this wrapper (typed, unlike `Instrument.__enter__`) for ``with`` blocks."""
261
+ self.open()
262
+ return self
263
+
264
+ @property
265
+ def channel_map(self) -> dict[str, str]:
266
+ """Attribute path to channel name (without the instrument prefix) for every published property."""
267
+ return dict(self._channel_names)
268
+
269
+ def detach(self) -> None:
270
+ """Stop the background daemon, stop publishing, and restore the original classes. Idempotent."""
271
+ # A daemon left running would keep reading the device, through whichever recorder attaches next.
272
+ self.stop()
273
+ while self._attached:
274
+ obj, cls = self._attached.pop()
275
+ obj.__dict__.pop(_SINK_ATTR, None)
276
+ obj.__class__ = cls
277
+
278
+ def close(self) -> None:
279
+ """Stop the daemon, close the publishers, detach, and close the device if ``close_device``."""
280
+ try:
281
+ super().close()
282
+ finally:
283
+ try:
284
+ self.detach()
285
+ finally:
286
+ if self._close_device:
287
+ self._device.adapter.close()
288
+
289
+ @staticmethod
290
+ def _load_map(channel_map: ChannelMap | dict[str, Any] | str | Path | None) -> ChannelMap:
291
+ if channel_map is None:
292
+ return ChannelMap.defaults()
293
+ if isinstance(channel_map, ChannelMap):
294
+ return channel_map
295
+ if isinstance(channel_map, dict):
296
+ return ChannelMap.from_dict(channel_map)
297
+ return ChannelMap.load(channel_map)
298
+
299
+ def _add_pymeasure_tags(self, instrument: CommonBase) -> None:
300
+ for package in ("instro-pymeasure", "pymeasure"):
301
+ try:
302
+ self.default_tags.setdefault(package, version(package))
303
+ except PackageNotFoundError:
304
+ pass
305
+ self.default_tags.setdefault("pymeasure-class", original_class(type(instrument)).__name__)
306
+
307
+ def _attach(self, obj: Any, prefix: str) -> None:
308
+ cls = type(obj)
309
+ obj.__class__ = _published_class(cls)
310
+ obj.__dict__[_SINK_ATTR] = _Sink(self, prefix)
311
+ self._attached.append((obj, cls))
312
+ for attr, child in child_attributes(obj):
313
+ if child.__dict__.get(_SINK_ATTR) is None:
314
+ self._attach(child, f"{prefix}{attr}.")
315
+
316
+ def _poll_once(self) -> None:
317
+ for path in self._poll:
318
+ target: Any = self._device
319
+ for attr in path.split("."):
320
+ target = getattr(target, attr)
321
+
322
+ def _on_read(self, path: str, read: Callable[[], Any]) -> Any:
323
+ with self._lock:
324
+ value = read()
325
+ self._publish_safely(path, value, command=False)
326
+ return value
327
+
328
+ def _on_write(self, path: str, value: Any, write: Callable[[], None]) -> None:
329
+ with self._lock:
330
+ write()
331
+ self._publish_safely(path, value, command=True)
332
+
333
+ def _publish_safely(self, path: str, value: Any, *, command: bool) -> None:
334
+ name = self._channel_names.get(path)
335
+ if name is None:
336
+ return
337
+ # The instrument already acted; raising here would hide the value, or invite a retried write.
338
+ try:
339
+ self._publish_values(path, name, value, timestamp=time.time_ns(), command=command)
340
+ except Exception:
341
+ logger.exception(
342
+ "Failed to publish %s of '%s' on instrument '%s'", "write" if command else "read", path, self.name
343
+ )
344
+
345
+ def _publish_values(self, path: str, name: str, value: Any, *, timestamp: int, command: bool) -> None:
346
+ pairs = _flatten(value)
347
+ if pairs is None:
348
+ if path not in self._warned:
349
+ self._warned.add(path)
350
+ logger.warning(
351
+ "Not publishing '%s' on instrument '%s': %s values aren't publishable "
352
+ "(scalars and lists of up to %d scalars are)",
353
+ path,
354
+ self.name,
355
+ type(value).__name__,
356
+ _MAX_SPLIT,
357
+ )
358
+ return
359
+ tags = dict(self.default_tags)
360
+ if command:
361
+ self.publish(
362
+ Command(
363
+ channel_data={f"{self.name}.{name}{suffix}.cmd": item for suffix, item in pairs},
364
+ timestamp=timestamp,
365
+ tags=tags,
366
+ )
367
+ )
368
+ else:
369
+ channel_data: dict[str, list[float] | list[str]] = {}
370
+ for suffix, item in pairs:
371
+ key = f"{self.name}.{name}{suffix}"
372
+ if isinstance(item, str):
373
+ channel_data[key] = [item]
374
+ else:
375
+ channel_data[key] = [float(item)]
376
+ self.publish(Measurement(channel_data=channel_data, timestamps=[timestamp], tags=tags))
377
+
378
+
379
+ def attach(
380
+ instrument: T,
381
+ name: str,
382
+ publishers: list[Publisher] | None = None,
383
+ *,
384
+ channel_map: ChannelMap | dict[str, Any] | str | Path | None = None,
385
+ poll: list[str] | None = None,
386
+ **kwargs: Any,
387
+ ) -> PymeasureInstrument[T]:
388
+ """Start publishing an existing pymeasure instrument's traffic, without changing how it is used.
389
+
390
+ Your code keeps the pymeasure object and keeps calling it; this only adds publishing. Closing
391
+ the returned handle flushes and closes the publishers and detaches, but leaves the instrument
392
+ connected (``close_device=False``).
393
+
394
+ Example::
395
+
396
+ keithley = Keithley2400("GPIB::24") # existing code
397
+ recorder = attach(keithley, "smu", [FilePublisher(format="jsonl")])
398
+ keithley.source_voltage = 1.0 # existing code, now published
399
+ recorder.close()
400
+
401
+ Args:
402
+ instrument: The pymeasure instrument.
403
+ name: Channel-name prefix for everything published.
404
+ publishers: Publishers that receive the commands and measurements.
405
+ channel_map: See `PymeasureInstrument`.
406
+ poll: See `PymeasureInstrument`.
407
+ **kwargs: Any other `PymeasureInstrument` argument, default tags, or ``dataset_rid=``.
408
+
409
+ Returns:
410
+ The `PymeasureInstrument` doing the publishing; use it as a context manager or call ``close()``.
411
+ """
412
+ kwargs.setdefault("close_device", False)
413
+ return PymeasureInstrument(name, instrument, publishers, channel_map=channel_map, poll=poll, **kwargs)
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.5
2
+ Name: instro-pymeasure
3
+ Version: 0.1.0
4
+ Summary: Publish pymeasure instrument traffic through any instro publisher
5
+ Project-URL: Homepage, https://github.com/nominal-io/instro
6
+ Project-URL: Documentation, https://instro.nominal.io
7
+ Project-URL: Repository, https://github.com/nominal-io/instro
8
+ Project-URL: Issues, https://github.com/nominal-io/instro/issues
9
+ Project-URL: Changelog, https://github.com/nominal-io/instro/blob/main/packages/instro-pymeasure/CHANGELOG.md
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: instro,instrument-control,nominal,pymeasure,scpi,test-and-measurement
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Manufacturing
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: Python :: 3.14
24
+ Classifier: Topic :: Scientific/Engineering
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Topic :: Software Development :: Testing
27
+ Classifier: Topic :: System :: Hardware
28
+ Classifier: Topic :: System :: Hardware :: Hardware Drivers
29
+ Requires-Python: <3.15,>=3.11
30
+ Requires-Dist: instro>=1.23.0
31
+ Requires-Dist: pymeasure>=0.14
32
+ Description-Content-Type: text/markdown
33
+
34
+ # instro-pymeasure
35
+
36
+ Publish [pymeasure](https://pymeasure.readthedocs.io) instrument commands and readings through any [instro](https://github.com/nominal-io/instro) publisher. Your drivers don't change.
37
+
38
+ This package is pre-1.0: its API may change between minor releases.
39
+
40
+ Setting a property publishes a command on `<name>.<channel>.cmd`. Reading one publishes a measurement on `<name>.<channel>`.
41
+
42
+ ```bash
43
+ pip install "instro[pymeasure]"
44
+ ```
45
+
46
+ ```python
47
+ from pymeasure.instruments.keithley import Keithley2400
48
+
49
+ from instro.lib import NominalCorePublisher
50
+ from instro.pymeasure import attach
51
+
52
+ keithley = Keithley2400("GPIB::24")
53
+ recorder = attach(keithley, "smu", [NominalCorePublisher(dataset_rid="<dataset rid>")])
54
+
55
+ keithley.source_voltage = 1.0 # publishes smu.source_voltage.cmd
56
+ print(keithley.current) # publishes smu.current
57
+
58
+ recorder.close()
59
+ ```
60
+
61
+ See the [guide](https://instro.nominal.io/library/pymeasure) for `PymeasureInstrument`, channel maps and polling, and the [example notebook](https://github.com/nominal-io/instro/blob/main/examples/notebooks/pymeasure_publishing.md) for a version that runs without hardware.
@@ -0,0 +1,9 @@
1
+ instro/pymeasure/__init__.py,sha256=xjqzEo_4boW3GurcehAJbX9EZkzzRr5hhdZIHUldxnU,728
2
+ instro/pymeasure/channel_map.py,sha256=axdbhWjchnEURn0-6WFJxsBbwpzvel7XblAOhqZx8cU,12044
3
+ instro/pymeasure/cli.py,sha256=V0VnqXlDYRuJJjquC-ceKDchL2OCQykO91Z7WXoRwoY,3801
4
+ instro/pymeasure/inspection.py,sha256=6Z75jzOkfQLxzD9JEiraUioI4HICJ_KbYCZy27DCtps,6889
5
+ instro/pymeasure/wrapper.py,sha256=qkhQV8S-E8tgu9LwuFZbptD4uXSC69zEuBB14gxdCLc,17185
6
+ instro_pymeasure-0.1.0.dist-info/METADATA,sha256=H-UygqnxEnT5BWCBhBL1YHrdMw-qRSuIEX8T64oxY_0,2697
7
+ instro_pymeasure-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ instro_pymeasure-0.1.0.dist-info/licenses/LICENSE,sha256=56kVRDG5UzQJESdzBOwRd2WYg-9D9Nay_G9b1YyJyG0,11316
9
+ instro_pymeasure-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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 describing the origin of the Work and
141
+ 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 2025-2026 Nominal, Inc.
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.