pylablib.devices.Thorlabs package

Submodules

pylablib.devices.Thorlabs.TLCamera module

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

Bases: 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

get_opened_num()[source]

Get number of opened devices

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

firmware_version
model
name
serial_number
class pylablib.devices.Thorlabs.TLCamera.TSensorInfo(sensor_type, bit_depth)

Bases: tuple

bit_depth
sensor_type
class pylablib.devices.Thorlabs.TLCamera.TColorInfo(filter_array_phase, correction_matrix, default_white_balance_matrix)

Bases: tuple

correction_matrix
default_white_balance_matrix
filter_array_phase
class pylablib.devices.Thorlabs.TLCamera.TColorFormat(color_format, color_space)

Bases: tuple

color_format
color_space
class pylablib.devices.Thorlabs.TLCamera.TFrameInfo(frame_index, framestamp, pixelclock, pixeltype, offset)

Bases: tuple

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

Bases: IBinROICamera, 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='139946256118160'>
TimeoutError = <Mock spec='str' id='139946262881744'>
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).

get_sensor_info()[source]

Get camera sensor info.

Return tuple (sensor_type, bit_depth), where sensor type is "mono", "bayer", or "mono_pol", and bit depth is an integer.

get_color_info()[source]

Get camera color info.

Return tuple (filter_array_phase, correction_matrix, default_white_balance_matrix), or None if the sensor type is not "bayer".

get_white_balance_matrix()[source]

Get the white balance matrix

set_white_balance_matrix(matrix=None)[source]

Set the white balance matrix.

Can be None (the default matrix), a 3-number 1D array (multipliers for RGB), or a full 3x3 matrix.

set_color_format(color_output='auto', color_space='linear')[source]

Set camera color format.

color_output determines the output frame format, and can be "raw" (raw pixel values without debayering), "rgb" (color images with the color corresponding to the last array axis), "grayscale" (average of the colored images), or "auto" ("rgb" for cameras supporting color and "raw" otherwise). Note that setting "rgb" for monochrome cameras is not allowed. color_space defines the output color space, and can be "linear" (linear in the pixel values), or "srgb" (sRGB color space, which is a non-linear transformation of the linear values).

get_color_format()[source]

Get camera color format as a tuple (color_output, color_space)

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_frame_period_range()[source]

Get minimal and maximal frame period (s)

set_frame_period(frame_period)[source]

Set camera frame period.

If it is 0 or None, set to the auto-rate mode, which automatically selects the highest frame rate.

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_gain_range()[source]

Return the available gain range (in dB)

get_gain()[source]

Return the current gain (in dB)

set_gain(gain, truncate=True)[source]

Set the current gain (in dB).

If truncate==True, truncate the value to lie within the allowed range; otherwise, out-of-range values cause an error.

get_black_level_range()[source]

Return the available black level range

get_black_level()[source]

Return the current black level

set_black_level(level, truncate=True)[source]

Set the current black level.

If truncate==True, truncate the value to lie within the allowed range; otherwise, out-of-range values cause an error.

is_nir_boost_enabled()[source]

Check if NIR boost is enabled

enable_nir_boost(enable=True)[source]

Enable or disable NIR boost

is_cooling_enabled()[source]

Check if cooling is enabled

enable_cooling(enable=True)[source]

Enable or disable cooling

is_led_enabled()[source]

Check if led is enabled

enable_led(enable=True)[source]

Enable or disable led

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, return_rng=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. if return_rng==True, return the range covered resulting frames; if missing_frame=="skip", the range can be smaller than the supplied rng if some frames are skipped.

FrameTransferError

alias of DefaultFrameTransferError

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), "array" (a single 3D array), or "chunks" (list of 3D “chunk” arrays; supported for some cameras and provides the best performance).

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 "chunks" frame format), 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='skip', 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, stop=True, setup_after=None, start_after=True, combine_nested=True)

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 stopping (by default, use the class default specified as _clear_pausing_acquisition attribute). If stop==True, stop the acquisition (if clear==True, stop regardless). If setup_after==True, setup the acquisition after pause if necessary (None means setup only if clearing was required). If start_after==True, start the acquisition after pause if necessary (None means start only if stopping was required). If combine_nested==True, then any nested pausing_acquisition calls will stop/clear acquisition as necessary, but won’t setup/start it again until this pausing_acquisition call is complete.

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), "array" (a single 3D array), "chunks" (list of 3D “chunk” arrays; supported for some cameras and provides the best performance), or "try_chunks" (same as "chunks", but if chunks are not supported, set to "list" instead). If format is "chunks" and chunks are not supported by the camera, it results in one frame per chunk. Note that if the format is set to "array" or "chunks", the frame info format is also automatically set to "array". If the format is set to "chunks", then the image info is also returned in chunks form (list of 2D info arrays with the same length as the corresponding frame chunks).

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 "chunks" frame format), 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; note that order or include_fields is ignored, and the resulting fields are always ordered same as in the original.

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: DeviceError

