pylablib.devices.Thorlabs package

Submodules

pylablib.devices.Thorlabs.TLCamera module

class pylablib.devices.Thorlabs.TLCamera.LibraryController(lib)[source]

Bases: pylablib.devices.utils.load_lib.LibraryController

close(opid)[source]

Mark device closing.

Return tuple (close_result, uninit_result) with the results of the closing and the shutdown. If library does not need to be shut down yet, set uninit_result=None

open()[source]

Mark device opening.

Return tuple (init_result, open_result, opid) with the results of the initialization and the opening, and the opening ID which should afterwards be used for closing. If library is already initialized, set init_result=None

preinit()[source]

Pre-initialize the library, if it hasn’t been done already

shutdown()[source]

Close all opened connections and shutdown the library

temp_open()[source]

Context for temporarily opening a new device connection

pylablib.devices.Thorlabs.TLCamera.list_cameras()[source]

List connected TLCamera cameras

pylablib.devices.Thorlabs.TLCamera.get_cameras_number()[source]

Get number of connected TLCamera cameras

class pylablib.devices.Thorlabs.TLCamera.TDeviceInfo(model, name, serial_number, firmware_version)

Bases: tuple

count()

Return number of occurrences of value.

firmware_version
index()

Return first index of value.

Raises ValueError if the value is not present.

model
name
serial_number
class pylablib.devices.Thorlabs.TLCamera.TFrameInfo(frame_index, framestamp, pixelclock, pixeltype, offset)

Bases: tuple

count()

Return number of occurrences of value.

frame_index
framestamp
index()

Return first index of value.

Raises ValueError if the value is not present.

offset
pixelclock
pixeltype
class pylablib.devices.Thorlabs.TLCamera.ThorlabsTLCamera(serial=None)[source]

Bases: pylablib.devices.interface.camera.IBinROICamera, pylablib.devices.interface.camera.IExposureCamera

Thorlabs TSI camera.

Parameters:serial (str) – camera serial number; can be either a string obtained using list_cameras() function, or None, which means connecting to the first available camera (not recommended unless only one camera is connected)
Error = <Mock name='mock.ThorlabsTLCameraError' id='140128532676688'>
TimeoutError = <Mock spec='str' id='140128542376208'>
open()[source]

Open connection to the camera

close()[source]

Close connection to the camera

is_opened()[source]

Check if the device is connected

get_device_info()[source]

Get camera model data.

Return tuple (model, name, serial_number, firmware_version).

class RingBuffer[source]

Bases: object

Frames ring buffer.

Reacts to each new frame and stores it in the internal buffer.

reset()[source]

Reset buffer and internal counters

setup(buffsize, frame_dim)[source]

Setup a new buffer with the given maximal number of frames and frame dimensions

cleanup()[source]

Cleanup the buffer

new_frame(handle, buffer, idx, metadata, metadata_size, context)[source]

Callback for receiving a new frame

wait_for_frame(idx=None, timeout=None)[source]

Wait for a new frame acquisition

get_frame(idx)[source]

Get the frame with the given index (or None if it is outside the buffer range)

get_status()[source]

Get buffer status (acquired, missed, stored)

get_frame_timings()[source]

Get acquisition timing.

Return tuple (exposure, frame_period).

set_exposure(exposure)[source]

Set camera exposure

get_trigger_mode()[source]

Get trigger mode.

Can be "int" (internal/software), "ext" (external/hardware), or "bulb" (bulb trigger).

set_trigger_mode(mode)[source]

Set trigger mode.

Can be "int" (internal/software), "ext" (external/hardware), or "bulb" (bulb trigger).

get_ext_trigger_parameters()[source]

Return external trigger polarity

setup_ext_trigger(polarity)[source]

Setup external trigger polarity ("rise" or "fall")

send_software_trigger()[source]

Send software trigger signal

get_pixel_correction_parameters()[source]

Return pixel correction parameters (enabled, threshold)

setup_pixel_correction(enable=True, threshold=None)[source]

Enable or disable hotpixel correction and set its threshold (None means keep unchanged)

get_timestamp_clock_frequency()[source]

Return frequency of the frame timestamp clock (in Hz)

setup_acquisition(nframes=100)[source]

Setup acquisition.

nframes determines number of size of the ring buffer (by default, 100).

clear_acquisition()[source]

Clear acquisition settings

start_acquisition(frames_per_trigger='default', auto_start=True, nframes=None)[source]

Start camera acquisition.

Parameters:
  • frames_per_trigger – number of frames to acquire per trigger (software of hardware); None means unlimited number; by default, set to None for software trigger (i.e., run until stopped), and 1 for hardware trigger (i.e., one frame per trigger pulse)
  • auto_start – if True and the trigger is set into software mode, automatically start recording; otherwise, only start recording when send_software_trigger() is called explicitly; this value is meaningless in the hardware or bulb trigger mode
  • nframes – number of frames in the ring buffer
stop_acquisition()[source]

Stop acquisition

acquisition_in_progress()[source]

Check if acquisition is in progress

get_detector_size()[source]

Get camera detector size (in pixels) as a tuple (width, height)

get_roi()[source]

Get current ROI.

Return tuple (hstart, hend, vstart, vend, hbin, vbin). hstart and hend specify horizontal image extent, vstart and vend specify vertical image extent (start is inclusive, stop is exclusive, starting from 0), hbin and vbin specify binning.

set_roi(hstart=0, hend=None, vstart=0, vend=None, hbin=1, vbin=1)[source]

Setup camera ROI.

hstart and hend specify horizontal image extent, vstart and vend specify vertical image extent (start is inclusive, stop is exclusive, starting from 0), hbin and vbin specify binning. By default, all non-supplied parameters take extreme values (0 for start, maximal for end, 1 for binning).

get_roi_limits(hbin=1, vbin=1)[source]

Get the minimal and maximal ROI parameters.

Return tuple (hlim, vlim), where each element is in turn a limit 5-tuple (min, max, pstep, sstep, maxbin) with, correspondingly, minimal and maximal size, position and size step, and the maximal binning. In some cameras, the step and the minimal size depend on the binning, which can be supplied.

read_multiple_images(rng=None, peek=False, missing_frame='skip', return_info=False)[source]

Read multiple images specified by rng (by default, all un-read images).

If rng is specified, it is a tuple (first, last) with images range (first inclusive). If no new frames are available, return an empty list; if no acquisition is running, return None. If peek==True, return images but not mark them as read. missing_frame determines what to do with frames which are out of range (missing or lost): can be "none" (replacing them with None), "zero" (replacing them with zero-filled frame), or "skip" (skipping them). If return_info==True, return tuple (frames, infos), where infos is a list of TFrameInfo instances describing frame index and frame metadata, which contains framestamp, pixel clock, pixel format, and pixel offset; if some frames are missing and missing_frame!="skip", the corresponding frame info is None.

FrameTransferError

alias of pylablib.devices.interface.camera.DefaultFrameTransferError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

apply_settings(settings)

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

get_acquisition_parameters()

Get acquisition parameters.

Return dictionary {name: value}

get_data_dimensions()

Get readout data dimensions (in pixels) as a tuple (width, height); take indexing mode into account

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_exposure()

Get current exposure

get_frame_format()

Get format for the returned images.

Can be "list" (list of 2D arrays, or 3D array for some fastbuff cameras), "array" (a single 3D array).

get_frame_info_fields()

Get the names of frame info fields.

Applicable when frame info format (set by set_frame_info_format()) is "list" or "array".

get_frame_info_format()

Get format of the frame info.

Can be "namedtuple" (potentially nested named tuples; convenient to get particular values), "list" (flat list of values, with field names are given by get_frame_info_fields(); convenient for building a table), "array" (same as "list", but with a numpy array, which is easier to use for fastbuff readout supported by some cameras), or "dict" (flat dictionary with the same fields as the "list" format; more resilient to future format changes)

get_frame_info_period()

Get period of frame info acquisition.

Frame info might be skipped (set to None) except for frames which indices are divisible by period. Useful for certain cameras where acquiring frame info takes a lot of time and can reduce performance at higher frame rates. Note that this parameter can still be ignored (i.e., always set to 1) if the performance is not an issue for a given camera class.

get_frame_period()

Get frame period (time between two consecutive frames in the internal trigger mode)

get_frames_status()

Get acquisition and buffer status.

Return tuple (acquired, unread, skipped, size), where acquired is the total number of acquired frames, unread is the number of acquired but not read frames, skipped is the number of skipped (not read and then written over) frames, and buffer_size is the total buffer size (in frames).

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_image_indexing()

Get indexing for the returned images.

Can be "rct" (first index row, second index column, rows counted from the top), "rcb" (same as "rc", rows counted from the bottom), "xyt" (first index column, second index row, rows counted from the top), or "xyb" (same as "xyt", rows counted from the bottom)

get_new_images_range()

Get the range of the new images.

Return tuple (first, last) with images range (first inclusive). If no images are available, return None. If some images were in the buffer were overwritten, exclude them from the range.

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

