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
@@ -0,0 +1,422 @@
1
+ """The Python a workspace's scripts run with: its scripts started by the
2
+ daemon (thzdaq script start), the bench's own measurements started from it,
3
+ and the kernels of the window's consoles.
4
+
5
+ A workspace names it in thzdaq.toml (python): an environment's folder or its
6
+ interpreter, relative to the workspace or absolute. A workspace that names
7
+ none, and the program's own folder, run them with the program's own Python
8
+ (host.script_python: this interpreter from sources, a build's own through
9
+ thzdaq-cli run-script). This module is the one owner of that rule: whoever
10
+ starts a script asks it with the workspace the script runs in (the daemon
11
+ with the one the operation names, the window with its own).
12
+
13
+ A person chooses among the environments found here: the workspace's .venv
14
+ (or the nearest one above it, as uv finds a project's), uv's tool
15
+ environments, conda's; or any interpreter. A chosen one is checked: that it
16
+ runs, its Python, and that it has thzdaq of exactly this program's version.
17
+ The packages of ThzDAQ require each other at one version, and a script's
18
+ contract with the daemon (its declarations, its inputs, the console's kernel)
19
+ changes with it, beyond what the daemon's API_VERSION tells. A console's
20
+ kernel also needs ipykernel there.
21
+ """
22
+
23
+ import json
24
+ import os
25
+ import platform
26
+ import shutil
27
+ import subprocess
28
+ import sys
29
+ import tempfile
30
+ from importlib import util
31
+ from pathlib import Path
32
+ from typing import List, Optional, Sequence, Tuple
33
+
34
+ import msgspec
35
+
36
+ from thzdaq_api import host
37
+ from thzdaq_api.daemon import API_VERSION
38
+ from thzdaq_api.errors import ErrorCode, LabError
39
+ from thzdaq_api.workspace import FILE, PathLike, read
40
+
41
+ PACKAGE = "thzdaq" # what a person installs, and a script imports
42
+ CONTRACT = "thzdaq-api" # the package whose version is the program's
43
+ KERNEL_PACKAGE = "ipykernel" # what a console's kernel needs besides
44
+ VENV = ".venv" # the folder of a project's environment, as uv makes it
45
+ CHECK_S = 20.0 # an interpreter answers within this (a first start is slow)
46
+ FIND_S = 20.0 # uv and conda list their environments within this
47
+ CONDA_ENV = "CONDA_EXE" # where conda's shells put conda itself
48
+ OLDEST = (3, 11) # the Python thzdaq needs at least (requires-python)
49
+
50
+ # Kinds of environments, as people see them
51
+ OWN, PROJECT, UV, CONDA, CHOSEN = "built-in", "venv", "uv", "conda", "path"
52
+
53
+ # What a checked interpreter tells of itself: one JSON line
54
+ PROBE = f"""\
55
+ import json, platform
56
+ from importlib import metadata, util
57
+ told = {{"version": platform.python_version()}}
58
+ try:
59
+ import {PACKAGE}
60
+ from thzdaq_api.daemon import API_VERSION
61
+ told["thzdaq"] = metadata.version({CONTRACT!r})
62
+ told["api"] = API_VERSION
63
+ except Exception as e:
64
+ told["missing"] = f"{{type(e).__name__}}: {{e}}"
65
+ told["console"] = util.find_spec({KERNEL_PACKAGE!r}) is not None
66
+ print(json.dumps(told))
67
+ """
68
+
69
+
70
+ def python_in(path: PathLike) -> Path:
71
+ """The interpreter of an environment's folder (a venv's, a conda one's),
72
+ or the interpreter given; LabError NOT_FOUND when there is none."""
73
+ path = Path(path).expanduser()
74
+ if path.is_file():
75
+ return path
76
+ if path.is_dir():
77
+ for inside in _interpreters(path):
78
+ if inside.is_file():
79
+ return inside
80
+ raise LabError(
81
+ ErrorCode.NOT_FOUND,
82
+ f"No Python in {path}",
83
+ "name an environment's folder (.venv) or its interpreter",
84
+ )
85
+ raise LabError(ErrorCode.NOT_FOUND, f"No Python at {path}: it is not there")
86
+
87
+
88
+ def _interpreters(folder: Path) -> Tuple[Path, ...]:
89
+ """Where an environment keeps its interpreter: a venv's Scripts\\ on
90
+ Windows and bin/ elsewhere; a conda one's at its top on Windows."""
91
+ if sys.platform == "win32":
92
+ return (folder / "Scripts" / "python.exe", folder / "python.exe")
93
+ return (folder / "bin" / "python3", folder / "bin" / "python")
94
+
95
+
96
+ def chosen(folder: Optional[PathLike]) -> Optional[Path]:
97
+ """The interpreter a workspace names; None when it names none (or for no
98
+ workspace: the program's own folder). LabError when its thzdaq.toml is
99
+ broken or names one that is not there."""
100
+ if folder is None:
101
+ return None
102
+ named = read(folder).python
103
+ if not named:
104
+ return None
105
+ try:
106
+ return python_in(Path(folder) / Path(named).expanduser())
107
+ except LabError as e:
108
+ raise LabError(
109
+ e.code,
110
+ f"{Path(folder) / FILE} names the Python {named!r}: {e.message}",
111
+ "choose another: File → Workspace settings, or thzdaq python set",
112
+ ) from None
113
+
114
+
115
+ def scripts_python(folder: Optional[PathLike]) -> Tuple[str, ...]:
116
+ """How a script of a workspace runs: [its interpreter], else the program's
117
+ own (host.script_python), as a command the file and its arguments
118
+ follow."""
119
+ found = chosen(folder)
120
+ return (str(found),) if found is not None else host.script_python()
121
+
122
+
123
+ def module_command(
124
+ folder: Optional[PathLike], module: str, *arguments: str
125
+ ) -> List[str]:
126
+ """How a module runs as a program with a workspace's Python (python -m
127
+ module arguments; a console's kernel)."""
128
+ found = chosen(folder)
129
+ if found is None:
130
+ return host.python_module(module, *arguments)
131
+ return [str(found), "-m", module, *arguments]
132
+
133
+
134
+ def located(path: PathLike) -> Path:
135
+ """Where a Python typed here is: absolute, the links to it followed but
136
+ not its own (a venv's interpreter links to the Python it was made from,
137
+ which runs without the venv)."""
138
+ path = Path(os.path.abspath(Path(path).expanduser()))
139
+ return path.parent.resolve() / path.name
140
+
141
+
142
+ def stored(folder: PathLike, path: PathLike) -> str:
143
+ """How thzdaq.toml names a Python typed here: relative to the workspace
144
+ when it is in it (the folder moves with it), else absolute."""
145
+ path = located(path)
146
+ try:
147
+ return path.relative_to(Path(folder).resolve()).as_posix()
148
+ except ValueError:
149
+ return str(path)
150
+
151
+
152
+ # The environments a person chooses among
153
+ class Environment(msgspec.Struct, frozen=True):
154
+ """An environment found here: what kind, how a person knows it, its
155
+ folder ("" for the program's own)."""
156
+
157
+ kind: str
158
+ name: str
159
+ path: str = ""
160
+
161
+ @property
162
+ def own(self) -> bool:
163
+ """The program's own Python."""
164
+ return not self.path
165
+
166
+ def interpreter(self) -> Optional[Path]:
167
+ """Its interpreter (None: the program's own); one that is not there
168
+ is where it would be."""
169
+ if self.own:
170
+ return None
171
+ try:
172
+ return python_in(self.path)
173
+ except LabError:
174
+ return Path(self.path)
175
+
176
+ def runs(self, interpreter: Optional[Path]) -> bool:
177
+ """Whether it is the environment of an interpreter (None: the
178
+ program's own). Two venvs' interpreters link to one Python, so they
179
+ are told apart by where they are, not by what they link to."""
180
+ mine = self.interpreter()
181
+ if mine is None or interpreter is None:
182
+ return mine is None and interpreter is None
183
+ return same_place(mine, interpreter)
184
+
185
+
186
+ def same_place(one: PathLike, other: PathLike) -> bool:
187
+ """Whether two paths name one place (located: their own links kept)."""
188
+ return os.path.normcase(located(one)) == os.path.normcase(located(other))
189
+
190
+
191
+ def own() -> Environment:
192
+ """The program's own Python."""
193
+ return Environment(OWN, f"the program's own (Python {python_version()})")
194
+
195
+
196
+ def python_version() -> str:
197
+ return platform.python_version()
198
+
199
+
200
+ def environments(
201
+ folder: Optional[PathLike],
202
+ conda: Optional[Sequence[str]] = None,
203
+ uv: Optional[Sequence[str]] = None,
204
+ ) -> Tuple[Environment, ...]:
205
+ """The program's own first, then the workspace's .venv (and those above
206
+ it), uv's tool environments, conda's, each once, and last the one the
207
+ workspace names when it is none of them. conda, uv: how they are run
208
+ (None: found here, () for none); one that fails finds nothing."""
209
+ found: List[Environment] = [own()]
210
+ if folder is not None:
211
+ found += projects(Path(folder))
212
+ found += uv_tools(uv_command() if uv is None else uv)
213
+ found += conda_environments(conda_command() if conda is None else conda)
214
+ seen, unique = set(), []
215
+ for environment in found:
216
+ key = os.path.normcase(environment.path)
217
+ if key not in seen:
218
+ seen.add(key)
219
+ unique.append(environment)
220
+ named = named_environment(folder)
221
+ if named is not None and not any(e.runs(named.interpreter()) for e in unique):
222
+ unique.append(named)
223
+ return tuple(unique)
224
+
225
+
226
+ def current(
227
+ found: Sequence[Environment], folder: Optional[PathLike]
228
+ ) -> Optional[Environment]:
229
+ """The one of found that a workspace's scripts run with (environments()
230
+ lists it): the program's own when it names none."""
231
+ named = named_environment(folder)
232
+ if named is None:
233
+ return next((e for e in found if e.own), None)
234
+ interpreter = named.interpreter()
235
+ return next((e for e in found if e == named or e.runs(interpreter)), None)
236
+
237
+
238
+ def named_environment(folder: Optional[PathLike]) -> Optional[Environment]:
239
+ """The Python a workspace names, as it names it (it may not be there);
240
+ None when it names none."""
241
+ named = read(folder).python if folder is not None else ""
242
+ if not named:
243
+ return None
244
+ return Environment(CHOSEN, named, str(Path(folder) / Path(named).expanduser()))
245
+
246
+
247
+ def projects(folder: Path) -> List[Environment]:
248
+ """The .venv of the folder, and of each folder above it."""
249
+ found = []
250
+ here = folder.resolve()
251
+ for above in (here, *here.parents):
252
+ venv = above / VENV
253
+ if any(inside.is_file() for inside in _interpreters(venv)):
254
+ name = VENV if above == here else f"{above.name}/{VENV}"
255
+ found.append(Environment(PROJECT, name, str(venv)))
256
+ return found
257
+
258
+
259
+ def uv_command() -> Sequence[str]:
260
+ found = shutil.which("uv")
261
+ return (found,) if found else ()
262
+
263
+
264
+ def conda_command() -> Sequence[str]:
265
+ found = os.environ.get(CONDA_ENV) or shutil.which("conda")
266
+ return (found,) if found else ()
267
+
268
+
269
+ def _asked(command: Sequence[str]) -> str:
270
+ """What a program answered; "" when it did not (the environments it
271
+ knows are not found then)."""
272
+ try:
273
+ done = subprocess.run(
274
+ list(command), capture_output=True, text=True, timeout=FIND_S,
275
+ stdin=subprocess.DEVNULL, **host.windowless(),
276
+ ) # fmt: skip
277
+ except (OSError, subprocess.TimeoutExpired):
278
+ return ""
279
+ return done.stdout if done.returncode == 0 else ""
280
+
281
+
282
+ def uv_tools(uv: Sequence[str]) -> List[Environment]:
283
+ """The environments of uv's tools (uv tool install thzdaq makes one)."""
284
+ if not uv:
285
+ return []
286
+ answered = _asked([*uv, "tool", "dir"]).strip()
287
+ if not answered or not Path(answered).is_dir():
288
+ return []
289
+ return [
290
+ Environment(UV, f"tool {tool.name}", str(tool))
291
+ for tool in sorted(Path(answered).iterdir())
292
+ if any(inside.is_file() for inside in _interpreters(tool))
293
+ ]
294
+
295
+
296
+ def conda_environments(conda: Sequence[str]) -> List[Environment]:
297
+ """conda's environments (conda env list): base by its folder, the others
298
+ by their names."""
299
+ if not conda:
300
+ return []
301
+ try:
302
+ listed = json.loads(_asked([*conda, "env", "list", "--json"]) or "{}")
303
+ except json.JSONDecodeError:
304
+ return []
305
+ found = []
306
+ for path in listed.get("envs", []):
307
+ folder = Path(path)
308
+ name = folder.name if folder.parent.name == "envs" else str(folder)
309
+ found.append(Environment(CONDA, name, str(folder)))
310
+ return found
311
+
312
+
313
+ # A chosen one, checked
314
+ class Checked(msgspec.Struct, frozen=True):
315
+ """What a Python is to the bench's scripts: its version, the thzdaq it
316
+ has, whether a console's kernel runs there; problem: why scripts cannot
317
+ run with it ("" when they can), hint: what mends it."""
318
+
319
+ python: str # the interpreter; "" for the program's own
320
+ version: str = "" # of Python; "" when it did not run
321
+ thzdaq: str = "" # its thzdaq's version; "" without one
322
+ console: bool = False # ipykernel is there
323
+ problem: str = ""
324
+ hint: str = ""
325
+
326
+ @property
327
+ def ok(self) -> bool:
328
+ return not self.problem
329
+
330
+ def summary(self) -> str:
331
+ """What it is to scripts, short: the problem, or its versions (and
332
+ that a console needs ipykernel there)."""
333
+ if not self.ok:
334
+ return self.problem
335
+ told = f"Python {self.version}, {PACKAGE} {self.thzdaq}"
336
+ if not self.console:
337
+ told += f"; a console needs {KERNEL_PACKAGE}"
338
+ return told
339
+
340
+ def remedy(self) -> str:
341
+ """What mends it; "" when nothing needs to."""
342
+ if not self.ok:
343
+ return self.hint
344
+ return "" if self.console else install(self.python, KERNEL_PACKAGE)
345
+
346
+ def text(self) -> str:
347
+ """One line for people."""
348
+ remedy = self.remedy()
349
+ return f"{self.summary()}: {remedy}" if remedy else self.summary()
350
+
351
+
352
+ def install(python: str, *packages: str) -> str:
353
+ """How packages are installed into an interpreter ("": the program's own,
354
+ from PyPI): by uv, or by its pip."""
355
+ named = " ".join(f'"{package}"' for package in packages)
356
+ if not python:
357
+ return f"pip install {named} where thzdaq is installed"
358
+ return (
359
+ f'uv pip install --python "{python}" {named}, '
360
+ f'or "{python}" -m pip install {named}'
361
+ )
362
+
363
+
364
+ def wanted() -> str:
365
+ """thzdaq as a script's interpreter needs it: this program's version."""
366
+ return f"{PACKAGE}=={host.app_version()}"
367
+
368
+
369
+ def check_own() -> Checked:
370
+ """The program's own Python: it runs here, with the program's thzdaq."""
371
+ return Checked(
372
+ "", python_version(), host.app_version(),
373
+ util.find_spec(KERNEL_PACKAGE) is not None,
374
+ ) # fmt: skip
375
+
376
+
377
+ def check(python: PathLike, timeout: float = CHECK_S) -> Checked:
378
+ """Whether scripts run with an interpreter (or an environment's folder):
379
+ it runs, has thzdaq of this program's version (and ipykernel for a
380
+ console). Never raises: what is wrong is told. It runs in an empty
381
+ folder: nothing there stands for a module it imports."""
382
+ try:
383
+ interpreter = str(python_in(python))
384
+ except LabError as e:
385
+ return Checked(str(python), problem=e.message, hint=e.hint)
386
+ try:
387
+ with tempfile.TemporaryDirectory() as empty:
388
+ done = subprocess.run(
389
+ [interpreter, "-c", PROBE], capture_output=True, text=True,
390
+ timeout=timeout, stdin=subprocess.DEVNULL, cwd=empty,
391
+ **host.windowless(),
392
+ ) # fmt: skip
393
+ except subprocess.TimeoutExpired:
394
+ return Checked(interpreter, problem=f"It did not answer in {timeout:g} s")
395
+ except OSError as e:
396
+ return Checked(interpreter, problem=f"It does not run: {e}")
397
+ try:
398
+ told = json.loads(done.stdout.strip().splitlines()[-1])
399
+ except (IndexError, json.JSONDecodeError):
400
+ why = (done.stderr or done.stdout).strip()[-500:]
401
+ return Checked(interpreter, problem=f"It does not run as Python: {why}")
402
+ return judged(interpreter, told)
403
+
404
+
405
+ def judged(interpreter: str, told: dict) -> Checked:
406
+ """What scripts make of what an interpreter told of itself (PROBE)."""
407
+ version, has, console = told["version"], told.get("thzdaq", ""), told["console"]
408
+ found = Checked(interpreter, version, has, console)
409
+ hint = install(interpreter, wanted())
410
+ if tuple(int(part) for part in version.split(".")[:2]) < OLDEST:
411
+ oldest = ".".join(map(str, OLDEST))
412
+ problem = f"Python {version} is older than {oldest}, which {PACKAGE} needs"
413
+ hint = f"choose an environment with Python {oldest} or newer"
414
+ elif not has:
415
+ problem = f"Python {version} has no {PACKAGE} ({told.get('missing', '')})"
416
+ elif told.get("api") != API_VERSION:
417
+ problem = f"Its {PACKAGE} {has} speaks another contract than this program's"
418
+ elif has != host.app_version() and host.app_version() != host.UNKNOWN:
419
+ problem = f"Its {PACKAGE} is {has}, this program is {host.app_version()}"
420
+ else:
421
+ return found
422
+ return msgspec.structs.replace(found, problem=problem, hint=hint)
thzdaq_api/kernel.py ADDED
@@ -0,0 +1,137 @@
1
+ """The kernel of a console of the window: IPython's kernel (ipykernel) that
2
+ completes the bench, run as a program with the scripts' Python:
3
+
4
+ python -m thzdaq_api.kernel -f <connection file>
5
+
6
+ It runs only where ipykernel is (the window's Python, a build), started by the
7
+ window (thzdaq_api.console). Any Jupyter kernel completes the same after
8
+ %load_ext thzdaq_api.kernel.
9
+
10
+ IPython completes live objects itself: lab["…"] by the devices' refs
11
+ (Bench._ipython_key_completions_), the attributes of a device by its __dir__.
12
+ Its matchers here say more, as the completion's type: after the dot of a
13
+ device its quantities with their units and limits and its actions with their
14
+ arguments, and in lab.run("…") the names of the procedures. Completion never
15
+ reads a quantity: a device is described, not looked at.
16
+ """
17
+
18
+ import re
19
+ from typing import Any, Dict, List, Optional
20
+
21
+ from ipykernel.kernelapp import IPKernelApp
22
+ from IPython.core.completer import CompletionContext, SimpleCompletion, context_matcher
23
+
24
+ from thzdaq_api.devices import ActionInfo, QuantityInfo, shown
25
+ from thzdaq_api.errors import LabError
26
+ from thzdaq_api.lab import Bench, Device
27
+
28
+ # bias.vol| or lab["sis_bias_1"].vol| (the cursor at |)
29
+ ATTRIBUTE = re.compile(
30
+ r"""(?P<name>[A-Za-z_]\w*)(?:\[\s*(?P<quote>["'])(?P<ref>[^"']+)(?P=quote)\s*\])?"""
31
+ r"""\.(?P<typed>\w*)$"""
32
+ )
33
+ # lab.run("sis.cur| or lab.start('...
34
+ PROCEDURE = re.compile(
35
+ r"""(?P<name>[A-Za-z_]\w*)\.(?:run|start)\(\s*["'](?P<typed>[\w.]*)$"""
36
+ )
37
+ QUANTITY, ACTION, PROCEDURE_TYPE = "quantity", "action", "procedure"
38
+
39
+
40
+ def quantity_hint(quantity: QuantityInfo) -> str:
41
+ """What a quantity is, as its completion says: its unit, the range it
42
+ takes, or that it is only read."""
43
+ unit = quantity.unit or quantity.kind
44
+ if not quantity.settable:
45
+ return f"{QUANTITY}, {unit}, read only"
46
+ if quantity.minimum is None or quantity.maximum is None:
47
+ return f"{QUANTITY}, {unit}"
48
+ low = shown(quantity.minimum, quantity.unit, quantity.prefixes)
49
+ high = shown(quantity.maximum, quantity.unit, quantity.prefixes)
50
+ return f"{QUANTITY}, {unit}, {low} … {high}"
51
+
52
+
53
+ def action_hint(action: ActionInfo) -> str:
54
+ arguments = ", ".join(a.key for a in action.arguments)
55
+ return f"{ACTION}({arguments})" + (f": {action.danger}" if action.danger else "")
56
+
57
+
58
+ class BenchCompletions:
59
+ """The bench's matchers of a shell: they look its names up, never run code."""
60
+
61
+ def __init__(self, shell):
62
+ self.shell = shell
63
+
64
+ def named(self, name: str, ref: Optional[str]) -> Any:
65
+ """The object a name of the shell is (lab["ref"]: that device)."""
66
+ found = self.shell.user_ns.get(name)
67
+ if ref is None:
68
+ return found
69
+ return found[ref] if isinstance(found, Bench) else None
70
+
71
+ def device(self, context: CompletionContext) -> Dict[str, Any]:
72
+ typed = ATTRIBUTE.search(context.text_until_cursor)
73
+ found = None if typed is None else self.named(typed["name"], typed["ref"])
74
+ if not isinstance(found, Device):
75
+ return {"completions": []}
76
+ try:
77
+ described = found.describe()
78
+ except LabError: # the daemon does not answer: nothing of the bench to offer
79
+ return {"completions": []}
80
+ completions: List[SimpleCompletion] = [
81
+ SimpleCompletion(q.key, type=quantity_hint(q)) for q in described.quantities
82
+ ]
83
+ completions += [
84
+ SimpleCompletion(a.key, type=action_hint(a)) for a in described.actions
85
+ ]
86
+ completions = [c for c in completions if c.text.startswith(typed["typed"])]
87
+ # A device has only these: IPython's own would list them again, untold
88
+ return {
89
+ "completions": completions,
90
+ "matched_fragment": typed["typed"],
91
+ "suppress": True,
92
+ }
93
+
94
+ def procedure(self, context: CompletionContext) -> Dict[str, Any]:
95
+ typed = PROCEDURE.search(context.text_until_cursor)
96
+ found = None if typed is None else self.named(typed["name"], None)
97
+ if not isinstance(found, Bench):
98
+ return {"completions": []}
99
+ try:
100
+ procedures = found.procedures()
101
+ except LabError:
102
+ return {"completions": []}
103
+ return {
104
+ "completions": [
105
+ SimpleCompletion(p.name, type=f"{PROCEDURE_TYPE}: {p.title}")
106
+ for p in procedures
107
+ if p.name.startswith(typed["typed"])
108
+ ],
109
+ "matched_fragment": typed["typed"],
110
+ "suppress": True,
111
+ }
112
+
113
+
114
+ def load_ipython_extension(shell) -> None:
115
+ """The bench's matchers in a shell (%load_ext thzdaq_api.kernel)."""
116
+ completions = BenchCompletions(shell)
117
+
118
+ @context_matcher(identifier="thzdaq.device")
119
+ def device(context: CompletionContext) -> Dict[str, Any]:
120
+ return completions.device(context)
121
+
122
+ @context_matcher(identifier="thzdaq.procedure")
123
+ def procedure(context: CompletionContext) -> Dict[str, Any]:
124
+ return completions.procedure(context)
125
+
126
+ shell.Completer.custom_matchers.extend((device, procedure))
127
+
128
+
129
+ def main() -> None:
130
+ app = IPKernelApp.instance()
131
+ app.initialize()
132
+ load_ipython_extension(app.shell)
133
+ app.start()
134
+
135
+
136
+ if __name__ == "__main__":
137
+ main()