thzdaq-api 0.0.6b3__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.
Files changed (57) hide show
  1. thzdaq_api/__init__.py +1 -0
  2. thzdaq_api/analysis.py +62 -0
  3. thzdaq_api/approvals.py +87 -0
  4. thzdaq_api/assistant/agents.md +202 -0
  5. thzdaq_api/assistant/assistant.md +23 -0
  6. thzdaq_api/assistant/hints.md +15 -0
  7. thzdaq_api/atomic.py +79 -0
  8. thzdaq_api/catalog.py +131 -0
  9. thzdaq_api/console.py +70 -0
  10. thzdaq_api/custom.py +326 -0
  11. thzdaq_api/daemon.py +183 -0
  12. thzdaq_api/data.py +55 -0
  13. thzdaq_api/declare.py +193 -0
  14. thzdaq_api/declaring.py +125 -0
  15. thzdaq_api/devices.py +307 -0
  16. thzdaq_api/errors.py +47 -0
  17. thzdaq_api/events.py +224 -0
  18. thzdaq_api/examples/hot_cold.py +67 -0
  19. thzdaq_api/examples/hot_cold_grid.py +74 -0
  20. thzdaq_api/examples/iv_analysis.py +34 -0
  21. thzdaq_api/examples/map.py +42 -0
  22. thzdaq_api/examples/monitor.py +35 -0
  23. thzdaq_api/examples/raw_instrument.py +37 -0
  24. thzdaq_api/examples/sweep.py +38 -0
  25. thzdaq_api/examples.py +79 -0
  26. thzdaq_api/guides.py +61 -0
  27. thzdaq_api/host.py +494 -0
  28. thzdaq_api/interpreters.py +422 -0
  29. thzdaq_api/kernel.py +137 -0
  30. thzdaq_api/lab.py +562 -0
  31. thzdaq_api/lanes.py +170 -0
  32. thzdaq_api/leases.py +29 -0
  33. thzdaq_api/lock.py +65 -0
  34. thzdaq_api/measurement_file.py +459 -0
  35. thzdaq_api/measurements.py +433 -0
  36. thzdaq_api/operation.py +52 -0
  37. thzdaq_api/origins.py +86 -0
  38. thzdaq_api/present.py +376 -0
  39. thzdaq_api/procedures.py +124 -0
  40. thzdaq_api/raw.py +272 -0
  41. thzdaq_api/remote.py +267 -0
  42. thzdaq_api/rights.py +81 -0
  43. thzdaq_api/script.py +382 -0
  44. thzdaq_api/scripts.py +133 -0
  45. thzdaq_api/sessions.py +176 -0
  46. thzdaq_api/station.py +192 -0
  47. thzdaq_api/terminal.py +66 -0
  48. thzdaq_api/tools.py +275 -0
  49. thzdaq_api/transport.py +93 -0
  50. thzdaq_api/ui.py +152 -0
  51. thzdaq_api/windows.py +192 -0
  52. thzdaq_api/wire.py +35 -0
  53. thzdaq_api/workspace.py +239 -0
  54. thzdaq_api-0.0.6b3.dist-info/METADATA +30 -0
  55. thzdaq_api-0.0.6b3.dist-info/RECORD +57 -0
  56. thzdaq_api-0.0.6b3.dist-info/WHEEL +4 -0
  57. thzdaq_api-0.0.6b3.dist-info/licenses/LICENSE +21 -0
