Skip to content

Python API

The laborchestra package: pip install laborchestra. It is the same package for devices, scripts and procedures.

Base class of all Python devices.

Class attributes configure it: annotated without default = required option, with a default = optional option. state is a dict that is published whenever it changes, persist lists the state keys that are saved.

Class attributes a device may set:

Attribute Meaning
state dict of what the device shows; every change, also nested, is published, recorded and kept in the history
persist list of state keys that are saved and restored after a restart
profiles the profiles the device follows, e.g. [PressureSensor]
kind "device" (default) or "service"
annotated attributes options: port: str is required, baudrate: int = 9600 is optional; set per device on the Devices page

Inside a device, self.lock is an RLock for hardware access that must not overlap (actions run in parallel threads).

False once the device is asked to stop. Use it as while self.running:.

self.sleep(seconds: float) -> bool

Sleep, but wake up early when the device is asked to stop. Returns True if stopping.

Access to all devices of the lab: self.lab["pressure"].state.

self.offline(reason: str) -> None

Say that the instrument cannot be reached (cable, power, network). The device stays alive: it is shown as offline with the reason, actions are refused with it, and the state keeps its last values. Call online when it is back. Raising ConnectionError or TimeoutError in run() does this for you and reconnects with backoff (close(), then connect(), then run() again).

self.online() -> None

The instrument answers again (after offline).

(no description yet)

self.connect() -> None

Open connections to hardware. Raise to report that the device cannot start.

self.run() -> None

Long-running loop. Plain functions run in their own thread, coroutines as a task.

self.close() -> None

Release hardware after run() ended.

Mark a method as callable from the dashboard, scripts and other devices. The type hints of its parameters are checked and make the form in the dashboard.

A background task: it runs all the time, watches or does things, and is no instrument.

A service is a device (the same lifecycle, restart with backoff, logs, state, settings, options with secrets, and it can read and call other devices), and the interface treats it as what it is for the people who use it: it has its own section on the Devices page, is kept off the dashboards, and restarts by itself when its file changes (there is no hardware to touch)::

class PressureUploader(Service):
device: str = "pressure" # options, as in any device
api_key: str # (a secret is given by reference in devices.json)
def run(self):
while self.running:
... # self.lab["pressure"].state, self.lab["turbo"].start(0)
self.sleep(60)
laborchestra.connect(url: str | None = None, token: str | None = None, timeout: float = 10, name: str = 'script') -> Lab

Connect to the server (LABORCHESTRA_URL / LABORCHESTRA_TOKEN if not given).

On the lab PC, connect() needs nothing: it finds the address and passphrase of the server installed there. For another computer, give its address and the passphrase (or a token).

name says who you are in the record of changes (“script”, or e.g. “notebook”).

laborchestra.connect_async(url: str | None = None, token: str | None = None, timeout: float = 10, name: str = 'script') -> AsyncLab

The same for asyncio code: every method below is a coroutine there.

Blocking client. lab = laborchestra.connect(), then lab.pressure.state. lab.<device> (or lab["device"]) is a device, see below. A Lab is a context manager: with laborchestra.connect() as lab: closes it at the end.

lab.close() -> None

Closes the connection to the server.

lab.logs(source: str | None = None, level: str | None = None, since: int = 0, limit: int = 200) -> list[dict]

Log entries as dicts (seq, time, level, source, logger, message, traceback).

source is “server”, “device:” or None for all. With since=0 you get the latest entries, otherwise the entries after that seq, so that since=entries[-1]["seq"] follows the log.

lab.events(device: str | None = None, kind: str | None = None, since: float = 0, until: float = 0, limit: int = 500) -> list[dict]

What happened to devices, oldest first (persistent, also when nothing was recording): kind is “action” (data: action, args) or “status” (data: status, error); by says who caused it. since/until are unix times.

lab.history(device: str, path: str, since: float = 0, until: float = 0, max_points: int = 1000) -> list[list[float]]

A numeric state field over time as [unix time, value] pairs, e.g. history("pressure", "channels.1.pressure", since=time.time() - 86400). The server keeps one value per field per ten seconds for 30 days; longer series are averaged into max_points.

lab.add_note(text: str, refs: list[str] | None = None) -> str

A note, optionally pointing at devices, recordings or other ids (refs); returns its id.

lab.notes(ref: str | None = None, since: float = 0, limit: int = 200) -> list[dict]