grab(nframes=1, frame_timeout=5.0, missing_frame='none', return_info=False, buff_size=None)

Snap nframes images (with preset image read mode parameters)

buff_size determines buffer size (if None, use the default size). Timeout is specified for a single-frame acquisition, not for the whole acquisition time. missing_frame determines what to do with frames which have been lost: can be "none" (replacing them with None), "zero" (replacing them with zero-filled frame), or "skip" (skipping them, while still keeping total returned frames number to n). If return_info==True, return tuple (frames, infos), where infos is a list of frame info tuples (camera-dependent); if some frames are missing and missing_frame!="skip", the corresponding frame info is None.

is_acquisition_setup()

Check if acquisition is set up.

If the camera does not support separate acquisition setup, always return True.

pausing_acquisition(clear=None)

Context manager which temporarily pauses acquisition during execution of with block.

Useful for applying certain settings which can’t be changed during the acquisition. If clear==True, clear acquisition in addition to pausing (by default, use the class default specified as _clear_pausing_acquisition attribute). Yields tuple (acq_in_progress, acq_params), which indicates whether acquisition is currently in progress, and what are the current acquisition parameters.

read_newest_image(peek=False, return_info=False)

Read the newest un-read image.

If no un-read frames are available, return None. If peek==True, return the image but not mark it as read. If return_info==True, return tuple (frame, info), where info is an info tuples (camera-dependent, see read_multiple_images()).

read_oldest_image(peek=False, return_info=False)

Read the oldest un-read image.

If no un-read frames are available, return None. If peek==True, return the image but not mark it as read. If return_info==True, return tuple (frame, info), where info is an info tuples (camera-dependent, see read_multiple_images()).

set_device_variable(key, value)

Set the value of a settings parameter

set_frame_format(fmt)

Set format for the returned images.

Can be "list" (list of 2D arrays, or 3D array for some fastbuff cameras), "array" (a single 3D array). Note that if the format is set to "array", the frame info format is also automatically set to "array".

set_frame_info_format(fmt, include_fields=None)

Set format of the frame info.

Can be "namedtuple" (potentially nested named tuples; convenient to get particular values), "list" (flat list of values, with field names are given by get_frame_info_fields(); convenient for building a table), "array" (same as "list", but with a numpy array, which is easier to use for fastbuff readout supported by some cameras), or "dict" (flat dictionary with the same fields as the "list" format; more resilient to future format changes) If include_fields is not None, it specifies the fields included for non-"tuple" formats.

set_frame_info_period(period=1)

Set period of frame info acquisition.

Frame info might be skipped (set to None) except for frames which indices are divisible by period. Useful for certain cameras where acquiring frame info takes a lot of time and can reduce performance at higher frame rates. Note that this parameter can still be ignored (i.e., always set to 1) if the performance is not an issue for a given camera class.

set_image_indexing(indexing)

Set up indexing for the returned images.

Can be "rct" (first index row, second index column, rows counted from the top), "rcb" (same as "rc", rows counted from the bottom), "xyt" (first index column, second index row, rows counted from the top), or "xyb" (same as "xyt", rows counted from the bottom)

snap(timeout=5.0, return_info=False)

Snap a single frame

wait_for_frame(since='lastread', nframes=1, timeout=20.0, error_on_stopped=False)

Wait for one or several new camera frames.

since specifies the reference point for waiting to acquire nframes frames; can be “lastread”`` (from the last read frame), "lastwait" (wait for the last successful wait_for_frame() call), "now" (from the start of the current call), or "start" (from the acquisition start, i.e., wait until nframes frames have been acquired). timeout can be either a number, None (infinite timeout), or a tuple (timeout, frame_timeout), in which case the call times out if the total time exceeds timeout, or a single frame wait exceeds frame_timeout. If the call times out, raise TimeoutError. If error_on_stopped==True and the acquisition is not running, raise Error; otherwise, simply return False without waiting.

pylablib.devices.Thorlabs.base module

exception pylablib.devices.Thorlabs.base.ThorlabsError[source]

Bases: pylablib.core.devio.base.DeviceError

Generic Thorlabs error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception pylablib.devices.Thorlabs.base.ThorlabsBackendError(exc)[source]

Bases: pylablib.devices.Thorlabs.base.ThorlabsError, pylablib.core.devio.comm_backend.DeviceBackendError

Thorlabs backend communication error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception pylablib.devices.Thorlabs.base.ThorlabsTimeoutError[source]

Bases: pylablib.devices.Thorlabs.base.ThorlabsError

Thorlabs timeout error

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

pylablib.devices.Thorlabs.kinesis module

pylablib.devices.Thorlabs.kinesis.list_kinesis_devices(filter_ids=True)[source]

List all Thorlabs APT/Kinesis devices connected to this PC.

Return list of tuples (conn, description).
If filter_ids==True, only leave devices with Thorlabs-like IDs (8-digit numbers). Otherwise, show all devices (some of them might not be Thorlabs-related).
class pylablib.devices.Thorlabs.kinesis.TDeviceInfo(serial_no, model_no, fw_ver, hw_type, hw_ver, mod_state, nchannels, notes)

Bases: tuple

count()

Return number of occurrences of value.

fw_ver
hw_type
hw_ver
index()

Return first index of value.

Raises ValueError if the value is not present.

mod_state
model_no
nchannels
notes
serial_no
class pylablib.devices.Thorlabs.kinesis.BasicKinesisDevice(conn, timeout=3.0)[source]

Bases: pylablib.core.devio.comm_backend.ICommBackendWrapper

Generic Kinesis device.

Implements FTDI chip connectivity via pyft232 (virtual serial interface).

Parameters:conn – serial connection parameters (usually an 8-digit device serial number).
Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

static list_devices(filter_ids=True)[source]

List all connected devices.

Return list of tuples (conn, description). If filter_ids==True, only leave devices with Thorlabs-like IDs (8-digit numbers). Otherwise, show all devices (some of them might not be Thorlabs-related).

send_comm(messageID, param1=0, param2=0, source=1, dest=80)[source]

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest=80)[source]

Send a message with associated data.

For details, see APT communications protocol.