thzdaq_api/declare.py ADDED
@@ -0,0 +1,193 @@
1
+ """Declarations at the top of a script, which make it a measurement of its own
2
+ with a form (thzdaq_api.custom): device(...) a slot, value(...) a parameter,
3
+ plot(...) a plot it fills, instrument(...) an instrument it brings into the
4
+ profile (thzdaq_api.raw: its raw commands named by reading and setting).
5
+
6
+ bias = device("SIS bias", kind="sis_bias")
7
+ voltage = value("Bias voltage", "0:7:351", unit="mV")
8
+ pv = plot("P-V", table="pv", x="voltage", y="power", group_by="load")
9
+ gauge = instrument("gauge_1", driver="generic.scpi",
10
+ connection="tcp://169.254.0.50:5025",
11
+ pressure=reading("PR1?", unit="Pa", scale=100))
12
+
13
+ Run by the daemon (Start in a window, thzdaq run custom.x), device() is the
14
+ device chosen for the slot and value() the value given, in SI. Run as it is
15
+ (python x.py), device() is the first device that suits the slot (as a form
16
+ offers it) and value() the default, which the daemon parses: the first
17
+ declaration connects to it, and connect() returns that bench. Described, they
18
+ are only noted, and the script ends with the last one.
19
+ """
20
+
21
+ import sys
22
+ from typing import Any, Iterable, Mapping, Optional, Union
23
+
24
+ from thzdaq_api.custom import (
25
+ BOOL,
26
+ DEVICE,
27
+ FLOAT,
28
+ FLOAT_LIST,
29
+ INSTRUMENT,
30
+ INT,
31
+ PLOT,
32
+ SWEEP,
33
+ VALUE,
34
+ Given,
35
+ InstrumentDeclared,
36
+ ParseValue,
37
+ SlotDeclared,
38
+ ValueDeclared,
39
+ )
40
+ from thzdaq_api.data import Measured
41
+ from thzdaq_api.declaring import STATE
42
+ from thzdaq_api.errors import ErrorCode, LabError
43
+ from thzdaq_api.lab import Bench, Device, connect
44
+ from thzdaq_api.measurements import PlotInfo, SlotInfo
45
+ from thzdaq_api.origins import agent
46
+ from thzdaq_api.raw import RawInstrument, Reading, named_values
47
+ from thzdaq_api.sessions import Swept
48
+ from thzdaq_api.station import DeclareInstrument
49
+
50
+
51
+ def _bench() -> Bench:
52
+ """The bench the declarations use: connected at the first that needs it."""
53
+ if STATE.bench is None:
54
+ STATE.bench = connect()
55
+ return STATE.bench
56
+
57
+
58
+ def _chosen(slot: SlotDeclared) -> str:
59
+ """The device of a slot run as it is: the first that suits it."""
60
+ info = SlotInfo(slot.name, slot.title, slot.capabilities, slot.kind)
61
+ suitable = [found.ref for found in info.candidates(_bench().devices())]
62
+ if not suitable:
63
+ raise LabError(
64
+ ErrorCode.NOT_FOUND,
65
+ f"No device suits {slot.name} ({slot.title})",
66
+ "add one in Setup, or name another kind in device(...)",
67
+ )
68
+ if len(suitable) > 1:
69
+ others = ", ".join(suitable[1:])
70
+ print(f"{slot.name}: {suitable[0]} (also {others})", file=sys.stderr)
71
+ return suitable[0]
72
+
73
+
74
+ def device(title: str, *capabilities: str, kind: Optional[str] = None) -> Device:
75
+ """A device the form chooses: one with the capabilities named
76
+ ("PowerDetector"), those of the kind (sis_bias) first."""
77
+ name = STATE.name(DEVICE, title, len(STATE.slots))
78
+ slot = SlotDeclared(name, title, tuple(capabilities), kind)
79
+ STATE.slots.append(slot)
80
+ STATE.declared()
81
+ if STATE.describing:
82
+ return None
83
+ given = STATE.inputs.devices.get(name) if STATE.inputs else None
84
+ return _bench()[given or _chosen(slot)]
85
+
86
+
87
+ def python_value(given: Given, title: str) -> Any:
88
+ """A value as the script uses it: a number with its unit (Measured), a
89
+ sweep for m.sweep (Swept), the rest as it is."""
90
+ if given.kind == FLOAT:
91
+ return Measured(given.value, given.unit, title)
92
+ if given.kind == INT:
93
+ return int(given.value)
94
+ if given.kind == BOOL:
95
+ return bool(given.value)
96
+ if given.kind == SWEEP:
97
+ return Swept(
98
+ given.value["start"], given.value["stop"], given.value["points"],
99
+ given.unit,
100
+ ) # fmt: skip
101
+ if given.kind == FLOAT_LIST:
102
+ return tuple(Measured(item, given.unit, title) for item in given.value)
103
+ return tuple(given.value) if isinstance(given.value, list) else given.value
104
+
105
+
106
+ def value(
107
+ title: str,
108
+ default: Any,
109
+ unit: str = "",
110
+ minimum: Optional[float] = None,
111
+ maximum: Optional[float] = None,
112
+ choices: Iterable[Any] = (),
113
+ help: str = "",
114
+ ) -> Any:
115
+ """A parameter of the form, as people type it: a number in unit (its
116
+ limits too), a sweep "start:stop:points", true/false, one of choices, a
117
+ text, a list."""
118
+ name = STATE.name(VALUE, title, len(STATE.values))
119
+ declared = ValueDeclared(
120
+ name, title, default, unit, minimum, maximum, tuple(choices), help
121
+ )
122
+ STATE.values.append(declared)
123
+ STATE.declared()
124
+ if STATE.describing:
125
+ return default
126
+ given = STATE.inputs.values.get(name) if STATE.inputs else None
127
+ if given is None:
128
+ given = _bench().lab.call(ParseValue(value=declared))
129
+ STATE.given[name] = given
130
+ return python_value(given, title)
131
+
132
+
133
+ def plot(
134
+ title: str,
135
+ table: str,
136
+ x: str,
137
+ y: str,
138
+ group_by: Union[str, Iterable[str]] = (),
139
+ kind: str = "line",
140
+ z: Optional[str] = None,
141
+ into: Optional[str] = None,
142
+ ) -> PlotInfo:
143
+ """A plot of a table the measurement fills, known before it starts;
144
+ curves by the values of group_by. into: a graph of the window (its
145
+ title) it is drawn into, when there is one of the same units; the dock
146
+ of the measurement may choose another."""
147
+ name = STATE.name(PLOT, title, len(STATE.plots))
148
+ grouped = (group_by,) if isinstance(group_by, str) else tuple(group_by)
149
+ declared = PlotInfo(
150
+ key=name, title=title, table=table, x=x, y=y, group_by=grouped,
151
+ kind=kind, z=z, into=into,
152
+ ) # fmt: skip
153
+ STATE.plots.append(declared)
154
+ STATE.declared()
155
+ return declared
156
+
157
+
158
+ def instrument(
159
+ id: str,
160
+ driver: str,
161
+ connection: Union[str, Mapping[str, Any]],
162
+ **quantities: Reading,
163
+ ) -> RawInstrument:
164
+ """An instrument of the profile by its id there, its driver
165
+ (generic.scpi: one without a driver of its own, raw commands only) and
166
+ how it is reached (tcp://169.254.0.50:5025, prologix://host/19,
167
+ serial://COM3, visa://<resource>; or the fields as the profile holds
168
+ them). Not in the profile yet, or there with another driver or
169
+ connection, it is put there once a person allows it, in the window or
170
+ in this terminal; an agent's script is refused. quantities: names of its
171
+ raw commands, reading(...) and setting(...)."""
172
+ named = named_values(quantities)
173
+ name = STATE.name(INSTRUMENT, id, len(STATE.instruments))
174
+ given = connection if isinstance(connection, str) else dict(connection)
175
+ STATE.instruments.append(InstrumentDeclared(name, id, driver, given))
176
+ STATE.declared()
177
+ if STATE.describing:
178
+ return None
179
+ bench = _bench()
180
+ declare = DeclareInstrument(instrument=id, driver=driver, connection=given)
181
+ try:
182
+ bench.approve(lambda: bench.lab.call(declare))
183
+ except LabError as e:
184
+ if e.code != ErrorCode.DENIED or not agent(bench.origin):
185
+ raise
186
+ raise LabError(
187
+ ErrorCode.DENIED,
188
+ f"{id} ({driver}) is not in the profile as declared, and an"
189
+ " agent's script does not change the profile",
190
+ "a person adds it: runs this script once, or Setup → Add"
191
+ " instrument → Generic (raw) in the ThzDAQ window",
192
+ ) from None
193
+ return RawInstrument(bench, id, named)
@@ -0,0 +1,125 @@
1
+ """What the script of this process declares at its top (thzdaq_api.declare) and
2
+ how it runs: described (the daemon learns its form), run by the daemon with
3
+ the devices and values chosen, or run as it is. A described script ends with
4
+ its last declaration (or at connect(), if it makes fewer than its text
5
+ does); connect() of a script whose declarations connected already returns
6
+ that bench.
7
+ """
8
+
9
+ import atexit
10
+ import os
11
+ import re
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import Any, Callable, Dict, List, Optional, Tuple
15
+
16
+ import msgspec
17
+
18
+ from thzdaq_api.custom import (
19
+ DESCRIBE_ENV,
20
+ INPUTS_ENV,
21
+ DeclarationError,
22
+ Declarations,
23
+ Given,
24
+ Inputs,
25
+ InstrumentDeclared,
26
+ SlotDeclared,
27
+ ValueDeclared,
28
+ declared_names,
29
+ )
30
+ from thzdaq_api.measurements import PlotInfo
31
+
32
+
33
+ def main_text() -> Optional[str]:
34
+ """The text of the script this process runs; None without a file (a
35
+ notebook, the interpreter's prompt)."""
36
+ path = getattr(sys.modules["__main__"], "__file__", None)
37
+ return Path(path).read_text(encoding="utf-8") if path else None
38
+
39
+
40
+ def slug(title: str) -> str:
41
+ """ "Bias voltage" -> bias_voltage: a name where the text names none."""
42
+ return re.sub(r"\W+", "_", title.strip().lower()).strip("_") or "value"
43
+
44
+
45
+ class Declaring:
46
+ def __init__(
47
+ self,
48
+ describe: Optional[str] = None,
49
+ inputs: Optional[Inputs] = None,
50
+ text: Callable[[], Optional[str]] = main_text,
51
+ ):
52
+ """describe: the file the declarations are written into (the script
53
+ is described); inputs: what a run by the daemon was given; text: the
54
+ script's, which names the declarations (read at the first one)."""
55
+ self.describe = describe
56
+ self.inputs = inputs
57
+ self.text = text
58
+ self.slots: List[SlotDeclared] = []
59
+ self.values: List[ValueDeclared] = []
60
+ self.plots: List[PlotInfo] = []
61
+ self.instruments: List[InstrumentDeclared] = []
62
+ self.given: Dict[str, Given] = {} # the values, as given or parsed
63
+ self.bench: Any = None # the bench the declarations connected to
64
+ self._names: Optional[Tuple[Tuple[str, str], ...]] = None
65
+ self._named = False # a text names them
66
+ if describe:
67
+ atexit.register(self.write) # a script that never connects
68
+
69
+ @classmethod
70
+ def of_process(cls) -> "Declaring":
71
+ given = os.environ.get(INPUTS_ENV)
72
+ return cls(
73
+ os.environ.get(DESCRIBE_ENV) or None,
74
+ msgspec.json.decode(given, type=Inputs) if given else None,
75
+ )
76
+
77
+ @property
78
+ def describing(self) -> bool:
79
+ return self.describe is not None
80
+
81
+ def name(self, declaration: str, title: str, made: int) -> str:
82
+ """The name of the declaration made as the made-th of its kind: the
83
+ name the text assigns it to; without a text, one from its title."""
84
+ if self._names is None:
85
+ text = self.text()
86
+ self._names = () if text is None else declared_names(text)
87
+ self._named = text is not None
88
+ if not self._named:
89
+ return slug(title)
90
+ names = [name for kind, name in self._names if kind == declaration]
91
+ if made >= len(names):
92
+ raise DeclarationError(
93
+ f"{declaration}({title!r}) is not at the top of the file:"
94
+ " declare each once, assigned to a name, before connect()"
95
+ )
96
+ return names[made]
97
+
98
+ def declared(self) -> None:
99
+ """After each declaration: a described script ends with its last one,
100
+ before anything else it does."""
101
+ made = sum(map(len, (self.slots, self.values, self.plots, self.instruments)))
102
+ if self.describing and self._named and made >= len(self._names):
103
+ self.described()
104
+
105
+ def declarations(self) -> Declarations:
106
+ return Declarations(
107
+ tuple(self.slots),
108
+ tuple(self.values),
109
+ tuple(self.plots),
110
+ tuple(self.instruments),
111
+ )
112
+
113
+ def write(self) -> None:
114
+ """The declarations into the file the daemon reads."""
115
+ if self.describe is not None:
116
+ Path(self.describe).write_bytes(msgspec.json.encode(self.declarations()))
117
+
118
+ def described(self) -> None:
119
+ """A described script's form is known (its last declaration, or
120
+ connect()): it ends before it touches the bench."""
121
+ self.write()
122
+ raise SystemExit(0)
123
+
124
+
125
+ STATE = Declaring.of_process() # this process's script
thzdaq_api/devices.py ADDED
@@ -0,0 +1,307 @@
1
+ """Devices of the bench: what they are, what they read and what can be set."""
2
+
3
+ import math
4
+ from typing import Dict, Optional, Sequence, Tuple, Union
5
+
6
+ import msgspec
7
+
8
+ from thzdaq_api.operation import Operation, Rights
9
+
10
+ Value = Union[bool, int, float, str, None]
11
+
12
+ # Kinds of devices nobody configures: an instrument and its fixed channel
13
+ INSTRUMENT = "instrument"
14
+ CHANNEL = "channel"
15
+
16
+ # Axes of traces: the power of a spectrum, the magnitude of an S-parameter
17
+ POWER_DBM = "Power, dBm"
18
+ S_DB = "|S|, dB"
19
+
20
+
21
+ class Prefix(msgspec.Struct, frozen=True):
22
+ """An SI prefix a value is shown and typed in: ("G", 1e9, "×10⁹")."""
23
+
24
+ name: str
25
+ factor: float
26
+ note: str
27
+
28
+
29
+ def shown(value: Value, unit: str = "", prefixes: Sequence[Prefix] = ()) -> str:
30
+ """A value as people read it: an SI number with the prefix that keeps it
31
+ from 1 to 999 ("2.3 mV"), a switch as on or off. The daemon reads it back
32
+ in a text with its unit."""
33
+ if value is None:
34
+ return "--"
35
+ if isinstance(value, bool):
36
+ return "on" if value else "off"
37
+ if not isinstance(value, (int, float)):
38
+ return f"{value} {unit}".strip()
39
+ if not prefixes or value == 0 or not math.isfinite(value):
40
+ return f"{value:.6g} {unit}".strip()
41
+ ascending = sorted(prefixes, key=lambda p: p.factor)
42
+ prefix = next(
43
+ (p for p in reversed(ascending) if abs(value) >= p.factor), ascending[0]
44
+ )
45
+ return f"{value / prefix.factor:.6g} {prefix.name}{unit}"
46
+
47
+
48
+ class QuantityInfo(msgspec.Struct, frozen=True):
49
+ """A value a device reads or takes, in SI units (power in dBm, angles in deg).
50
+ minimum and maximum bound what it takes: its own range, the passport of the
51
+ instrument and the bench limits together."""
52
+
53
+ key: str
54
+ title: str
55
+ unit: str = ""
56
+ kind: str = "float" # float, int, bool or text
57
+ readable: bool = True
58
+ settable: bool = False
59
+ persistent: bool = False # configuration of the instrument, kept in the profile
60
+ minimum: Optional[float] = None
61
+ maximum: Optional[float] = None
62
+ choices: Tuple[str, ...] = () # the values a text quantity takes
63
+ # A soft range of the bench inside minimum..maximum: beyond it, ask first
64
+ warn_minimum: Optional[float] = None
65
+ warn_maximum: Optional[float] = None
66
+ step: Optional[float] = None # the largest change in one command: more in steps
67
+ rate: Optional[float] = None # units per second at most between the steps
68
+ danger: str = "" # what may go wrong when it is set, shown first; empty when safe
69
+ prefixes: Tuple[Prefix, ...] = () # to show it in; none for dBm, dB, deg
70
+
71
+ @property
72
+ def label(self) -> str:
73
+ """As a form names it: "Power, dBm"."""
74
+ return f"{self.title}, {self.unit}" if self.unit else self.title
75
+
76
+
77
+ class DeviceInfo(msgspec.Struct, frozen=True):
78
+ """A device: an instrument, its fixed channel or a device configured on it."""
79
+
80
+ ref: str # the id measurements and operations name it by
81
+ title: str
82
+ instrument: str # the instrument it is or belongs to
83
+ driver: str # of that instrument, as the profile names it
84
+ kind: str # instrument, channel, or the configured kind (sis_bias)
85
+ type: str # what device it is: the configured kind, else the instrument's type
86
+ capabilities: Tuple[str, ...]
87
+ channel: Optional[str] = None
88
+ configured: bool = False
89
+ raw: bool = False # its instrument takes raw commands (raw_command)
90
+
91
+
92
+ class ArgumentInfo(msgspec.Struct, frozen=True):
93
+ """An argument of an action, in SI units; without a default it is required."""
94
+
95
+ key: str
96
+ title: str
97
+ unit: str = ""
98
+ kind: str = "float" # float, int, bool or text
99
+ default: Value = None
100
+ minimum: Optional[float] = None
101
+ maximum: Optional[float] = None
102
+ choices: Tuple[str, ...] = ()
103
+ prefixes: Tuple[Prefix, ...] = ()
104
+
105
+
106
+ class ActionInfo(msgspec.Struct, frozen=True):
107
+ """What a device does on request beyond setting a quantity (turn to the hot
108
+ load, read a trace)."""
109
+
110
+ key: str
111
+ title: str
112
+ arguments: Tuple[ArgumentInfo, ...] = ()
113
+ danger: str = "" # what may go wrong, shown before it runs; empty when safe
114
+ changes: bool = True # false for a read: a running measurement is not disturbed
115
+ help: str = ""
116
+
117
+
118
+ class DeviceDescription(msgspec.Struct, frozen=True):
119
+ device: DeviceInfo
120
+ quantities: Tuple[QuantityInfo, ...]
121
+ actions: Tuple[ActionInfo, ...] = ()
122
+ # What a configured device keeps in the profile (a SIS bias's offsets)
123
+ settings: Tuple[QuantityInfo, ...] = ()
124
+
125
+
126
+ class Trace(msgspec.Struct, frozen=True):
127
+ """A trace versus frequency (Hz): the power (dBm) of a spectrum analyzer, or
128
+ the complex S-parameter of a network analyzer as real and imaginary parts."""
129
+
130
+ frequency: Tuple[float, ...]
131
+ values: Tuple[float, ...] # dBm, or the real part
132
+ imaginary: Optional[Tuple[float, ...]] = None
133
+ parameter: str = "" # S21
134
+
135
+ def label(self) -> str:
136
+ """The axis of its values: the power, or the magnitude in dB."""
137
+ return POWER_DBM if self.imaginary is None else S_DB
138
+
139
+
140
+ class Reading(msgspec.Struct, frozen=True):
141
+ ref: str
142
+ values: Dict[str, Value]
143
+
144
+
145
+ class QuantityValue(msgspec.Struct, frozen=True):
146
+ ref: str
147
+ key: str
148
+ value: Value
149
+
150
+
151
+ class ActionResult(msgspec.Struct, frozen=True):
152
+ ref: str
153
+ action: str
154
+ result: Union[Value, Trace] = None
155
+
156
+
157
+ class SafeValue(msgspec.Struct, frozen=True):
158
+ """A value of the safe state as it went: set, or why not."""
159
+
160
+ ref: str
161
+ key: str
162
+ value: Value
163
+ error: str = "" # empty when it was set
164
+
165
+
166
+ class Poll(msgspec.Struct, frozen=True):
167
+ id: int # to cancel it
168
+ ref: str
169
+ interval: float
170
+
171
+
172
+ # Raw commands: what a driver does not wrap yet, sent as typed
173
+ QUERY_MARK = "?" # in a command that asks and changes nothing
174
+ UNCHECKED = "Limits and the bench protection do not check a raw command"
175
+
176
+
177
+ def raw_query(command: str) -> bool:
178
+ """A raw command that asks and changes nothing: it has a ?. Any other is a
179
+ write, also one whose answer is read."""
180
+ return QUERY_MARK in command
181
+
182
+
183
+ def raw_question(instrument: str, command: str) -> str:
184
+ """What a person confirms before a raw write."""
185
+ return f"{UNCHECKED}. Send {command!r} to {instrument}?"
186
+
187
+
188
+ class RawReply(msgspec.Struct, frozen=True):
189
+ """What a raw command got: the instrument's answer (None when none was
190
+ read) and, after a write, the devices whose values are unknown until
191
+ they are read again."""
192
+
193
+ instrument: str
194
+ command: str
195
+ answer: Optional[str] = None
196
+ unknown: Tuple[str, ...] = ()
197
+
198
+
199
+ class ListDevices(Operation[Tuple[DeviceInfo, ...]]):
200
+ """Every device of the bench: its instruments, their fixed channels and the
201
+ devices configured on them (a SIS bias on a SIS block)."""
202
+
203
+
204
+ class DescribeDevice(Operation[DeviceDescription]):
205
+ """A device with its quantities: what it reads and what can be set, with
206
+ units and limits."""
207
+
208
+ ref: str
209
+
210
+
211
+ class ReadDevice(Operation[Reading]):
212
+ """Read a device: every readable quantity, or the listed keys. Values are
213
+ in SI units (power in dBm). session: the number of the script's session the
214
+ read belongs to (the device joins it)."""
215
+
216
+ ref: str
217
+ keys: Optional[Tuple[str, ...]] = None
218
+ session: Optional[int] = None
219
+
220
+
221
+ class SetQuantity(Operation[QuantityValue]):
222
+ """Set a quantity of a device. A number is in SI units; a text may carry
223
+ its unit ("2.3mV", "223 GHz"); switches take true or false. Returns the
224
+ value set, in SI units. A value outside the limits of the device is refused
225
+ (out_of_limits) before anything is sent; a change larger than the bench
226
+ step goes in steps at the bench rate. A device a running measurement sweeps
227
+ is refused (conflict) unless share is true; the measurements using it
228
+ record the change. session: the number of the script's session the set
229
+ belongs to: its devices are its own, and the session tells what it sets."""
230
+
231
+ rights = Rights.SET
232
+ ref: str
233
+ key: str
234
+ value: Union[bool, int, float, str]
235
+ share: bool = False
236
+ session: Optional[int] = None
237
+
238
+
239
+ class CallAction(Operation[ActionResult]):
240
+ """Make a device do something beyond setting a quantity: turn the load to
241
+ hot or cold, start or stop the chopper rotation, set up an analyzer and read
242
+ its trace. describe_device lists the actions of a device with their
243
+ arguments; numbers are in SI units, a text may carry its unit ("12 Hz"). A
244
+ device a running measurement sweeps is refused (conflict) unless share is
245
+ true, except for reads; the measurements using it record the call.
246
+ session: the number of the script's session the call belongs to."""
247
+
248
+ rights = Rights.SET
249
+ ref: str
250
+ action: str
251
+ arguments: Dict[str, Union[bool, int, float, str]] = msgspec.field(
252
+ default_factory=dict
253
+ )
254
+ share: bool = False
255
+ session: Optional[int] = None
256
+
257
+
258
+ class RawCommand(Operation[RawReply]):
259
+ """Send an instrument a command as it is typed, for what its driver does
260
+ not wrap yet; instrument is its id in the profile (get_station), not a
261
+ device on it. A command with ? is a query: its answer is read and
262
+ returned. Any other is a write that neither the limits nor the bench
263
+ protection check: a person confirms it, a script needs a person's yes or
264
+ allow raw:<instrument> at its start, agents may never write. answer: read
265
+ the answer of a write too (a query without ?). The command waits its turn
266
+ in the instrument's lane and holds its link, so measurements and polls go
267
+ on. A write to an instrument a device of which a running measurement
268
+ sweeps is refused (conflict) unless share is true; the measurements using
269
+ its devices record it, and its devices are read again. session: the
270
+ number of the script's session the command belongs to."""
271
+
272
+ rights = Rights.RAW_WRITE
273
+ instrument: str
274
+ command: str
275
+ answer: bool = False
276
+ share: bool = False
277
+ session: Optional[int] = None
278
+
279
+ @property
280
+ def query(self) -> bool:
281
+ return raw_query(self.command)
282
+
283
+
284
+ class SafeState(Operation[Tuple[SafeValue, ...]]):
285
+ """Set every device of the profile's safe state to its safe value, in steps
286
+ where the bench limits ask for them. A device that fails, or that a running
287
+ measurement sweeps (unless share is true), does not stop the others: each
288
+ value says how it went."""
289
+
290
+ rights = Rights.STOP
291
+ share: bool = False
292
+
293
+
294
+ class SubscribePoll(Operation[Poll]):
295
+ """Read a device every `interval` seconds (all readable quantities, or the
296
+ listed keys); readings come as values events. The daemon polls a device
297
+ once, at the shortest interval its subscribers ask for."""
298
+
299
+ ref: str
300
+ interval: float
301
+ keys: Optional[Tuple[str, ...]] = None
302
+
303
+
304
+ class CancelPoll(Operation[None]):
305
+ """Stop a poll started by subscribe_poll."""
306
+
307
+ id: int
thzdaq_api/errors.py ADDED
@@ -0,0 +1,47 @@
1
+ """How an operation fails: a code clients act on, a message people read, a hint."""
2
+
3
+ from enum import Enum
4
+
5
+ import msgspec
6
+
7
+
8
+ class ErrorCode(str, Enum):
9
+ INVALID_ARGUMENTS = "invalid_arguments" # the arguments do not fit the operation
10
+ UNKNOWN_OPERATION = "unknown_operation"
11
+ NOT_FOUND = "not_found" # no such device, quantity, measurement
12
+ NOT_ALLOWED = "not_allowed" # the operation does not apply: a read-only value
13
+ INSTRUMENT = "instrument" # the instrument failed or did not answer
14
+ # Outside the passport of the instrument or the bench limits: nothing was sent
15
+ OUT_OF_LIMITS = "out_of_limits"
16
+ CONFLICT = "conflict" # a device in exclusive use: repeat with share to go on
17
+ DENIED = "denied" # a person said no, or the caller may not do it: read why
18
+ INTERNAL = "internal" # a fault of the daemon: its log has the details
19
+ UNREACHABLE = "unreachable" # no daemon answers: not running, or gone
20
+ UNAUTHORIZED = "unauthorized" # the token is not this daemon's (a stale host file)
21
+ WRONG_VERSION = "wrong_version" # the daemon speaks another version of the contract
22
+
23
+
24
+ class Failure(msgspec.Struct, frozen=True):
25
+ """A failed operation as it travels."""
26
+
27
+ code: ErrorCode
28
+ message: str
29
+ hint: str = ""
30
+
31
+
32
+ class LabError(Exception):
33
+ def __init__(self, code: ErrorCode, message: str, hint: str = ""):
34
+ super().__init__(message)
35
+ self.code = code
36
+ self.message = message
37
+ self.hint = hint
38
+
39
+ def failure(self) -> Failure:
40
+ return Failure(self.code, self.message, self.hint)
41
+
42
+ @classmethod
43
+ def from_failure(cls, failure: Failure) -> "LabError":
44
+ return cls(failure.code, failure.message, failure.hint)
45
+
46
+ def __str__(self) -> str:
47
+ return f"{self.message} ({self.hint})" if self.hint else self.message