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/lab.py ADDED
@@ -0,0 +1,562 @@
1
+ """The bench as a client sees it: operations called by their arguments, events
2
+ heard as they happen (Lab); and as a script uses it (Bench, connect).
3
+
4
+ RemoteLab calls the daemon; LocalLab (thzdaq-core) calls its use cases in the
5
+ same process. Both raise LabError when an operation fails.
6
+
7
+ A script's bench has the commands of the thzdaq command line as functions,
8
+ each one operation, and its devices as objects whose attributes are their
9
+ quantities and whose methods are their actions:
10
+
11
+ from thzdaq import connect
12
+
13
+ lab = connect() # finds the daemon, or starts it
14
+ bias, pm = lab["sis_bias_1"], lab["power_meter_1"]
15
+ bias.voltage_set = "2.3mV" # = lab.set(...) = thzdaq set ...
16
+ bias.read() # = thzdaq read sis_bias_1: SI values
17
+ pm.power # one quantity
18
+ lab["chopper_1"].to_hot() # an action
19
+ lab.raw("signal_generator_1", "*IDN?") # a raw command, as typed
20
+ run = lab.run("sis.current_vs_voltage", bias=bias, voltage="0:7:351")
21
+ run.show() # its plots in a window of their own
22
+ run.wait()
23
+ iv = run.table("iv")
24
+
25
+ Readings are Measured: floats in SI units that know their unit, title and
26
+ device. Values to set are SI numbers or texts with their unit.
27
+ """
28
+
29
+ import os
30
+ import sys
31
+ from pathlib import Path
32
+ from typing import (
33
+ Any,
34
+ Callable,
35
+ Dict,
36
+ Iterable,
37
+ List,
38
+ Mapping,
39
+ Optional,
40
+ Protocol,
41
+ Tuple,
42
+ TypeVar,
43
+ Union,
44
+ )
45
+
46
+ from thzdaq_api import host, windows
47
+ from thzdaq_api.data import Measured, decode_values
48
+ from thzdaq_api.declaring import STATE, Declaring
49
+ from thzdaq_api.devices import (
50
+ CallAction,
51
+ DescribeDevice,
52
+ DeviceDescription,
53
+ DeviceInfo,
54
+ ListDevices,
55
+ RawCommand,
56
+ ReadDevice,
57
+ SetQuantity,
58
+ Value,
59
+ shown,
60
+ )
61
+ from thzdaq_api.errors import ErrorCode, LabError
62
+ from thzdaq_api.events import Event
63
+ from thzdaq_api.measurement_file import RUNNING, Measurement, Table, read_measurement
64
+ from thzdaq_api.measurements import (
65
+ CancelMeasurement,
66
+ DescribeProcedure,
67
+ GetRunSnapshot,
68
+ ListProcedures,
69
+ ListRuns,
70
+ ProcedureSummary,
71
+ RunInfo,
72
+ StartMeasurement,
73
+ WaitMeasurement,
74
+ fill_slots,
75
+ )
76
+ from thzdaq_api.operation import Operation
77
+ from thzdaq_api.origins import (
78
+ ANSWERING_CLI,
79
+ CLI,
80
+ CONSOLE,
81
+ CONSOLE_CLIENT,
82
+ CONSOLE_ENV,
83
+ GUI,
84
+ PLOTS,
85
+ SCRIPT_CLIENT,
86
+ agent_shell,
87
+ script,
88
+ )
89
+ from thzdaq_api.procedures import entry
90
+ from thzdaq_api.remote import RemoteLab
91
+ from thzdaq_api.script import (
92
+ AnsweredHere,
93
+ Described,
94
+ Session,
95
+ Where,
96
+ described,
97
+ place,
98
+ ref_of,
99
+ script_source,
100
+ )
101
+ from thzdaq_api.scripts import SCRIPT_ID_ENV, SIMULATE_ENV
102
+ from thzdaq_api.sessions import SILENT_S, StartSession, Swept
103
+ from thzdaq_api.terminal import person_here
104
+ from thzdaq_api.workspace import chosen, expected_profile, profile_warning
105
+
106
+ R = TypeVar("R")
107
+ WAIT_S = 1.0 # how often wait() tells the progress
108
+
109
+
110
+ class Lab(Protocol):
111
+ origin: str # who calls (gui, cli, mcp:<name>); the runs it starts carry it
112
+
113
+ def call(self, operation: Operation[R]) -> R:
114
+ ...
115
+
116
+ def subscribe(
117
+ self, listener: Callable[[Event], None], since: Optional[int] = None
118
+ ) -> Callable[[], None]:
119
+ """Hear every event after `since` (a snapshot's seq; None: from now);
120
+ returns what stops it. The listener runs in the lab's thread: it hands
121
+ the event on (a Qt signal, a queue) and returns."""
122
+ ...
123
+
124
+
125
+ class Readout(dict):
126
+ """What a device read, by quantity: readout["voltage"] or readout.voltage."""
127
+
128
+ def __getattr__(self, key: str) -> Any:
129
+ try:
130
+ return self[key]
131
+ except KeyError:
132
+ raise AttributeError(
133
+ f"nothing read as {key!r}: {', '.join(self)}"
134
+ ) from None
135
+
136
+
137
+ def plain(value: Any) -> Any:
138
+ """A value as it travels: a Measured as a float, a declared sweep as
139
+ {start, stop, points} in SI."""
140
+ if isinstance(value, Swept):
141
+ return {"start": value.start, "stop": value.stop, "points": value.points}
142
+ return float(value) if isinstance(value, float) else value
143
+
144
+
145
+ class Device:
146
+ """A device of the bench as an object: its quantities are attributes (read
147
+ when looked at, set when assigned; device["key"] too) and its actions
148
+ methods, as describe_device lists them. It only calls the bench's functions."""
149
+
150
+ def __init__(self, bench: "Bench", ref: str):
151
+ object.__setattr__(self, "bench", bench)
152
+ object.__setattr__(self, "ref", ref)
153
+
154
+ def describe(self) -> DeviceDescription:
155
+ return self.bench.describe(self.ref)
156
+
157
+ def read(self, *keys: str, display: bool = False) -> Readout:
158
+ return self.bench.read(self.ref, *keys, display=display)
159
+
160
+ def __getattr__(self, name: str) -> Any:
161
+ if name.startswith("_"):
162
+ raise AttributeError(name)
163
+ found = self.describe()
164
+ if any(q.key == name for q in found.quantities):
165
+ return self[name]
166
+ if any(a.key == name for a in found.actions):
167
+ return lambda **arguments: self.bench.call(self.ref, name, **arguments)
168
+ raise AttributeError(f"{self.ref} has no quantity or action {name!r}")
169
+
170
+ def __setattr__(self, name: str, value: Any) -> None:
171
+ self.bench.set(self.ref, name, value)
172
+
173
+ def __getitem__(self, key: str) -> Any:
174
+ return self.read(key)[key]
175
+
176
+ def __setitem__(self, key: str, value: Any) -> None:
177
+ self.bench.set(self.ref, key, value)
178
+
179
+ def __dir__(self) -> Iterable[str]:
180
+ found = self.describe()
181
+ return [q.key for q in found.quantities] + [a.key for a in found.actions]
182
+
183
+ def __repr__(self) -> str:
184
+ return f"<device {self.ref}>"
185
+
186
+
187
+ class Run:
188
+ """A measurement started in the daemon, followed from here."""
189
+
190
+ def __init__(self, bench: "Bench", info: RunInfo):
191
+ self.bench = bench
192
+ self.info = info
193
+ self.id = info.id
194
+
195
+ def wait(self, progress: bool = True) -> RunInfo:
196
+ """Until it ends; its progress on stderr."""
197
+ self.info = self.bench.wait(self.id, progress)
198
+ return self.info
199
+
200
+ def cancel(self) -> RunInfo:
201
+ self.info = self.bench.cancel(self.id)
202
+ return self.info
203
+
204
+ def show(self, where: Where = PLOTS) -> None:
205
+ """Its plots on screen as it runs: in a window of their own (plots),
206
+ or in the main window (gui); see Bench.show."""
207
+ self.bench.show(self.id, where)
208
+
209
+ def measurement(self) -> Measurement:
210
+ """What it holds: its file once it ended, its records so far while it
211
+ runs."""
212
+ self.info = self.bench.lab.call(WaitMeasurement(id=self.id, timeout=0))
213
+ if self.info.status != RUNNING:
214
+ return read_measurement(self.info.path)
215
+ snapshot = self.bench.lab.call(GetRunSnapshot(id=self.id))
216
+ found = Measurement(self.info.procedure, self.info.title, self.id)
217
+ for table, rows in snapshot.rows.items():
218
+ for row in rows:
219
+ found.append(table, decode_values(row))
220
+ return found
221
+
222
+ def table(self, name: str) -> Table:
223
+ """A table of its records: columns by key (iv["voltage"]), in SI units."""
224
+ tables = self.measurement().tables
225
+ if name not in tables:
226
+ raise LabError(
227
+ ErrorCode.NOT_FOUND,
228
+ f"#{self.id} has no table {name!r}",
229
+ f"it has: {', '.join(tables) or 'none yet'}",
230
+ )
231
+ return tables[name]
232
+
233
+ def __repr__(self) -> str:
234
+ return f"<run #{self.id} {self.info.title}: {self.info.status}>"
235
+
236
+
237
+ class Bench:
238
+ """The bench as a script uses it: the CLI's commands as functions, its
239
+ devices as objects (bench["sis_bias_1"]), its own measurements as sessions
240
+ (bench.measurement)."""
241
+
242
+ def __init__(
243
+ self,
244
+ lab: Lab,
245
+ workspace: Union[str, Path, None] = None,
246
+ script=None,
247
+ approve: Optional[Callable[[Callable[[], Any]], Any]] = None,
248
+ simulate: bool = False,
249
+ declared: Optional[Declaring] = None,
250
+ ):
251
+ """workspace: the folder whose data/ gets its measurements (None: the
252
+ program's, where the daemon writes); script: the ScriptSource its
253
+ sessions keep; approve: how a call a person allows is made (asked in
254
+ this terminal too); simulate: the lab is the simulator's daemon,
255
+ the windows it opens work with it too; declared: what the script
256
+ declared at its top (its plots are its measurements' from the start)."""
257
+ self.lab = lab
258
+ self.workspace = Path(workspace).resolve() if workspace else None
259
+ self.script = script
260
+ self.approve = approve or (lambda call: call())
261
+ self.simulate = simulate
262
+ self.declared = declared or Declaring()
263
+ self.session: Optional[Session] = None # the with block running now
264
+ self._described: Dict[str, DeviceDescription] = {}
265
+
266
+ @property
267
+ def origin(self) -> str:
268
+ return self.lab.origin
269
+
270
+ def _folder(self) -> Optional[str]:
271
+ """The workspace as operations name it."""
272
+ return str(self.workspace) if self.workspace else None
273
+
274
+ def _session_id(self) -> Optional[int]:
275
+ return self.session.id if self.session is not None else None
276
+
277
+ def _entered(self, session: Optional[Session]) -> None:
278
+ self.session = session
279
+
280
+ # Devices
281
+ def __getitem__(self, ref: str) -> Device:
282
+ return Device(self, ref)
283
+
284
+ def _ipython_key_completions_(self) -> List[str]:
285
+ """What completes bench["…"] in IPython (a console): the devices' refs."""
286
+ return [device.ref for device in self.devices()]
287
+
288
+ def devices(self) -> Tuple[DeviceInfo, ...]:
289
+ return self.lab.call(ListDevices())
290
+
291
+ def describe(self, ref: str) -> DeviceDescription:
292
+ if ref not in self._described:
293
+ self._described[ref] = self.lab.call(DescribeDevice(ref=ref))
294
+ return self._described[ref]
295
+
296
+ def read(self, ref: str, *keys: str, display: bool = False) -> Readout:
297
+ """Every readable quantity, or the keys: SI numbers that know their
298
+ unit (Measured); display: texts in the units people read."""
299
+ values = self.lab.call(
300
+ ReadDevice(ref=ref, keys=keys or None, session=self._session_id())
301
+ ).values
302
+ quantities = {q.key: q for q in self.describe(ref).quantities}
303
+ return Readout(
304
+ (key, self._value(ref, quantities[key], value, display))
305
+ for key, value in values.items()
306
+ )
307
+
308
+ @staticmethod
309
+ def _value(ref: str, quantity, value: Value, display: bool) -> Any:
310
+ if display:
311
+ return shown(value, quantity.unit, quantity.prefixes)
312
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
313
+ return Measured(
314
+ value, quantity.unit, quantity.title, entry(ref, quantity.key)
315
+ )
316
+ return value
317
+
318
+ def set(self, ref: str, key: str, value: Any, share: bool = False) -> Value:
319
+ """An SI number or a text with its unit ("2.3mV"); returns what was set."""
320
+ done = self.lab.call(
321
+ SetQuantity(
322
+ ref=ref, key=key, value=plain(value), share=share,
323
+ session=self._session_id(),
324
+ )
325
+ ) # fmt: skip
326
+ return done.value
327
+
328
+ def call(
329
+ self, ref: str, action: str, /, share: bool = False, **arguments: Any
330
+ ) -> Any:
331
+ """A device's action; arguments as SI numbers or texts with units."""
332
+ done = self.lab.call(
333
+ CallAction(
334
+ ref=ref, action=action,
335
+ arguments={k: plain(v) for k, v in arguments.items()},
336
+ share=share, session=self._session_id(),
337
+ )
338
+ ) # fmt: skip
339
+ return done.result
340
+
341
+ def raw(
342
+ self, instrument: str, command: str, answer: bool = False, share: bool = False
343
+ ) -> Optional[str]:
344
+ """Send an instrument (its id in the profile) a command as typed, for
345
+ what its driver does not wrap yet; returns its answer: of a query
346
+ (with ?), or of a write with answer. No limit checks a write: it waits
347
+ for a person, unless the script was started with --allow
348
+ raw:<instrument>; within a measurement (with lab.measurement) the
349
+ person's yes to the first holds until it ends. Put a command used
350
+ often into the driver, or name it (instrument(...): reading,
351
+ setting)."""
352
+ command = RawCommand(
353
+ instrument=instrument, command=command, answer=answer, share=share,
354
+ session=self._session_id(),
355
+ ) # fmt: skip
356
+ if command.query:
357
+ return self.lab.call(command).answer
358
+ return self.approve(lambda: self.lab.call(command)).answer
359
+
360
+ # Procedures
361
+ def procedures(self) -> Tuple[ProcedureSummary, ...]:
362
+ """Every procedure the bench can run (thzdaq procedures)."""
363
+ return self.lab.call(ListProcedures())
364
+
365
+ def start(
366
+ self,
367
+ procedure: str,
368
+ devices: Optional[Mapping[str, Any]] = None,
369
+ comment: str = "",
370
+ share: bool = False,
371
+ **parameters: Any,
372
+ ) -> RunInfo:
373
+ """Start a procedure (thzdaq run --detach). A device given as a
374
+ parameter (bias=bias) fills its slot, a text is typed as describe
375
+ shows it ("0:7:351" in mV), a number is SI; a slot left out takes the
376
+ only device that suits it."""
377
+ given = {slot: ref_of(d) for slot, d in (devices or {}).items()}
378
+ given.update(
379
+ (name, value.ref)
380
+ for name, value in parameters.items()
381
+ if isinstance(value, Device)
382
+ )
383
+ typed = {k: v for k, v in parameters.items() if isinstance(v, str)}
384
+ values = {
385
+ k: plain(v)
386
+ for k, v in parameters.items()
387
+ if not isinstance(v, (str, Device))
388
+ }
389
+ info = self.lab.call(
390
+ DescribeProcedure(procedure=procedure, parameters=values, typed=typed)
391
+ )
392
+ chosen, choices = fill_slots(info.slots, self.devices(), given)
393
+ if choices:
394
+ slot, refs = next(iter(choices.items()))
395
+ raise LabError(
396
+ ErrorCode.INVALID_ARGUMENTS,
397
+ f"{slot}: one of {', '.join(refs)}",
398
+ f"name it: {slot}=lab[...]",
399
+ )
400
+ return self.lab.call(
401
+ StartMeasurement(
402
+ procedure=procedure, parameters=values, typed=typed,
403
+ devices=chosen, comment=comment, share=share,
404
+ workspace=self._folder(),
405
+ )
406
+ ) # fmt: skip
407
+
408
+ def run(
409
+ self,
410
+ procedure: str,
411
+ devices: Optional[Mapping[str, Any]] = None,
412
+ comment: str = "",
413
+ share: bool = False,
414
+ **parameters: Any,
415
+ ) -> Run:
416
+ """Start a procedure and follow it: run.wait(), run.table("iv")."""
417
+ return Run(self, self.start(procedure, devices, comment, share, **parameters))
418
+
419
+ def status(self) -> Tuple[RunInfo, ...]:
420
+ """The measurements running now."""
421
+ return tuple(run for run in self.measurements() if run.status == RUNNING)
422
+
423
+ def measurements(self) -> Tuple[RunInfo, ...]:
424
+ """The daemon's measurements: running and lately ended."""
425
+ return self.lab.call(ListRuns())
426
+
427
+ def cancel(self, id: int) -> RunInfo:
428
+ return self.lab.call(CancelMeasurement(id=id))
429
+
430
+ # Windows: each a program of its own, apart from this script
431
+ def plot(
432
+ self,
433
+ measurement: Union[int, str, Path],
434
+ table: Optional[str] = None,
435
+ x: Optional[str] = None,
436
+ y: Optional[str] = None,
437
+ group_by: Iterable[str] = (),
438
+ ) -> None:
439
+ """The plots of a measurement in a window of their own (thzdaq plot):
440
+ one of the daemon by its number, drawn as it runs, or a file. With
441
+ table, x and y the window draws that plot instead (curves by the
442
+ values of group_by). The script does not wait for the window."""
443
+ which = measurement if isinstance(measurement, int) else str(measurement)
444
+ own = windows.OwnPlot.asked(table, x, y, tuple(group_by))
445
+ windows.open_plots(self.lab.call, which, self.simulate, own)
446
+
447
+ def show(self, id: int, where: Where = PLOTS) -> None:
448
+ """A measurement of the daemon on screen as it runs: in a window of
449
+ its own with only its plots (plots, or True), or in the main window
450
+ (gui), opened in this workspace unless one is open already."""
451
+ shows = {PLOTS: self.plot, GUI: self._main_window}
452
+ if place(where) not in shows:
453
+ raise LabError(
454
+ ErrorCode.INVALID_ARGUMENTS,
455
+ f"No window {where!r} to show #{id} in",
456
+ f"one of: {', '.join(shows)}",
457
+ )
458
+ shows[place(where)](id)
459
+
460
+ def _main_window(self, id: int) -> None:
461
+ """A main window draws every measurement running: one is opened
462
+ when none listens."""
463
+ if not windows.window_open(self.lab.call):
464
+ host.start_apart(windows.gui_command(self.workspace, self.simulate))
465
+
466
+ def wait(self, id: int, progress: bool = False) -> RunInfo:
467
+ """Until the measurement ends; progress: told on stderr as it goes."""
468
+ info = self.lab.call(WaitMeasurement(id=id, timeout=0))
469
+ while info.status == RUNNING:
470
+ if progress:
471
+ done = f"{info.done}/{info.total}" if info.total else f"{info.done}"
472
+ print(f"\r#{id} {info.title}: {done}", end="", file=sys.stderr)
473
+ info = self.lab.call(WaitMeasurement(id=id, timeout=WAIT_S))
474
+ if progress:
475
+ print(f"\r#{id} {info.title}: {info.status}", file=sys.stderr)
476
+ return info
477
+
478
+ # A script's own measurement
479
+ def measurement(
480
+ self,
481
+ title: str,
482
+ devices: Iterable[Any] = (),
483
+ exclusive: Iterable[Any] = (),
484
+ share: Iterable[Any] = (),
485
+ parameters: Optional[Mapping[str, Any]] = None,
486
+ comment: str = "",
487
+ columns: Optional[Mapping[str, Described]] = None,
488
+ total: Optional[int] = None,
489
+ silent: float = SILENT_S,
490
+ ) -> Session:
491
+ """A measurement of this script (with ... as m): devices it uses,
492
+ those it sweeps (exclusive), those it shares while another measurement
493
+ sweeps them (share); columns: (title, unit) of record keys. Its
494
+ parameters are the values the script declared, and those given."""
495
+ given = {name: found.value for name, found in self.declared.given.items()}
496
+ start = StartSession(
497
+ title=title,
498
+ devices=tuple(ref_of(d) for d in devices),
499
+ exclusive=tuple(ref_of(d) for d in exclusive),
500
+ share=tuple(ref_of(d) for d in share),
501
+ parameters={**given, **(parameters or {})},
502
+ comment=comment,
503
+ workspace=self._folder(),
504
+ script=self.script,
505
+ columns=tuple(described(k, c) for k, c in (columns or {}).items()),
506
+ total=total,
507
+ silent=silent,
508
+ plots=tuple(self.declared.plots),
509
+ )
510
+ return Session(self.lab, start, self.approve, self._entered, self.show)
511
+
512
+ def __repr__(self) -> str:
513
+ return f"<bench of {self.origin}>"
514
+
515
+
516
+ def connect(
517
+ simulate: Optional[bool] = None,
518
+ name: Optional[str] = None,
519
+ workspace: Union[str, Path, None] = None,
520
+ ) -> Bench:
521
+ """The bench of this machine (its simulator with simulate) as this script
522
+ uses it, as script:<name> (the script's file name by default;
523
+ script:agent:<name> in a shell an agent drives: the script has the rights
524
+ of whoever started it), or as console in the kernel of a window's console
525
+ (thzdaq_api.console); the daemon is started when none runs. A person at this terminal is asked here too
526
+ what a measurement's start needs allowed. A script the daemon started
527
+ (thzdaq script start) finds that daemon, its own number and its workspace
528
+ by its environment, and is allowed what it was started with. Its
529
+ measurements go to the workspace given, else to the nearest one from here
530
+ up (thzdaq.toml), else to the program's; a daemon started here loads the
531
+ profile that workspace expects. A script the daemon describes
532
+ (thzdaq_api.custom) ends here; one whose declarations connected already
533
+ gets that bench."""
534
+ if STATE.describing:
535
+ STATE.described()
536
+ if STATE.bench is not None:
537
+ return STATE.bench
538
+ path = getattr(sys.modules["__main__"], "__file__", None) # none in a notebook
539
+ if simulate is None:
540
+ simulate = os.environ.get(SIMULATE_ENV) == "1"
541
+ origin, kind = caller(name or (Path(path).stem if path else "interactive"))
542
+ folder = chosen(workspace)
543
+ lab = host.connect_or_start(simulate, expected_profile(folder), origin, kind)
544
+ warning = profile_warning(lab, folder)
545
+ if warning:
546
+ print(warning, file=sys.stderr)
547
+ approve = None
548
+ if person_here():
549
+ person = RemoteLab(lab.host, CLI, ANSWERING_CLI, find=lab.find)
550
+ approve = AnsweredHere(person, lab.origin)
551
+ return Bench(lab, folder, script_source(path, folder), approve, simulate, STATE)
552
+
553
+
554
+ def caller(name: str) -> Tuple[str, str]:
555
+ """What this process calls the daemon as, and the kind of client it
556
+ listens as: the kernel of a window's console (its window set CONSOLE_ENV)
557
+ as console; a script as script:<name>, with its number when the daemon
558
+ runs it, as an agent's in a shell an agent drives."""
559
+ if os.environ.get(CONSOLE_ENV):
560
+ return CONSOLE, CONSOLE_CLIENT
561
+ number = os.environ.get(SCRIPT_ID_ENV)
562
+ return script(name, int(number) if number else None, agent_shell()), SCRIPT_CLIENT