Generic Thorlabs error

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

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

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

Bases: ThorlabsError, DeviceBackendError

Thorlabs backend communication error

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

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

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

Bases: ThorlabsError

Thorlabs timeout error

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

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

pylablib.devices.Thorlabs.elliptec module

pylablib.devices.Thorlabs.elliptec.muxaddr(*args, argname='addr', **kwargs)[source]

Multiplex the function over its addr argument

class pylablib.devices.Thorlabs.elliptec.TDeviceInfo(serial_no, model_no, year, fw_ver, hw_ver, travel, pulse)

Bases: tuple

fw_ver
hw_ver
model_no
pulse
serial_no
travel
year
class pylablib.devices.Thorlabs.elliptec.TMotorInfo(loop, motor, current, ramp_up, ramp_down, fw_freq, bk_freq)

Bases: tuple

bk_freq
current
fw_freq
loop
motor
ramp_down
ramp_up
class pylablib.devices.Thorlabs.elliptec.ElliptecMotor(conn, addrs='all', default_addr=None, scale='stage', timeout=3.0, valid_status=('ok', 'mech_timeout'))[source]

Bases: ICommBackendWrapper

Basic Elliptec stage device.

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

  • addrs – list of device addresses (between 0 and 15) connected to this serial port; if "all", automatically detect all connected devices

  • default_addr – address used by default when not supplied; by default, use the first address among the connected

  • scale – scale of the position units to the internals units; can be "stage" (use stage units such as mm or deg based on its internal calibration), "step" (directly use step units), or a number which multiplies user-supplied units to produce steps

  • timeout – default communication timeout

  • valid_status – status which are considered valid and do not raise an error on status check

Error

alias of ThorlabsError

get_connected_addrs()[source]

Get a list of all connected device addresses

get_default_addr()[source]

Get the current default address

set_default_addr(addr)[source]

Set the current default address

using_default_addr(addr)[source]

Context manager which temporarily changes the default address

send_comm(comm, data='', addr=None)[source]

Send a message with the given data to the devices at a given address.

For details, see ELLx communications protocol.

class CommData(comm, data, addr)

Bases: tuple

addr
comm
data
recv_comm(comm=None, addr=None, datalen='auto', timeout=None)[source]

Receive a message.

comm, addr, and datalen can specify the expected return command, address, or the length of the data field (if "auto", determine based on the return command). timeout specifies the waiting timeout (by default, same as supplied upon the device connection).

For details, see ELLx communications protocol.

query(comm, data='', addr=None, reply_comm=None, reply_addr='auto', reply_datalen='auto', timeout=None)[source]

Send a query to the device and receive the reply.

A combination of send_comm() and recv_comm().

add_background_comm(comm)[source]

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

If it is received instead during recv_comm or query operations, it is ignored, and the corresponding counter is increased.

check_background_comm(comm, addr=None)[source]

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

change_addr(newaddr, addr=None)[source]

Change the device address to a new value (between 0 and 15)

store_parameters(addr=None)[source]

Store current device parameters (e.g., frequencies) to the energy-independent memory

get_device_info(addr=None)[source]

Get device info.

Return tuple (serial_no, model_no, year, fw_ver, hw_ver, travel, pulse).

get_status(addr=None)[source]

Get device status

get_motor_info(motor=1, addr=None)[source]

Get info for a given motor (between 1 and 3).

Return tuple (loop_ena, motor_ena, current, ramp_up, ramp_down, fw_freq, bk_freq).

get_scale(addr=None)[source]

Get scale parameter for the specified address.

Can be "stage", "step", or a proportionality coefficient.

set_scale(scale, addr=None)[source]