Notes (id, time, author, text, refs), oldest first; with ref only those that point at it.

lab.stream(device: str, stream: str, parameters: dict | None = None, window: int = 8, max_fps: float = 30) -> SyncStream

with lab.stream("het", "display", {...}) as frames: for frame in frames: (see laborchestra.stream).

lab.get_recording() -> dict

{“active”: False} or name, start_time, elapsed_s, events, tags of the running recording.

lab.start_recording(name: str, tags: dict | None = None) -> dict

Start recording every change of every device (and the data streams) under this name.

lab.stop_recording() -> dict

Stops the recording that is going on and returns its header (name, files, end time).

lab.abort_recording(discard: bool = False) -> dict

Stops the recording that is going on; with discard=True its files are deleted (and its number is given back).

lab.snapshot(name: str, tags: dict | None = None) -> dict

Save the state of all devices now, in one file.

lab.list_recordings(limit: int = 100) -> list[dict]

The latest recordings and snapshots (name, time, tags, path), newest first.

lab.recording(name: str, tags: dict | None = None) -> _Recording

with lab.recording("scan 1", tags={...}): starts and, even after an error, stops it.

lab.restart_device(device_id: str) -> None

Stops a device and starts it again (refused while a recording is going on).

lab.list_procedures() -> list[dict]

The procedures of the workspace: name, title, doc, devices, params (name, type, default, required). A file that cannot be loaded has an error.

lab.start_procedure(procedure: str, /, **params: Any) -> dict

Starts a procedure with these parameters and returns the run (see wait_for_run). Raises RemoteError (ReservationError) when a device it declares is reserved by another run.

lab.get_run(run_id: str) -> dict

A run: status (preparing, starting, running, paused, aborting, finished, failed, aborted, crashed), progress, message, result, error, …

lab.list_runs(limit: int = 50) -> list[dict]

The latest procedure runs with status, progress and outcome, newest first.

lab.abort_run(run_id: str, force: bool = False) -> None

Asks the procedure to stop (its finally blocks run). force=True kills its process at once.

lab.pause_run(run_id: str) -> None

Pauses at the procedure’s next sleep, checkpoint or device call.

lab.resume_run(run_id: str) -> None

Resumes a paused procedure run.

lab.wait_for_run(run_id: str, timeout: float = 3600) -> dict

Waits until the run is over and returns it. Raises TimeoutError.

lab.list_presets() -> list[dict]

Saved parameter sets of procedures, the shipped ones included: id, title, procedure, params, the required parameters they leave open.

lab.run_preset(preset: str, /, **params) -> dict

Starts a preset’s procedure; params add to its parameters or replace them. Returns the run.

lab.save_preset(preset: str, procedure: str, /, title: str | None = None, **params) -> None

Saves parameters of a procedure as a preset of the workspace (presets.json); the dashboard shows it as a button.

lab.delete_preset(preset: str) -> None

Removes a preset of the workspace.

lab.list_device_files() -> list[dict]

Python files of the workspace with the ids of the devices that use them: {“file”, “devices”}.

lab.describe_device_file(file: str) -> dict

What a device file offers, without starting it: class, doc, options (name, type, default, required), actions.

lab.list_drivers() -> list[dict]

C# drivers that can be used with driver=: driver, class, doc.

lab.describe_driver(driver: str) -> dict

What a C# driver offers: its options, actions, state and profiles.

lab.add_device(device_id: str, file: str | None = None, config: dict | None = None, python: str | None = None, description: str | None = None, driver: str | None = None, remote: bool = False) -> None

Add a device to devices.json and start it: a Python file, a C# driver, or remote=True for a worker on another machine (then create_token gives that worker its token). config holds its options; a value {"secret": "name"} refers to a secret.

lab.list_environments() -> list[dict]

The Python environments of the devices: key, python, dependencies, size_mb, last_used (unix time), used_by (device ids).

lab.cleanup_environments(older_than_days: int = 30) -> list[dict]

Delete environments that no device runs in and that were not used for older_than_days days; returns those removed.

lab.list_pythons() -> list[dict]

Pythons on this computer that a device may use (python= of add_device): version, path, implementation.

lab.create_token(device_id: str, label: str | None = None) -> dict

A token for a worker on another machine that runs the remote device device_id. Returns {"token", "id", ...}; the token is shown only now. Start the worker with laborchestra worker device.py --id <device_id> --url <server> --token <token>.

