Python SDK

API Reference

Complete reference for all classes, methods, and their signatures. Each entry includes the function signature, parameter descriptions, and return type.

SemphonyClient

Thin HTTP client for the Semphony control server REST API. Authenticates with a Bearer token and provides methods to create runs and download artifacts.

Import: from semphony import SemphonyClient

SemphonyClient (base_url: str, api_key: str)

Create a new client instance. The base_url is the root URL of your Semphony control server (trailing slash is stripped). The api_key is a personal access token generated in the Semphony dashboard.

.run (name: str, *, resume: bool = True, metadata: dict | None = None, system: str | None = None) → Run

Create a new run or resume an existing one with the same name. When resume=True (default), a run with the same name is resumed if it exists; otherwise a new run is created. Pass system to target a specific system (e.g. "tescan-001"). Optional metadata dict is stored with the run.

.invoke_capability (run_id: int, session_id: int, capability_id: str, payload: dict | None = None) → dict

Low-level method to invoke a capability on an attached device. You typically don't call this directly; device classes use it internally. Posts to /api/runs/{run_id}/sessions/{session_id}/commands/{capability_id}.

.download_image (image_id: str | int, *, target_path: str | None = None) → bytes | str

Download an acquisition artifact by its ID. If target_path is provided, streams the image to that file and returns the path. Otherwise returns raw bytes. Raises SemphonyApiError if image_id is None or on HTTP errors.

Run

Represents an experiment instance. Created via client.run().

Import: from semphony import Run

.session (guardrails: ImagingGuardrails | None = None) → Session

Create a new session for this run. Use as a context manager (with run.session() as s:) or call .start() / .close() manually for notebooks. Pass guardrails to enable safety checks during the session.

Properties

  • id : int — Server-assigned run ID.
  • name : str — Name of the run.
  • status : str — Current run status (e.g. "pending", "running").

Session

A session belongs to a run and is the scope in which devices are attached and commands are executed. Supports both context manager and explicit start/close usage.

.start () → Session

Explicitly create the session on the server. Useful in notebooks where you need the session across multiple cells. If guardrails are set, they are sent to the server after session creation. Idempotent: calling start on an already-started session is a no-op.

.close () → None

Mark the session (and underlying run) as finished on the server. Idempotent: safe to call multiple times. Also called automatically when exiting the context manager.

ImagingDevice

Imaging-capable device abstraction for SEMs and similar instruments. Exposes .chamber, .imaging, and .stage interfaces.

Import: from semphony.systems import ImagingDevice

ImagingDevice (client: SemphonyClient, *, device_slug: str | None = None, device_id: int | None = None)

Create an imaging device instance. Provide either device_slug (e.g. "tescan-001") or device_id. At least one is required.

.attach (session: Session, force_close: bool = False) → None

Attach this device to a session so it can receive capability calls. Must be called before any imaging, stage, or chamber operations.

.acquire (config: AcquisitionConfig, *, download: bool = False, target_path: str | None = None) → AcquisitionResult

Convenience alias for imaging.acquire(). Acquires an image with the given configuration. Set download=True to fetch the image from the server; provide target_path to save to disk.

ImagingInterface (.imaging)

Accessed via device.imaging. Core imaging operations, ROI management, autofocus, and human-in-the-loop. Also exposes .geometric_transformations and .centerings sub-interfaces.

.acquire (config: AcquisitionConfig, *, download: bool = False, target_path: str | None = None) → AcquisitionResult

Acquire an image with the given configuration. Blocks until the device completes. Retries up to 2 times on 504 timeout. Raises SemphonyApiError on failure. If download=True and the result includes an image_id, the image is downloaded via the API.

.save_roi (name: str, spec: RoiSpec, *, config: AcquisitionConfig | None = None, target_dir: str | None = None, inter_level_delay_s: float = 1.0) → SavedRoi

Capture a pyramidal ROI at the current stage position. Acquires images at each level whose FOV in the spec is > 0. Optionally saves images and manifest to target_dir. A short delay between levels allows hardware settling.

.find_roi (roi_path: str, *, stage_mode: str = "same_session", max_iters: int = 8, px_tol: float = 15.0, ...) → FindRoiResult

Navigate back to a previously saved ROI using correlative image matching. Loads the saved pyramid, then iteratively acquires live images and corrects stage position. Requires semphony[find-roi].

All parameters
  • roi_path — path to saved ROI directory or manifest.json.
  • stage_mode — "same_session" or "cross_session".
  • initial_pose — optional initial stage position dict.
  • start_level — level to start from (e.g. "l0").
  • base_config — base AcquisitionConfig for live images.
  • max_initial_fov_um — max FOV for initial overview.
  • max_zoom_out_retries — retries with wider FOV (default 0).
  • max_iters — total iterations across levels (default 8).
  • max_iters_per_level — max iterations per level (default 4).
  • px_tol — pixel tolerance for convergence (default 15.0).
  • rot_tol_rad — rotation tolerance in radians (default 0.017).
  • scale_tol — scale tolerance (default 0.02).
  • gain_xy, gain_rot, gain_fov — correction gains (default 0.8).
  • min_confidence — minimum match confidence (default 0.25).
.autofocus (config: AutofocusConfig) → AutofocusResult