Set scale parameter for the specified address.

Can be "stage", "step", or a proportionality coefficient.

home(home_dir='cw', paddles='all', addr=None)[source]

Home the device.

The operation is synchronous, i.e., it will not finish until the homing is done. If the device is a rotary stage, then home_dir specifies homing direction ("cw" or "ccw"). If the device is a paddle polarization controller, then paddles is a list of all paddle indices (1 to 3) to home ("all" is the same as [1,2,3]).

get_home_offset(addr=None)[source]

Get homing offset

set_home_offset(offset, addr=None)[source]

Set homing offset (note: the manufacturer advises against it)

get_velocity(addr=None)[source]

Get velocity as a percentage from the maximal velocity (0 to 100)

set_velocity(velocity=100, addr=None)[source]

Set velocity as a percentage from the maximal velocity (0 to 100)

get_frequency(motor=1, addr=None)[source]

Get frequencies at a given motor as a tuple (fw_freq, bk_freq)

set_frequency(fw_freq=None, bk_freq=None, motor=1, addr=None)[source]

Set frequencies at a given motor.

Values set as None stay the same.

search_frequency(motor=1, addr=None)[source]

Run the automated frequency search on a given motor.

The position might change slightly throughout the process.

get_position(addr=None)[source]

Get the current position

move_to(position, addr=None, timeout=30.0)[source]

Move to the given position.

The operation is synchronous, i.e., it will not finish until the motion is stopped. Return True if the position was reached successfully or False otherwise.

move_by(distance, addr=None, timeout=30.0)[source]

Move by the given distance.

The operation is synchronous, i.e., it will not finish until the motion is stopped. Return True if the position was reached successfully or False otherwise.

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)

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

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

Bases: 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).

  • is_rack_system – specify whether the device is a rack system or a standalone USB device (default mode).

Error

alias of 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='host')[source]

Send a message with no associated data.

For details, see APT communications protocol.

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

Send a message with associated data.

For details, see APT communications protocol.

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

Bases: tuple

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

Bases: tuple

data
dest
messageID
source
recv_comm(expected_id=None, timeout=None)[source]

Receive a message.

Return either BasicKinesisDevice.CommShort or BasicKinesisDevice.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. If timeout is not None, it can specify the timeout to read the command header (the rest is done with the usual timeout). For details, see APT communications protocol.

flush_comm(nmax=1000)[source]

Flush any commands in the queue.

if nmax is not None, it specifies the maximal number of commands to flush.

query(messageID, param1=0, param2=0, source=1, dest='host', replyID=-1, flush='auto')[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). flush specifies whether input queue will be flushed before reading; "auto" means that it will be flushed if the expected reply is among the background messages, i.e., it could be already present in the queue.

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='host')[source]

Get device info.

Return tuple (serial_no, model_no, fw_ver, hw_type, hw_ver, mod_state, nchannels, notes).

get_number_of_channels()[source]

Get number of channels on the device

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

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
max_velocity
min_velocity
class pylablib.devices.Thorlabs.kinesis.TJogParams(mode, step_size, min_velocity, acceleration, max_velocity, stop_mode)

Bases: tuple

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

Bases: tuple

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

Bases: tuple

home_direction
limit_switch
offset_distance
velocity
class pylablib.devices.Thorlabs.kinesis.TPolCtlParams(velocity, home_position, jog1, jog2, jog3)

Bases: tuple

home_position
jog1
jog2
jog3
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

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

Bases: tuple

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

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
max_voltage
velocity
class pylablib.devices.Thorlabs.kinesis.TPZMotorJogParams(mode, step_size_fw, step_size_bk, velocity, acceleration)

Bases: tuple

acceleration
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, is_rack_system=False)[source]

Bases: IMultiaxisStage, BasicKinesisDevice

Overarching Kinesis class containing all of the necessary private methods.

