thzdaq-api 0.0.6b4__tar.gz

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 (68) hide show
  1. thzdaq_api-0.0.6b4/.gitignore +25 -0
  2. thzdaq_api-0.0.6b4/LICENSE +21 -0
  3. thzdaq_api-0.0.6b4/PKG-INFO +30 -0
  4. thzdaq_api-0.0.6b4/README.md +8 -0
  5. thzdaq_api-0.0.6b4/pyproject.toml +34 -0
  6. thzdaq_api-0.0.6b4/src/thzdaq_api/__init__.py +1 -0
  7. thzdaq_api-0.0.6b4/src/thzdaq_api/analysis.py +62 -0
  8. thzdaq_api-0.0.6b4/src/thzdaq_api/approvals.py +87 -0
  9. thzdaq_api-0.0.6b4/src/thzdaq_api/assistant/agents.md +202 -0
  10. thzdaq_api-0.0.6b4/src/thzdaq_api/assistant/assistant.md +23 -0
  11. thzdaq_api-0.0.6b4/src/thzdaq_api/assistant/hints.md +15 -0
  12. thzdaq_api-0.0.6b4/src/thzdaq_api/atomic.py +79 -0
  13. thzdaq_api-0.0.6b4/src/thzdaq_api/catalog.py +131 -0
  14. thzdaq_api-0.0.6b4/src/thzdaq_api/console.py +70 -0
  15. thzdaq_api-0.0.6b4/src/thzdaq_api/custom.py +326 -0
  16. thzdaq_api-0.0.6b4/src/thzdaq_api/daemon.py +183 -0
  17. thzdaq_api-0.0.6b4/src/thzdaq_api/data.py +55 -0
  18. thzdaq_api-0.0.6b4/src/thzdaq_api/declare.py +193 -0
  19. thzdaq_api-0.0.6b4/src/thzdaq_api/declaring.py +125 -0
  20. thzdaq_api-0.0.6b4/src/thzdaq_api/devices.py +307 -0
  21. thzdaq_api-0.0.6b4/src/thzdaq_api/errors.py +47 -0
  22. thzdaq_api-0.0.6b4/src/thzdaq_api/events.py +224 -0
  23. thzdaq_api-0.0.6b4/src/thzdaq_api/examples/hot_cold.py +67 -0
  24. thzdaq_api-0.0.6b4/src/thzdaq_api/examples/hot_cold_grid.py +74 -0
  25. thzdaq_api-0.0.6b4/src/thzdaq_api/examples/iv_analysis.py +34 -0
  26. thzdaq_api-0.0.6b4/src/thzdaq_api/examples/map.py +42 -0
  27. thzdaq_api-0.0.6b4/src/thzdaq_api/examples/monitor.py +35 -0
  28. thzdaq_api-0.0.6b4/src/thzdaq_api/examples/raw_instrument.py +37 -0
  29. thzdaq_api-0.0.6b4/src/thzdaq_api/examples/sweep.py +38 -0
  30. thzdaq_api-0.0.6b4/src/thzdaq_api/examples.py +79 -0
  31. thzdaq_api-0.0.6b4/src/thzdaq_api/guides.py +61 -0
  32. thzdaq_api-0.0.6b4/src/thzdaq_api/host.py +494 -0
  33. thzdaq_api-0.0.6b4/src/thzdaq_api/interpreters.py +422 -0
  34. thzdaq_api-0.0.6b4/src/thzdaq_api/kernel.py +137 -0
  35. thzdaq_api-0.0.6b4/src/thzdaq_api/lab.py +562 -0
  36. thzdaq_api-0.0.6b4/src/thzdaq_api/lanes.py +170 -0
  37. thzdaq_api-0.0.6b4/src/thzdaq_api/leases.py +29 -0
  38. thzdaq_api-0.0.6b4/src/thzdaq_api/lock.py +65 -0
  39. thzdaq_api-0.0.6b4/src/thzdaq_api/measurement_file.py +459 -0
  40. thzdaq_api-0.0.6b4/src/thzdaq_api/measurements.py +435 -0
  41. thzdaq_api-0.0.6b4/src/thzdaq_api/operation.py +52 -0
  42. thzdaq_api-0.0.6b4/src/thzdaq_api/origins.py +86 -0
  43. thzdaq_api-0.0.6b4/src/thzdaq_api/present.py +389 -0
  44. thzdaq_api-0.0.6b4/src/thzdaq_api/procedures.py +124 -0
  45. thzdaq_api-0.0.6b4/src/thzdaq_api/raw.py +272 -0
  46. thzdaq_api-0.0.6b4/src/thzdaq_api/remote.py +267 -0
  47. thzdaq_api-0.0.6b4/src/thzdaq_api/rights.py +81 -0
  48. thzdaq_api-0.0.6b4/src/thzdaq_api/script.py +382 -0
  49. thzdaq_api-0.0.6b4/src/thzdaq_api/scripts.py +133 -0
  50. thzdaq_api-0.0.6b4/src/thzdaq_api/sessions.py +176 -0
  51. thzdaq_api-0.0.6b4/src/thzdaq_api/station.py +192 -0
  52. thzdaq_api-0.0.6b4/src/thzdaq_api/terminal.py +66 -0
  53. thzdaq_api-0.0.6b4/src/thzdaq_api/tools.py +275 -0
  54. thzdaq_api-0.0.6b4/src/thzdaq_api/transport.py +93 -0
  55. thzdaq_api-0.0.6b4/src/thzdaq_api/ui.py +152 -0
  56. thzdaq_api-0.0.6b4/src/thzdaq_api/windows.py +192 -0
  57. thzdaq_api-0.0.6b4/src/thzdaq_api/wire.py +35 -0
  58. thzdaq_api-0.0.6b4/src/thzdaq_api/workspace.py +239 -0
  59. thzdaq_api-0.0.6b4/tests/test_atomic.py +47 -0
  60. thzdaq_api-0.0.6b4/tests/test_console.py +151 -0
  61. thzdaq_api-0.0.6b4/tests/test_contract.py +150 -0
  62. thzdaq_api-0.0.6b4/tests/test_examples.py +51 -0
  63. thzdaq_api-0.0.6b4/tests/test_host.py +166 -0
  64. thzdaq_api-0.0.6b4/tests/test_interpreters.py +302 -0
  65. thzdaq_api-0.0.6b4/tests/test_measurement_file.py +129 -0
  66. thzdaq_api-0.0.6b4/tests/test_raw.py +108 -0
  67. thzdaq_api-0.0.6b4/tests/test_renamed.py +68 -0
  68. thzdaq_api-0.0.6b4/tests/test_workspace.py +121 -0