lab.list_tokens() -> list[dict]

The tokens of remote workers, without the tokens themselves.

lab.revoke_token(token_id: str) -> None

Revokes a token: whoever uses it cannot connect again.

lab.update_device(device_id: str, file: str | None = None, config: dict | None = None, python: str | None = None, description: str | None = None, driver: str | None = None) -> None

Replace the entry of a device (it restarts if anything but the description changed).

lab.remove_device(device_id: str) -> None

Stops a device and removes it from devices.json (its file stays in the workspace).

lab.get_device_config(device_id: str) -> dict

The entry of devices.json: file, python, config, description.

lab.list_secrets() -> list[str]

Names of the stored secrets (their values are never sent back).

lab.set_secret(name: str, value: str) -> None

Store a secret; devices whose config has {“secret”: name} are restarted.

lab.delete_secret(name: str) -> None

Deletes a stored secret.

The ids of all devices and services.

lab.vacuum_gauge gives the device. Its actions are methods (lab.vacuum_gauge.set_pressure(0, 1e-3)); they return when the device is done.

Last known state (read-only, kept up to date by the server).

ready, starting, degraded, reconnecting, error, stopped, …

What the device offers: options, actions with their parameters, units, profiles.

Why the device does not work, or None.

True when the device’s file changed after it started: what runs is not what is on disk.

device.call(action: str, *args: Any) -> Any

Calls an action by its name (the same as device.<action>(...)); returns when the device is done.

device.logs(level: str | None = None, since: int = 0, limit: int = 200) -> list[dict]

Log entries of this device (see AsyncLab.logs).

device.restart() -> None

Stop the worker of this device and start it again.

device.wait_for(predicate, timeout: float = 30) -> dict

Wait until the device is ready and predicate(state) is true; returns the state. Raises TimeoutError.

device.wait_ready(timeout: float = 30) -> dict

Wait until the device is ready (registered and running); returns its state.

Marks an async def as a procedure. The first parameter receives the lab (see Run), the others are the parameters of the run: type hints make the form, defaults make them optional. devices lists every device the procedure uses. on starts the procedure by itself when such an event happens ("recording.finished", …): a parameter named event (event: dict | None = None) receives what the server says about it.

The lab of a procedure: the devices (lab.cavity_detuning.set_frequency(0, 1e6)), and what a run adds.

lab.device(device_id: str) -> _Device

A device by id (also for ids that are not valid Python names).

lab.checkpoint() -> None

Waits here while the run is paused (a pause takes effect at the next checkpoint; sleep, progress over async for, device calls and recordings have one). Never waits once the run is being aborted, so that cleanup can run.

lab.sleep(seconds: float) -> None

Like asyncio.sleep, but a pause stops the clock.

lab.progress(items: Iterable | int, label: str | None = None) -> _Progress

for x in lab.progress(items): shows the run’s progress in the UI (async for pauses at each item).

lab.status(text: str) -> None

A line that says what the run is doing now, shown next to the progress (and in the run’s log).

lab.recording(name: str, tags: dict | None = None) -> _Recording

async with lab.recording("scan 1", tags={...}): a recording that is stopped when the block ends, however it ends. The server also stops it if the run dies, and notes the run (procedure, source, parameters) in its metadata.

laborchestra.load_recording(path: str | Path) -> Recording

Load a recording or snapshot: pass the .yaml file or the name without extension. Needs pip install "laborchestra[analysis]".

The devices whose state the recording has.

rec.state_at(t: float | None = None) -> dict[str, dict]

The state of every device at time t (seconds since the start); without t the state at the end.

rec.changes(device: str | None = None, by: str | None = None) -> Iterator[dict]

Events, optionally of one device and/or caused by by (“script”, “ui”, “device”, …).

rec.series(path: str)

Times and values of one field, e.g. "pressure.channels.1.pressure": the value at the start, then at every change. Returns numpy arrays if numpy is installed, else lists.

rec.channel(device: str, index: int, mmap: bool = True)

A data stream the device wrote (<device>_C<index>.npy), by default as a memory map.

Base class of all errors raised by this package.

An error that happened on the other side of a call.

type and traceback come from the remote exception, if the other side sent them.

The server rejected the token.

The connection was lost while a call was pending.

A device does not follow the conventions (names, types).