Subclasses are expected to make some of them visible by renaming, and to define device variables and opening behavior accordingly.

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

  • timeout – device communication timeout.

  • default_channel – starting default channel used when no channel is supplied to a channel-level command (such as move_to or get_position).

  • is_rack_system – specify whether the device is a rack system or a standalone USB device (default mode).

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, 'hw_bk_lim'), (2, 'hw_fw_lim'), (4, 'sw_bk_lim'), (8, 'sw_fw_lim'), (16, 'moving_bk'), (32, 'moving_fw'), (64, 'jogging_bk'), (128, 'jogging_fw'), (256, 'connected'), (512, 'homing'), (1024, 'homed'), (2048, 'initializing'), (4096, 'tracking'), (8192, 'settled'), (16384, 'motion_error'), (32768, 'instr_error'), (65536, 'interlock'), (131072, 'overtemp'), (262144, 'volt_supply_fault'), (524288, 'commutation_error'), (1048576, 'digio1'), (2097152, 'digio2'), (4194304, 'digio3'), (8388608, 'digio4'), (16777216, 'current_limit'), (33554432, 'encoder_fault'), (67108864, 'overcurrent'), (134217728, 'curr_supply_fault'), (268435456, 'power_ok'), (536870912, 'active'), (1073741824, 'error'), (2147483648, 'enabled')]
Error

alias of ThorlabsError

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

flush_comm(nmax=1000)

Flush any commands in the queue.

if nmax is not None, it specifies the maximal number of commands to flush.

get_all_axes()

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

get_device_info(dest='host')

Get device info.

Return tuple (serial_no, model_no, fw_ver, hw_type, hw_ver, mod_state, nchannels, notes).

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='host', replyID=-1, flush='auto')

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). flush specifies whether input queue will be flushed before reading; "auto" means that it will be flushed if the expected reply is among the background messages, i.e., it could be already present in the queue.

recv_comm(expected_id=None, timeout=None)

Receive a message.

Return either BasicKinesisDevice.CommShort or BasicKinesisDevice.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. If timeout is not None, it can specify the timeout to read the command header (the rest is done with the usual timeout). 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='host')

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest='host')

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

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: 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 "hw_fw_lim" (forward hardware limit switch reached), "hw_bk_lim" (backward hardware limit switch reached), "sw_fw_lim" (forward software limit switch reached), "sw_bk_lim" (backward software limit switch reached), "moving_fw" (moving forward), "moving_bk" (moving backward), "jogging_fw" (jogging forward), "jogging_bk" (jogging backward), "connected" (motor is connected), "homing" (homing), "homed" (homing done), "initializing" (3-phase motor phase initialization), "tracking" (position is within trajectory), "settled" (position has been stable), "motion_error" (excessive position error), "instr_error" (legacy instrument command error), "interlock" (interlock is on), "overtemp" (temperature above limit), "volt_supply_fault" (supply voltage is too low), "commutation_error" (3-phase motor commutation error), "digio1" (state of digital input 1), "digio2" (state of digital input 2), "digio3" (state of digital input 3), "digio4" (state of digital input 4), "current_limit" (motor current limit exceeded for a long time), "encoder_fault" (encoder problems), "overcurrent" (motor current limit exceeded temporarily), "curr_supply_fault" (current drawn from supply is too high), "power_ok" (power is ok), "active" (moving), "error" (any error), "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.

Error

alias of ThorlabsError

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

flush_comm(nmax=1000)

Flush any commands in the queue.

if nmax is not None, it specifies the maximal number of commands to flush.

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='host')

Get device info.

Return tuple (serial_no, model_no, fw_ver, hw_type, hw_ver, mod_state, nchannels, notes).

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='host', replyID=-1, flush='auto')

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). flush specifies whether input queue will be flushed before reading; "auto" means that it will be flushed if the expected reply is among the background messages, i.e., it could be already present in the queue.

recv_comm(expected_id=None, timeout=None)

Receive a message.