@@ -0,0 +1,25 @@
1
+ .idea
2
+ venv
3
+ .venv
4
+ .uv-cache
5
+ build
6
+ dist
7
+ *__pycache__
8
+ *.log
9
+ *.DS_Store
10
+ *.spec
11
+ !ThzDAQ.spec
12
+ *.ipynb
13
+ .env
14
+ /data/
15
+ # What a daemon run from sources keeps between runs
16
+ /daemon.json
17
+ /daemon-sim.json
18
+ # Window layout and perspectives of a local run
19
+ /settings.ini
20
+ # What a daemon run from sources keeps of instruments (a grid's angle)
21
+ /state.json
22
+ /state-sim.json
23
+ # The program's own measurements and the profiles' previous versions
24
+ /measurements/
25
+ stations/.history/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 yarvod
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.5
2
+ Name: thzdaq-api
3
+ Version: 0.0.6b4
4
+ Summary: ThzDAQ contract and client: operations, data types and events of the bench daemon
5
+ Project-URL: Homepage, https://github.com/yarvod/ThzDAQ
6
+ Project-URL: Documentation, https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md
7
+ Project-URL: Issues, https://github.com/yarvod/ThzDAQ/issues
8
+ Project-URL: Releases, https://github.com/yarvod/ThzDAQ/releases
9
+ Author: yarvod
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Topic :: Scientific/Engineering :: Physics
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: msgspec>=0.19
21
+ Description-Content-Type: text/markdown
22
+
23
+ # thzdaq-api
24
+
25
+ The contract between the ThzDAQ bench daemon and its clients (GUI, CLI, MCP, scripts):
26
+ operations, data types, events and errors, and the client that calls the daemon. It
27
+ depends only on `msgspec`: no Qt, no numpy, no instrument drivers. Install it with
28
+ [`thzdaq`](https://pypi.org/project/thzdaq/); see
29
+ [docs/daemon.md](https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md),
30
+ «Пакеты, слои и границы».
@@ -0,0 +1,8 @@
1
+ # thzdaq-api
2
+
3
+ The contract between the ThzDAQ bench daemon and its clients (GUI, CLI, MCP, scripts):
4
+ operations, data types, events and errors, and the client that calls the daemon. It
5
+ depends only on `msgspec`: no Qt, no numpy, no instrument drivers. Install it with
6
+ [`thzdaq`](https://pypi.org/project/thzdaq/); see
7
+ [docs/daemon.md](https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md),
8
+ «Пакеты, слои и границы».
@@ -0,0 +1,34 @@
1
+ [project]
2
+ name = "thzdaq-api"
3
+ version = "0.0.6b4"
4
+ description = "ThzDAQ contract and client: operations, data types and events of the bench daemon"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "yarvod" }]
10
+ classifiers = [
11
+ "Development Status :: 3 - Alpha",
12
+ "Intended Audience :: Science/Research",
13
+ "Operating System :: OS Independent",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Topic :: Scientific/Engineering :: Physics",
18
+ ]
19
+ dependencies = [
20
+ "msgspec>=0.19",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/yarvod/ThzDAQ"
25
+ Documentation = "https://github.com/yarvod/ThzDAQ/blob/master/docs/daemon.md"
26
+ Issues = "https://github.com/yarvod/ThzDAQ/issues"
27
+ Releases = "https://github.com/yarvod/ThzDAQ/releases"
28
+
29
+ [build-system]
30
+ requires = ["hatchling>=1.27"]
31
+ build-backend = "hatchling.build"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/thzdaq_api"]
@@ -0,0 +1 @@
1
+ """ThzDAQ contract and client: what clients of the bench daemon may call and receive."""
@@ -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()
@@ -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.
@@ -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()