Skip to content

Scan development API

This reference describes the scan class, hooks, metadata, and runtime operations used to implement a custom scan. For a complete example, see Write an alternating-position scan. For lifecycle design and recovery responsibilities, see The scan lifecycle.

Scan class and inputs

Import the base class and trigger type from bec_server.scan_server.scans.scan_base. Subclass ScanBase, define experimental inputs in __init__, and forward server arguments with super().__init__(**kwargs).

Attribute Default Contract
scan_name "base_scan" Override with a unique, valid Python identifier; this becomes the client callable name
scan_type ScanType.SOFTWARE_TRIGGERED Software triggering issues triggers through scan operations; hardware triggering delegates acquisition timing to a device
is_scan True Whether the request creates an acquisition scan
is_internal False Internal scans are omitted from the public client scan namespace
arg_input {} Ordered types/annotations for repeated positional argument bundles; unnecessary for fixed signatures
arg_bundle_size {"bundle": 0, "min": None, "max": None} Bundle width and minimum/maximum bundle counts; set together with arg_input for bundled signatures

ScanType.HARDWARE_TRIGGERED and ScanType.SOFTWARE_TRIGGERED describe who supplies the acquisition trigger. They do not by themselves specify whether a motor moves continuously.

For individual inputs, use Annotated[T, ScanArgument(...)] from bec_lib.scan_args. ScanArgument can supply descriptions, bounds such as gt/ge, units, and GUI labels. reference_units="motor" refers to the device argument named motor. DefaultArgType.Relative and DefaultArgType.ExposureTime provide common input annotations. The server serializes the scan signature for client validation and help.

gui_config, when defined on the class, maps display groups to parameter names. Plugin argument modifiers can change the published signature and defaults. Inspect the installed scan's client help when using a deployment's customized interface.

Server resources and scan state

The assembler supplies required scan_id, redis_connector, device_manager, instruction_handler, request_inputs, and system_config. Optional base arguments include readout selections (monitored, on_request), scan_modifier, user/request metadata, scan_queue, run_on_exception_hook, and additional_scan_parameters. Do not construct these resources in the client or issue runtime device RPC in __init__.

Instance attribute Purpose
dev Server device container
actions ScanActions instance for this scan
components ScanComponents instance for this scan
scan_info Validated ScanInfo model used in published scan state
positions Author-managed trajectory; initialize and publish it during preparation
start_positions Author-managed starting positions, initialized as an empty list

positions on the scan and scan_info.positions are separate attributes: update the published metadata explicitly. For N visits and M motors, use an array of shape (N, M); a per-point target passed to a component has shape (M,).

Metadata used by step scans

ScanInfo field Default Meaning
positions None Combined motor targets in visit order
num_points 0 Number of logical visits/points
num_monitored_readouts 0 Expected monitored readouts during preparation; updated to the actual requested count at normal close
relative False Coordinate convention recorded for this scan
exp_time 0 Nonnegative exposure time in seconds
frames_per_trigger 1 Positive detector frame count per trigger
burst_at_each_point 1 Positive number of trigger/read cycles per logical point
scan_report_devices [] Devices included in scan reporting; device objects are stored by name
run_on_exception_hook True Whether exception cleanup is requested. Halt skips the hook through a queue-item override; this field remains unchanged

Set positions, counts, and acquisition settings before open_scan. For standard step acquisition, expected monitored readouts are num_points * burst_at_each_point. Model assignment is validated. update_scan_info writes known model fields and stores unrecognized keyword names in additional_scan_parameters.

Bases: ABC

update_scan_info(num_points=None, num_monitored_readouts=None, positions=None, exp_time=None, frames_per_trigger=None, settling_time=None, settling_time_after_trigger=None, burst_at_each_point=None, relative=None, run_on_exception_hook=None, scan_report_devices=None, monitored=None, on_request=None, **kwargs)

Update the scan info with the given keyword arguments. If the scan info model has an attribute with the same name as the keyword argument, it will be updated. Otherwise, the keyword argument will be added to the additional_scan_parameters dictionary. This allows for flexible scan info management, where standard parameters can be defined as attributes of the ScanInfo model, and any additional parameters can be stored in the additional_scan_parameters dictionary.

Parameters:

Name Type Description Default
num_points int

Number of points in the scan. Defaults to None.

None
num_monitored_readouts int

Number of monitored readouts that will be collected during the scan. Defaults to None.

None
positions ndarray

Positions for the scan, shape (num_points, num_motors). Defaults to None.

None
exp_time float

Exposure time for the scan. Defaults to None.