Return either BasicKinesisDevice.CommShort or BasicKinesisDevice.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. If timeout is not None, it can specify the timeout to read the command header (the rest is done with the usual timeout). 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='host')

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest='host')

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, 'hw_bk_lim'), (2, 'hw_fw_lim'), (4, 'sw_bk_lim'), (8, 'sw_fw_lim'), (16, 'moving_bk'), (32, 'moving_fw'), (64, 'jogging_bk'), (128, 'jogging_fw'), (256, 'connected'), (512, 'homing'), (1024, 'homed'), (2048, 'initializing'), (4096, 'tracking'), (8192, 'settled'), (16384, 'motion_error'), (32768, 'instr_error'), (65536, 'interlock'), (131072, 'overtemp'), (262144, 'volt_supply_fault'), (524288, 'commutation_error'), (1048576, 'digio1'), (2097152, 'digio2'), (4194304, 'digio3'), (8388608, 'digio4'), (16777216, 'current_limit'), (33554432, 'encoder_fault'), (67108864, 'overcurrent'), (134217728, 'curr_supply_fault'), (268435456, 'power_ok'), (536870912, 'active'), (1073741824, 'error'), (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', default_channel=1, is_rack_system=False)[source]

Bases: 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

  • default_channel – starting default channel used when no channel is supplied to a channel-level command (such as move_to or get_position).

  • is_rack_system – specify whether the device is a rack system or a standalone USB device (default mode).

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

set_supported_channels(channels=1)

Set the channels in the device.

Can be either a list of channels, a single number defining the number of channels numbered from 1 to channels (inclusive).

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 "hw_fw_lim" (forward hardware limit switch reached), "hw_bk_lim" (backward hardware limit switch reached), "sw_fw_lim" (forward software limit switch reached), "sw_bk_lim" (backward software limit switch reached), "moving_fw" (moving forward), "moving_bk" (moving backward), "jogging_fw" (jogging forward), "jogging_bk" (jogging backward), "connected" (motor is connected), "homing" (homing), "homed" (homing done), "initializing" (3-phase motor phase initialization), "tracking" (position is within trajectory), "settled" (position has been stable), "motion_error" (excessive position error), "instr_error" (legacy instrument command error), "interlock" (interlock is on), "overtemp" (temperature above limit), "volt_supply_fault" (supply voltage is too low), "commutation_error" (3-phase motor commutation error), "digio1" (state of digital input 1), "digio2" (state of digital input 2), "digio3" (state of digital input 3), "digio4" (state of digital input 4), "current_limit" (motor current limit exceeded for a long time), "encoder_fault" (encoder problems), "overcurrent" (motor current limit exceeded temporarily), "curr_supply_fault" (current drawn from supply is too high), "power_ok" (power is ok), "active" (moving), "error" (any error), "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.

get_polctl_parameters(scale=True)

Get current polarizer controller parameters (velocity, home_position, jog1, jog2, jog3)

If scale==True, return values in the physical units (see class description); otherwise, return it in the device internal units. velocity is always returned in percent units (0 to 100).

setup_polctl(velocity=None, home_position=None, jog1=None, jog2=None, jog3=None, scale=True)

Set polarizer controller 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. velocity is always set in percent units (0 to 100).

Error

alias of ThorlabsError

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

flush_comm(nmax=1000)

Flush any commands in the queue.

if nmax is not None, it specifies the maximal number of commands to flush.

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='host')

Get device info.

Return tuple (serial_no, model_no, fw_ver, hw_type, hw_ver, mod_state, nchannels, notes).

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='host', replyID=-1, flush='auto')

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). flush specifies whether input queue will be flushed before reading; "auto" means that it will be flushed if the expected reply is among the background messages, i.e., it could be already present in the queue.

recv_comm(expected_id=None, timeout=None)

Receive a message.

Return either BasicKinesisDevice.CommShort or BasicKinesisDevice.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. If timeout is not None, it can specify the timeout to read the command header (the rest is done with the usual timeout). 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='host')

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest='host')

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, 'hw_bk_lim'), (2, 'hw_fw_lim'), (4, 'sw_bk_lim'), (8, 'sw_fw_lim'), (16, 'moving_bk'), (32, 'moving_fw'), (64, 'jogging_bk'), (128, 'jogging_fw'), (256, 'connected'), (512, 'homing'), (1024, 'homed'), (2048, 'initializing'), (4096, 'tracking'), (8192, 'settled'), (16384, 'motion_error'), (32768, 'instr_error'), (65536, 'interlock'), (131072, 'overtemp'), (262144, 'volt_supply_fault'), (524288, 'commutation_error'), (1048576, 'digio1'), (2097152, 'digio2'), (4194304, 'digio3'), (8388608, 'digio4'), (16777216, 'current_limit'), (33554432, 'encoder_fault'), (67108864, 'overcurrent'), (134217728, 'curr_supply_fault'), (268435456, 'power_ok'), (536870912, 'active'), (1073741824, 'error'), (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: 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.

Error

alias of ThorlabsError

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

flush_comm(nmax=1000)

Flush any commands in the queue.

if nmax is not None, it specifies the maximal number of commands to flush.

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='host')