Run DeepFocus iterative autofocus. For each iteration: reads current WD/stigmation, acquires two perturbed images (WD +/- sigma), predicts corrections with the trained CNN, applies them, and repeats until convergence. Requires semphony[autofocus].

.await_human (message: str) → dict

Pause the workflow and display a message in the Semphony UI. Blocks until the operator clicks Continue. Use for sample loading, manual ROI selection, or any step requiring human interaction.

.get_focus_params () → dict

Get current focus parameters: working distance (mm), stigmation X and Y. Returns a dict with keys wd_mm, stigm_x, stigm_y.

.set_focus_params (wd_mm: float | None = None, stigm_x: float | None = None, stigm_y: float | None = None) → dict

Set working distance and/or stigmation values. Only provided (non-None) parameters are sent.

.set_view_field (fov_um: float) → dict

Set the field of view in micrometres without acquiring an image. Dispatches to the device's SetViewField capability.

.set_beam (enabled: bool) → dict

Turn the electron beam on or off. Guardrails enforce that vacuum must be present before enabling.

.get_metrics () → dict

Return current device metrics snapshot: beam status, stage position, vacuum, stigmator, magnification, etc.

ImagingChamber (.chamber)

Accessed via device.chamber. Vacuum control for the SEM chamber.

.vent () → dict

Vent the chamber (release vacuum). Used before loading or exchanging a sample. Guardrails require beam to be off.

.pump () → dict

Pump (evacuate) the chamber. Typically called after loading a sample and closing the chamber door.

ImagingStageInterface (.stage)

Accessed via device.stage. Absolute and relative stage movement. Coordinates in millimetres (x, y, z) and degrees (r, t).

.get_pos () → dict

Query the device for the live stage position (x, y, z, r, t). Raises SemphonyApiError on 502/504.

.get_latest_pos () → dict

Return the last-reported stage position from server-stored metrics. Faster than get_pos(), but may be stale. Raises SemphonyApiError on 409 (stale).

.move_to (x: float, y: float, z: float | None = None, r: float | None = None) → dict

Move the stage to an absolute position. Only x and y are required. Coordinates in mm (x, y, z) and degrees (r). Subject to stage guardrails if configured.

.move_delta (dx: float = 0, dy: float = 0, dz: float | None = None, dr: float | None = None, dt: float | None = None) → dict

Move the stage by a relative offset. dx/dy in mm; dr/dt in degrees. When relative guardrails are active, the max move may be limited to a percentage of the current FOV.

GeometricTransformations (.imaging.geometric_transformations)

SharkSEM-style geometric transformations (beam shift, tilt correction, rotation, etc.). Access by name (fuzzy, case-insensitive) or by numeric index.

.list () → dict

List all available geometry parameters. Returns a dict keyed by index with name, count, and unit for each geometry.

.get (name_or_index, *, index: int | None = None, name: str | None = None) → dict

Get the current value(s) for a geometry parameter. Accepts a positional name/index or keyword arguments. Example: .get("tilt_correction") or .get(index=0).

.set (name_or_index, *, index: int | None = None, name: str | None = None, x: float = 0.0, y: float | None = None) → dict

Set a geometry parameter's value(s). Provide x (required) and optionally y for 2D geometries. Example: .set("tilt_correction", x=0.0).

.reset () → dict

Reset all geometry parameters to zero. Returns a summary with reset indices.

Centerings (.imaging.centerings)

SharkSEM-style centerings (beam shift, aperture alignment, etc.). Same API pattern as geometric transformations: access by name or index.

.list () → dict

List all available centering parameters with name, count, and unit.

.get (name_or_index, *, index: int | None = None, name: str | None = None) → dict

Get current value(s) for a centering. Example: .get("beam_shift").

.set (name_or_index, *, index: int | None = None, name: str | None = None, x: float = 0.0, y: float | None = None) → dict

Set a centering parameter. Example: .set("beam_shift", x=0.0, y=0.0).

DeformationDevice

Base device for deformation stages (tensile stages, load frames). Attach to sessions and invoke capabilities. High-level APIs are extensible as new devices are added.

Import: from semphony.systems import DeformationDevice

DeformationDevice (client: SemphonyClient, *, device_slug: str | None = None, device_id: int | None = None)

Create a deformation device instance. Provide device_slug or device_id.

.attach (session: Session, force_close: bool = False) → None

Attach this device to a session so it can receive capability calls.

Exceptions

SemphonyApiError extends RuntimeError

Raised when the control server cannot be reached, returns a non-2xx status, or returns a non-JSON response (e.g. a login redirect). Also wraps device-level failures (e.g. ScScanXY errors).

Import: from semphony.client import SemphonyApiError

SemphonyGuardrailException extends Exception

Raised when a guardrail rule is violated before executing a capability. Includes guardrail_type (str) and details (dict) attributes.

Import: from semphony import SemphonyGuardrailException

Convenience functions

semphony.run (name: str, *, client: SemphonyClient, resume: bool = True, metadata: dict | None = None, system: str | None = None) → Run

Module-level convenience helper. Equivalent to client.run(...).

load_roi_from_fs (path: str) → SavedRoi

Load a SavedRoi from the filesystem. Accepts either a directory containing manifest.json or the path to the manifest itself. Resolves relative level paths to absolute paths.

Import: from semphony.models import load_roi_from_fs