None
frames_per_trigger int

Number of frames per trigger. Defaults to None.

None
settling_time float

Settling time before the software trigger. Defaults to None.

None
settling_time_after_trigger float

Settling time after the software trigger. Defaults to None.

None
burst_at_each_point int

Number of bursts at each point. Defaults to None.

None
relative bool

Whether the positions are relative or absolute. Defaults to None.

None
run_on_exception_hook bool

Whether to run the on_exception hook if the scan is interrupted. Defaults to None.

None
scan_report_devices Sequence[str | DeviceBase]

Devices to report during the scan. Device objects are stored by name. Defaults to None.

None
monitored Sequence[str | DeviceBase]

Devices to be put on the readout priority monitored. Defaults to None.

None
on_request Sequence[str | DeviceBase]

Devices to be put on the readout priority on_request. Defaults to None.

None
**kwargs

Keyword arguments to update the scan info with.

{}

Lifecycle hooks

Implement all abstract hooks, and decorate overrides with @scan_hook from bec_server.scan_server.scans.scan_modifier so scan modifiers can attach to them. The decorator does not schedule a hook or create a per-point loop.

Hook Caller and responsibility
prepare_scan() Worker: resolve positions, check limits, initialize metadata and preparation statuses
open_scan() Worker: call actions.open_scan() to publish the opening state
stage() Worker: configure devices and track partial setup
pre_scan() Worker: finish required preparation immediately before acquisition
scan_core() Worker: execute the experimental sequence
at_each_point(...) Scan/component: execute one visit; its signature must match the caller
post_scan() Worker: complete acquisition and perform normal recovery
unstage() Worker: release device setup
close_scan() Worker: account for outstanding work and call actions.close_scan()
on_exception(exception) Conditional exception path: recover from partial setup/execution; remaining normal hooks are not automatically run

Normal worker order is prepare → open → stage → pre → core → post → unstage → close. An exception breaks that sequence. Halt disables the exception hook; shutdown can bypass cleanup. A custom scan must not assume that starting positions, device staging, or its own settings are fully initialized when recovery begins.

Actions

ScanActions belongs to one scan. Operations with wait=True wait before returning; wait=False returns a ScanStatus for later checking. Lists of device names or DeviceBase objects are accepted by the operations below where their signatures allow them. Runtime actions check the worker's interruption state and operate with the scan's device ownership. They are not ordinary client scan submissions. Most actions require a running scan and belong in lifecycle hooks. Configuration methods such as set_device_readout_priority can also be called in __init__.

The following methods cover opening/closing, device preparation, movement, readout selection, and acquisition. readout_time is a scan argument published to devices. The standard step-scan components do not apply it as an additional delay. The trigger/read component applies exposure and settling delays.

Class to handle the core actions for the scan logic.

open_scan()

Open the scan. We fetch all relevant metadata from the scan object and emit a new scan status.

stage_all_devices(wait=True, exclude=None)

Stage all devices for the scan. This will call the "stage" method on all devices.

If you want to stage only specific devices, use the "stage" method.

.. note :: We exclude devices that are on_request or continuous as they are not expected to be staged for a scan.

Parameters:

Name Type Description Default
wait bool

if True, wait for the staging to complete. Defaults to True.

True
exclude str | DeviceBase | list[str | DeviceBase] | None

device(s) to exclude from staging. Defaults to None.

None

Returns:

Name Type Description
ScanStatus ScanStatus

status object to track the staging process

pre_scan_all_devices(wait=True, exclude=None)

Pre-scan steps to be executed before the main scan logic. This will call the "pre_scan" method all devices that implement it.

This is typically the last chance to prepare the devices before the core scan logic is executed. For example, this is a good place to initialize time-critical devices, e.g. devices that have a short timeout.

Parameters:

Name Type Description Default
wait bool

if True, wait for the pre-scan steps to complete. Defaults to True.

True
exclude str | DeviceBase | list[str | DeviceBase] | None

device(s) to exclude from pre-scan. Defaults to None.

None

Returns:

Name Type Description
ScanStatus ScanStatus

status object to track the pre-scan process

set_device_readout_priority(devices, priority)

Set the readout priority for the given devices. This will determine when the devices are read out during the scan. The provided list of devices is a modification to the existing readout priority.

Adding device A that is by default a baseline device to priority "monitored" will move it from the baseline readout to the monitored readout. All other devices will keep their default readout priority. This method is particularly useful for adding scan motors to the monitored readouts so that their positions are included in the scan report for each point.

Parameters:

Name Type Description Default
devices list[str | DeviceBase]