Get device info.

Return tuple (serial_no, model_no, fw_ver, hw_type, hw_ver, mod_state, nchannels, notes).

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='host', replyID=-1, flush='auto')

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). flush specifies whether input queue will be flushed before reading; "auto" means that it will be flushed if the expected reply is among the background messages, i.e., it could be already present in the queue.

recv_comm(expected_id=None, timeout=None)

Receive a message.

Return either BasicKinesisDevice.CommShort or BasicKinesisDevice.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. If timeout is not None, it can specify the timeout to read the command header (the rest is done with the usual timeout). 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='host')

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest='host')

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, 'hw_bk_lim'), (2, 'hw_fw_lim'), (4, 'sw_bk_lim'), (8, 'sw_fw_lim'), (16, 'moving_bk'), (32, 'moving_fw'), (64, 'jogging_bk'), (128, 'jogging_fw'), (256, 'connected'), (512, 'homing'), (1024, 'homed'), (2048, 'initializing'), (4096, 'tracking'), (8192, 'settled'), (16384, 'motion_error'), (32768, 'instr_error'), (65536, 'interlock'), (131072, 'overtemp'), (262144, 'volt_supply_fault'), (524288, 'commutation_error'), (1048576, 'digio1'), (2097152, 'digio2'), (4194304, 'digio3'), (8388608, 'digio4'), (16777216, 'current_limit'), (33554432, 'encoder_fault'), (67108864, 'overcurrent'), (134217728, 'curr_supply_fault'), (268435456, 'power_ok'), (536870912, 'active'), (1073741824, 'error'), (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

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

Bases: tuple

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

Bases: tuple

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

Bases: tuple

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

Bases: 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.

Error

alias of ThorlabsError

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

flush_comm(nmax=1000)

Flush any commands in the queue.

if nmax is not None, it specifies the maximal number of commands to flush.

get_device_info(dest='host')

Get device info.

Return tuple (serial_no, model_no, fw_ver, hw_type, hw_ver, mod_state, nchannels, notes).

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='host', replyID=-1, flush='auto')

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). flush specifies whether input queue will be flushed before reading; "auto" means that it will be flushed if the expected reply is among the background messages, i.e., it could be already present in the queue.

recv_comm(expected_id=None, timeout=None)

Receive a message.

Return either BasicKinesisDevice.CommShort or BasicKinesisDevice.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. If timeout is not None, it can specify the timeout to read the command header (the rest is done with the usual timeout). For details, see APT communications protocol.

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

Send a message with no associated data.

For details, see APT communications protocol.

send_comm_data(messageID, data, source=1, dest='host')

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

class pylablib.devices.Thorlabs.misc.TPMDeviceInfo(manufacturer, name, serial, firmware)

Bases: tuple

firmware
manufacturer
name
serial
class pylablib.devices.Thorlabs.misc.TPMSensorInfo(name, serial, calibration, type, subtype, flags)

Bases: tuple

calibration
flags
name
serial
subtype
type
class pylablib.devices.Thorlabs.misc.GenericPM(addr)[source]

Bases: SCPIDevice

Generic Thorlabs optical Power Meter.

Parameters:

addr – connection address (usually, a VISA connection string or a COM port for bluetooth devices)

Error

alias of ThorlabsError

ReraiseError

alias of ThorlabsBackendError

open()[source]

Open the backend

get_device_info()[source]

Get device info.

Return tuple (manufacturer, name, serial, firmware).

get_sensor_info()[source]

Get sensor info.

Return tuple (name, serial, calibration, type, subtype, flags). For devices with integrated sensors (e.g., PM160) the sensor name is the same as the device name.

update_sensor_modes()[source]

Update the list of supported sensor modes (only makes sense if the sensor has been changed since the connection was opened)

get_supported_sensor_modes()[source]

Get a list of supported sensor modes.

Can contain "power", "energy", "voltage", "current", or "frequency".

get_sensor_mode()[source]

Get current sensor mode.

Can be "power", "energy", "voltage", "current", or "frequency".

set_sensor_mode(sensor_mode='power')[source]

Set current sensor mode.

Can be one of the modes returned by get_supported_sensor_modes().

is_autorange_enabled(sensor_mode=None)[source]

Check if autorange is enabled for the given sensor mode.

If sensor_mode is None, return value for the current sensor mode.