class CommShort(messageID, param1, param2, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
param1
param2
source
class CommData(messageID, data, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

data
dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
source
recv_comm(expected_id=None)[source]

Receive a message.

Return either CommShort or CommData depending on the message type (fixed length with two parameters, or variable length with associated data). If expected_id is not None and the received message ID is different from expected_id, raise an error. For details, see APT communications protocol.

query(messageID, param1=0, param2=0, source=1, dest=80, replyID=-1)[source]

Send a query to the device and receive the reply.

A combination of send_comm() and recv_comm(). If replyID is not None, specifies the expected reply message ID; if -1 (default), set to te be messageID+1 (the standard convention).

add_background_comm(messageID)[source]

Mark given messageID as a ‘background’ message, which can be sent at any point without prompt (e.g., some operation confirmation).

If it is received instead during recv_comm_ operations, it is ignored, and the corresponding counter is increased.

check_background_comm(messageID)[source]

Return message counter and the last message value (None if not message received yet) of a given ‘background’ message

get_device_info(dest=80)[source]

Get device info.

get_number_of_channels()[source]

Get number of channels on the device

Identify the physical device (by, e.g., blinking status LED or screen)

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

apply_settings(settings)

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

close()

Close the backend

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

set_device_variable(key, value)

Set the value of a settings parameter

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

class pylablib.devices.Thorlabs.kinesis.TVelocityParams(min_velocity, acceleration, max_velocity)

Bases: tuple

acceleration
count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

max_velocity
min_velocity
class pylablib.devices.Thorlabs.kinesis.TJogParams(mode, step_size, min_velocity, acceleration, max_velocity, stop_mode)

Bases: tuple

acceleration
count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

max_velocity
min_velocity
mode
step_size
stop_mode
class pylablib.devices.Thorlabs.kinesis.TGenMoveParams(backlash_distance)

Bases: tuple

backlash_distance
count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

class pylablib.devices.Thorlabs.kinesis.THomeParams(home_direction, limit_switch, velocity, offset_distance)

Bases: tuple

count()

Return number of occurrences of value.

home_direction
index()

Return first index of value.

Raises ValueError if the value is not present.

limit_switch
offset_distance
velocity
class pylablib.devices.Thorlabs.kinesis.TLimitSwitchParams(hw_kind_cw, hw_kind_ccw, hw_swapped, sw_position_cw, sw_position_ccw, sw_kind)

Bases: tuple

count()

Return number of occurrences of value.

hw_kind_ccw
hw_kind_cw
hw_swapped
index()

Return first index of value.

Raises ValueError if the value is not present.

sw_kind
sw_position_ccw
sw_position_cw
class pylablib.devices.Thorlabs.kinesis.TKCubeTrigIOParams(trig1_mode, trig1_pol, trig2_mode, trig2_pol)

Bases: tuple

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

trig1_mode
trig1_pol
trig2_mode
trig2_pol
class pylablib.devices.Thorlabs.kinesis.TKCubeTrigPosParams(start_fw, step_fw, num_fw, start_bk, step_bk, num_bk, width, ncycles)

Bases: tuple

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

ncycles
num_bk
num_fw
start_bk
start_fw
step_bk
step_fw
width
class pylablib.devices.Thorlabs.kinesis.TPZMotorDriveParams(max_voltage, velocity, acceleration)

Bases: tuple

acceleration
count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

max_voltage
velocity
class pylablib.devices.Thorlabs.kinesis.TPZMotorJogParams(mode, step_size_fw, step_size_bk, velocity, acceleration)

Bases: tuple

acceleration
count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

mode
step_size_bk
step_size_fw
velocity
pylablib.devices.Thorlabs.kinesis.muxchannel(*args, **kwargs)
class pylablib.devices.Thorlabs.kinesis.KinesisDevice(conn, timeout=3.0, default_channel=1)[source]

Bases: pylablib.devices.interface.stage.IMultiaxisStage, pylablib.devices.Thorlabs.kinesis.BasicKinesisDevice

get_all_channels()[source]

Get the list of all available channels; alias of get_all_axes method

set_default_channel(channel)[source]

Set the default channel for all channel-related methods

using_channel(channel)[source]

Context manager for temporarily using a different default channel

status_bits = [(1, 'sw_bk_lim'), (2, 'sw_fw_lim'), (16, 'moving_bk'), (32, 'moving_fw'), (64, 'jogging_bk'), (128, 'jogging_fw'), (512, 'homing'), (1024, 'homed'), (4096, 'tracking'), (8192, 'settled'), (16384, 'motion_error'), (16777216, 'current_limit'), (2147483648, 'enabled')]
class CommData(messageID, data, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

data
dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
source
class CommShort(messageID, param1, param2, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
param1
param2
source
Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

add_background_comm(messageID)

Mark given messageID as a ‘background’ message, which can be sent at any point without prompt (e.g., some operation confirmation).

If it is received instead during recv_comm_ operations, it is ignored, and the corresponding counter is increased.

apply_settings(settings)

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

Identify the physical device (by, e.g., blinking status LED or screen)

check_background_comm(messageID)

Return message counter and the last message value (None if not message received yet) of a given ‘background’ message

close()

Close the backend

get_all_axes()

Get the list of all available axes (taking mapping into account)

get_device_info(dest=80)

Get device info.

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_number_of_channels()

Get number of channels on the device

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

static list_devices(filter_ids=True)

List all connected devices.

Return list of tuples (conn, description). If filter_ids==True, only leave devices with Thorlabs-like IDs (8-digit numbers). Otherwise, show all devices (some of them might not be Thorlabs-related).

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

query(messageID, param1=0, param2=0, source=1, dest=80, replyID=-1)

Send a query to the device and receive the reply.

A combination of send_comm() and recv_comm(). If replyID is not None, specifies the expected reply message ID; if -1 (default), set to te be messageID+1 (the standard convention).

recv_comm(expected_id=None)

Receive a message.

Return either CommShort or CommData depending on the message type (fixed length with two parameters, or variable length with associated data). If expected_id is not None and the received message ID is different from expected_id, raise an error. For details, see APT communications protocol.

remap_axes(mapping, accept_original=True)

Rename axes to the new labels.

mapping is the new axes mapping, which can be a list of new axes name (corresponding to the old axes in order returned by get_all_axes()), or a dictionary {alias: original} of the new axes aliases.

send_comm(messageID, param1=0, param2=0, source=1, dest=80)

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest=80)

Send a message with associated data.

For details, see APT communications protocol.

set_device_variable(key, value)

Set the value of a settings parameter

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

class pylablib.devices.Thorlabs.kinesis.TFlipperParameters(transit_time, io1_oper_mode, io1_sig_mode, io1_pulse_width, io2_oper_mode, io2_sig_mode, io2_pulse_width)

Bases: tuple

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

io1_oper_mode
io1_pulse_width
io1_sig_mode
io2_oper_mode
io2_pulse_width
io2_sig_mode
transit_time
class pylablib.devices.Thorlabs.kinesis.MFF(conn)[source]

Bases: pylablib.devices.Thorlabs.kinesis.KinesisDevice

MFF (Motorized Filter Flip Mount) device.

Implements FTDI chip connectivity via pyft232 (virtual serial interface).

Parameters:conn – serial connection parameters (usually 8-digit device serial number).
get_status_n(channel=None)

Get numerical status of the device.

For details, see APT communications protocol.

get_status(channel=None)

Get device status.

Return list of status strings, which can include "sw_fw_lim" (forward limit switch reached), "sw_bk_lim" (backward limit switch reached), "moving_fw" (moving forward), "moving_bk" (moving backward), "jogging_fw" (jogging forward), "jogging_bk" (jogging backward), "homing" (homing), "homed" (homing done), "tracking", "settled", "motion_error" (excessive position error), "current_limit" (motor current limit exceeded), or "enabled" (motor is enabled).

wait_for_status(status, enabled, channel=None, timeout=None, period=0.05)

Wait until the given status (or list of status bits) is in the desired state.

status is a string or a list of strings describing the status bits to monitor; for possible values, see get_status(). If enabled==True, wait until one of the given statuses is enabled; otherwise, wait until all given statuses are disabled. period specifies status checking period (in s).

move_to_state(state, channel=None)[source]

Move to the given flip mount state (either 0 or 1)

get_state(channel=None)[source]

Get the flip mount state (either 0 or 1).

Return None if the mount is current moving (i.e., the state os undefined)

get_flipper_parameters(channel=None)[source]

Get current flipper parameters (transit_time, io1_oper_mode, io1_sig_mode, io1_pulse_width, io2_oper_mode, io2_sig_mode, io2_pulse_width)

transit_time specifies transit time (in seconds between 0.3 and 2.8); io*_oper_mode specifies operation mode (in vs. out and position vs. motion input/indication), io*_sig_mode specifies signal mode (button input, voltage edge input, edge output or pulse output). io*_pulse_width specifies output pulse width if the corresponding output mode is selected. For detailed mode description, see the flip mirror or APT manual.

setup_flipper(transit_time=None, io1_oper_mode=None, io1_sig_mode=None, io1_pulse_width=None, io2_oper_mode=None, io2_sig_mode=None, io2_pulse_width=None, channel=None)[source]

Set flipper parameters.

transit_time specifies transit time (in seconds between 0.3 and 2.8); io*_oper_mode specifies operation mode (in vs. out and position vs. motion input/indication), io*_sig_mode specifies signal mode (button input, voltage edge input, edge output or pulse output). io*_pulse_width specifies output pulse width if the corresponding output mode is selected. If any parameter is None, use the current value. For detailed mode description, see the flip mirror or APT manual.

class CommData(messageID, data, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

data
dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
source
class CommShort(messageID, param1, param2, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
param1
param2
source
Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

add_background_comm(messageID)

Mark given messageID as a ‘background’ message, which can be sent at any point without prompt (e.g., some operation confirmation).

If it is received instead during recv_comm_ operations, it is ignored, and the corresponding counter is increased.

apply_settings(settings)

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

Identify the physical device (by, e.g., blinking status LED or screen)

check_background_comm(messageID)

Return message counter and the last message value (None if not message received yet) of a given ‘background’ message

close()

Close the backend

get_all_axes()

Get the list of all available axes (taking mapping into account)

get_all_channels()

Get the list of all available channels; alias of get_all_axes method

get_device_info(dest=80)

Get device info.

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_number_of_channels()

Get number of channels on the device

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

static list_devices(filter_ids=True)

List all connected devices.

Return list of tuples (conn, description). If filter_ids==True, only leave devices with Thorlabs-like IDs (8-digit numbers). Otherwise, show all devices (some of them might not be Thorlabs-related).

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

query(messageID, param1=0, param2=0, source=1, dest=80, replyID=-1)

Send a query to the device and receive the reply.

A combination of send_comm() and recv_comm(). If replyID is not None, specifies the expected reply message ID; if -1 (default), set to te be messageID+1 (the standard convention).

recv_comm(expected_id=None)

Receive a message.

Return either CommShort or CommData depending on the message type (fixed length with two parameters, or variable length with associated data). If expected_id is not None and the received message ID is different from expected_id, raise an error. For details, see APT communications protocol.

remap_axes(mapping, accept_original=True)

Rename axes to the new labels.

mapping is the new axes mapping, which can be a list of new axes name (corresponding to the old axes in order returned by get_all_axes()), or a dictionary {alias: original} of the new axes aliases.

send_comm(messageID, param1=0, param2=0, source=1, dest=80)

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest=80)

Send a message with associated data.

For details, see APT communications protocol.

set_default_channel(channel)

Set the default channel for all channel-related methods

set_device_variable(key, value)

Set the value of a settings parameter

status_bits = [(1, 'sw_bk_lim'), (2, 'sw_fw_lim'), (16, 'moving_bk'), (32, 'moving_fw'), (64, 'jogging_bk'), (128, 'jogging_fw'), (512, 'homing'), (1024, 'homed'), (4096, 'tracking'), (8192, 'settled'), (16384, 'motion_error'), (16777216, 'current_limit'), (2147483648, 'enabled')]
unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_channel(channel)

Context manager for temporarily using a different default channel

class pylablib.devices.Thorlabs.kinesis.KinesisMotor(conn, scale='step')[source]

Bases: pylablib.devices.Thorlabs.kinesis.KinesisDevice

Thorlabs motor controller.

Implements FTDI chip connectivity via pyft232 (virtual serial interface).

The physical units are encoder steps for position (ratio to m or degrees depends on the connected stage), steps/sec for velocity, and steps/sec^2 for acceleration.

Parameters:
  • conn (str) – serial connection parameters (usually an 8-digit device serial number).
  • scale – scale of the position, velocity, and acceleration units to the internals units; can be "stage" (attempt to autodetect motor and stage parameters), a string with the name of the stage, e.g., "MTS50-Z8" or "DDR100" (use the stage name to extract the scale; determine velocity and acceleration from this scale and the motor model), "step" (use encoder/motor steps as units; determine velocity and acceleration from this scale and the motor model), a single number (use this as the ratio of internal steps to physical units; determine velocity and acceleration from this scale and the motor model), or a 3-tuple of numbers (position_scale, velocity_scale, acceleration_scale) which gives the ratio of internal units to physical units (useful for new or unrecognized controllers or stages, as no autodetection is required); in the case of unrecognized devices, use internal units (same as setting scale=(1,1,1)); if the scale can’t be autodetected, it can be obtained from the APT manual knowing the device and the stage model
get_scale()

Get the scaling coefficients.

Return a tuple (position_scale, velocity_scale, acceleration_scale) for scaling of the physical units in terms of internal units. To get the coefficients source and physical units, use get_scale_units().

get_scale_units()[source]

Get units used for calculating scaled position, velocity and acceleration values.

Can be "deg" (autodetected rotational stage: deg, deg/s and deg/s^2), "m" (autodetected translational stage: m, m/sec and m/sec^2), "step" (autodetected driver but not detected step scale: steps, steps/sec and steps/sec^2) "user_step" (autodetected driver and user supplied step scale: user-supplied step scale for position, same units per sec or sec^2 for velocity and acceleration), 'user" (all three scales are supplied by user), or "internal" (no scales are supplied or detected, use device internal units)

get_stage()[source]

Return the name of the stage which was supplied by the usr or autodetected.

If the stake is unknown, return None

get_status_n(channel=None)

Get numerical status of the device.

For details, see APT communications protocol.

get_status(channel=None)

Get device status.

Return list of status strings, which can include "sw_fw_lim" (forward limit switch reached), "sw_bk_lim" (backward limit switch reached), "moving_fw" (moving forward), "moving_bk" (moving backward), "jogging_fw" (jogging forward), "jogging_bk" (jogging backward), "homing" (homing), "homed" (homing done), "tracking", "settled", "motion_error" (excessive position error), "current_limit" (motor current limit exceeded), or "enabled" (motor is enabled).

wait_for_status(status, enabled, channel=None, timeout=None, period=0.05)

Wait until the given status (or list of status bits) is in the desired state.

status is a string or a list of strings describing the status bits to monitor; for possible values, see get_status(). If enabled==True, wait until one of the given statuses is enabled; otherwise, wait until all given statuses are disabled. period specifies status checking period (in s).

home(sync=True, force=False, channel=None, timeout=None)

Home the device.

If sync==True, wait until homing is done (with the given timeout). If force==False, only home if the device isn’t homed already.

is_homing(channel=None)

Check if homing is in progress

is_homed(channel=None)

Check if the device is homed

wait_for_home(channel=None, timeout=None)

Wait until the device is homed

get_position(channel=None, scale=True)

Get current position.

If scale==True, return value in the physical units (see class description); otherwise, return it in the device internal units (steps).

set_position_reference(position=0, channel=None, scale=True)

Set position reference (actual motor position stays the same).

If scale==True, assume that the position is in the physical units (see class description); otherwise, assume it is in the device internal units (steps).

move_by(distance=1, channel=None, scale=True)

Move by a given amount (positive or negative) from the current position.

If scale==True, assume that the distance is in the physical units (see class description); otherwise, assume it is in the device internal units (steps).

move_to(position, channel=None, scale=True)

Move to position (positive or negative).

If scale==True, assume that the position is in the physical units (see class description); otherwise, assume it is in the device internal units (steps).

jog(direction, channel=None, kind='continuous')

Jog in the given direction ("+" or "-").

If kind=="continuous", simply start motion in the given direction at the maximal speed until either the motor is stopped explicitly, or the limit is reached (this uses MOT_MOVE_VELOCITY command). If kind=="builtin", use the built-in MOT_MOVE_JOG command, whose parameters are specified by get_jog_parameters().

is_moving(channel=None)

Check if motion is in progress

wait_move(channel=None, timeout=None)

Wait until motion command is done

stop(immediate=False, sync=True, channel=None, timeout=None)

Stop the motion.

If immediate==True make an abrupt stop; otherwise, slow down gradually. If sync==True, wait until the motion is stopped.

wait_for_stop(channel=None, timeout=None)

Wait until motion or homing is done

get_velocity_parameters(channel=None, scale=True)

Get current velocity parameters (min_velocity, acceleration, max_velocity)

If scale==True, return values in the physical units (see class description); otherwise, return it in the device internal units.

setup_velocity(min_velocity=None, acceleration=None, max_velocity=None, channel=None, scale=True)

Set velocity parameters.

If any parameter is None, use the current value. If scale==True, assume that the specified values are in the physical units (see class description); otherwise, assume it is in the device internal units.

get_jog_parameters(channel=None, scale=True)

Get current jog parameters (mode, step_size, min_velocity, acceleration, max_velocity, stop_mode)

If scale==True, return values in the physical units (see class description); otherwise, return it in the device internal units.

setup_jog(mode=None, step_size=None, min_velocity=None, acceleration=None, max_velocity=None, stop_mode=None, channel=None, scale=True)

Set jog parameters.

If any parameter is None, use the current value. If scale==True, assume that the specified values are in the physical units (see class description); otherwise, assume it is in the device internal units.

get_homing_parameters(channel=None, scale=True)

Get current homing parameters (home_direction, limit_switch, velocity, offset_distance)

If scale==True, return values are in the physical units (see class description); otherwise, return it in the device internal units.

setup_homing(home_direction=None, limit_switch=None, velocity=None, offset_distance=None, channel=None, scale=True)

Set homing parameters.

If any parameter is None, use the current value. If scale==True, assume that the specified values are in the physical units (see class description); otherwise, assume it is in the device internal units.

get_gen_move_parameters(channel=None, scale=True)

Get general move parameters parameters (backlash_distance)

If scale==True, return values in the physical units (see class description); otherwise, return it in the device internal units.

setup_gen_move(backlash_distance=None, channel=None, scale=True)

Set jog parameters.

If any parameter is None, use the current value. If scale==True, assume that the specified value is in the physical units (see class description); otherwise, assume it is in the device internal units.

get_limit_switch_parameters(channel=None, scale=True)

Get current limit switch parameters (hw_kind_cw, hw_kind_ccw, hw_flipped, sw_position_cw, sw_position_ccw, sw_kind)

If scale==True, return values in the physical units (see class description); otherwise, return it in the device internal units (steps).

setup_limit_switch(hw_kind_cw=None, hw_kind_ccw=None, hw_swapped=None, sw_position_cw=None, sw_position_ccw=None, sw_kind=None, channel=None, scale=True)

Set limit switch parameters.

If any parameter is None, use the current value. If scale==True, assume that the specified values are in the physical units (see class description); otherwise, assume it is in the device internal units (Steps).

get_kcube_trigio_parameters()

Get KCube trigger IO parameters (trig1_pol, trig1_pol, trig2_mode, trig2_pol)

setup_kcube_trigio(trig1_mode=None, trig1_pol=None, trig2_mode=None, trig2_pol=None)

Set KCube trigger IO parameters.

If any parameter is None, use the current value.

get_kcube_trigpos_parameters(scale=True)

Get KCube trigger position parameters (start_fw, step_fw, num_fw, start_bk, step_bk, num_bk, width, ncycles).

If scale==True, return positions and steps in the physical units (see class description); otherwise, return it in the device internal units (steps). Pulse width is always defined in seconds.

setup_kcube_trigpos(start_fw=None, step_fw=None, num_fw=None, start_bk=None, step_bk=None, num_bk=None, width=None, ncycles=None, scale=True)

Set KCube trigger IO parameters.

If any parameter is None, use the current value.

If scale==True, return positions and steps in the physical units (see class description); otherwise, return it in the device internal units (steps). Pulse width is always defined in seconds.

class CommData(messageID, data, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

data
dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
source
class CommShort(messageID, param1, param2, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
param1
param2
source
Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

add_background_comm(messageID)

Mark given messageID as a ‘background’ message, which can be sent at any point without prompt (e.g., some operation confirmation).

If it is received instead during recv_comm_ operations, it is ignored, and the corresponding counter is increased.

apply_settings(settings)

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

Identify the physical device (by, e.g., blinking status LED or screen)

check_background_comm(messageID)

Return message counter and the last message value (None if not message received yet) of a given ‘background’ message

close()

Close the backend

get_all_axes()

Get the list of all available axes (taking mapping into account)

get_all_channels()

Get the list of all available channels; alias of get_all_axes method

get_device_info(dest=80)

Get device info.

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_number_of_channels()

Get number of channels on the device

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

static list_devices(filter_ids=True)

List all connected devices.

Return list of tuples (conn, description). If filter_ids==True, only leave devices with Thorlabs-like IDs (8-digit numbers). Otherwise, show all devices (some of them might not be Thorlabs-related).

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

query(messageID, param1=0, param2=0, source=1, dest=80, replyID=-1)

Send a query to the device and receive the reply.

A combination of send_comm() and recv_comm(). If replyID is not None, specifies the expected reply message ID; if -1 (default), set to te be messageID+1 (the standard convention).

recv_comm(expected_id=None)

Receive a message.

Return either CommShort or CommData depending on the message type (fixed length with two parameters, or variable length with associated data). If expected_id is not None and the received message ID is different from expected_id, raise an error. For details, see APT communications protocol.

remap_axes(mapping, accept_original=True)

Rename axes to the new labels.

mapping is the new axes mapping, which can be a list of new axes name (corresponding to the old axes in order returned by get_all_axes()), or a dictionary {alias: original} of the new axes aliases.

send_comm(messageID, param1=0, param2=0, source=1, dest=80)

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest=80)

Send a message with associated data.

For details, see APT communications protocol.

set_default_channel(channel)

Set the default channel for all channel-related methods

set_device_variable(key, value)

Set the value of a settings parameter

status_bits = [(1, 'sw_bk_lim'), (2, 'sw_fw_lim'), (16, 'moving_bk'), (32, 'moving_fw'), (64, 'jogging_bk'), (128, 'jogging_fw'), (512, 'homing'), (1024, 'homed'), (4096, 'tracking'), (8192, 'settled'), (16384, 'motion_error'), (16777216, 'current_limit'), (2147483648, 'enabled')]
unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_channel(channel)

Context manager for temporarily using a different default channel

class pylablib.devices.Thorlabs.kinesis.KinesisPiezoMotor(conn, default_channel=1)[source]

Bases: pylablib.devices.Thorlabs.kinesis.KinesisDevice

Thorlabs piezo motor (TIM/KIM series) controller.

Implements FTDI chip connectivity via pyft232 (virtual serial interface).

Parameters:conn (str) – serial connection parameters (usually an 8-digit device serial number).
get_enabled_channels()

Check which specific piezo motor channels are enabled.

Can be None (none enabled), or a tuple with either one or two channels: (1,) to (4,), (1,2) or (3,4).

enable_channels(channel)

Enable specific piezo motor channel.

Can be None (none enabled), and integer 1 to 4, or a tuple (1,2) or (3,4) (enable 2 channel simultaneously).

get_status_n(channel=None)

Get numerical status of the piezo motor.

For details, see APT communications protocol.

get_status(channel=None)

Get piezo motor status.

Return list of status strings, which can include "sw_fw_lim" (forward limit switch reached), "sw_bk_lim" (backward limit switch reached), "moving_fw" (moving forward), "moving_bk" (moving backward), "jogging_fw" (jogging forward), "jogging_bk" (jogging backward), "homing" (homing), "homed" (homing done), "tracking", "settled", "motion_error" (excessive position error), "current_limit" (motor current limit exceeded), or "enabled" (motor is enabled).

wait_for_status(status, enabled, timeout=None, period=0.05, channel=None)
get_position(channel=None)

Get current piezo-motor position

set_position_reference(position=0, channel=None)

Set piezo-motor position reference (actual position stays the same)

move_by(distance=1, auto_enable=True, channel=None)

Move piezo-motor by a given distance (positive or negative)

move_to(position, auto_enable=True, channel=None)

Move piezo-motor to position (positive or negative)

jog(direction, kind='continuous', auto_enable=True, channel=None)

Jog piezo motor in the given direction ("+" or "-").

If kind=="continuous", simply start motion in the given direction at the standard jog speed until either the motor is stopped explicitly, or the limit is reached. If kind=="builtin", use the built-in jog command, whose parameters are specified by get_jog_parameters(). Note that kind=="continuous" is still implemented through the builtin jog, so it changes its parameters; hence, afterwards the jog parameters need to be manually restored.

is_moving(channel=None)

Check if motion is in progress

wait_move(channel=None, timeout=None)

Wait until motion command is done

stop(channel=None, sync=True)

Stop the piezo motor motion

get_drive_parameters(channel=None)

Get current piezo-motor drive parameters (max_voltage, velocity, acceleration)

Voltage is defined in volts, velocity in steps/s, and acceleration in steps/s^2.

setup_drive(max_voltage=None, velocity=None, acceleration=None, channel=None)

Set piezo-motor drive parameters.

If any parameter is None, use the current value. Voltage is defined in volts, velocity in steps/s, and acceleration in steps/s^2.

get_jog_parameters(channel=None)

Get current piezo-motor jog parameters (mode, step_size_fw, step_size_bk, velocity, acceleration)

Step size is defined in piezo steps, velocity in steps/s, and acceleration in step/s^2.

setup_jog(mode=None, step_size_fw=None, step_size_bk=None, velocity=None, acceleration=None, channel=None)

Set piezo-motor jog parameters.

If any parameter is None, use the current value. Step size is defined in piezo steps, velocity in steps/s, and acceleration in step/s^2. TIM-series controllers do not support separate step size, so step_size_bk is ignored for them.

class CommData(messageID, data, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

data
dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
source
class CommShort(messageID, param1, param2, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
param1
param2
source
Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

add_background_comm(messageID)

Mark given messageID as a ‘background’ message, which can be sent at any point without prompt (e.g., some operation confirmation).

If it is received instead during recv_comm_ operations, it is ignored, and the corresponding counter is increased.

apply_settings(settings)

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

Identify the physical device (by, e.g., blinking status LED or screen)

check_background_comm(messageID)

Return message counter and the last message value (None if not message received yet) of a given ‘background’ message

close()

Close the backend

get_all_axes()

Get the list of all available axes (taking mapping into account)

get_all_channels()

Get the list of all available channels; alias of get_all_axes method

get_device_info(dest=80)

Get device info.

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_number_of_channels()

Get number of channels on the device

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

static list_devices(filter_ids=True)

List all connected devices.

Return list of tuples (conn, description). If filter_ids==True, only leave devices with Thorlabs-like IDs (8-digit numbers). Otherwise, show all devices (some of them might not be Thorlabs-related).

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

query(messageID, param1=0, param2=0, source=1, dest=80, replyID=-1)

Send a query to the device and receive the reply.

A combination of send_comm() and recv_comm(). If replyID is not None, specifies the expected reply message ID; if -1 (default), set to te be messageID+1 (the standard convention).

recv_comm(expected_id=None)

Receive a message.

Return either CommShort or CommData depending on the message type (fixed length with two parameters, or variable length with associated data). If expected_id is not None and the received message ID is different from expected_id, raise an error. For details, see APT communications protocol.

remap_axes(mapping, accept_original=True)

Rename axes to the new labels.

mapping is the new axes mapping, which can be a list of new axes name (corresponding to the old axes in order returned by get_all_axes()), or a dictionary {alias: original} of the new axes aliases.

send_comm(messageID, param1=0, param2=0, source=1, dest=80)

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest=80)

Send a message with associated data.

For details, see APT communications protocol.

set_default_channel(channel)

Set the default channel for all channel-related methods

set_device_variable(key, value)

Set the value of a settings parameter

status_bits = [(1, 'sw_bk_lim'), (2, 'sw_fw_lim'), (16, 'moving_bk'), (32, 'moving_fw'), (64, 'jogging_bk'), (128, 'jogging_fw'), (512, 'homing'), (1024, 'homed'), (4096, 'tracking'), (8192, 'settled'), (16384, 'motion_error'), (16777216, 'current_limit'), (2147483648, 'enabled')]
unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_channel(channel)

Context manager for temporarily using a different default channel

class pylablib.devices.Thorlabs.kinesis.TQuadDetectorPIDParams(p, i, d)

Bases: tuple

count()

Return number of occurrences of value.

d
i
index()

Return first index of value.

Raises ValueError if the value is not present.

p
class pylablib.devices.Thorlabs.kinesis.TQuadDetectorSetpoint(xpos, ypos)

Bases: tuple

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

xpos
ypos
class pylablib.devices.Thorlabs.kinesis.TQuadDetectorReadings(xdiff, ydiff, sum, xpos, ypos)

Bases: tuple

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

sum
xdiff
xpos
ydiff
ypos
class pylablib.devices.Thorlabs.kinesis.TQuadDetectorOutputParams(xmin, xmax, ymin, ymax, xgain, ygain, route, open_loop_out)

Bases: tuple

count()

Return number of occurrences of value.

index()

Return first index of value.

Raises ValueError if the value is not present.

open_loop_out
route
xgain
xmax
xmin
ygain
ymax
ymin
class pylablib.devices.Thorlabs.kinesis.KinesisQuadDetector(conn, timeout=3.0)[source]

Bases: pylablib.devices.Thorlabs.kinesis.BasicKinesisDevice

Kinesis quadrature detectors: KPA101, TPA101, TQD001.

Implements FTDI chip connectivity via pyft232 (virtual serial interface).

Parameters:conn (str) – serial connection parameters (usually an 8-digit device serial number).
get_pid_parameters()[source]

Get current PID gain parameters (p, i, d)

set_pid_parameters(p=None, i=None, d=None)[source]

Set current PID gain parameters (p, i, d).

If any parameter is None, use the current value.

get_manual_output()[source]

Get current manual output values (xpos, ypos) (used in open loop mode)

set_manual_output(xpos=None, ypos=None)[source]

Set current manual output values (used in open loop mode).

If any parameter is None, use the current value.

get_readings()[source]

Get current readings (xdiff, ydiff, sum, xpos, ypos)

get_operation_mode()[source]

Get current operation mode: "monitor", "open_loop", "closed_loop", or "auto_loop"

set_operation_mode(mode)[source]

Set current operation mode: "monitor", "open_loop", "closed_loop", or "auto_loop"

get_output_parameters()[source]

Get current output parameters (xmin, xmax, ymin, ymax, xgain, ygain, route, open_loop_out)

set_output_parameters(xmin=None, xmax=None, ymin=None, ymax=None, xgain=None, ygain=None, route=None, open_loop_out=None)[source]

Set current PID gain parameters (xmin, xmax, ymin, ymax, xgain, ygain, route, open_loop_out).

xmin, xmax, ymin, and ymax specify output limits, xgain and ygain specify additional separate gain (between -1 and 1), route sets where output is routed in the closed loop mode (either "sma_only" or "sma_hub"), open_loop_out specifies the output source in the open loop mode (either "zero" or "fixed"). If any parameter is None, use the current value.

class CommData(messageID, data, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

data
dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
source
class CommShort(messageID, param1, param2, source, dest)

Bases: tuple

count()

Return number of occurrences of value.

dest
index()

Return first index of value.

Raises ValueError if the value is not present.

messageID
param1
param2
source
Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

add_background_comm(messageID)

Mark given messageID as a ‘background’ message, which can be sent at any point without prompt (e.g., some operation confirmation).

If it is received instead during recv_comm_ operations, it is ignored, and the corresponding counter is increased.

apply_settings(settings)

Apply the settings.

settings is the dict {name: value} of the device available settings. Non-applicable settings are ignored.

Identify the physical device (by, e.g., blinking status LED or screen)

check_background_comm(messageID)

Return message counter and the last message value (None if not message received yet) of a given ‘background’ message

close()

Close the backend

get_device_info(dest=80)

Get device info.

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_number_of_channels()

Get number of channels on the device

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

static list_devices(filter_ids=True)

List all connected devices.

Return list of tuples (conn, description). If filter_ids==True, only leave devices with Thorlabs-like IDs (8-digit numbers). Otherwise, show all devices (some of them might not be Thorlabs-related).

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

query(messageID, param1=0, param2=0, source=1, dest=80, replyID=-1)

Send a query to the device and receive the reply.

A combination of send_comm() and recv_comm(). If replyID is not None, specifies the expected reply message ID; if -1 (default), set to te be messageID+1 (the standard convention).

recv_comm(expected_id=None)

Receive a message.

Return either CommShort or CommData depending on the message type (fixed length with two parameters, or variable length with associated data). If expected_id is not None and the received message ID is different from expected_id, raise an error. For details, see APT communications protocol.

send_comm(messageID, param1=0, param2=0, source=1, dest=80)

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest=80)

Send a message with associated data.

For details, see APT communications protocol.

set_device_variable(key, value)

Set the value of a settings parameter

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

pylablib.devices.Thorlabs.misc module

pylablib.devices.Thorlabs.serial module

class pylablib.devices.Thorlabs.serial.ThorlabsSerialInterface(conn)[source]

Bases: pylablib.core.devio.SCPI.SCPIDevice

Generic Thorlabs device interface using Serial communication.

Parameters:conn – serial connection parameters (usually port or a tuple containing port and baudrate)
Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

ReraiseError

alias of pylablib.devices.Thorlabs.base.ThorlabsBackendError

open()[source]

Open the backend

BackendError

alias of pylablib.core.devio.comm_backend.DeviceBackendError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

apply_settings(settings)

Apply the settings.

settings is a dict {name: value} of the available device settings. Non-applicable settings are ignored.

ask(msg, data_type='string', delay=0.0, timeout=None, read_echo=False)

Write a message and read a reply.

msg is the query message, delay is the delay between write and read. Other parameters are the same as in read(). If read_echo==True, assume that the device first echoes the input and skip it.

close()

Close the backend

flush(one_line=False)

Flush the read buffer (read all the available data and return the number of bytes read).

If one_line==True, read only a single line.

static get_arg_type(arg)

Autodetect argument type

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_esr(timeout=None)

Get the device status register (by default, "*ESR?" command)

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_id(timeout=None)

Get the device IDN. (query SCPI '*IDN?' command)

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

static parse_array_data(data, fmt, include_header=False)

Parse the data returned by the device. fmt is DataFormat description in numpy format (e.g., "<u2").

If include_header==True, the data is assumed to be in a (somewhat) standard SCPI format: b'#', then a single digit s denoting length of the size block, then s digits denoting length of the data (in bytes) followed by the actual data. Otherwise (include_header==False), assume that the header is already removed.

read(data_type='string', timeout=None)

Read data from the device.

data_type determines the type of the data. Can be 'raw' (just raw data), 'string' (with trailing and leading spaces stripped), 'int', 'float', 'bool' (interprets 0 or 'off' as False, anything else as True), 'value' (returns tuple (value, unit), where value is float), a callable (return the result of this callable applied to the string value), a dictionary (return the stored value corresponding to the string value, or to the value converted into integer if the string value is not present), or a list of data types (the result is treated as a list of values with the given types separated by commas). timeout overrides the default value.

read_binary_array_data(include_header=False, timeout=None, flush_term=True)

Read a binary data in the from the device.

The data assumes the standard binary transfer header consisting of "#" symbol, then a single digit with the size of the length string, then the length string containing the length of the binary data (in bytes). If include_header==True, return the data with the header; otherwise, return only the content. If flush_term==True, flush the following line to skip terminator characters after the binary data, which are added by some devices. timeout overrides the default value.

reconnect(new_instrument=True, ignore_error=True)

Remake the connection.

If new_instrument==True, create a new backend instance. If ignore_error==True, ignore errors on closing.

reset()

Reset the device (by default, "*RST" command)

set_device_variable(key, value)

Set the value of a settings parameter

sleep(delay)

Wait for delay seconds

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_write_buffer()

Context manager for using a write buffer.

While it’s active, all the consecutive write() operations are bundled together with ; delimiter. The actual write is performed at the read()/ask() operation or at the end of the block.

wait(wait_type='sync', timeout=None, wait_callback=None)

Pause execution until device overlapped commands are complete.

wait_type is either 'sync' (perform wait_sync()), 'dev' (perform wait_dev()) or 'none' (do nothing).

wait_dev()

Pause execution of the device commands until device overlapped commands (e.g., taking sweeps) are complete.

Note that the code execution is not paused.

wait_sync(timeout=None, wait_callback=None)

Pause execution of the script until device overlapped commands (e.g., taking sweeps) are complete.

timeout and wait_callback override default constructor parameters.

write(msg, arg=None, arg_type=None, unit=None, bool_selector=None, wait_sync=None, read_echo=False, read_echo_delay=0.0)

Send a command.

Parameters:
  • msg (str) – Text message.
  • arg – Optional argument to append in the end. If a list of arguments is supplied, the result is joined with ",".
  • arg_type (str) – Argument type. Can be 'raw' (in which case data is sent raw), 'string', 'int', 'float', 'bool', a format string (such as '{:.3f}') or a list of argument types (for an iterable argument); if format string is used and the argument is a list or a tuple, then it is expanded as a list of arguments (e.g., arg_type='{0};{1}' with arg=[1,2] will produce a string '1;2'); if a list of types is used, each element of arg is converted using the corresponding type, and the result is joined with ",".
  • unit (str) – If not None, use it as a unit to append after the value.
  • bool_selector (tuple) – A tuple (false_value, true_value) of two strings to represent bool argument; by default, use ._bool_selector attribute.
  • wait_sync – if True, append the sync command (specified as ._wait_sync_comm attribute, "*OPC?" by default) after the message and pause the execution command is complete; useful in long set operations, where the device might ignore later inputs until the current command is complete; if None, use the class default ._default_write_sync attribute (False by default).
  • read_echo (bool) – If True, read a single line after write.
  • read_echo_delay (float) – The delay between write and read if read_echo==True.
class pylablib.devices.Thorlabs.serial.FW(conn, respect_bound=True)[source]

Bases: pylablib.devices.Thorlabs.serial.ThorlabsSerialInterface

Thorlabs FW102/212 motorized filter wheels.

Parameters:
  • conn – serial connection parameters (usually port or a tuple containing port and baudrate)
  • respect_bound (bool) – if True, avoid crossing the boundary between the first and the last position in the wheel
ask(msg, data_type='string', delay=0.0, timeout=None, read_echo=False)[source]

Write a message and read a reply.

msg is the query message, delay is the delay between write and read. Other parameters are the same as in read(). If read_echo==True, assume that the device first echoes the input and skip it.

get_position()[source]

Get the wheel position (starting from 1)

set_position(pos)[source]

Set the wheel position (starting from 1)

get_pcount()[source]

Get the number of wheel positions (6 or 12)

set_pcount(pcount)[source]

Set the number of wheel positions (6 or 12)

get_speed_mode()[source]

Get the motion speed mode ("low" or "high")

set_speed_mode(speed_mode)[source]

Set the motion speed mode ("low" or "high")

get_trigger_mode()[source]

Get the trigger mode ("in" to input external trigger, "out" to output trigger)

set_trigger_mode(trigger_mode)[source]

Set the trigger mode ("in" to input external trigger, "out" to output trigger)

get_sensor_mode()[source]

Get the sensor mode ("off" to turn off when idle to eliminate stray light, "on" to remain on)

set_sensor_mode(sensor_mode)[source]

Set the sensor mode ("off" to turn off when idle to eliminate stray light, "on" to remain on)

store_settings()[source]

Store current settings as default

BackendError

alias of pylablib.core.devio.comm_backend.DeviceBackendError

Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

ReraiseError

alias of pylablib.devices.Thorlabs.base.ThorlabsBackendError

apply_settings(settings)

Apply the settings.

settings is a dict {name: value} of the available device settings. Non-applicable settings are ignored.

close()

Close the backend

flush(one_line=False)

Flush the read buffer (read all the available data and return the number of bytes read).

If one_line==True, read only a single line.

static get_arg_type(arg)

Autodetect argument type

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_esr(timeout=None)

Get the device status register (by default, "*ESR?" command)

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_id(timeout=None)

Get the device IDN. (query SCPI '*IDN?' command)

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

static parse_array_data(data, fmt, include_header=False)

Parse the data returned by the device. fmt is DataFormat description in numpy format (e.g., "<u2").

If include_header==True, the data is assumed to be in a (somewhat) standard SCPI format: b'#', then a single digit s denoting length of the size block, then s digits denoting length of the data (in bytes) followed by the actual data. Otherwise (include_header==False), assume that the header is already removed.

read(data_type='string', timeout=None)

Read data from the device.

data_type determines the type of the data. Can be 'raw' (just raw data), 'string' (with trailing and leading spaces stripped), 'int', 'float', 'bool' (interprets 0 or 'off' as False, anything else as True), 'value' (returns tuple (value, unit), where value is float), a callable (return the result of this callable applied to the string value), a dictionary (return the stored value corresponding to the string value, or to the value converted into integer if the string value is not present), or a list of data types (the result is treated as a list of values with the given types separated by commas). timeout overrides the default value.

read_binary_array_data(include_header=False, timeout=None, flush_term=True)

Read a binary data in the from the device.

The data assumes the standard binary transfer header consisting of "#" symbol, then a single digit with the size of the length string, then the length string containing the length of the binary data (in bytes). If include_header==True, return the data with the header; otherwise, return only the content. If flush_term==True, flush the following line to skip terminator characters after the binary data, which are added by some devices. timeout overrides the default value.

reconnect(new_instrument=True, ignore_error=True)

Remake the connection.

If new_instrument==True, create a new backend instance. If ignore_error==True, ignore errors on closing.

reset()

Reset the device (by default, "*RST" command)

set_device_variable(key, value)

Set the value of a settings parameter

sleep(delay)

Wait for delay seconds

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_write_buffer()

Context manager for using a write buffer.

While it’s active, all the consecutive write() operations are bundled together with ; delimiter. The actual write is performed at the read()/ask() operation or at the end of the block.

wait(wait_type='sync', timeout=None, wait_callback=None)

Pause execution until device overlapped commands are complete.

wait_type is either 'sync' (perform wait_sync()), 'dev' (perform wait_dev()) or 'none' (do nothing).

wait_dev()

Pause execution of the device commands until device overlapped commands (e.g., taking sweeps) are complete.

Note that the code execution is not paused.

wait_sync(timeout=None, wait_callback=None)

Pause execution of the script until device overlapped commands (e.g., taking sweeps) are complete.

timeout and wait_callback override default constructor parameters.

write(msg, arg=None, arg_type=None, unit=None, bool_selector=None, wait_sync=None, read_echo=False, read_echo_delay=0.0)

Send a command.

Parameters:
  • msg (str) – Text message.
  • arg – Optional argument to append in the end. If a list of arguments is supplied, the result is joined with ",".
  • arg_type (str) – Argument type. Can be 'raw' (in which case data is sent raw), 'string', 'int', 'float', 'bool', a format string (such as '{:.3f}') or a list of argument types (for an iterable argument); if format string is used and the argument is a list or a tuple, then it is expanded as a list of arguments (e.g., arg_type='{0};{1}' with arg=[1,2] will produce a string '1;2'); if a list of types is used, each element of arg is converted using the corresponding type, and the result is joined with ",".
  • unit (str) – If not None, use it as a unit to append after the value.
  • bool_selector (tuple) – A tuple (false_value, true_value) of two strings to represent bool argument; by default, use ._bool_selector attribute.
  • wait_sync – if True, append the sync command (specified as ._wait_sync_comm attribute, "*OPC?" by default) after the message and pause the execution command is complete; useful in long set operations, where the device might ignore later inputs until the current command is complete; if None, use the class default ._default_write_sync attribute (False by default).
  • read_echo (bool) – If True, read a single line after write.
  • read_echo_delay (float) – The delay between write and read if read_echo==True.
class pylablib.devices.Thorlabs.serial.FWv1(conn, pcount=6, respect_bound=True)[source]

Bases: pylablib.devices.Thorlabs.serial.ThorlabsSerialInterface

Thorlabs FW102/212 v1.0 (older version) motorized filter wheels.

Parameters:
  • conn – serial connection parameters (usually port or a tuple containing port and baudrate)
  • pcount – number of positions in the wheel
  • respect_bound (bool) – if True, avoid crossing the boundary between the first and the last position in the wheel
ask(msg, data_type='string', delay=0.0, timeout=None, read_echo=False)[source]

Write a message and read a reply.

msg is the query message, delay is the delay between write and read. Other parameters are the same as in read(). If read_echo==True, assume that the device first echoes the input and skip it.

get_position()[source]

Get the wheel position (starting from 1)

set_position(pos)[source]

Set the wheel position (starting from 1)

get_pcount()[source]

Get the number of wheel positions (6 or 12)

get_trigger_mode()[source]

Get the trigger mode ("in" to input external trigger, "out" to output trigger)

set_trigger_mode(trigger_mode)[source]

Set the trigger mode ("in" to input external trigger, "out" to output trigger)

BackendError

alias of pylablib.core.devio.comm_backend.DeviceBackendError

Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

ReraiseError

alias of pylablib.devices.Thorlabs.base.ThorlabsBackendError

apply_settings(settings)

Apply the settings.

settings is a dict {name: value} of the available device settings. Non-applicable settings are ignored.

close()

Close the backend

flush(one_line=False)

Flush the read buffer (read all the available data and return the number of bytes read).

If one_line==True, read only a single line.

static get_arg_type(arg)

Autodetect argument type

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_esr(timeout=None)

Get the device status register (by default, "*ESR?" command)

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_id(timeout=None)

Get the device IDN. (query SCPI '*IDN?' command)

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

static parse_array_data(data, fmt, include_header=False)

Parse the data returned by the device. fmt is DataFormat description in numpy format (e.g., "<u2").

If include_header==True, the data is assumed to be in a (somewhat) standard SCPI format: b'#', then a single digit s denoting length of the size block, then s digits denoting length of the data (in bytes) followed by the actual data. Otherwise (include_header==False), assume that the header is already removed.

read(data_type='string', timeout=None)

Read data from the device.

data_type determines the type of the data. Can be 'raw' (just raw data), 'string' (with trailing and leading spaces stripped), 'int', 'float', 'bool' (interprets 0 or 'off' as False, anything else as True), 'value' (returns tuple (value, unit), where value is float), a callable (return the result of this callable applied to the string value), a dictionary (return the stored value corresponding to the string value, or to the value converted into integer if the string value is not present), or a list of data types (the result is treated as a list of values with the given types separated by commas). timeout overrides the default value.

read_binary_array_data(include_header=False, timeout=None, flush_term=True)

Read a binary data in the from the device.

The data assumes the standard binary transfer header consisting of "#" symbol, then a single digit with the size of the length string, then the length string containing the length of the binary data (in bytes). If include_header==True, return the data with the header; otherwise, return only the content. If flush_term==True, flush the following line to skip terminator characters after the binary data, which are added by some devices. timeout overrides the default value.

reconnect(new_instrument=True, ignore_error=True)

Remake the connection.

If new_instrument==True, create a new backend instance. If ignore_error==True, ignore errors on closing.

reset()

Reset the device (by default, "*RST" command)

set_device_variable(key, value)

Set the value of a settings parameter

sleep(delay)

Wait for delay seconds

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_write_buffer()

Context manager for using a write buffer.

While it’s active, all the consecutive write() operations are bundled together with ; delimiter. The actual write is performed at the read()/ask() operation or at the end of the block.

wait(wait_type='sync', timeout=None, wait_callback=None)

Pause execution until device overlapped commands are complete.

wait_type is either 'sync' (perform wait_sync()), 'dev' (perform wait_dev()) or 'none' (do nothing).

wait_dev()

Pause execution of the device commands until device overlapped commands (e.g., taking sweeps) are complete.

Note that the code execution is not paused.

wait_sync(timeout=None, wait_callback=None)

Pause execution of the script until device overlapped commands (e.g., taking sweeps) are complete.

timeout and wait_callback override default constructor parameters.

write(msg, arg=None, arg_type=None, unit=None, bool_selector=None, wait_sync=None, read_echo=False, read_echo_delay=0.0)

Send a command.

Parameters:
  • msg (str) – Text message.
  • arg – Optional argument to append in the end. If a list of arguments is supplied, the result is joined with ",".
  • arg_type (str) – Argument type. Can be 'raw' (in which case data is sent raw), 'string', 'int', 'float', 'bool', a format string (such as '{:.3f}') or a list of argument types (for an iterable argument); if format string is used and the argument is a list or a tuple, then it is expanded as a list of arguments (e.g., arg_type='{0};{1}' with arg=[1,2] will produce a string '1;2'); if a list of types is used, each element of arg is converted using the corresponding type, and the result is joined with ",".
  • unit (str) – If not None, use it as a unit to append after the value.
  • bool_selector (tuple) – A tuple (false_value, true_value) of two strings to represent bool argument; by default, use ._bool_selector attribute.
  • wait_sync – if True, append the sync command (specified as ._wait_sync_comm attribute, "*OPC?" by default) after the message and pause the execution command is complete; useful in long set operations, where the device might ignore later inputs until the current command is complete; if None, use the class default ._default_write_sync attribute (False by default).
  • read_echo (bool) – If True, read a single line after write.
  • read_echo_delay (float) – The delay between write and read if read_echo==True.
class pylablib.devices.Thorlabs.serial.MDT69xA(conn)[source]

Bases: pylablib.devices.Thorlabs.serial.ThorlabsSerialInterface

Thorlabs MDT693A/4A high-voltage source.

Uses MDT693A program interface, so should be compatible with both A and B versions (though it doesn’t support all functions of MDT693B/4B)

Parameters:conn – serial connection parameters (usually port or a tuple containing port and baudrate)
get_voltage(channel='x')[source]

Get the output voltage in Volts at a given channel

set_voltage(voltage, channel='x')[source]

Set the output voltage in Volts at a given channel

get_voltage_range()[source]

Get the selected voltage range in Volts (75, 100 or 150)

BackendError

alias of pylablib.core.devio.comm_backend.DeviceBackendError

Error

alias of pylablib.devices.Thorlabs.base.ThorlabsError

class NoParameterCaller(device, kind)

Bases: object

Class to simplify calling functions without a parameter

ReraiseError

alias of pylablib.devices.Thorlabs.base.ThorlabsBackendError

apply_settings(settings)

Apply the settings.

settings is a dict {name: value} of the available device settings. Non-applicable settings are ignored.

ask(msg, data_type='string', delay=0.0, timeout=None, read_echo=False)

Write a message and read a reply.

msg is the query message, delay is the delay between write and read. Other parameters are the same as in read(). If read_echo==True, assume that the device first echoes the input and skip it.

close()

Close the backend

flush(one_line=False)

Flush the read buffer (read all the available data and return the number of bytes read).

If one_line==True, read only a single line.

static get_arg_type(arg)

Autodetect argument type

get_device_variable(key)

Get the value of a settings, status, or full info parameter

get_esr(timeout=None)

Get the device status register (by default, "*ESR?" command)

get_full_info(include=0)

Get dict {name: value} containing full device information (including status and settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_full_status(include=0)

Get dict {name: value} containing the device status (including settings).

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

get_id(timeout=None)

Get the device IDN. (query SCPI '*IDN?' command)

get_settings(include=0)

Get dict {name: value} containing all the device settings.

include specifies either a list of variables (only these variables are returned), a priority threshold (only values with the priority equal or higher are returned), or "all" (all available variables). Since the lowest priority is -10, setting include=-10 queries all available variables, which is equivalent to include="all".

is_opened()

Check if the device is connected

lock(timeout=None)

Lock the access to the device from other threads/processes (isn’t necessarily implemented)

locking(timeout=None)

Context manager for lock & unlock

open()

Open the backend

static parse_array_data(data, fmt, include_header=False)

Parse the data returned by the device. fmt is DataFormat description in numpy format (e.g., "<u2").

If include_header==True, the data is assumed to be in a (somewhat) standard SCPI format: b'#', then a single digit s denoting length of the size block, then s digits denoting length of the data (in bytes) followed by the actual data. Otherwise (include_header==False), assume that the header is already removed.

read(data_type='string', timeout=None)

Read data from the device.

data_type determines the type of the data. Can be 'raw' (just raw data), 'string' (with trailing and leading spaces stripped), 'int', 'float', 'bool' (interprets 0 or 'off' as False, anything else as True), 'value' (returns tuple (value, unit), where value is float), a callable (return the result of this callable applied to the string value), a dictionary (return the stored value corresponding to the string value, or to the value converted into integer if the string value is not present), or a list of data types (the result is treated as a list of values with the given types separated by commas). timeout overrides the default value.

read_binary_array_data(include_header=False, timeout=None, flush_term=True)

Read a binary data in the from the device.

The data assumes the standard binary transfer header consisting of "#" symbol, then a single digit with the size of the length string, then the length string containing the length of the binary data (in bytes). If include_header==True, return the data with the header; otherwise, return only the content. If flush_term==True, flush the following line to skip terminator characters after the binary data, which are added by some devices. timeout overrides the default value.

reconnect(new_instrument=True, ignore_error=True)

Remake the connection.

If new_instrument==True, create a new backend instance. If ignore_error==True, ignore errors on closing.

reset()

Reset the device (by default, "*RST" command)

set_device_variable(key, value)

Set the value of a settings parameter

sleep(delay)

Wait for delay seconds

unlock()

Unlock the access to the device from other threads/processes (isn’t necessarily implemented)

using_write_buffer()

Context manager for using a write buffer.

While it’s active, all the consecutive write() operations are bundled together with ; delimiter. The actual write is performed at the read()/ask() operation or at the end of the block.

wait(wait_type='sync', timeout=None, wait_callback=None)

Pause execution until device overlapped commands are complete.

wait_type is either 'sync' (perform wait_sync()), 'dev' (perform wait_dev()) or 'none' (do nothing).

wait_dev()

Pause execution of the device commands until device overlapped commands (e.g., taking sweeps) are complete.

Note that the code execution is not paused.

wait_sync(timeout=None, wait_callback=None)

Pause execution of the script until device overlapped commands (e.g., taking sweeps) are complete.

timeout and wait_callback override default constructor parameters.

write(msg, arg=None, arg_type=None, unit=None, bool_selector=None, wait_sync=None, read_echo=False, read_echo_delay=0.0)

Send a command.

Parameters:
  • msg (str) – Text message.
  • arg – Optional argument to append in the end. If a list of arguments is supplied, the result is joined with ",".
  • arg_type (str) – Argument type. Can be 'raw' (in which case data is sent raw), 'string', 'int', 'float', 'bool', a format string (such as '{:.3f}') or a list of argument types (for an iterable argument); if format string is used and the argument is a list or a tuple, then it is expanded as a list of arguments (e.g., arg_type='{0};{1}' with arg=[1,2] will produce a string '1;2'); if a list of types is used, each element of arg is converted using the corresponding type, and the result is joined with ",".
  • unit (str) – If not None, use it as a unit to append after the value.
  • bool_selector (tuple) – A tuple (false_value, true_value) of two strings to represent bool argument; by default, use ._bool_selector attribute.
  • wait_sync – if True, append the sync command (specified as ._wait_sync_comm attribute, "*OPC?" by default) after the message and pause the execution command is complete; useful in long set operations, where the device might ignore later inputs until the current command is complete; if None, use the class default ._default_write_sync attribute (False by default).
  • read_echo (bool) – If True, read a single line after write.
  • read_echo_delay (float) – The delay between write and read if read_echo==True.

Module contents