List of device names or DeviceBase instances to set the readout priority for.

required
priority str

Readout priority to set for the devices. Should be one of "baseline", "monitored", "on_request", or "async".

required

set(device, value, wait=True)

Set one or multiple devices to specific values. This will call the "set" method on the specified device(s) with the given value(s).

Parameters:

Name Type Description Default
device str or DeviceBase or list[str or DeviceBase] or list[str] or list[DeviceBase]

device(s) to set

required
value float or list[float]

target value(s) for the device(s)

required
wait bool

if True, wait for the set operation to complete. Defaults to True.

True

Returns:

Name Type Description
ScanStatus ScanStatus

status object to track the set process

read_baseline_devices(wait=True)

Read from the baseline devices. This will call the "read" method on all devices that are configured with readout priority "baseline".

Parameters:

Name Type Description Default
wait bool

if True, wait for the read to complete. Defaults to True.

True

Returns:

Name Type Description
ScanStatus ScanStatus

status object to track the read process

trigger_all_devices(min_wait=None, wait=True)

Trigger all devices for the scan. The list of devices to trigger is determined automatically based on their softwareTrigger configuration. This will call the "trigger" method on all devices that are configured to be triggered for the scan.

Parameters:

Name Type Description Default
min_wait float

minimum time to wait before the trigger is executed. This can be used to ensure that the system has settled before the trigger is executed. Defaults to None.

None
wait bool

if True, wait for the trigger to complete. Defaults to True.

True

read_monitored_devices(wait=True)

Read from the monitored devices. This will call the "read" method on all devices that are currently configured with readout priority "monitored".

Parameters:

Name Type Description Default
wait bool

if True, wait for the read to complete. Defaults to True.

True

Returns:

Name Type Description
ScanStatus ScanStatus

status object to track the read process

complete_all_devices(wait=True, exclude=None)

Complete all devices for the scan. This will call the "complete" method on all devices that are enabled for the scan.

If you want to complete only specific devices, use the complete method.

Parameters:

Name Type Description Default
wait bool

if True, wait for the completion to complete. Defaults to True.

True
exclude str | DeviceBase | list[str | DeviceBase] | None

device(s) to exclude from completion. Defaults to None.

None

Returns:

Name Type Description
ScanStatus ScanStatus

status object to track the completion process

unstage_all_devices(wait=True, exclude=None)

Unstage all devices for the scan. This will call the "unstage" method on all devices.

If you want to unstage only specific devices, use the "unstage" method.

Parameters:

Name Type Description Default
wait bool

if True, wait for the unstaging to complete. Defaults to True.

True
exclude str | DeviceBase | list[str | DeviceBase] | None

device(s) to exclude from unstaging. Defaults to None.

None

add_scan_report_instruction_scan_progress(points=0, show_table=True)

Add a scan progress report instruction to the instruction handler. Scan progress instructions inform clients to print a table-like report of the scan progress. If you don't know the number of points in advance, you can set points to 0. The progressbar will not be able to estimate the remaining time in this case, but it will still show the elapsed time and the number of points completed.

Parameters:

Name Type Description Default
points int

total number of points in the scan, used to calculate the progress percentage. Defaults to 0.

0
show_table bool

if True, show a progress table with estimated time remaining. Defaults to True.

True

close_scan()

Close the scan.

Components

ScanComponents combines operations while leaving scan metadata, lifecycle ownership, and recovery in the scan class. Component methods below wait for their necessary operations and do not return a ScanStatus for callers to wait on.

  • move_and_wait accepts one target per motor. With last_positions, it skips targets considered unchanged by numpy.isclose.
  • get_start_positions returns current motor positions as a list.
  • check_limits checks each motor column against inclusive limits. A device whose low limit is not below its high limit is treated as having no configured limits.
  • step_scan iterates trajectory rows and bursts, invoking its per-point callback. The callback receives (motors, position_row, last_positions=...); the initial last_positions is one combined position of shape (M,), not a whole trajectory.
  • The default per-point operation moves and waits, then calls trigger_and_read. When the scan owns software-triggered devices, triggering waits for exposure time multiplied by frames per trigger and for device completion before reading monitored devices. With no such devices, the trigger action returns immediately.

Class to handle the components for the scan logic. The components are reusable building blocks for the scan logic, such as step scans or grid scans. They use ScanActions to execute the scan logic.

move_and_wait(motors, positions, last_positions=None)

Move the given motors to the given positions and wait for the movement to complete. If last_positions is provided, only the motors with changed positions will be moved.

Parameters:

