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/events.py ADDED
@@ -0,0 +1,224 @@
1
+ """What the bench tells its clients as it happens, numbered.
2
+
3
+ A client takes a snapshot (GetSnapshot: the values known now and the number of
4
+ the last event), then listens from that number; one that fell behind the
5
+ daemon's buffer gets Resync and takes a new snapshot.
6
+ """
7
+
8
+ from typing import Any, Dict, Optional, Tuple, Union
9
+
10
+ import msgspec
11
+
12
+ from thzdaq_api.approvals import Answer, Approval
13
+ from thzdaq_api.devices import Value
14
+ from thzdaq_api.leases import LeaseInfo
15
+ from thzdaq_api.measurements import PlotInfo, ProcedureSummary, RunInfo
16
+ from thzdaq_api.operation import Operation
17
+ from thzdaq_api.scripts import ScriptInfo
18
+
19
+
20
+ class QuantitySet(msgspec.Struct, tag="quantity_set", frozen=True):
21
+ """A quantity was set: by whom, from what (if known) to what."""
22
+
23
+ ref: str
24
+ key: str
25
+ value: Value
26
+ before: Value = None
27
+ origin: str = ""
28
+
29
+
30
+ class ActionDone(msgspec.Struct, tag="action_done", frozen=True):
31
+ """A device did an action (turned to the hot load): by whom, with what."""
32
+
33
+ ref: str
34
+ action: str
35
+ arguments: Dict[str, Value]
36
+ origin: str = ""
37
+
38
+
39
+ class RawSent(msgspec.Struct, tag="raw_sent", frozen=True):
40
+ """A raw command went to an instrument: by whom, what it answered. After a
41
+ write the values of the devices in unknown are unknown; values events
42
+ follow as they are read again."""
43
+
44
+ instrument: str
45
+ command: str
46
+ answer: Optional[str] = None
47
+ unknown: Tuple[str, ...] = ()
48
+ origin: str = ""
49
+
50
+
51
+ class Values(msgspec.Struct, tag="values", frozen=True):
52
+ """Readings of a polled device."""
53
+
54
+ ref: str
55
+ values: Dict[str, Value]
56
+
57
+
58
+ class ReadFailed(msgspec.Struct, tag="read_failed", frozen=True):
59
+ """A polled device did not answer or failed."""
60
+
61
+ ref: str
62
+ message: str
63
+
64
+
65
+ class MeasurementStarted(msgspec.Struct, tag="measurement_started", frozen=True):
66
+ """A measurement started; plots: those it will fill, to show at once."""
67
+
68
+ run: RunInfo
69
+ plots: Tuple[PlotInfo, ...]
70
+
71
+
72
+ class MeasurementRecords(msgspec.Struct, tag="measurement_records", frozen=True):
73
+ """Records of a running measurement, a few at a time. Values are encoded as
74
+ in measurement files: thzdaq_api.data.decode_values gives them back."""
75
+
76
+ id: int
77
+ table: str
78
+ rows: Tuple[Dict[str, Any], ...]
79
+
80
+
81
+ class MeasurementProgress(msgspec.Struct, tag="measurement_progress", frozen=True):
82
+ id: int
83
+ done: int
84
+ total: Union[int, None] = None
85
+
86
+
87
+ class MeasurementLog(msgspec.Struct, tag="measurement_log", frozen=True):
88
+ id: int
89
+ message: str
90
+
91
+
92
+ class MeasurementPlotted(msgspec.Struct, tag="measurement_plotted", frozen=True):
93
+ """A running measurement draws another plot from now on (a script's)."""
94
+
95
+ id: int
96
+ plot: PlotInfo
97
+
98
+
99
+ class MeasurementFinished(msgspec.Struct, tag="measurement_finished", frozen=True):
100
+ run: RunInfo
101
+
102
+
103
+ class ScriptStarted(msgspec.Struct, tag="script_started", frozen=True):
104
+ """The daemon started a script (thzdaq script start, Run in a window)."""
105
+
106
+ script: ScriptInfo
107
+
108
+
109
+ class ScriptOutput(msgspec.Struct, tag="script_output", frozen=True):
110
+ """What a running script printed lately: the bytes since..next of its log.
111
+ A client that came later reads the log up to since first (ReadScriptLog)."""
112
+
113
+ id: int
114
+ text: str
115
+ since: int
116
+ next: int
117
+
118
+
119
+ class ScriptEnded(msgspec.Struct, tag="script_ended", frozen=True):
120
+ """A script ended: by itself (exited, with its exit code) or stopped. Its
121
+ output came before."""
122
+
123
+ script: ScriptInfo
124
+
125
+
126
+ class ProceduresChanged(msgspec.Struct, tag="procedures_changed", frozen=True):
127
+ """The procedures the bench runs changed: a measurement of its own was
128
+ added, saved, removed or described anew. procedures: all of them now."""
129
+
130
+ procedures: Tuple[ProcedureSummary, ...]
131
+
132
+
133
+ class StationChanged(msgspec.Struct, tag="station_changed", frozen=True):
134
+ """The profile changed (edited, or another loaded): devices may differ."""
135
+
136
+ name: str
137
+ path: Union[str, None]
138
+
139
+
140
+ class LeasesChanged(msgspec.Struct, tag="leases_changed", frozen=True):
141
+ """A measurement took or gave back its devices: every lease now."""
142
+
143
+ leases: Tuple[LeaseInfo, ...]
144
+
145
+
146
+ class ApprovalRequested(msgspec.Struct, tag="approval_requested", frozen=True):
147
+ """Something waits for a person: an agent's operation, or its question."""
148
+
149
+ approval: Approval
150
+
151
+
152
+ class ApprovalAnswered(msgspec.Struct, tag="approval_answered", frozen=True):
153
+ """What waited is answered (by "timeout" when nobody did): it is gone."""
154
+
155
+ id: int
156
+ answer: Answer
157
+
158
+
159
+ class UiRequested(msgspec.Struct, tag="ui_requested", frozen=True):
160
+ """An agent asks one window (by its id) to do an operation of thzdaq_api.ui,
161
+ its arguments as JSON; the window answers it with answer_ui."""
162
+
163
+ id: int
164
+ window: str
165
+ operation: str
166
+ arguments: Dict[str, Any]
167
+ origin: str = ""
168
+
169
+
170
+ class Resync(msgspec.Struct, tag="resync", frozen=True):
171
+ """Events were lost: take a new snapshot."""
172
+
173
+
174
+ Body = Union[
175
+ QuantitySet,
176
+ ActionDone,
177
+ RawSent,
178
+ Values,
179
+ ReadFailed,
180
+ MeasurementStarted,
181
+ MeasurementRecords,
182
+ MeasurementProgress,
183
+ MeasurementLog,
184
+ MeasurementPlotted,
185
+ MeasurementFinished,
186
+ ScriptStarted,
187
+ ScriptOutput,
188
+ ScriptEnded,
189
+ ProceduresChanged,
190
+ StationChanged,
191
+ LeasesChanged,
192
+ ApprovalRequested,
193
+ ApprovalAnswered,
194
+ UiRequested,
195
+ Resync,
196
+ ]
197
+
198
+
199
+ def run_id(body: Body) -> Optional[int]:
200
+ """The number of the measurement an event tells about; None for another."""
201
+ if isinstance(body, (MeasurementStarted, MeasurementFinished)):
202
+ return body.run.id
203
+ if isinstance(
204
+ body,
205
+ (MeasurementRecords, MeasurementProgress, MeasurementLog, MeasurementPlotted),
206
+ ):
207
+ return body.id
208
+ return None
209
+
210
+
211
+ class Event(msgspec.Struct, frozen=True):
212
+ seq: int
213
+ at: str # wall time, ISO
214
+ body: Body
215
+
216
+
217
+ class Snapshot(msgspec.Struct, frozen=True):
218
+ seq: int # the last event it includes; listen from here
219
+ values: Dict[str, Dict[str, Value]] # last known values by device and key
220
+
221
+
222
+ class GetSnapshot(Operation[Snapshot]):
223
+ """What the bench knows now (the last values of every device read or set)
224
+ and the number of the last event, to listen from."""
@@ -0,0 +1,67 @@
1
+ """Hot/cold P-V: Y-factor and noise temperature against bias.
2
+
3
+ IF power against bias on the hot and the cold load: the chopper turns to
4
+ each load in turn and the bias is swept on each. The table "pv" holds both
5
+ sweeps, "y_factor" what follows from them. The bias goes back and the cold
6
+ load is set however the measurement ends. Needs the analysis package
7
+ (thzdaq[analysis]; the program has it).
8
+ """
9
+
10
+ import math
11
+
12
+ from thzdaq import connect, device, plot, value
13
+ from thzdaq_analysis.noise import match_hot_cold, noise_temperature
14
+
15
+ bias = device("SIS bias", kind="sis_bias")
16
+ detector = device("Detector", "PowerDetector")
17
+ load = device("Load", "LoadSwitch") # turns to the hot or the cold load
18
+ voltage = value("Bias voltage", "0:7:351", unit="mV")
19
+ t_hot = value("Hot load", 300, unit="K")
20
+ t_cold = value("Cold load", 77, unit="K")
21
+ load_settle = value("Load settle", 2, unit="s", help="after the load turns")
22
+ settle = value("Settle", 10, unit="ms", help="after each bias step")
23
+ pv = plot("P-V", table="pv", x="voltage", y="power", group_by="load")
24
+ tn = plot("Tn-V", table="y_factor", x="voltage", y="noise_temperature")
25
+
26
+ lab = connect()
27
+ with lab.measurement(
28
+ "pv_hot_cold",
29
+ devices=[bias, detector, load],
30
+ exclusive=[bias],
31
+ total=2 * voltage.points,
32
+ ) as m:
33
+ m.restore(bias, "voltage_set")
34
+ m.on_exit(load, "to_cold") # the daemon turns to the cold load at the end
35
+ sweeps = {}
36
+ for state in ("hot", "cold"):
37
+ getattr(load, f"to_{state}")()
38
+ m.sleep(load_settle)
39
+ points = []
40
+ for v in m.sweep(voltage):
41
+ bias.voltage_set = v
42
+ m.sleep(settle)
43
+ reading = bias.read()
44
+ power = detector.power
45
+ m.record(
46
+ "pv",
47
+ load=state,
48
+ voltage_set=v,
49
+ voltage=reading.voltage,
50
+ current=reading.current,
51
+ power=power,
52
+ )
53
+ points.append((reading.voltage, power))
54
+ m.progress()
55
+ sweeps[state] = points
56
+ best = math.inf
57
+ for v, hot, cold in match_hot_cold(sweeps["hot"], sweeps["cold"]):
58
+ temperature = noise_temperature(hot, cold, t_hot, t_cold)
59
+ m.record(
60
+ "y_factor", voltage=v, y_factor=hot - cold, noise_temperature=temperature
61
+ )
62
+ if temperature < best: # NaN where there is no contrast: never the best
63
+ best, best_voltage = temperature, v
64
+
65
+ if math.isfinite(best):
66
+ print(f"Tn {best:.1f} K at {best_voltage * 1e3:.3f} mV")
67
+ print(f"#{m.run.id} {m.run.status}: {m.run.path}")
@@ -0,0 +1,74 @@
1
+ """Hot/cold P-V over the grid's angles: Y-factor and Tn at each angle.
2
+
3
+ At each angle of the wire grid the chopper turns to the hot and the cold
4
+ load and the bias is swept on each, as in hot_cold. The table "pv" holds
5
+ every sweep with its angle and load, "y_factor" what follows at each angle.
6
+ The bias and the grid go back and the cold load is set however the
7
+ measurement ends. Needs the analysis package (thzdaq[analysis]; the program
8
+ has it).
9
+ """
10
+
11
+ from thzdaq import connect, device, plot, value
12
+ from thzdaq_analysis.noise import match_hot_cold, noise_temperature
13
+
14
+ bias = device("SIS bias", kind="sis_bias")
15
+ detector = device("Detector", "PowerDetector")
16
+ load = device("Load", "LoadSwitch") # turns to the hot or the cold load
17
+ grid = device("Grid", "Rotator")
18
+ voltage = value("Bias voltage", "0:7:351", unit="mV")
19
+ angle = value("Grid angle", "0:90:10", unit="deg")
20
+ t_hot = value("Hot load", 300, unit="K")
21
+ t_cold = value("Cold load", 77, unit="K")
22
+ grid_settle = value("Grid settle", 1, unit="s", help="after the grid turns")
23
+ load_settle = value("Load settle", 2, unit="s", help="after the load turns")
24
+ settle = value("Settle", 10, unit="ms", help="after each bias step")
25
+ pv = plot("P-V", table="pv", x="voltage", y="power", group_by=("angle", "load"))
26
+ tn = plot(
27
+ "Tn-V", table="y_factor", x="voltage", y="noise_temperature", group_by="angle"
28
+ )
29
+
30
+ lab = connect()
31
+ with lab.measurement(
32
+ "pv_hot_cold_grid",
33
+ devices=[bias, detector, load, grid],
34
+ exclusive=[bias, grid],
35
+ total=angle.points * 2 * voltage.points,
36
+ ) as m:
37
+ m.restore(bias, "voltage_set")
38
+ m.restore(grid, "angle")
39
+ m.on_exit(load, "to_cold") # the daemon turns to the cold load at the end
40
+ for a in m.sweep(angle):
41
+ grid.angle = a
42
+ m.sleep(grid_settle)
43
+ sweeps = {}
44
+ for state in ("hot", "cold"):
45
+ getattr(load, f"to_{state}")()
46
+ m.sleep(load_settle)
47
+ points = []
48
+ for v in m.sweep(voltage):
49
+ bias.voltage_set = v
50
+ m.sleep(settle)
51
+ reading = bias.read()
52
+ power = detector.power
53
+ m.record(
54
+ "pv",
55
+ angle=a,
56
+ load=state,
57
+ voltage_set=v,
58
+ voltage=reading.voltage,
59
+ current=reading.current,
60
+ power=power,
61
+ )
62
+ points.append((reading.voltage, power))
63
+ m.progress()
64
+ sweeps[state] = points
65
+ for v, hot, cold in match_hot_cold(sweeps["hot"], sweeps["cold"]):
66
+ m.record(
67
+ "y_factor",
68
+ angle=a,
69
+ voltage=v,
70
+ y_factor=hot - cold,
71
+ noise_temperature=noise_temperature(hot, cold, t_hot, t_cold),
72
+ )
73
+
74
+ print(f"#{m.run.id} {m.run.status}: {m.run.path}")
@@ -0,0 +1,34 @@
1
+ """I-V curve and analysis: a built-in procedure, then your numbers.
2
+
3
+ Runs the SIS I-V curve as its dock would (sis.current_vs_voltage), waits for it and
4
+ works on its table here: the normal resistance from a line fitted above the
5
+ gap, the gap voltage where the current rises fastest. Put your analysis in
6
+ their place; the measurement keeps its data either way.
7
+ """
8
+
9
+ import numpy as np
10
+
11
+ from thzdaq import connect, device, value
12
+
13
+ bias = device("SIS bias", kind="sis_bias")
14
+ voltage = value("Bias voltage", "0:7:351", unit="mV")
15
+ above_gap = value("Fit above", 4, unit="mV", help="Rn is fitted above this bias")
16
+
17
+ lab = connect()
18
+ run = lab.run("sis.current_vs_voltage", bias=bias, voltage=voltage)
19
+ print(f"#{run.id} {run.info.title} started")
20
+ ended = run.wait(progress=False)
21
+ if ended.status != "completed":
22
+ raise SystemExit(f"#{run.id} {ended.status}: {ended.error or 'no analysis'}")
23
+
24
+ iv = run.table("iv")
25
+ measured = np.asarray(iv["voltage"], dtype=float) # V
26
+ current = np.asarray(iv["current"], dtype=float) # A
27
+ above = measured > above_gap
28
+ slope, _ = np.polyfit(measured[above], current[above], 1)
29
+ rise = np.gradient(current, measured)
30
+ gap = measured[int(np.nanargmax(rise))]
31
+
32
+ print(f"Rn = {1 / slope:.2f} Ohm (above {above_gap * 1e3:g} mV)")
33
+ print(f"Vgap = {gap * 1e3:.3f} mV")
34
+ print(f"#{run.id}: {ended.path}")
@@ -0,0 +1,42 @@
1
+ """Map: IF power over the SIS bias and its coil current.
2
+
3
+ The coil current goes over a range; at each the bias is swept, a record of
4
+ the table "map" per point, drawn as a map as it goes. The bias and the coil
5
+ go back to where they were however the measurement ends.
6
+ """
7
+
8
+ from thzdaq import connect, device, plot, value
9
+
10
+ bias = device("SIS bias", kind="sis_bias")
11
+ coil = device("SIS coil", kind="sis_coil")
12
+ detector = device("Detector", "PowerDetector")
13
+ voltage = value("Bias voltage", "0:7:71", unit="mV")
14
+ current = value("Coil current", "0:20:11", unit="mA")
15
+ settle = value("Settle", 10, unit="ms", help="after each step")
16
+ power = plot(
17
+ "P(V, I coil)", table="map", x="voltage", y="coil_current", z="power",
18
+ kind="map",
19
+ ) # fmt: skip
20
+
21
+ lab = connect()
22
+ with lab.measurement(
23
+ "map",
24
+ devices=[bias, coil, detector],
25
+ exclusive=[bias, coil],
26
+ total=voltage.points * current.points,
27
+ ) as m:
28
+ m.restore(bias, "voltage_set")
29
+ m.restore(coil, "current_set")
30
+ for i in m.sweep(current):
31
+ coil.current_set = i
32
+ m.sleep(settle)
33
+ for v in m.sweep(voltage):
34
+ bias.voltage_set = v
35
+ m.sleep(settle)
36
+ m.record(
37
+ "map", coil_current=i, voltage=bias.read().voltage,
38
+ power=detector.power,
39
+ ) # fmt: skip
40
+ m.progress()
41
+
42
+ print(f"#{m.run.id} {m.run.status}: {m.run.path}")
@@ -0,0 +1,35 @@
1
+ """Monitor: device readings against time, until Stop.
2
+
3
+ The detector and the SIS bias are read at an interval, a record of the
4
+ table "samples" per reading; the IF power and the SIS current are drawn as
5
+ it goes. It runs for the duration, or until Stop: the measurement then ends
6
+ cancelled and keeps what was read.
7
+ """
8
+
9
+ import time
10
+
11
+ from thzdaq import connect, device, plot, value
12
+
13
+ detector = device("Detector", "PowerDetector")
14
+ bias = device("SIS bias", kind="sis_bias")
15
+ interval = value("Interval", 1.0, unit="s")
16
+ duration = value("Duration", 0.0, unit="s", help="0: until Stop")
17
+ p_t = plot("P-t", table="samples", x="time", y="power")
18
+ i_t = plot("I-t", table="samples", x="time", y="current")
19
+
20
+ lab = connect()
21
+ with lab.measurement("monitor", devices=[detector, bias]) as m:
22
+ started = time.monotonic()
23
+ while not duration or time.monotonic() - started < duration:
24
+ reading = bias.read()
25
+ m.record(
26
+ "samples",
27
+ time=time.monotonic() - started,
28
+ power=detector.power,
29
+ voltage=reading.voltage,
30
+ current=reading.current,
31
+ )
32
+ m.progress()
33
+ m.sleep(interval) # Stop ends it here
34
+
35
+ print(f"#{m.run.id} {m.run.status}: {m.run.done} readings in {m.run.path}")
@@ -0,0 +1,37 @@
1
+ """Instrument without a driver: a level swept by raw commands.
2
+
3
+ An instrument no driver knows, reached by its connection alone: the script
4
+ names its raw commands (a level written within its limits and read back,
5
+ the output switched on and off) and sweeps the level, each point a record
6
+ with its unit. Its first run asks a person to add the instrument to the
7
+ profile, and to allow raw writes in the measurement; then they go on their
8
+ own until it ends. A simulator answers a query with what was written.
9
+ """
10
+
11
+ from thzdaq import connect, instrument, plot, setting, value
12
+
13
+ source = instrument(
14
+ "source_1",
15
+ driver="generic.scpi", # text commands, no quantities of its own
16
+ connection="tcp://169.254.0.60:5025", # only this goes into the profile
17
+ level=setting("VOLT?", "VOLT {:.6f}", unit="V", minimum=0, maximum=5),
18
+ output=setting("OUTP?", "OUTP {}", parse={"ON": True, "OFF": False}),
19
+ )
20
+ level = value("Level", "0:5:51", unit="V")
21
+ settle = value("Settle", 20, unit="ms", help="after each step")
22
+ read_back = plot("Level read back", table="levels", x="set", y="level")
23
+
24
+ lab = connect()
25
+ print(source.raw("*IDN?")) # any command as typed
26
+ with lab.measurement("level_sweep", devices=[source], total=level.points) as m:
27
+ source.output = True
28
+ try:
29
+ for v in m.sweep(level): # each step looks for a Stop
30
+ source.level = v
31
+ m.sleep(settle)
32
+ m.record("levels", set=v, level=source.level, on=source.output)
33
+ m.progress()
34
+ finally:
35
+ source.output = False
36
+
37
+ print(f"#{m.run.id} {m.run.status}: {m.run.path}")
@@ -0,0 +1,38 @@
1
+ """Bias sweep: I-V and P-V of a SIS junction.
2
+
3
+ The SIS bias goes over a range, each point a record of the table "iv";
4
+ I-V and P-V are drawn as it runs. The bias goes back to where it was
5
+ however the measurement ends, Stop too.
6
+ """
7
+
8
+ from thzdaq import connect, device, plot, value
9
+
10
+ bias = device("SIS bias", kind="sis_bias") # the device swept
11
+ detector = device("Detector", "PowerDetector") # read at each point
12
+ voltage = value("Bias voltage", "0:7:351", unit="mV")
13
+ settle = value("Settle", 10, unit="ms", help="after each step")
14
+ iv = plot("I-V", table="iv", x="voltage", y="current")
15
+ pv = plot("P-V", table="iv", x="voltage", y="power")
16
+
17
+ lab = connect()
18
+ with lab.measurement(
19
+ "bias_sweep",
20
+ devices=[bias, detector],
21
+ exclusive=[bias], # another's change of the bias would spoil the data
22
+ total=voltage.points,
23
+ ) as m:
24
+ m.restore(bias, "voltage_set") # the daemon sets it back at the end
25
+ for v in m.sweep(voltage): # each step looks for a Stop
26
+ bias.voltage_set = v
27
+ m.sleep(settle)
28
+ reading = bias.read() # voltage and current in one read
29
+ m.record(
30
+ "iv",
31
+ voltage_set=v,
32
+ voltage=reading.voltage,
33
+ current=reading.current,
34
+ power=detector.power,
35
+ )
36
+ m.progress()
37
+
38
+ print(f"#{m.run.id} {m.run.status}: {m.run.path}")
thzdaq_api/examples.py ADDED
@@ -0,0 +1,79 @@
1
+ """Examples of the bench's own measurements: files of this package
2
+ (examples/), each a script with declarations (thzdaq_api.custom) that runs as
3
+ it is on the simulators of the example profile; a person copies one into the
4
+ library (measurements/) and makes it theirs. The first line of its docstring
5
+ is its title, the rest says what it does. They are files of the package, so
6
+ every installation has them: the build, a PyPI install and the sources."""
7
+
8
+ import ast
9
+ from importlib import resources
10
+ from importlib.resources.abc import Traversable
11
+ from pathlib import Path
12
+ from typing import Tuple
13
+
14
+ import msgspec
15
+
16
+ from thzdaq_api.errors import ErrorCode, LabError
17
+
18
+ FOLDER = "examples"
19
+ SUFFIX = ".py"
20
+
21
+
22
+ class Example(msgspec.Struct, frozen=True):
23
+ name: str # its file without the suffix: the name a new script gets
24
+ title: str
25
+ about: str # what it does
26
+ text: str
27
+
28
+
29
+ def folder() -> Traversable:
30
+ return resources.files(__package__) / FOLDER
31
+
32
+
33
+ def read(item: Traversable) -> Example:
34
+ text = item.read_text(encoding="utf-8")
35
+ title, _, about = (ast.get_docstring(ast.parse(text)) or "").partition("\n")
36
+ return Example(item.name.removesuffix(SUFFIX), title, about.strip(), text)
37
+
38
+
39
+ def examples() -> Tuple[Example, ...]:
40
+ """Every example, by name."""
41
+ found = [read(item) for item in folder().iterdir() if item.name.endswith(SUFFIX)]
42
+ return tuple(sorted(found, key=lambda t: t.name))
43
+
44
+
45
+ def example(name: str) -> Example:
46
+ """LabError NOT_FOUND names the examples there are."""
47
+ for found in examples():
48
+ if found.name == name:
49
+ return found
50
+ raise LabError(
51
+ ErrorCode.NOT_FOUND,
52
+ f"No example {name!r}",
53
+ f"known: {', '.join(e.name for e in examples())}",
54
+ )
55
+
56
+
57
+ def write_new(folder: Path, name: str, text: str) -> Path:
58
+ """text as a new script folder/name.py, or name_2.py, name_3.py, ... when
59
+ that is taken: never over a file there."""
60
+ folder.mkdir(parents=True, exist_ok=True)
61
+ number = 1
62
+ while True:
63
+ path = folder / (
64
+ f"{name}{SUFFIX}" if number == 1 else f"{name}_{number}{SUFFIX}"
65
+ )
66
+ try:
67
+ # newline="": the text as it is, line ends too (a kept script's
68
+ # hash stays its own)
69
+ with open(path, "x", encoding="utf-8", newline="") as file:
70
+ file.write(text)
71
+ return path
72
+ except FileExistsError:
73
+ number += 1
74
+
75
+
76
+ def create(name: str, folder: Path) -> Path:
77
+ """A new script from the example name in folder, under its name."""
78
+ found = example(name)
79
+ return write_new(folder, found.name, found.text)