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.
- thzdaq_api/__init__.py +1 -0
- thzdaq_api/analysis.py +62 -0
- thzdaq_api/approvals.py +87 -0
- thzdaq_api/assistant/agents.md +202 -0
- thzdaq_api/assistant/assistant.md +23 -0
- thzdaq_api/assistant/hints.md +15 -0
- thzdaq_api/atomic.py +79 -0
- thzdaq_api/catalog.py +131 -0
- thzdaq_api/console.py +70 -0
- thzdaq_api/custom.py +326 -0
- thzdaq_api/daemon.py +183 -0
- thzdaq_api/data.py +55 -0
- thzdaq_api/declare.py +193 -0
- thzdaq_api/declaring.py +125 -0
- thzdaq_api/devices.py +307 -0
- thzdaq_api/errors.py +47 -0
- thzdaq_api/events.py +224 -0
- thzdaq_api/examples/hot_cold.py +67 -0
- thzdaq_api/examples/hot_cold_grid.py +74 -0
- thzdaq_api/examples/iv_analysis.py +34 -0
- thzdaq_api/examples/map.py +42 -0
- thzdaq_api/examples/monitor.py +35 -0
- thzdaq_api/examples/raw_instrument.py +37 -0
- thzdaq_api/examples/sweep.py +38 -0
- thzdaq_api/examples.py +79 -0
- thzdaq_api/guides.py +61 -0
- thzdaq_api/host.py +494 -0
- thzdaq_api/interpreters.py +422 -0
- thzdaq_api/kernel.py +137 -0
- thzdaq_api/lab.py +562 -0
- thzdaq_api/lanes.py +170 -0
- thzdaq_api/leases.py +29 -0
- thzdaq_api/lock.py +65 -0
- thzdaq_api/measurement_file.py +459 -0
- thzdaq_api/measurements.py +433 -0
- thzdaq_api/operation.py +52 -0
- thzdaq_api/origins.py +86 -0
- thzdaq_api/present.py +376 -0
- thzdaq_api/procedures.py +124 -0
- thzdaq_api/raw.py +272 -0
- thzdaq_api/remote.py +267 -0
- thzdaq_api/rights.py +81 -0
- thzdaq_api/script.py +382 -0
- thzdaq_api/scripts.py +133 -0
- thzdaq_api/sessions.py +176 -0
- thzdaq_api/station.py +192 -0
- thzdaq_api/terminal.py +66 -0
- thzdaq_api/tools.py +275 -0
- thzdaq_api/transport.py +93 -0
- thzdaq_api/ui.py +152 -0
- thzdaq_api/windows.py +192 -0
- thzdaq_api/wire.py +35 -0
- thzdaq_api/workspace.py +239 -0
- thzdaq_api-0.0.6b3.dist-info/METADATA +30 -0
- thzdaq_api-0.0.6b3.dist-info/RECORD +57 -0
- thzdaq_api-0.0.6b3.dist-info/WHEEL +4 -0
- thzdaq_api-0.0.6b3.dist-info/licenses/LICENSE +21 -0
thzdaq_api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""ThzDAQ contract and client: what clients of the bench daemon may call and receive."""
|
thzdaq_api/analysis.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Analysis of measured data, done by the daemon so every client gets the same
|
|
2
|
+
result. Values are in SI units: volts, amperes, ohms."""
|
|
3
|
+
|
|
4
|
+
from typing import Optional, Tuple
|
|
5
|
+
|
|
6
|
+
import msgspec
|
|
7
|
+
|
|
8
|
+
from thzdaq_api.operation import Operation
|
|
9
|
+
|
|
10
|
+
Point = Tuple[float, float] # (V, A)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class IVOptions(msgspec.Struct, frozen=True, forbid_unknown_fields=True):
|
|
14
|
+
"""Where the I-V analysis looks, in volts; an unset field keeps the
|
|
15
|
+
analysis default (rn_to unset: up to the end of the curve)."""
|
|
16
|
+
|
|
17
|
+
rn_from: Optional[float] = None # Rn: a line fitted above this voltage
|
|
18
|
+
rn_to: Optional[float] = None
|
|
19
|
+
rj_from: Optional[float] = None # Rj: the tangent from the origin below the gap
|
|
20
|
+
rj_to: Optional[float] = None
|
|
21
|
+
gap_from: Optional[float] = None # where the current step is searched
|
|
22
|
+
gap_to: Optional[float] = None
|
|
23
|
+
gap_slope_factor: Optional[float] = None # the step ends where the slope falls
|
|
24
|
+
smoothing_window: Optional[int] = None # odd number of points
|
|
25
|
+
smoothing_degree: Optional[int] = None
|
|
26
|
+
interpolation_points: Optional[int] = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class IVLine(msgspec.Struct, frozen=True):
|
|
30
|
+
"""A straight line on the I-V curve: current = slope * voltage + intercept."""
|
|
31
|
+
|
|
32
|
+
resistance: float # ohm
|
|
33
|
+
slope: float # A/V
|
|
34
|
+
intercept: float # A
|
|
35
|
+
voltage_range: Tuple[float, float] # where to draw it
|
|
36
|
+
point: Point # the reference point of a fit, the touch point of a tangent
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class IVGap(msgspec.Struct, frozen=True):
|
|
40
|
+
voltage: float # the middle of the current step
|
|
41
|
+
current_step: float
|
|
42
|
+
lower: Point
|
|
43
|
+
upper: Point
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class IVAnalysis(msgspec.Struct, frozen=True):
|
|
47
|
+
rn: IVLine # normal-state resistance: the fit above the gap
|
|
48
|
+
rj: IVLine # subgap resistance: the supporting tangent from the origin
|
|
49
|
+
q: float # Rj / Rn
|
|
50
|
+
r_squared: float # of the Rn fit
|
|
51
|
+
gap: Optional[IVGap] = None # None when no step is found
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class AnalyzeIv(Operation[IVAnalysis]):
|
|
55
|
+
"""Analyze a SIS I-V curve: normal resistance Rn (a line fitted above the
|
|
56
|
+
gap), subgap resistance Rj (the tangent from the origin), their ratio Q and
|
|
57
|
+
the gap voltage and current step. Voltage in volts, current in amperes;
|
|
58
|
+
options narrow where each value is searched."""
|
|
59
|
+
|
|
60
|
+
voltage: Tuple[float, ...]
|
|
61
|
+
current: Tuple[float, ...]
|
|
62
|
+
options: IVOptions = IVOptions()
|
thzdaq_api/approvals.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""What waits for a person: an operation an agent may do only once a person
|
|
2
|
+
allows it, or a question an agent asks.
|
|
3
|
+
|
|
4
|
+
A person sees what will change ("sis_bias_1 · Voltage: 2.1 mV → 2.3 mV"),
|
|
5
|
+
may allow it with another value, or say no with words the agent reads.
|
|
6
|
+
The first person to answer closes it for every client (approval_answered).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Optional, Tuple
|
|
10
|
+
|
|
11
|
+
import msgspec
|
|
12
|
+
|
|
13
|
+
from thzdaq_api.operation import Operation, Rights
|
|
14
|
+
|
|
15
|
+
# The longest a call waits for a person: less than an agent's tool timeout
|
|
16
|
+
ANSWER_S = 50.0
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Approval(msgspec.Struct, frozen=True):
|
|
20
|
+
"""What waits for a person. An operation has its name in operation; a
|
|
21
|
+
question has none, and maybe options to choose from."""
|
|
22
|
+
|
|
23
|
+
id: int
|
|
24
|
+
origin: str # who asks: mcp:<agent>, assistant, script:<name>
|
|
25
|
+
title: str # what: "sis_bias_1 · Voltage", "Start I-V curve"
|
|
26
|
+
text: str # how it changes, or the question
|
|
27
|
+
warning: str = "" # what may break (a dangerous step), a conflict
|
|
28
|
+
confirm: str = "" # typed by the person to allow a dangerous step
|
|
29
|
+
value: Optional[str] = None # the value asked for, in its unit: may be changed
|
|
30
|
+
options: Tuple[str, ...] = () # a question's choices
|
|
31
|
+
operation: str = ""
|
|
32
|
+
asked: str = "" # wall time, ISO
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Answer(msgspec.Struct, frozen=True):
|
|
36
|
+
"""A person's answer: allowed or not, with words for the agent."""
|
|
37
|
+
|
|
38
|
+
allowed: bool
|
|
39
|
+
text: str = "" # why not, what to do instead; or a question's answer in words
|
|
40
|
+
value: Optional[str] = None # the value to set instead of the one asked for
|
|
41
|
+
choice: Optional[str] = None # one of a question's options
|
|
42
|
+
by: str = "" # who answered; "timeout" when nobody did
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class UserAnswer(msgspec.Struct, frozen=True):
|
|
46
|
+
"""An agent's question: answered, or pending (wait_answer goes on)."""
|
|
47
|
+
|
|
48
|
+
id: int
|
|
49
|
+
pending: bool
|
|
50
|
+
answer: Optional[Answer] = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ListApprovals(Operation[Tuple[Approval, ...]]):
|
|
54
|
+
"""What waits for a person now."""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class AnswerApproval(Operation[None]):
|
|
58
|
+
"""Answer what waits: allow it or not, with words for the agent. value
|
|
59
|
+
allows an operation with another value (in its unit, "2.2 mV"); choice is
|
|
60
|
+
one of a question's options; confirm repeats what a dangerous step asks to
|
|
61
|
+
type. Only people answer, in the window or a terminal."""
|
|
62
|
+
|
|
63
|
+
rights = Rights.ANSWER
|
|
64
|
+
id: int
|
|
65
|
+
allowed: bool
|
|
66
|
+
text: str = ""
|
|
67
|
+
value: Optional[str] = None
|
|
68
|
+
choice: Optional[str] = None
|
|
69
|
+
confirm: str = ""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class AskUser(Operation[UserAnswer]):
|
|
73
|
+
"""Ask the person at the bench and wait for the answer, at most timeout
|
|
74
|
+
seconds (up to 50): a choice of options, words, or both. Still pending
|
|
75
|
+
after that: wait_answer goes on waiting."""
|
|
76
|
+
|
|
77
|
+
question: str
|
|
78
|
+
options: Tuple[str, ...] = ()
|
|
79
|
+
timeout: float = ANSWER_S
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class WaitAnswer(Operation[UserAnswer]):
|
|
83
|
+
"""Wait for the answer to a question asked with ask_user, at most timeout
|
|
84
|
+
seconds (up to 50)."""
|
|
85
|
+
|
|
86
|
+
id: int
|
|
87
|
+
timeout: float = ANSWER_S
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# ThzDAQ: measuring with an agent
|
|
2
|
+
|
|
3
|
+
ThzDAQ runs a SIS mixer bench. A daemon holds the instruments; the person at the bench
|
|
4
|
+
watches the ThzDAQ window. You reach the bench through the MCP server `thzdaq` (its tools
|
|
5
|
+
below) or the command `thzdaq` in your shell. Both are clients of the same daemon: what you
|
|
6
|
+
do is seen in the window, and what you change waits for the person's consent.
|
|
7
|
+
|
|
8
|
+
## Rules
|
|
9
|
+
|
|
10
|
+
1. **Describe before you act.** `describe_device(ref)` lists what a device reads and takes:
|
|
11
|
+
units, the range it accepts, the range beyond which a person is asked, steps and rate,
|
|
12
|
+
and DANGER for a step that may harm it. `describe_procedure(procedure)` lists the
|
|
13
|
+
parameters in the units they are typed in and the devices that suit each slot.
|
|
14
|
+
2. **Units.** Answers carry units (`2.3 mV`, `-45.1 dBm`). Type values with their unit:
|
|
15
|
+
`"2.3mV"`, `"223 GHz"`, `"10 uA"`. A bare number is SI (V, A, Hz, s, K, Pa); power is in
|
|
16
|
+
dBm, angles in degrees. Never guess a unit.
|
|
17
|
+
3. **Stay in the working range.** Do not set a value outside the range `describe_device`
|
|
18
|
+
shows. A value beyond the limits is refused (`out_of_limits`) and nothing is sent; a
|
|
19
|
+
large change goes in steps at the bench rate on its own: do not split it yourself to get
|
|
20
|
+
around a question.
|
|
21
|
+
4. **Dangerous steps** (DANGER in a description: switching a bias off, writing a
|
|
22
|
+
calibration) need a reason. Say it in words first (`ask_user`), then make the call; the
|
|
23
|
+
window asks the person to type the device's name to allow it.
|
|
24
|
+
5. **What you change waits for the person.** `set_quantity`, `call_action` and
|
|
25
|
+
`start_measurement` open a dialog in the window; the call waits up to 50 s. Reading,
|
|
26
|
+
describing, waiting and cancelling need nobody.
|
|
27
|
+
- Allowed: the call goes on, maybe with another value the person typed; the answer
|
|
28
|
+
tells the value that was set.
|
|
29
|
+
- Refused: the result is an error `denied: … not allowed: <their words>`. Read the
|
|
30
|
+
words and do as they say. Do not repeat the same call.
|
|
31
|
+
- `nobody answered in 50 s`: ask once more later, or ask in words (`ask_user`).
|
|
32
|
+
- `no person can answer now`: the window is closed. Tell the user to open ThzDAQ (or run
|
|
33
|
+
`thzdaq approvals watch` in a terminal) and wait; do not look for another way.
|
|
34
|
+
6. **Long measurements.** `start_measurement` returns at once with the run's number
|
|
35
|
+
(`#12`). Then call `wait_measurement(id, timeout)` (at most 60 s) until it ends: it tells
|
|
36
|
+
the progress while it waits and answers with a summary (records, the range of each
|
|
37
|
+
column with its unit, results) and the file. `cancel_measurement(id)` stops a run: it
|
|
38
|
+
restores what it changed. `dry_run: true` checks a start without running it.
|
|
39
|
+
7. **One sweep per device.** A device another measurement sweeps is refused (`conflict`).
|
|
40
|
+
Share it (`share: true`) only when the person agrees: both measurements note it.
|
|
41
|
+
8. **Data.** Measurements of this folder go to its `data/` as JSON
|
|
42
|
+
(`data/<date>/<number>_<procedure>.json`); `thzdaq show <file>` tells what one holds.
|
|
43
|
+
Read the file to analyse it; never pass arrays through tools.
|
|
44
|
+
9. **Ask in words** when the plan is unclear: `ask_user(question, options)` shows the
|
|
45
|
+
question in the window; still waiting after `timeout`, `wait_answer(id)` waits on.
|
|
46
|
+
10. **Raw commands** go to an instrument as typed, for what its driver does not wrap
|
|
47
|
+
(`raw_command(instrument, command)`, `instrument` is its id in the profile, not a
|
|
48
|
+
device on it). A query (with `?`, `*IDN?`) waits for the person like a set. A write
|
|
49
|
+
is refused to agents whatever you are allowed: no limit checks it. When the bench
|
|
50
|
+
needs one, say which command and why (`ask_user`); the person sends it.
|
|
51
|
+
11. **The bench's own measurements** (`custom.<name>`) are Python scripts in the bench's
|
|
52
|
+
library (`measurements/` of the program's folder, `list_custom` names it). Read one
|
|
53
|
+
(`read_custom`), check a change (`check_custom` with `text`) before you write it
|
|
54
|
+
(`write_custom`: the person sees the change first), and run it with
|
|
55
|
+
`start_measurement(procedure="custom.<name>", typed=..., devices=...)` as any
|
|
56
|
+
procedure. The format is below.
|
|
57
|
+
12. **Show the curves.** A run is drawn in the ThzDAQ window by itself. When the window
|
|
58
|
+
is closed, `thzdaq plot <number|file>` opens a window with only the plots of that
|
|
59
|
+
measurement, live while it runs (a plot of your own: `--table pv --x voltage --y
|
|
60
|
+
power --group load`); it changes nothing and needs nobody. In a script: `m.show()`
|
|
61
|
+
within `lab.measurement`, `run.show()` of `lab.run`, `lab.plot(<number|file>)`.
|
|
62
|
+
|
|
63
|
+
13. **Show the person where.** When the person does it in the window, or asks how,
|
|
64
|
+
point there instead of doing it: `ui_state` tells what the window shows (its docks,
|
|
65
|
+
the controls of the bar on top, the measurement chosen there and its form), by the
|
|
66
|
+
names `ui_open` and `ui_highlight` take. `ui_fill_measurement` chooses a measurement in
|
|
67
|
+
the bar on top and fills its form (values as `start_measurement` takes them); it
|
|
68
|
+
starts nothing: the person checks the form and presses Start, so it needs nobody's
|
|
69
|
+
consent. Then `ui_highlight(anchor="run:start", text="…")` shows them the button.
|
|
70
|
+
Highlight one place at a time with a few words; it goes when the person acts there.
|
|
71
|
+
These go to the window the person was at last, or to the `window` you name (one of
|
|
72
|
+
`windows` in `ui_state`); `no ThzDAQ window is open`: tell the user to open one.
|
|
73
|
+
|
|
74
|
+
## Tools of the MCP server `thzdaq`
|
|
75
|
+
|
|
76
|
+
| Tool | What it does |
|
|
77
|
+
|---|---|
|
|
78
|
+
| `list_devices`, `describe_device`, `read_device` | the devices, what they take, what they read now |
|
|
79
|
+
| `set_quantity(ref, key, value)` | set a value (with its unit); a person allows it |
|
|
80
|
+
| `call_action(ref, action, arguments)` | an action of a device (turn the load, read a trace) |
|
|
81
|
+
| `raw_command(instrument, command)` | a raw query (with `?`) to an instrument; a person allows it |
|
|
82
|
+
| `list_connections` | the connections the instruments share, open or broken |
|
|
83
|
+
| `list_procedures`, `describe_procedure` | what the bench measures and how a run would go |
|
|
84
|
+
| `start_measurement` | start a procedure; a person allows it |
|
|
85
|
+
| `wait_measurement`, `summarize_measurement` | follow a run, what it holds so far |
|
|
86
|
+
| `cancel_measurement`, `list_runs` | stop a run; the runs of the daemon |
|
|
87
|
+
| `list_custom`, `read_custom` | the bench's own measurements: their scripts |
|
|
88
|
+
| `check_custom(script, text)` | what is wrong with a script, by line; the form it declares |
|
|
89
|
+
| `write_custom(script, text)` | save a script of the library; a person allows it |
|
|
90
|
+
| `ask_user`, `wait_answer` | a question to the person at the bench |
|
|
91
|
+
| `ui_state` | what the ThzDAQ window shows: docks, the bar on top, the chosen measurement's form |
|
|
92
|
+
| `ui_open(place)`, `ui_highlight(anchor, text)` | show a dock or a measurement; point at a place with a short text |
|
|
93
|
+
| `ui_fill_measurement` | fill a measurement's form in the window for the person to start |
|
|
94
|
+
| `get_daemon_status` | the daemon, its profile, clients, runs and problems |
|
|
95
|
+
|
|
96
|
+
Resources: `thzdaq://procedures`, `thzdaq://procedures/<name>`, `thzdaq://station` (the
|
|
97
|
+
profile; connections only by their kind) and `thzdaq://guide/<topic>` (this guide is
|
|
98
|
+
`agents`).
|
|
99
|
+
|
|
100
|
+
## Example: an I-V curve
|
|
101
|
+
|
|
102
|
+
1. `list_devices` → the SIS biases, e.g. `sis_bias_1`.
|
|
103
|
+
2. `describe_procedure(procedure="sis.current_vs_voltage")` → `voltage`: a sweep in mV,
|
|
104
|
+
default `0:7:351`; the slot `bias` takes `sis_bias_1` or `sis_bias_2`. A parameter
|
|
105
|
+
"used only when hot_cold=true" matters only with that value; names are
|
|
106
|
+
`<group>.<what is measured>_vs_<what is changed>`, and a name a procedure had before
|
|
107
|
+
(`sis.iv_curve`) still finds it.
|
|
108
|
+
3. `start_measurement(procedure="sis.current_vs_voltage", devices={"bias": "sis_bias_1"},
|
|
109
|
+
typed={"voltage": "0:7:351"})` → the person allows it in the window →
|
|
110
|
+
`#12 SIS I-V curve (sis.current_vs_voltage): running, 0/351 steps`.
|
|
111
|
+
4. `wait_measurement(id=12, timeout=60)` until `completed` → the summary: table `iv`, 351
|
|
112
|
+
records, `voltage` and `current` with their ranges, the file.
|
|
113
|
+
5. Read the file to find the gap, Rn and the rest.
|
|
114
|
+
|
|
115
|
+
## The command line
|
|
116
|
+
|
|
117
|
+
The same operations from your shell, with `--json` for answers to parse:
|
|
118
|
+
`thzdaq devices`, `thzdaq device sis_bias_1`, `thzdaq read sis_bias_1`,
|
|
119
|
+
`thzdaq set sis_bias_1 voltage_set 2.3mV`, `thzdaq procedures`,
|
|
120
|
+
`thzdaq describe sis.current_vs_voltage`, `thzdaq raw sis_block_1 "*IDN?"`,
|
|
121
|
+
`thzdaq run sis.current_vs_voltage --device bias=sis_bias_1 --set voltage=0:7:351`
|
|
122
|
+
(follows the run to its end; `--detach` only starts it), `thzdaq status`, `thzdaq cancel 12`,
|
|
123
|
+
`thzdaq plot 12` (its plots in a window of their own), `thzdaq show <file>`. In an agent's shell the command is the agent's (`cli:agent`): `--yes`
|
|
124
|
+
does not answer for the person, and what changes the bench waits for them as with MCP.
|
|
125
|
+
|
|
126
|
+
## Connecting an agent
|
|
127
|
+
|
|
128
|
+
`thzdaq agent-setup [<folder>]` writes into the folder `.mcp.json` (Claude Code),
|
|
129
|
+
`.codex/config.toml` (Codex), this guide as `AGENTS.md` and `CLAUDE.md` that takes it in.
|
|
130
|
+
The server is started by the absolute path of the `thzdaq` that wrote them (the build's
|
|
131
|
+
`thzdaq-cli.exe`, or the `thzdaq` of an environment) with `mcp --workspace <folder>`, so
|
|
132
|
+
measurements land in the folder's `data/`.
|
|
133
|
+
|
|
134
|
+
- Claude Code reads `.mcp.json` when it starts in the folder and asks once to trust the
|
|
135
|
+
server.
|
|
136
|
+
- Codex reads `.codex/config.toml` of a trusted project only. Otherwise put the table into
|
|
137
|
+
`~/.codex/config.toml`:
|
|
138
|
+
|
|
139
|
+
```toml
|
|
140
|
+
[mcp_servers.thzdaq]
|
|
141
|
+
command = "C:\\ThzDAQ\\thzdaq-cli.exe"
|
|
142
|
+
args = ["mcp", "--workspace", "C:\\Users\\lab\\experiment"]
|
|
143
|
+
tool_timeout_sec = 120 # a call waits up to 50 s for a person, a wait up to 60 s
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
`thzdaq --simulate agent-setup` points the agents at the simulator's daemon: a bench to
|
|
147
|
+
try things on without instruments.
|
|
148
|
+
|
|
149
|
+
## A measurement of the bench's own
|
|
150
|
+
|
|
151
|
+
A script whose top declares its form; the window, `thzdaq run custom.<name>` and
|
|
152
|
+
`start_measurement` give it the devices and values chosen. Each declaration is assigned
|
|
153
|
+
to a name (the slot or parameter of that name), all of them before `connect()`:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
"""P-V on both loads
|
|
157
|
+
|
|
158
|
+
IF power against bias on the hot and the cold load.
|
|
159
|
+
"""
|
|
160
|
+
from thzdaq import connect, device, plot, value
|
|
161
|
+
|
|
162
|
+
bias = device("SIS bias", kind="sis_bias") # a slot: a SIS bias
|
|
163
|
+
detector = device("Detector", "PowerDetector") # a slot: any power detector
|
|
164
|
+
load = device("Load", "LoadSwitch")
|
|
165
|
+
voltage = value("Bias voltage", "0:7:351", unit="mV") # a sweep, typed in mV
|
|
166
|
+
settle = value("Settle", 10, unit="ms") # a number, given in s
|
|
167
|
+
pv = plot("P-V", table="pv", x="voltage", y="power", group_by="load")
|
|
168
|
+
|
|
169
|
+
lab = connect()
|
|
170
|
+
with lab.measurement("pv", devices=[bias, detector, load], exclusive=[bias]) as m:
|
|
171
|
+
m.restore(bias, "voltage_set") # the daemon sets it back however it ends
|
|
172
|
+
m.on_exit(load, "to_cold")
|
|
173
|
+
for state in ("hot", "cold"):
|
|
174
|
+
getattr(load, f"to_{state}")()
|
|
175
|
+
for v in m.sweep(voltage): # stops at a cancel
|
|
176
|
+
bias.voltage_set = v
|
|
177
|
+
m.sleep(settle)
|
|
178
|
+
m.record("pv", load=state, voltage=bias.read().voltage, power=detector.power)
|
|
179
|
+
m.progress()
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
- `device(title, *capabilities, kind=...)`: the device chosen for the slot.
|
|
183
|
+
- `value(title, default, unit=..., minimum=..., maximum=..., choices=...)`: a number in
|
|
184
|
+
SI (typed in `unit`), a sweep for `m.sweep`, true/false, a choice, a text or a list.
|
|
185
|
+
- `plot(title, table, x, y, group_by=..., kind="map", z=...)`: a plot known before the start;
|
|
186
|
+
`m.plot(...)` adds one while it runs, `m.show()` opens the plots window.
|
|
187
|
+
- `instrument(id, driver="generic.scpi", connection="tcp://host:port", name=reading(...),
|
|
188
|
+
other=setting(...))`: an instrument without a driver of its own, spoken to in raw
|
|
189
|
+
commands. `reading(query, unit, parse, scale)` makes a value of an answer (`parse`: a
|
|
190
|
+
regular expression, a dict of answers, a function; `scale` to SI), `setting(query,
|
|
191
|
+
"CMD {:.6f}", unit, minimum, maximum)` writes one within its limits; `name.raw(cmd)`
|
|
192
|
+
sends any command. Its first run puts the instrument into the profile once a person
|
|
193
|
+
allows it, and a person allows its raw writes (then within the measurement they go on).
|
|
194
|
+
Your scripts are refused both: write the script, then ask the person to run it once
|
|
195
|
+
or to add the instrument in Setup → Add instrument → Generic (raw). Once it is in the
|
|
196
|
+
profile as declared, your script may read it (raw queries are asked like a set).
|
|
197
|
+
- The first line of the docstring is its title. Records: one table per kind of point,
|
|
198
|
+
every loop variable a column.
|
|
199
|
+
- Import what the program's own Python may lack (scipy, a module of your own) below
|
|
200
|
+
`connect()`, never at the top: the form and the catalog are read with the program's
|
|
201
|
+
Python, which stops at `connect()`; the run goes on with the Python of the workspace
|
|
202
|
+
it was started from (`thzdaq python show`).
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# ThzDAQ: the assistant in the window
|
|
2
|
+
|
|
3
|
+
You are the assistant in the ThzDAQ window, next to the person at a SIS mixer bench. A
|
|
4
|
+
daemon holds the instruments; you reach it through your tools, the same ones agents get
|
|
5
|
+
over MCP. You have no shell and no files: the rules below name the command line and the
|
|
6
|
+
MCP server for agents outside the window, you call the tools directly.
|
|
7
|
+
|
|
8
|
+
- The person sees each of your tool calls as a card in the chat, and what you change
|
|
9
|
+
(a set, an action, a start) asks them in a dialog of this window first. When they
|
|
10
|
+
refuse, their words come back to you: do as they say, do not try another way.
|
|
11
|
+
- Answer in the language the person writes in. Be short: say what you will do, do it,
|
|
12
|
+
tell what came of it with the units the tools gave.
|
|
13
|
+
- Plan before a measurement: name the procedure, its devices and the values, and why.
|
|
14
|
+
When the plan is not clear, ask in the chat and stop; a question with choices may go
|
|
15
|
+
to `ask_user`.
|
|
16
|
+
- You live in the person's window: `ui_state`, `ui_open`, `ui_fill_measurement` and
|
|
17
|
+
`ui_highlight` always go to it. When the person asks how to do something, show them:
|
|
18
|
+
fill the form and highlight where to click rather than describing the window in words.
|
|
19
|
+
- Read the data of a measurement through `summarize_measurement`: ranges, records and
|
|
20
|
+
results. You cannot read its file; the person sees its curves in the window's graphs
|
|
21
|
+
and opens it from Data.
|
|
22
|
+
- Measurements you start run in the daemon: they go on when the window closes, this
|
|
23
|
+
chat does not.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# ThzDAQ: code hints in the editor and the console
|
|
2
|
+
|
|
3
|
+
You write Python for the person at a SIS mixer bench, in the editor of the ThzDAQ window
|
|
4
|
+
(a script of the bench) or in its Python console. A daemon holds the instruments; code
|
|
5
|
+
reaches them through `lab` of `from thzdaq import connect`.
|
|
6
|
+
|
|
7
|
+
- Answer with code only, in one ```python block. Say what is not obvious in a short
|
|
8
|
+
comment inside it, never in words around it.
|
|
9
|
+
- What you write is a proposal: the person sees it as a change, takes it or not, and
|
|
10
|
+
runs it. You run nothing yourself.
|
|
11
|
+
- Name only the devices listed below, by their refs; values with units go as strings
|
|
12
|
+
(`"2.3 mV"`) or in SI. Loops that wait between points use `m.sleep` within a
|
|
13
|
+
measurement, else `time.sleep`.
|
|
14
|
+
- Keep the code where it goes: its indentation, its names, its style. Change only what
|
|
15
|
+
is asked; a fix changes what the error needs.
|
thzdaq_api/atomic.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Coordinate atomic file replacement with readers, including on Windows."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import os
|
|
5
|
+
import sys
|
|
6
|
+
import tempfile
|
|
7
|
+
from contextlib import contextmanager, nullcontext
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from thzdaq_api.lock import FileLock
|
|
11
|
+
|
|
12
|
+
ACCESS_S = 15.0
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _key(path: Path) -> str:
|
|
16
|
+
"""One name per file however the path is spelled, never beside the file:
|
|
17
|
+
the folders of data stay as people left them."""
|
|
18
|
+
where = os.path.normcase(str(path.parent.resolve() / path.name))
|
|
19
|
+
return hashlib.sha256(where.encode("utf-8")).hexdigest()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def read_bytes(path: Path) -> bytes:
|
|
23
|
+
# POSIX permits replacing an open file; Windows needs the same guard as
|
|
24
|
+
# its writer. A named mutex lets readers use a read-only folder too.
|
|
25
|
+
with file_access(path) if sys.platform == "win32" else nullcontext():
|
|
26
|
+
return path.read_bytes()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
if sys.platform == "win32":
|
|
30
|
+
import ctypes
|
|
31
|
+
from ctypes import wintypes
|
|
32
|
+
|
|
33
|
+
_kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
34
|
+
_kernel.CreateMutexW.argtypes = [wintypes.LPVOID, wintypes.BOOL, wintypes.LPCWSTR]
|
|
35
|
+
_kernel.CreateMutexW.restype = wintypes.HANDLE
|
|
36
|
+
_kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
|
|
37
|
+
_kernel.WaitForSingleObject.restype = wintypes.DWORD
|
|
38
|
+
_kernel.ReleaseMutex.argtypes = [wintypes.HANDLE]
|
|
39
|
+
_kernel.ReleaseMutex.restype = wintypes.BOOL
|
|
40
|
+
_kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
|
41
|
+
_kernel.CloseHandle.restype = wintypes.BOOL
|
|
42
|
+
|
|
43
|
+
@contextmanager
|
|
44
|
+
def file_access(path: Path, timeout: float = ACCESS_S):
|
|
45
|
+
"""Serialize access across threads, processes and Windows sessions."""
|
|
46
|
+
name = "Global\\ThzDAQ-file-" + _key(path)
|
|
47
|
+
handle = _kernel.CreateMutexW(None, False, name)
|
|
48
|
+
if not handle:
|
|
49
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
50
|
+
try:
|
|
51
|
+
result = _kernel.WaitForSingleObject(handle, max(0, int(timeout * 1000)))
|
|
52
|
+
if result == 0x102:
|
|
53
|
+
raise TimeoutError(f"File access timed out: {path}")
|
|
54
|
+
if result not in (0, 0x80): # acquired, or abandoned by a dead owner
|
|
55
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
56
|
+
try:
|
|
57
|
+
yield
|
|
58
|
+
finally:
|
|
59
|
+
if not _kernel.ReleaseMutex(handle):
|
|
60
|
+
raise ctypes.WinError(ctypes.get_last_error())
|
|
61
|
+
finally:
|
|
62
|
+
_kernel.CloseHandle(handle)
|
|
63
|
+
|
|
64
|
+
else:
|
|
65
|
+
# This user's locks, as a named mutex is this machine's: a folder of /tmp
|
|
66
|
+
# one user made the others could not write in
|
|
67
|
+
LOCKS = Path(tempfile.gettempdir()) / f"thzdaq-locks-{os.getuid()}"
|
|
68
|
+
|
|
69
|
+
@contextmanager
|
|
70
|
+
def file_access(path: Path, timeout: float = ACCESS_S):
|
|
71
|
+
"""Serialize publishers; POSIX readers need no lock for replacement."""
|
|
72
|
+
LOCKS.mkdir(parents=True, exist_ok=True)
|
|
73
|
+
lock = FileLock(LOCKS / f"{_key(path)}.lock")
|
|
74
|
+
if not lock.acquire(timeout):
|
|
75
|
+
raise TimeoutError(f"File access timed out: {path}")
|
|
76
|
+
try:
|
|
77
|
+
yield
|
|
78
|
+
finally:
|
|
79
|
+
lock.release()
|
thzdaq_api/catalog.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Every operation of the bench, listed explicitly: MCP tools, the assistant's tools
|
|
2
|
+
and the CLI help are built from this list, and the daemon has one handler for each."""
|
|
3
|
+
|
|
4
|
+
from typing import Any, Dict, Tuple, Type
|
|
5
|
+
|
|
6
|
+
import msgspec
|
|
7
|
+
|
|
8
|
+
from thzdaq_api import (
|
|
9
|
+
analysis,
|
|
10
|
+
approvals,
|
|
11
|
+
custom,
|
|
12
|
+
daemon,
|
|
13
|
+
devices,
|
|
14
|
+
events,
|
|
15
|
+
leases,
|
|
16
|
+
measurements,
|
|
17
|
+
scripts,
|
|
18
|
+
sessions,
|
|
19
|
+
station,
|
|
20
|
+
ui,
|
|
21
|
+
)
|
|
22
|
+
from thzdaq_api.errors import ErrorCode, LabError
|
|
23
|
+
from thzdaq_api.operation import Operation
|
|
24
|
+
|
|
25
|
+
OPERATIONS: Tuple[Type[Operation], ...] = (
|
|
26
|
+
devices.ListDevices,
|
|
27
|
+
devices.DescribeDevice,
|
|
28
|
+
devices.ReadDevice,
|
|
29
|
+
devices.SetQuantity,
|
|
30
|
+
devices.CallAction,
|
|
31
|
+
devices.RawCommand,
|
|
32
|
+
devices.SafeState,
|
|
33
|
+
devices.SubscribePoll,
|
|
34
|
+
devices.CancelPoll,
|
|
35
|
+
events.GetSnapshot,
|
|
36
|
+
measurements.ListProcedures,
|
|
37
|
+
measurements.DescribeProcedure,
|
|
38
|
+
measurements.StartMeasurement,
|
|
39
|
+
measurements.ListRuns,
|
|
40
|
+
measurements.GetRunSnapshot,
|
|
41
|
+
measurements.WaitMeasurement,
|
|
42
|
+
measurements.SummarizeMeasurement,
|
|
43
|
+
measurements.CancelMeasurement,
|
|
44
|
+
measurements.AbortMeasurement,
|
|
45
|
+
measurements.SetComment,
|
|
46
|
+
sessions.StartSession,
|
|
47
|
+
sessions.KeepSession,
|
|
48
|
+
sessions.RecordSession,
|
|
49
|
+
sessions.AdvanceSession,
|
|
50
|
+
sessions.LogSession,
|
|
51
|
+
sessions.PlotSession,
|
|
52
|
+
sessions.RestoreOnExit,
|
|
53
|
+
sessions.CallOnExit,
|
|
54
|
+
sessions.EndSession,
|
|
55
|
+
sessions.ParseSweep,
|
|
56
|
+
custom.ParseValue,
|
|
57
|
+
custom.ListCustom,
|
|
58
|
+
custom.ReadCustom,
|
|
59
|
+
custom.CheckCustom,
|
|
60
|
+
custom.WriteCustom,
|
|
61
|
+
scripts.StartScript,
|
|
62
|
+
scripts.ListScripts,
|
|
63
|
+
scripts.ReadScriptLog,
|
|
64
|
+
scripts.StopScript,
|
|
65
|
+
station.GetStation,
|
|
66
|
+
station.LoadStation,
|
|
67
|
+
station.NewStation,
|
|
68
|
+
station.UpdateStation,
|
|
69
|
+
station.DeclareInstrument,
|
|
70
|
+
station.ListDrivers,
|
|
71
|
+
station.ListConnectionKinds,
|
|
72
|
+
station.ConnectInstrument,
|
|
73
|
+
station.GetSisCalibration,
|
|
74
|
+
station.SetSisCalibration,
|
|
75
|
+
station.ListConnections,
|
|
76
|
+
station.ResetConnection,
|
|
77
|
+
leases.ListLeases,
|
|
78
|
+
analysis.AnalyzeIv,
|
|
79
|
+
approvals.ListApprovals,
|
|
80
|
+
approvals.AnswerApproval,
|
|
81
|
+
approvals.AskUser,
|
|
82
|
+
approvals.WaitAnswer,
|
|
83
|
+
ui.UiState,
|
|
84
|
+
ui.UiOpen,
|
|
85
|
+
ui.UiFillMeasurement,
|
|
86
|
+
ui.UiHighlight,
|
|
87
|
+
ui.WindowActive,
|
|
88
|
+
ui.AnswerUi,
|
|
89
|
+
daemon.GetDaemonStatus,
|
|
90
|
+
daemon.GetDaemonSettings,
|
|
91
|
+
daemon.SetDaemonSettings,
|
|
92
|
+
daemon.ReadDaemonLog,
|
|
93
|
+
daemon.ResetLane,
|
|
94
|
+
daemon.StopDaemon,
|
|
95
|
+
daemon.RestartDaemon,
|
|
96
|
+
)
|
|
97
|
+
BY_NAME: Dict[str, Type[Operation]] = {op.name: op for op in OPERATIONS}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def operation(name: str) -> Type[Operation]:
|
|
101
|
+
try:
|
|
102
|
+
return BY_NAME[name]
|
|
103
|
+
except KeyError:
|
|
104
|
+
raise LabError(
|
|
105
|
+
ErrorCode.UNKNOWN_OPERATION,
|
|
106
|
+
f"No operation {name!r}",
|
|
107
|
+
f"known: {', '.join(sorted(BY_NAME))}",
|
|
108
|
+
) from None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def schema(op: Type[Operation]) -> Dict[str, Any]:
|
|
112
|
+
"""JSON schema of the arguments; its description is the operation's docstring."""
|
|
113
|
+
return msgspec.json.schema(op)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def description(op: Type[Operation]) -> str:
|
|
117
|
+
"""What the operation does, for a model: its docstring in one paragraph."""
|
|
118
|
+
return " ".join((op.__doc__ or "").split())
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def tool_schema(op: Type[Operation]) -> Dict[str, Any]:
|
|
122
|
+
"""The arguments as a tool takes them (MCP, a model's tools): the object at
|
|
123
|
+
the top, the types it refers to under $defs; the description goes apart."""
|
|
124
|
+
found = schema(op)
|
|
125
|
+
types = dict(found.get("$defs", {}))
|
|
126
|
+
arguments = dict(types.pop(op.__name__))
|
|
127
|
+
arguments.pop("title", None)
|
|
128
|
+
arguments.pop("description", None)
|
|
129
|
+
if types:
|
|
130
|
+
arguments["$defs"] = types
|
|
131
|
+
return arguments
|
thzdaq_api/console.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""A Python console of the window: what the window gives the kernel of each
|
|
2
|
+
console it opens.
|
|
3
|
+
|
|
4
|
+
The kernel is IPython's (ipykernel, thzdaq_api.kernel), a process of its own
|
|
5
|
+
that the window talks to over the Jupyter protocol: code that hangs or dies
|
|
6
|
+
there leaves the window and the daemon alone. It runs with the Python of the
|
|
7
|
+
window's workspace, as its scripts do (thzdaq_api.interpreters: the one its
|
|
8
|
+
thzdaq.toml names, else the program's own), so it has every module a script
|
|
9
|
+
has; a kernel keeps the one it started with until it restarts. It is a client of the daemon as a script is: it
|
|
10
|
+
calls as console (thzdaq_api.origins), with the rights of a person's script,
|
|
11
|
+
in the window's workspace, on the window's daemon (the simulator's too).
|
|
12
|
+
|
|
13
|
+
IPython keeps the history of every console of the program in one base, in the
|
|
14
|
+
program's own folder (not the person's ~/.ipython: their startup files and
|
|
15
|
+
settings stay out of the bench's console).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Dict, List, Optional
|
|
20
|
+
|
|
21
|
+
from thzdaq_api import host, interpreters
|
|
22
|
+
from thzdaq_api.origins import CONSOLE_ENV
|
|
23
|
+
from thzdaq_api.scripts import SIMULATE_ENV
|
|
24
|
+
from thzdaq_api.workspace import WORKSPACE_ENV
|
|
25
|
+
|
|
26
|
+
KERNEL = "thzdaq_api.kernel" # the module the kernel runs
|
|
27
|
+
CONNECTION = "{connection_file}" # where jupyter_client names the kernel's file
|
|
28
|
+
IPYTHON_DIR_ENV = "IPYTHONDIR" # where IPython keeps its history and settings
|
|
29
|
+
# What a console runs as it opens, and again after each restart
|
|
30
|
+
OPENING = "from thzdaq import *\nlab = connect()"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def kernel_command(
|
|
34
|
+
workspace: Optional[Path] = None, built: Optional[Path] = None
|
|
35
|
+
) -> List[str]:
|
|
36
|
+
"""How the window starts a console's kernel: with the Python of its
|
|
37
|
+
workspace; built: with that build's thzdaq-cli (the release checks its
|
|
38
|
+
build so). LabError when the workspace names a Python that is not
|
|
39
|
+
there."""
|
|
40
|
+
if built is not None:
|
|
41
|
+
return host.built_module(built, KERNEL, "-f", CONNECTION)
|
|
42
|
+
return interpreters.module_command(workspace, KERNEL, "-f", CONNECTION)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def history_dir() -> Path:
|
|
46
|
+
"""IPython's folder of the program's consoles, their one history; made
|
|
47
|
+
when missing (IPython takes a temporary folder in place of one that is
|
|
48
|
+
not there)."""
|
|
49
|
+
found = host.user_dir() / "ipython"
|
|
50
|
+
found.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
return found
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def kernel_environment(simulate: bool, workspace: Optional[Path]) -> Dict[str, str]:
|
|
55
|
+
"""What the window adds to a kernel's environment: it calls as console,
|
|
56
|
+
the window's daemon (simulate) and workspace, IPython's folder."""
|
|
57
|
+
found = {
|
|
58
|
+
CONSOLE_ENV: "1",
|
|
59
|
+
SIMULATE_ENV: "1" if simulate else "0",
|
|
60
|
+
IPYTHON_DIR_ENV: str(history_dir()),
|
|
61
|
+
}
|
|
62
|
+
if workspace is not None:
|
|
63
|
+
found[WORKSPACE_ENV] = str(workspace)
|
|
64
|
+
return found
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def run_file(path: Path) -> str:
|
|
68
|
+
"""The code that runs a script in a console as IPython's %run does: as
|
|
69
|
+
__main__, its names left in the console to look at."""
|
|
70
|
+
return f'%run "{Path(path).as_posix()}"'
|