Name Type Description Default
motors list[str | DeviceBase] | list[str] | list[DeviceBase]

List of motor names or device instances to move.

required
positions ndarray | list[float]

Array or list of positions to move to, shape (len(motors),).

required
last_positions ndarray

Array of last positions, shape (len(motors),). If provided, only motors with changed positions will be moved. Defaults to None.

None

get_start_positions(motors)

Get the current position of the given motors. This can be used to make the positions relative to the current position of the motors.

Parameters:

Name Type Description Default
motors list[str | DeviceBase] | list[str] | list[DeviceBase]

List of motor names or device instances.

required

Returns:

Type Description
list[float]

list[float]: List of current positions of the motors.

check_limits(motors, positions)

Check if the given positions for the given motors are within the limits of the motors. If not, raise a LimitError.

Parameters:

Name Type Description Default
motors list[str | DeviceBase] | list[str] | list[DeviceBase]

List of motor names or device instances.

required
positions ndarray

Array of positions to check, shape (num_points, len(motors)).

required

Raises:

Type Description
LimitError

If any of the positions are out of limits for the corresponding motor.

step_scan_at_each_point(motors, pos, last_positions=None)

Execute a step scan at each point. This is the core logic that is executed at each point of the step scan. It is separated from the step_scan method to allow scan hooks to override the logic.

The logic is as follows
  1. Move the motors to the next position without waiting for each motor to complete
  2. Wait for each motor to complete
  3. Let the system settle before triggering
  4. Trigger the devices
  5. Let the system settle after the trigger
  6. Start the readout

Parameters:

Name Type Description Default
motors list[str | DeviceBase] | list[str] | list[DeviceBase]

List of motor names or device instances to move.

required
pos ndarray

Array of positions to move to, shape (len(motors),).

required
last_positions ndarray

Array of last positions, shape (len(motors),). If provided, only motors with changed positions will be moved. Defaults to None.

None

trigger_and_read()

Trigger the devices and start the readout. This is typically used for step scans after the motors have been moved to the next position.

The logic is as follows
  1. Let the system settle before triggering
  2. Trigger the devices
  3. Let the system settle after the trigger
  4. Start the readout

step_scan(motors, positions, at_each_point=None, last_positions=None)

Visit each row in positions, repeating the per-point operation according to scan_info.burst_at_each_point. Returns None after the loop completes.

Parameter Shape/type and default
motors List of device names or DeviceBase objects, one per trajectory column
positions NumPy array of shape (N, M)
at_each_point Callback (motors, position_row, last_positions=...); defaults to step_scan_at_each_point
last_positions Initial previous position of shape (M,); default None

The component copies the current row into last_positions after each visit. A callback must perform the intended acquisition; the loop does not add a second acquisition itself.

Status objects and errors

ScanStatus is a server operation status, distinct from the client's ScanReport. The main lookup operations are:

Member Contract
.wait(min_wait=None, timeout=inf, logger_wait=5, resolve_on_known_type=False) Wait for the operation and its sub-statuses; returns the status; raises on instruction failure or timeout
.done Completion flag; checking it marks the status as checked but does not by itself verify success
.result Result, or sub-results for a container; None until completed; a property, not a method
.add_status(status) Attach a sub-status to a container status

resolve_on_known_type is intended for internal RPC return-type handling. Custom scans normally leave it at False. A wait timeout does not itself request a device stop. Closing checks for unchecked or unfinished statuses and can issue warnings or wait for remaining work; explicitly check dependencies before using their results or closing.

Status object that can be used to wait for the completion of a device instruction.

result property

Get the result of the operation. If the status object is a container of multiple status objects, the result will be a list of the results of the sub status objects. If the status object is not done, the result will be None.

Returns:

Name Type Description
Any Any

Result of the operation, or list of results of the sub status objects.

done property writable

Get the done flag.

Returns:

Name Type Description
bool bool

Done flag

add_status(status)

Add a status object to the current status object. This can be used to wait for the completion of multiple status objects.

Parameters:

Name Type Description Default
status ScanStatus

Status object

required

Relevant exceptions are imported from bec_server.scan_server.errors:

Exception Meaning
LimitError A target is outside a motor's configured limits
DeviceInstructionError A device instruction failed; its error information is available to the worker
ScanAbortion Execution cannot continue or an interruption requests abortion
UserScanInterruption A user interruption carrying exit-state information; derived from ScanAbortion

These exceptions do not replace scan-specific recovery. Keep cleanup valid after partially completed work, and inspect device and queue state before resuming an interrupted experiment.