enable_autorange(enable=True, sensor_mode=None)[source]

Enable or disable autorange for the given sensor mode.

If sensor_mode is None, set value for the current sensor mode.

get_range(sensor_mode=None)[source]

Get measurement range for the given sensor mode.

If sensor_mode is None, return value for the current sensor mode.

set_range(rng=None, sensor_mode=None)[source]

Set measurement range for the given sensor mode.

If rng is None or "full", set the maximal range. If sensor_mode is None, return value for the current sensor mode.

get_wavelength()[source]

Get current wavelength (in nm)

get_wavelength_range()[source]

Get available wavelength range (in nm)

set_wavelength(wavelength)[source]

Set current wavelength (in nm)

get_reading(sensor_mode=None, measure=True, overrng='keep')[source]

Get the reading in a given mode.

If sensor_mode is None, return reading in the currently set up mode (get_sensor_mode()); otherwise, set the sensor mode to the requested one. If measure==True, initiate a new measurement; otherwise, return the last measured value. overrng describes behavior if the power readings are outside of the current range; can be "keep" (keep the default device behavior, which returns a very large number, about 9.9E37), "error" (raise an error), or "max" (trim to the maximal value for the current range).

get_power()[source]

Measure and return the optical power

BackendError

alias of DeviceBackendError

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.misc.PM160(addr)[source]

Bases: GenericPM

Thorlabs PM160 optical Power Meter.

Parameters:

addr – connection address (usually, a VISA connection string or a COM port for bluetooth devices)

BackendError

alias of DeviceBackendError

Error

alias of ThorlabsError

ReraiseError

alias of 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

enable_autorange(enable=True, sensor_mode=None)

Enable or disable autorange for the given sensor mode.

If sensor_mode is None, set value for the current sensor mode.

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_info()

Get device info.

Return tuple (manufacturer, name, serial, firmware).

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_power()

Measure and return the optical power

get_range(sensor_mode=None)

Get measurement range for the given sensor mode.

If sensor_mode is None, return value for the current sensor mode.

get_reading(sensor_mode=None, measure=True, overrng='keep')

Get the reading in a given mode.

If sensor_mode is None, return reading in the currently set up mode (get_sensor_mode()); otherwise, set the sensor mode to the requested one. If measure==True, initiate a new measurement; otherwise, return the last measured value. overrng describes behavior if the power readings are outside of the current range; can be "keep" (keep the default device behavior, which returns a very large number, about 9.9E37), "error" (raise an error), or "max" (trim to the maximal value for the current range).

get_sensor_info()

Get sensor info.

Return tuple (name, serial, calibration, type, subtype, flags). For devices with integrated sensors (e.g., PM160) the sensor name is the same as the device name.

get_sensor_mode()

Get current sensor mode.

Can be "power", "energy", "voltage", "current", or "frequency".

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".

get_supported_sensor_modes()

Get a list of supported sensor modes.

Can contain "power", "energy", "voltage", "current", or "frequency".

get_wavelength()

Get current wavelength (in nm)

get_wavelength_range()

Get available wavelength range (in nm)

is_autorange_enabled(sensor_mode=None)

Check if autorange is enabled for the given sensor mode.

If sensor_mode is None, return value for the current sensor mode.

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

set_range(rng=None, sensor_mode=None)

Set measurement range for the given sensor mode.

If rng is None or "full", set the maximal range. If sensor_mode is None, return value for the current sensor mode.

set_sensor_mode(sensor_mode='power')

Set current sensor mode.

Can be one of the modes returned by get_supported_sensor_modes().

set_wavelength(wavelength)

Set current wavelength (in nm)

sleep(delay)

Wait for delay seconds

unlock()

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

update_sensor_modes()

Update the list of supported sensor modes (only makes sense if the sensor has been changed since the connection was opened)

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.

pylablib.devices.Thorlabs.serial module

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

Bases: 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 ThorlabsError

ReraiseError

alias of ThorlabsBackendError

open()[source]

Open the backend

BackendError

alias of DeviceBackendError

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: 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 DeviceBackendError

Error

alias of ThorlabsError

ReraiseError

alias of 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: 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 DeviceBackendError

Error

alias of ThorlabsError

ReraiseError

alias of 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: 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 DeviceBackendError

Error

alias of ThorlabsError

ReraiseError

alias of 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