Python API
The laborchestra package: pip install laborchestra. It is the same package for devices, scripts and procedures.
Devices
Section titled “Devices”class Device
Section titled “class Device”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).
self.running
Section titled “self.running”False once the device is asked to stop. Use it as while self.running:.
self.sleep()
Section titled “self.sleep()”self.sleep(seconds: float) -> boolSleep, but wake up early when the device is asked to stop. Returns True if stopping.
self.lab
Section titled “self.lab”Access to all devices of the lab: self.lab["pressure"].state.
self.offline()
Section titled “self.offline()”self.offline(reason: str) -> NoneSay 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()
Section titled “self.online()”self.online() -> NoneThe instrument answers again (after offline).
self.is_offline
Section titled “self.is_offline”(no description yet)
self.connect()
Section titled “self.connect()”self.connect() -> NoneOpen connections to hardware. Raise to report that the device cannot start.
self.run()
Section titled “self.run()”self.run() -> NoneLong-running loop. Plain functions run in their own thread, coroutines as a task.
self.close()
Section titled “self.close()”self.close() -> NoneRelease hardware after run() ended.
@action
Section titled “@action”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.
class Service(Device)
Section titled “class Service(Device)”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)Scripts
Section titled “Scripts”laborchestra.connect()
Section titled “laborchestra.connect()”laborchestra.connect(url: str | None = None, token: str | None = None, timeout: float = 10, name: str = 'script') -> LabConnect 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()
Section titled “laborchestra.connect_async()”laborchestra.connect_async(url: str | None = None, token: str | None = None, timeout: float = 10, name: str = 'script') -> AsyncLabThe same for asyncio code: every method below is a coroutine there.
class Lab
Section titled “class Lab”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()
Section titled “lab.close()”lab.close() -> NoneCloses the connection to the server.
lab.logs()
Section titled “lab.logs()”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:since=0 you get the latest entries,
otherwise the entries after that seq, so that since=entries[-1]["seq"] follows the log.
lab.events()
Section titled “lab.events()”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()
Section titled “lab.history()”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()
Section titled “lab.add_note()”lab.add_note(text: str, refs: list[str] | None = None) -> strA note, optionally pointing at devices, recordings or other ids (refs); returns its id.
lab.notes()
Section titled “lab.notes()”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()
Section titled “lab.stream()”lab.stream(device: str, stream: str, parameters: dict | None = None, window: int = 8, max_fps: float = 30) -> SyncStreamwith lab.stream("het", "display", {...}) as frames: for frame in frames: (see laborchestra.stream).
lab.get_recording()
Section titled “lab.get_recording()”lab.get_recording() -> dict{“active”: False} or name, start_time, elapsed_s, events, tags of the running recording.
lab.start_recording()
Section titled “lab.start_recording()”lab.start_recording(name: str, tags: dict | None = None) -> dictStart recording every change of every device (and the data streams) under this name.
lab.stop_recording()
Section titled “lab.stop_recording()”lab.stop_recording() -> dictStops the recording that is going on and returns its header (name, files, end time).
lab.abort_recording()
Section titled “lab.abort_recording()”lab.abort_recording(discard: bool = False) -> dictStops the recording that is going on; with discard=True its files are deleted (and its number is given back).
lab.snapshot()
Section titled “lab.snapshot()”lab.snapshot(name: str, tags: dict | None = None) -> dictSave the state of all devices now, in one file.
lab.list_recordings()
Section titled “lab.list_recordings()”lab.list_recordings(limit: int = 100) -> list[dict]The latest recordings and snapshots (name, time, tags, path), newest first.
lab.recording()
Section titled “lab.recording()”lab.recording(name: str, tags: dict | None = None) -> _Recordingwith lab.recording("scan 1", tags={...}): starts and, even after an error, stops it.
lab.restart_device()
Section titled “lab.restart_device()”lab.restart_device(device_id: str) -> NoneStops a device and starts it again (refused while a recording is going on).
lab.list_procedures()
Section titled “lab.list_procedures()”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()
Section titled “lab.start_procedure()”lab.start_procedure(procedure: str, /, **params: Any) -> dictStarts 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()
Section titled “lab.get_run()”lab.get_run(run_id: str) -> dictA run: status (preparing, starting, running, paused, aborting, finished, failed, aborted, crashed), progress, message, result, error, …
lab.list_runs()
Section titled “lab.list_runs()”lab.list_runs(limit: int = 50) -> list[dict]The latest procedure runs with status, progress and outcome, newest first.
lab.abort_run()
Section titled “lab.abort_run()”lab.abort_run(run_id: str, force: bool = False) -> NoneAsks the procedure to stop (its finally blocks run). force=True kills its process at once.
lab.pause_run()
Section titled “lab.pause_run()”lab.pause_run(run_id: str) -> NonePauses at the procedure’s next sleep, checkpoint or device call.
lab.resume_run()
Section titled “lab.resume_run()”lab.resume_run(run_id: str) -> NoneResumes a paused procedure run.
lab.wait_for_run()
Section titled “lab.wait_for_run()”lab.wait_for_run(run_id: str, timeout: float = 3600) -> dictWaits until the run is over and returns it. Raises TimeoutError.
lab.list_presets()
Section titled “lab.list_presets()”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()
Section titled “lab.run_preset()”lab.run_preset(preset: str, /, **params) -> dictStarts a preset’s procedure; params add to its parameters or replace them. Returns the run.
lab.save_preset()
Section titled “lab.save_preset()”lab.save_preset(preset: str, procedure: str, /, title: str | None = None, **params) -> NoneSaves parameters of a procedure as a preset of the workspace (presets.json); the dashboard shows it as a button.
lab.delete_preset()
Section titled “lab.delete_preset()”lab.delete_preset(preset: str) -> NoneRemoves a preset of the workspace.
lab.list_device_files()
Section titled “lab.list_device_files()”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()
Section titled “lab.describe_device_file()”lab.describe_device_file(file: str) -> dictWhat a device file offers, without starting it: class, doc, options (name, type, default, required), actions.
lab.list_drivers()
Section titled “lab.list_drivers()”lab.list_drivers() -> list[dict]C# drivers that can be used with driver=: driver, class, doc.
lab.describe_driver()
Section titled “lab.describe_driver()”lab.describe_driver(driver: str) -> dictWhat a C# driver offers: its options, actions, state and profiles.
lab.add_device()
Section titled “lab.add_device()”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) -> NoneAdd 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()
Section titled “lab.list_environments()”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()
Section titled “lab.cleanup_environments()”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()
Section titled “lab.list_pythons()”lab.list_pythons() -> list[dict]Pythons on this computer that a device may use (python= of add_device): version, path, implementation.
lab.create_token()
Section titled “lab.create_token()”lab.create_token(device_id: str, label: str | None = None) -> dictA 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()
Section titled “lab.list_tokens()”lab.list_tokens() -> list[dict]The tokens of remote workers, without the tokens themselves.
lab.revoke_token()
Section titled “lab.revoke_token()”lab.revoke_token(token_id: str) -> NoneRevokes a token: whoever uses it cannot connect again.
lab.update_device()
Section titled “lab.update_device()”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) -> NoneReplace the entry of a device (it restarts if anything but the description changed).
lab.remove_device()
Section titled “lab.remove_device()”lab.remove_device(device_id: str) -> NoneStops a device and removes it from devices.json (its file stays in the workspace).
lab.get_device_config()
Section titled “lab.get_device_config()”lab.get_device_config(device_id: str) -> dictThe entry of devices.json: file, python, config, description.
lab.list_secrets()
Section titled “lab.list_secrets()”lab.list_secrets() -> list[str]Names of the stored secrets (their values are never sent back).
lab.set_secret()
Section titled “lab.set_secret()”lab.set_secret(name: str, value: str) -> NoneStore a secret; devices whose config has {“secret”: name} are restarted.
lab.delete_secret()
Section titled “lab.delete_secret()”lab.delete_secret(name: str) -> NoneDeletes a stored secret.
lab.devices
Section titled “lab.devices”The ids of all devices and services.
A device in a script
Section titled “A device in a script”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.
device.state
Section titled “device.state”Last known state (read-only, kept up to date by the server).
device.status
Section titled “device.status”ready, starting, degraded, reconnecting, error, stopped, …
device.schema
Section titled “device.schema”What the device offers: options, actions with their parameters, units, profiles.
device.error
Section titled “device.error”Why the device does not work, or None.
device.changed
Section titled “device.changed”True when the device’s file changed after it started: what runs is not what is on disk.
device.call()
Section titled “device.call()”device.call(action: str, *args: Any) -> AnyCalls an action by its name (the same as device.<action>(...)); returns when the device is done.
device.logs()
Section titled “device.logs()”device.logs(level: str | None = None, since: int = 0, limit: int = 200) -> list[dict]Log entries of this device (see AsyncLab.logs).
device.restart()
Section titled “device.restart()”device.restart() -> NoneStop the worker of this device and start it again.
device.wait_for()
Section titled “device.wait_for()”device.wait_for(predicate, timeout: float = 30) -> dictWait until the device is ready and predicate(state) is true; returns the state. Raises TimeoutError.
device.wait_ready()
Section titled “device.wait_ready()”device.wait_ready(timeout: float = 30) -> dictWait until the device is ready (registered and running); returns its state.
Procedures
Section titled “Procedures”@procedure
Section titled “@procedure”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
Section titled “The lab of a procedure”The lab of a procedure: the devices (lab.cavity_detuning.set_frequency(0, 1e6)), and what a run adds.
lab.device()
Section titled “lab.device()”lab.device(device_id: str) -> _DeviceA device by id (also for ids that are not valid Python names).
lab.checkpoint()
Section titled “lab.checkpoint()”lab.checkpoint() -> NoneWaits 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()
Section titled “lab.sleep()”lab.sleep(seconds: float) -> NoneLike asyncio.sleep, but a pause stops the clock.
lab.progress()
Section titled “lab.progress()”lab.progress(items: Iterable | int, label: str | None = None) -> _Progressfor x in lab.progress(items): shows the run’s progress in the UI (async for pauses at each item).
lab.status()
Section titled “lab.status()”lab.status(text: str) -> NoneA line that says what the run is doing now, shown next to the progress (and in the run’s log).
lab.recording()
Section titled “lab.recording()”lab.recording(name: str, tags: dict | None = None) -> _Recordingasync 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.
Recordings
Section titled “Recordings”laborchestra.load_recording()
Section titled “laborchestra.load_recording()”laborchestra.load_recording(path: str | Path) -> RecordingLoad a recording or snapshot: pass the .yaml file or the name without extension. Needs pip install "laborchestra[analysis]".
rec.devices
Section titled “rec.devices”The devices whose state the recording has.
rec.state_at()
Section titled “rec.state_at()”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()
Section titled “rec.changes()”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()
Section titled “rec.series()”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()
Section titled “rec.channel()”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.
Errors
Section titled “Errors”LabOrchestraError
Section titled “LabOrchestraError”Base class of all errors raised by this package.
RemoteError
Section titled “RemoteError”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.
AuthError
Section titled “AuthError”The server rejected the token.
ConnectionLost
Section titled “ConnectionLost”The connection was lost while a call was pending.
SchemaError
Section titled “SchemaError”A device does not follow the conventions (names, types).
Something wrong or missing on this page? Open a GitHub issue or use the form (no account needed).