
Instrumental¶
Instrumental is a Python-based library for controlling lab hardware like cameras, DAQs, oscilloscopes, spectrometers, and more. It has high-level drivers for instruments from NI, Tektronix, Thorlabs, PCO, Photometrics, Burleigh, and others.
Instrumental’s goal is to make common tasks simple to perform, while still providing the flexibility to perform complex tasks with relative ease. It also makes it easy to mess around with instruments in the shell. For example, to list the available instruments and open one of them:
>>> from instrumental import instrument, list_instruments
>>> insts = list_instruments()
>>> insts
[<TEKTRONIX 'DPO4034'>, <TEKTRONIX 'MSO4034'>, <NIDAQ 'Dev1'>]
>>> daq = instrument(insts[2])
>>> daq
<instrumental.drivers.daq.ni.NIDAQ at 0xb61...>
If you’re going to be using an instrument repeatedly, save it for later:
>>> daq.save_instrument('myDAQ')
Then you can simply open it by name:
>>> daq = instrument('myDAQ')
You can even access and control instruments on remote machines. Check out Working with Instruments for more detailed info.
Instrumental also bundles in some additional support code, including:
- Plotting and curve fitting utilities
- Utilities for acquiring and organizing data
Instrumental makes use of NumPy, SciPy, Matplotlib, and Pint, a Python units library. It optionally uses PyVISA/VISA and other drivers for interfacing with lab equipment.
To download Instrumental or browse its source, see our GitHub page.
Note
Instrumental is currently still under heavy development, so its interfaces are subject to change. Contributions are greatly appreciated, see the Developer’s Guide for more info.
User Guide¶
Installation¶
Brief Install Instructions¶
Starting with version 0.2.1, you can install Instrumental using pip:
$ pip install instrumental-lib
This will install the latest release version along with the core dependencies if they aren’t already installed. However, it’s recommended that you use the the Anaconda distribution so you don’t have to compile numpy and scipy (see the detailed install instructions below).
Installing the Development Version from GitHub¶
Once you have the core dependencies installed (numpy, scipy, and pint), download and extract a zip of Instrumental from the Github page or clone it using git. Now install:
$ cd /path/to/Instrumental
$ python setup.py install
Detailed Install Instructions¶
Python Sci-Comp Stack¶
To install the standard scientific computing stack, I recommend using Anaconda. Download the appropriate installer from the download page and run it to install Anaconda. The default installation will include NumPy, SciPy, and Matplotlib as well as lots of other useful stuff.
Pint¶
Next, install Pint for units support:
$ pip install pint
For more information, or to get a more recent version, check out the Pint install page.
Instrumental¶
If you’re using git, you can clone the Instrumental repository to get the source code. If you don’t know git or don’t want to set up a local repo yet, you can just download a zip file by clicking the ‘Download ZIP’ button on the right hand side of the Instrumental Github page. Unzip the code wherever you’d like, then open a command prompt to that directory and run:
$ python setup.py install
to install Instrumental to your Python site-packages directory. You’re all set! Now go check out
some of the examples in the examples
directory contained in the files you downloaded!
Optional Driver Libraries¶
VISA¶
To operate devices that communicate using VISA (e.g. Tektronix scopes) you will need:
- an implementation of VISA, and
- a Python interface layer called PyVISA
There are various implementations of VISA available, but two I know of are TekVISA (from Tektronix) and NI-VISA (from National Instruments). I would recommend NI-VISA, though either one should work fine. Installers for each can be downloaded from the NI or Tektronix websites, though you’ll have to create a free account.
Once you’ve installed VISA, install PyVISA by running:
$ pip install pyvisa
on the command line. As a quick test PyVISA has installed correctly, open a python interpreter and run:
>>> import visa
>>> rm = visa.ResourceManager()
>>> rm.list_resources()
More info about PyVISA, including more detailed install-related information can be found here.
Thorlabs DCx Cameras¶
To operate Thorlabs DCx cameras, you’ll need the drivers from Thorlabs under the “Software and Support” tab. Run the .exe installer which, among other things, will install the .dll shared libraries somewhere in your PATH (hopefully).
NI DAQs¶
NI-DAQmx support requires you to to have NI-DAQmx installed. You can find the installer on the National Instruments website.
Overview¶
Drivers¶
The drivers
subpackage’s purpose is to provide relatively high-level
‘drivers’ for interfacing with lab equipment. Currently it (fully or partially)
supports:
- Cameras
- PCO SDK(tested on PCO.Edge)
- PCO Pixelfly
- Photometrics PVCAM
- Thorlabs TSI
- Thorlabs UC480 / iDS uEye
- DAQs
- NI-DAQmx
- Function Generators
- Tektronix AFG3000 series
- Lasers
- Toptica FemtoFErb 1560
- Lock-in Amplifiers
- SRS SR850
- Motion Control
- Thorlabs Kinesis (FilterFlipper/TDC001/K10CR1 currently supported)
- Attocube ECC100 Controller
- Multimeters
- HP 34401A
- Optical Power Meters
- Newport 1830-C
- Thorlabs PM100x series
- Oscilloscopes
- Tektronix TDS300 and MSO/DPO4000 series (and probably others)
- Spectrometers
- Bristol 721 spectrum analyzer
- Thorlabs CCSxxx series
- Wavemeters
- Burleigh WA-1000/1500
It should be pretty easy to write drivers for other VISA-compatible devices via PyVISA. Driver submissions are greatly appreciated!
Plotting¶
The plotting
module provides or aims to provide
- Unit-aware plotting functions as a drop-in replacement for pyplot
- Easy slider-plots
Fitting¶
The fitting
module is a good place for curating ‘standard’ fitting tools
for common cases like
- Triple-lorentzian cavity scans
- Ringdown traces (exponential decay)
It should also provide optional unit-awareness.
Tools¶
The tools
module is used for full-fledged scripts and programs that may
make use of all of the other modules above. A good example would be a script
that pulls a trace from the scope, auto-fits a ringdown curve, and saves both
the raw data and fit parameters to files in a well-organized directory
structure.
Quickstart¶
Using Instruments¶
Much of Instrumental’s utility is in its ability to communicate with lab equipment. Our goal is to make interfacing with equipment as simple and powerful as it should be.
Connecting to a VISA instrument is easy:
>>> from instrumental import instrument
>>> scope = instrument(visa_address='TCPIP::0.0.0.1::INSTR')
>>> scope
<instrumental.drivers.scopes.tektronix.TDS_3000 object at 0x7f...>
It can be even easier if you’ve already set up an alias in your
instrumental.conf
file:
>>> scope = instrument('myScopeAlias')
<instrumental.drivers.scopes.tektronix.TDS_3000 object at 0x7f...>
For more detailed info, see Working with Instruments. Now we can use our new scope object to grab some data:
>>> x, y = scope.get_data()
>>> x
<Quantity([-9.99800000e-07, ..., 1.00000000e-06], 'second')>
>>> y
<Quantity([1.13007813, ..., -0.04835938], 'volt')>
Notice that our data already has units! By default, the scope grabs data from its first channel. We can grab data from the other channel by using:
>>> x, y = scope.get_data(channel=2)
Now let’s plot our data:
>>> import instrumental.plotting as plt
>>> plt.plot(x.to('ns'), y)
>>> plt.ylabel('Signal')
>>> plt.xlabel('Time')
>>> plt.show()
This gives us

But... where did those unit labels come from? Instrumental’s wrapped versions
of xlabel
and ylabel
add them automatically so you don’t have to.
Solving for and Plotting a Cavity Mode¶
A common use case for working with ray transfer matrices is solving for a cavity mode and looking at the mode’s spatial profile. Instrumental makes this easy. Here’s a short script that constructs a bowtie cavity with a crystal inside, solves for its tangential and sagittal modes, and plots them:
from instrumental import (plotting as plt, Space, Mirror, Interface,
find_cavity_modes, plot_profile)
# Indices of refraction
n0, nc = 1, 2.18
# Create cavity elements
cavity_elems = [Mirror(R='50mm', aoi='18deg'), Space('1.7cm'),
Interface(n0, nc), Space('5cm', nc),
Interface(nc, n0), Space('1.7cm'),
Mirror(R='50mm', aoi='18deg'), Space('6.86cm'),
Mirror(), Space('2.7cm'),
Mirror(), Space('6.86cm')]
# Find tangential and sagittal cavity modes
qt_r, qs_r = find_cavity_modes(cavity_elems)
# Beam profile inside the cavity
plot_profile(qt_r, qs_r, '1064nm', cavity_elems, cyclical=True)
plt.legend()
plt.show()
This will produce a plot that looks something like

We might also be interested in any losses from clipping, or aperture effects. To look at this, we can simply change the plotting line to:
plot_profile(qt_r, qs_r, '1064nm', cavity_elems, cyclical=True,
clipping=1e-6)
This will now plot the radial distance at which power losses from clipping become 1 part per million, i.e. 1e-6.

This example makes good use of Instrumental’s unit-friendliness. We’re using all sorts of length scales here, from nanometers to centimeters, all handled simply and explicitly. Are some of your lengths in inches? No problem! No more wondering ”...is this variable the wavelength in nanometers, or in meters?”
Working with Instruments¶
Getting Started¶
Instrumental tries to make it easy to find and open all the instruments
available to your computer. This is primarily accomplished using
list_instruments()
and instrument()
:
>>> from instrumental import instrument, list_instruments
>>> insts = list_instruments()
>>> insts
[<TEKTRONIX 'DPO4034'>, <TEKTRONIX 'MSO4034'>, <NIDAQ 'Dev1'>]
You can then use the output of list_instruments()
to open the instrument you
want:
>>> daq = instrument(insts[2])
>>> daq
<instrumental.drivers.daq.ni.NIDAQ at 0xb61...>
If you’re going to be using an instrument repeatedly, save it for later:
>>> daq.save_instrument('myDAQ')
Then you can simply open it by name:
>>> daq = instrument('myDAQ')
An Even Quicker Way¶
Here’s a shortcut for opening an instrument that means you don’t have to assign the instrument list to a variable, or even know how to count–just use part of the instrument’s string:
>>> list_instruments()
[<TEKTRONIX 'DPO4034'>, <TEKTRONIX 'MSO4034'>, <NIDAQ 'Dev1'>]
>>> instrument('DPO') # Opens the <TEKTRONIX 'DPO4034'>
>>> instrument('NIDAQ') # Opens the <NIDAQ 'Dev1'>
This will work as long as the string you use isn’t saved as an instrument alias. If you use a string that matches multiple instruments, it just picks the first in the list.
Remote Instruments¶
You can even control instruments that are attached to a remote computer:
>>> list_instruments(server='192.168.1.10')
This lists only the instruments located on the remote machine, not any local ones.
The remote PC must be running as an Instrumental server (and its firewall configured to allow
inbound connections on this port). To do this, run the script tools/server.py
that comes packaged
with Instrumental. The client needs to specify the server’s IP address (or hostname), and port
number (if differs from the default of 28265). Alternatively, you may save an alias for this server
in the [servers]
section of you instrumental.conf
file. See Saved Instruments for
more information about instrumental.conf
. Then you can list the remote instruments like this:
>>> list_instruments(server='myServer')
You can then open your instrument using instrument()
as usual, but now you’ll get a
RemoteInstrument
, which you can control just like a regular Instrument
.
How Does it All Work?¶
Listing Instruments¶
What exactly is list_instruments()
doing? Basically it walks through all the driver modules,
trying to import them one by one. If import fails (perhaps the DLL isn’t available because the user
doesn’t have this instrument), that module is skipped. Each module is responsible for returning a
list of its available instruments, e.g. the drivers.daqs.ni
module returns a list of all the NI
DAQs that are accessible. list_instruments()
combines all these instruments into one big list
and returns it.
There’s an unfortunate side-effect of this: if a module fails to import due to a bug, the exception is caught and ignored, so you don’t get a helpful traceback. To diagnose issues with a driver module, you can import the module directly:
>>> import instrumental.drivers.daq.ni
or enable logging before calling list_instruments()
:
>>> import logging
>>> logging.basicConfig(level=logging.INFO)
list_instruments()
doesn’t open instruments directly, but instead returns a list of
dictionary-like elements that contain info about how to open the instrument. For example, for our
DAQ:
>>> dict(insts[2])
{u'nidaq_devname': u'Dev1'}
This tells us that the daq is uniquely identified by the parameter
nidaq_devname
. So, we could also open it with keyword arguments:
>>> instrument(nidaq_devname='Dev1')
<instrumental.drivers.daq.ni.NIDAQ at 0xb69...>
or a dictionary:
>>> instrument({'nidaq_devname': 'Dev1'})
<instrumental.drivers.daq.ni.NIDAQ at 0xb62...>
Behind the scenes, instrument()
uses the keywords to figure out what type
of instrument you’re talking about, and what class should be instantiated.
Saved Instruments¶
Opening instruments using list_instruments()
is really helpful when you’re messing around in the
shell and don’t quite know what info you need yet, or you’re checking what devices are available to
you. But if you’ve found your device and want to write a script that reuses it constantly, it’s
nice to have it saved under an alias, which you can do easily with save_instrument()
as we showed
above.
When you do this, the instrument’s info gets saved in your instrumental.conf
config file. To find
where the file is located on your system, run:
>>> from instrumental.conf import user_conf_dir
>>> user_conf_dir
u'C:\\Users\\Lab\\AppData\\Local\\MabuchiLab\\Instrumental'
To save your instrument for repeated use, add its parameters to the [instruments]
section of instrumental.conf
. For our DAQ, that would look like:
# NI-DAQ device
myDAQ = {'nidaq_devname': 'Dev1'}
This gives our DAQ the alias myDAQ
, which can then be used to open it easily:
>>> instrument('myDAQ')
<instrumental.drivers.daq.ni.NIDAQ at 0xb71...>
The default version of instrumental.conf
also provides some commented-out
example entries to help make things clear.
API Documentation¶
Drivers¶
Instrumental drivers allow you to control and read data from various hardware devices.
Some devices (e.g. Thorlabs cameras) have drivers that act as wrappers to their drivers’ C
bindings, using ctypes
or cffi
. Others (e.g. Tektronix scopes and AFGs) utilize VISA and
PyVISA
, its Python wrapper. PyVISA
requires a local installation of the VISA library (e.g.
NI-VISA) to interface with connected devices.
Cameras¶
Create Camera
objects using instrument()
.
PCO Cameras¶
This module is for controlling PCO cameras that use the PCO.camera SDK. Note that not all PCO cameras use this SDK, e.g. older Pixelfly cameras have their own SDK.
This module requires the PCO SDK and the cffi
package.
You should install the PCO SDK provided on PCO’s website. Specifically, this module requires
SC2_Cam.dll
to be available in your PATH, as well as any interface-specific DLLs. Firewire
requires SC2_1394.dll
, and each type of Camera Link grabber requires its own DLL, e.g.
sc2_cl_me4.dll
for a Silicon Software microEnable IV grabber card.
PCO Pixelfly Cameras¶
This module is for controlling PCO Pixelfly cameras.
This module requires the Pixelfly SDK and the cffi
package.
You should install the Pixelfly SDK provided on PCO’s website. Specifically, this module requires
pf_cam.dll
to be available in your PATH.
Thorlabs TSI Cameras¶
This module is for controlling Thorlabs cameras that use the TSI SDK. Note that Thorlabs DCx cameras use a separate SDK.
This module requires the TSI SDK and the NiceLib
package.
-
class
instrumental.drivers.cameras.tsi.
TSI_Camera
(cam_num)¶ -
class
TriggerMode
¶ -
auto
= 'NORMAL'¶ Auto-trigger as fast as possible once capture has started
-
hw_bulb
= 'PDX'¶ Trigger a single exposure on an edge of a pulse, and stop the exposure at the end of the pulse
-
hw_edge
= 'TOE'¶ Trigger a single exposure on an edge, using a software-defined exposure time
-
-
TSI_Camera.
__init__
(cam_num)¶
-
TSI_Camera.
close
()¶
-
TSI_Camera.
get_captured_image
(timeout='1s', copy=True, wait_for_all=True, **kwds)¶ Get the image array(s) from the last capture sequence
Returns an image numpy array (or tuple of arrays for a multi-exposure sequence). The array has shape (height, width) for grayscale images, and (height, width, 3) for RGB images. Typically the dtype will be
uint8
, or sometimesuint16
in the case of 16-bit monochromatic cameras.Parameters: - timeout (Quantity([time]) or None, optional) – Max time to wait for wait for the image data to be ready. If None, will block forever. If timeout is exceeded, a TimeoutError will be raised.
- copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
-
TSI_Camera.
grab_image
(timeout='1s', copy=True, **kwds)¶ Perform a capture and return the resulting image array(s)
This is essentially a convenience function that calls
start_capture()
thenget_captured_image()
. Seeget_captured_image()
for information about the returned array(s).Parameters: - timeouts (Quantity([time]) or None, optional) – Max time to wait for wait for the image data to be ready. If None, will block forever. If timeout is exceeded, a TimeoutError will be raised.
- copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
- can specify other parameters of the capture as keyword arguments. These include (You) –
Other Parameters: - n_frames (int) – Number of exposures in the sequence
- vbin (int) – Vertical binning
- hbin (int) – Horizontal binning
- exposure_time (Quantity([time])) – Duration of each exposure
- width (int) – Width of the ROI
- height (int) – Height of the ROI
- cx (int) – X-axis center of the ROI
- cy (int) – Y-axis center of the ROI
- left (int) – Left edge of the ROI
- right (int) – Right edge of the ROI
- top (int) – Top edge of the ROI
- bot (int) – Bottom edge of the ROI
-
TSI_Camera.
latest_frame
(copy=True)¶ Get the latest image frame in live mode
Returns the image array received on the most recent successful call to
wait_for_frame()
.Parameters: copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
-
TSI_Camera.
start_capture
(**kwds)¶ Start a capture sequence and return immediately
Depending on your camera-specific shutter/trigger settings, this will either start the exposure immediately or ready the camera to start on an explicit (hardware or software) trigger.
It can be useful to invoke
capture()
andget_captured_image()
explicitly if you expect the capture sequence to take a long time and you’d like to perform some operations while you wait for the camera:>>> cam.capture() >>> do_other_useful_stuff() >>> arr = cam.get_captured_image()
See
grab_image()
for the set of available kwds.
-
TSI_Camera.
start_live_video
(**kwds)¶ Start live video mode
Once live video mode has been started, images will automatically and continuously be acquired. You can check if the next frame is ready by using
wait_for_frame()
, and access the most recent image’s data withget_captured_image()
.See
grab_image()
for the set of available kwds.
-
TSI_Camera.
stop_live_video
()¶ Stop live video mode
-
TSI_Camera.
wait_for_frame
(timeout=None)¶ Wait until the next frame is ready (in live mode)
Blocks and returns True once the next frame is ready, False if the timeout was reached. Using a timeout of 0 simply polls to see if the next frame is ready.
Parameters: timeout (Quantity([time]), optional) – How long to wait for wait for the image data to be ready. If None (the default), will block forever. Returns: frame_ready – True if the next frame is ready, False if the timeout was reached. Return type: bool
-
TSI_Camera.
DEFAULT_KWDS
= {'exposure_time': <Mock object>, 'right': None, 'vbin': 1, 'cx': None, 'top': None, 'bot': None, 'n_frames': 1, 'width': None, 'cy': None, 'fix_hotpixels': False, 'rising': True, 'gain': 0, 'hbin': 1, 'height': None, 'trig': 'auto', 'left': None}¶
-
TSI_Camera.
height
¶ Height of the camera image in pixels
-
TSI_Camera.
led_on
¶
-
TSI_Camera.
max_height
¶ Max settable height of the camera image, given current binning/subpixel settings
-
TSI_Camera.
max_width
¶ Max settable width of the camera image, given current binning/subpixel settings
-
TSI_Camera.
model
¶
-
TSI_Camera.
name
¶
-
TSI_Camera.
serial
¶
-
TSI_Camera.
width
¶ Width of the camera image in pixels
-
class
-
class
instrumental.drivers.cameras.tsi.
TSI_DLL_Camera
(ptr)¶ -
ClearError
()¶
-
Close
()¶
-
FreeImage
(image)¶
-
GetAcquisitionStatus
()¶
-
GetCameraName
()¶
-
GetDataTypeSize
(data_type)¶
-
GetErrorCode
()¶
-
GetErrorStr
(code)¶
-
GetExposeCount
()¶
-
GetFrameCount
()¶
-
GetLastErrorStr
()¶
-
GetParameter
(param_id)¶
-
GetPendingImage
()¶
-
Open
()¶
-
ResetCamera
()¶
-
ResetExposure
()¶
-
SetCameraName
(name)¶
-
SetParameter
(param_id, data)¶
-
Start
()¶
-
StartAndWait
(timeout_ms)¶
-
Status
()¶
-
Stop
()¶
-
WaitForImage
(timeout_ms=-1)¶
-
__init__
(ptr)¶
-
-
class
instrumental.drivers.cameras.tsi.
TSI_DLL_SDK
¶ -
Close
()¶
-
GetCamera
(camera_number)¶
-
GetCameraAddressStr
(camera_number, address_select)¶
-
GetCameraInterfaceTypeStr
(camera_number)¶
-
GetCameraName
(camera_number)¶
-
GetCameraSerialNumStr
(camera_number)¶
-
GetNumberOfCameras
()¶
-
Open
()¶
-
__init__
()¶
-
destroy
()¶
-
-
instrumental.drivers.cameras.tsi.
from_enum
(item)¶
-
instrumental.drivers.cameras.tsi.
list_instruments
()¶
UC480 (Thorlabs DCx) Cameras¶
This module is for controlling Thorlabs DCx cameras. You should install the corresponding drivers that can be found on the Thorlabs website. Specifically, this module requires either ‘uc480.dll’ or ‘uc480_64.dll’, depending on your system. The driver library must be visible to python, so you may need to add it to your PATH or copy it to your Windows system32 directory.
Photometrics Cameras¶
This module is for controlling photometrics cameras.
Driver for Photometrics cameras.
-
class
instrumental.drivers.cameras.pvcam.
PVCam
(name='')¶ -
__init__
(name='')¶
-
abort_sequence
()¶
-
bit_depth
()¶
-
close
()¶
-
get_captured_image
(timeout='1s', copy=True)¶ Get the image array(s) from the last capture sequence
Returns an image numpy array (or tuple of arrays for a multi-exposure sequence). The array has shape (height, width) for grayscale images, and (height, width, 3) for RGB images. Typically the dtype will be
uint8
, or sometimesuint16
in the case of 16-bit monochromatic cameras.Parameters: - timeout (Quantity([time]) or None, optional) – Max time to wait for wait for the image data to be ready. If None, will block forever. If timeout is exceeded, a TimeoutError will be raised.
- copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
-
get_param
(param_id, attrib)¶
-
grab_frame
(fresh_capture=True, force_list=False, timeout=-1)¶
-
grab_image
(timeout='1s', copy=True, **kwds)¶ Perform a capture and return the resulting image array(s)
This is essentially a convenience function that calls
start_capture()
thenget_captured_image()
. Seeget_captured_image()
for information about the returned array(s).Parameters: - timeouts (Quantity([time]) or None, optional) – Max time to wait for wait for the image data to be ready. If None, will block forever. If timeout is exceeded, a TimeoutError will be raised.
- copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
- can specify other parameters of the capture as keyword arguments. These include (You) –
Other Parameters: - n_frames (int) – Number of exposures in the sequence
- vbin (int) – Vertical binning
- hbin (int) – Horizontal binning
- exposure_time (Quantity([time])) – Duration of each exposure
- width (int) – Width of the ROI
- height (int) – Height of the ROI
- cx (int) – X-axis center of the ROI
- cy (int) – Y-axis center of the ROI
- left (int) – Left edge of the ROI
- right (int) – Right edge of the ROI
- top (int) – Top edge of the ROI
- bot (int) – Bottom edge of the ROI
-
grab_ndarray
(fresh_capture=True, force_list=False, timeout=-1)¶
-
image_array
()¶
-
image_buffer
()¶
-
latest_frame
(copy=True)¶ Get the latest image frame in live mode
Returns the image array received on the most recent successful call to
wait_for_frame()
.Parameters: copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
-
setup_sequence
(exp_time='100ms', nframes=1, mode='timed', regions=None)¶ Parameters:
-
start_capture
()¶ Start a capture sequence and return immediately
Depending on your camera-specific shutter/trigger settings, this will either start the exposure immediately or ready the camera to start on an explicit (hardware or software) trigger.
It can be useful to invoke
capture()
andget_captured_image()
explicitly if you expect the capture sequence to take a long time and you’d like to perform some operations while you wait for the camera:>>> cam.capture() >>> do_other_useful_stuff() >>> arr = cam.get_captured_image()
See
grab_image()
for the set of available kwds.
-
start_live_video
(**kwds)¶ Start live video mode
Once live video mode has been started, images will automatically and continuously be acquired. You can check if the next frame is ready by using
wait_for_frame()
, and access the most recent image’s data withget_captured_image()
.See
grab_image()
for the set of available kwds.
-
stop_live_video
()¶ Stop live video mode
-
wait_for_frame
(timeout=None)¶ Wait until the next frame is ready (in live mode)
Blocks and returns True once the next frame is ready, False if the timeout was reached. Using a timeout of 0 simply polls to see if the next frame is ready.
Parameters: timeout (Quantity([time]), optional) – How long to wait for wait for the image data to be ready. If None (the default), will block forever. Returns: frame_ready – True if the next frame is ready, False if the timeout was reached. Return type: bool
-
height
¶ Height of the camera image in pixels
-
num_cams_open
= 0¶
-
width
¶ Width of the camera image in pixels
-
Generic Camera Interface¶
Package containing a driver module/class for each supported camera type.
-
class
instrumental.drivers.cameras.
Camera
¶ A generic camera device.
Camera driver internals can often be quite different; however, Instrumental defines a few basic concepts that all camera drivers should have.
There are two basic modes: finite and continuous.
In finite mode, a camera performs a capture sequence, returning one or more images all at once, when the sequence is finished.
In continuous or live mode, the camera continuously retrieves images until it is manually stopped. This mode can be used e.g. to make a GUI that looks at a live view of the camera. The process looks like this:
>>> cam.start_live_video() >>> while not_done(): >>> frame_ready = cam.wait_for_frame() >>> if frame_ready: >>> arr = cam.latest_frame() >>> do_stuff_with(arr) >>> cam.stop_live_video()
-
fill_all_coords
(kwds, names)¶
-
find_hot_pixels
(stddevs=10, **kwds)¶ Generate the list of hot pixels on the camera sensor
-
get_captured_image
(timeout='1s', copy=True)¶ Get the image array(s) from the last capture sequence
Returns an image numpy array (or tuple of arrays for a multi-exposure sequence). The array has shape (height, width) for grayscale images, and (height, width, 3) for RGB images. Typically the dtype will be
uint8
, or sometimesuint16
in the case of 16-bit monochromatic cameras.Parameters: - timeout (Quantity([time]) or None, optional) – Max time to wait for wait for the image data to be ready. If None, will block forever. If timeout is exceeded, a TimeoutError will be raised.
- copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
-
grab_image
(timeouts='1s', copy=True, **kwds)¶ Perform a capture and return the resulting image array(s)
This is essentially a convenience function that calls
start_capture()
thenget_captured_image()
. Seeget_captured_image()
for information about the returned array(s).Parameters: - timeouts (Quantity([time]) or None, optional) – Max time to wait for wait for the image data to be ready. If None, will block forever. If timeout is exceeded, a TimeoutError will be raised.
- copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
- can specify other parameters of the capture as keyword arguments. These include (You) –
Other Parameters: - n_frames (int) – Number of exposures in the sequence
- vbin (int) – Vertical binning
- hbin (int) – Horizontal binning
- exposure_time (Quantity([time])) – Duration of each exposure
- width (int) – Width of the ROI
- height (int) – Height of the ROI
- cx (int) – X-axis center of the ROI
- cy (int) – Y-axis center of the ROI
- left (int) – Left edge of the ROI
- right (int) – Right edge of the ROI
- top (int) – Top edge of the ROI
- bot (int) – Bottom edge of the ROI
-
latest_frame
(copy=True)¶ Get the latest image frame in live mode
Returns the image array received on the most recent successful call to
wait_for_frame()
.Parameters: copy (bool, optional) – Whether to copy the image memory or directly reference the underlying buffer. It is recommended to use True (the default) unless you know what you’re doing.
-
save_hot_pixels
(path=None)¶ Save a file listing the hot pixels
-
set_defaults
(**kwds)¶
-
start_capture
(**kwds)¶ Start a capture sequence and return immediately
Depending on your camera-specific shutter/trigger settings, this will either start the exposure immediately or ready the camera to start on an explicit (hardware or software) trigger.
It can be useful to invoke
capture()
andget_captured_image()
explicitly if you expect the capture sequence to take a long time and you’d like to perform some operations while you wait for the camera:>>> cam.capture() >>> do_other_useful_stuff() >>> arr = cam.get_captured_image()
See
grab_image()
for the set of available kwds.
-
start_live_video
(**kwds)¶ Start live video mode
Once live video mode has been started, images will automatically and continuously be acquired. You can check if the next frame is ready by using
wait_for_frame()
, and access the most recent image’s data withget_captured_image()
.See
grab_image()
for the set of available kwds.
-
stop_live_video
()¶ Stop live video mode
-
wait_for_frame
(timeout=None)¶ Wait until the next frame is ready (in live mode)
Blocks and returns True once the next frame is ready, False if the timeout was reached. Using a timeout of 0 simply polls to see if the next frame is ready.
Parameters: timeout (Quantity([time]), optional) – How long to wait for wait for the image data to be ready. If None (the default), will block forever. Returns: frame_ready – True if the next frame is ready, False if the timeout was reached. Return type: bool
-
DEFAULT_KWDS
= {'exposure_time': <Mock object>, 'right': None, 'width': None, 'top': None, 'bot': None, 'fix_hotpixels': False, 'n_frames': 1, 'vbin': 1, 'cy': None, 'cx': None, 'gain': 0, 'left': None, 'height': None, 'hbin': 1}¶
-
height
¶ Height of the camera image in pixels
-
max_height
¶ Max settable height of the camera image, given current binning/subpixel settings
-
max_width
¶ Max settable width of the camera image, given current binning/subpixel settings
-
width
¶ Width of the camera image in pixels
-
DAQs¶
Create DAQ
objects using instrument()
.
NI DAQs¶
This module has been developed using an NI USB-6221 – the code should generally work for all DAQmx boards, but I’m sure there are plenty of compatibility bugs just waiting for you wonderful users to find and fix.
First, make sure you have NI’s DAQmx software installed. Instrumental will then use NiceLib to generate bindings from the header it finds.
The NIDAQ
class lets you interact with your board and all its various inputs
and outputs in a fairly simple way. Let’s say you’ve hooked up digital I/O P1.0
to analog input AI0, and your analog out AO1 to analog input AI1:
>>> from instrumental.drivers.daq.ni import NIDAQ, list_instruments
>>> list_instruments()
[<NIDAQ 'Dev0'>]
>>> daq = NIDAQ('Dev0')
>>> daq.ai0.read()
<Quantity(0.0154385786803, 'volt)>
>>> daq.port1[0].write(True)
>>> daq.ai0.read()
<Quantity(5.04241962841, 'volt')>
>>> daq.ao1.write('2.1V')
>>> daq.ai1.read()
<Quantity(2.10033320744, 'volt')>
Now let’s try using digital input. Assume P1.1 is attached to P1.2:
>>> daq.port1[1].write(False)
>>> daq.port1[2].read()
False
>>> daq.port1[1].write(True)
>>> daq.port1[2].read()
True
Let’s read and write more than one bit at a time. To write to multiple lines
simultaneously, pass an unsigned int to write()
. The line with the lowest
index corresponds to the lowest bit, and so on. If you read from multiple
lines, read() returns an int. Connect P1.0-3 to P1.4-7:
>>> daq.port1[0:3].write(5) # 0101 = decimal 5
>>> daq.port1[4:7].read() # Note that the last index IS included
5
>>> daq.port1[7:4].read() # This flips the ordering of the bits
10 # 1010 = decimal 10
>>> daq.port1[0].write(False) # Zero the ones bit individually
>>> daq.port1[4:7].read() # 0100 = decimal 4
4
You can also read and write arrays of buffered data. Use the same read()
and
write()
methods, just include your timing info (and pass in the data as an
array if writing). When writing, you must provide either freq
or fsamp
, and
may provide either duration
or reps
to specify for how long the waveform is
output. For example, there are many ways to output the same sinusoid:
>>> from instrumental import u
>>> from numpy import pi, sin, linspace
>>> data = sin( 2*pi * linspace(0, 1, 100, endpoint=False) )*5*u.V + 5*u.V
>>> daq.ao0.write(data, duration='1s', freq='500Hz')
>>> daq.ao0.write(data, duration='1s', fsamp='50kHz')
>>> daq.ao0.write(data, reps=500, freq='500Hz')
>>> daq.ao0.write(data, reps=500, fsamp='50kHz')
Note the use of endpoint=False
in linspace
. This ensures we don’t
repeat the start/end point (0V) of our sine waveform when outputting more than
one period.
All this stuff is great for simple tasks, but sometimes you may want to perform input and output on multiple channels simultaneously. To accomplish this we need to use Tasks.
Note
Tasks in the ni
module are similar, but not the same as Tasks in DAQmx
(and PyDAQmx). Our Tasks allow you to quickly and easily perform simultaneous
input and output with one Task without the hassle of having to create multiple
and hook their timing and triggers up.
Here’s an example of how to perform simultaneous input and output:
>>> from instrumental.drivers.daq.ni import NIDAQ, Task
>>> from instrumental import u
>>> from numpy import linspace
>>> daq = NIDAQ('Dev0')
>>> task = Task(daq.ao0, daq.ai0)
>>> task.set_timing(duration='1s', fsamp='10Hz')
>>> write_data = {'ao0': linspace(0, 9, 10) * u.V}
>>> task.run(write_data)
{u'ai0': <Quantity([ 1.00000094e+01 1.89578724e-04 9.99485542e-01 2.00007917e+00
3.00034866e+00 3.99964556e+00 4.99991698e+00 5.99954114e+00
6.99981625e+00 7.99976941e+00], 'volt')>,
u't': <Quantity([ 0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9], 'second')>}
As you can see, we create a dict as input to the run()
method. Its keys are
the names of the input channels, and its values are the corresponding array
Quantities that we want to write. Similarly, the run()
returns a dict that
contains the input that was read. This dict also contains the time data under
key ‘t’. Note that the read and write happen concurrently, so each voltage read
has not yet moved to its new setpoint.
-
class
instrumental.drivers.daq.ni.
NIDAQ
(dev_name)¶ -
Task
(*args)¶
-
__init__
(dev_name)¶
-
mx
¶
-
product_category
¶
-
product_type
¶
-
serial
¶
-
-
class
instrumental.drivers.daq.ni.
AnalogIn
(daq, chan_name)¶ -
__init__
(daq, chan_name)¶
-
read
(duration=None, fsamp=None, n_samples=None, vmin=None, vmax=None, reserve_timeout=None)¶ Read one or more analog input samples.
By default, reads and returns a single sample. If two of
duration
,fsamp
, andn_samples
are given, an array of samples is read and returned.Parameters: - duration (Quantity) – How long to read from the analog input, specified as a Quantity.
Use with
fsamp
orn_samples
. - fsamp (Quantity) – The sample frequency, specified as a Quantity. Use with
duration
orn_samples
. - n_samples (int) – The number of samples to read. Use with
duration
orfsamp
.
Returns: data – The data that was read from analog input.
Return type: scalar or array Quantity
- duration (Quantity) – How long to read from the analog input, specified as a Quantity.
Use with
-
read_sample
(timeout=None)¶
-
start_reading
(fsamp=None, vmin=None, vmax=None, overwrite=False, relative_to=<RelativeTo.CurrReadPos: 'CurrReadPos'>, offset=0, buf_size=10)¶
-
stop_reading
()¶
-
type
= 'AI'¶
-
-
class
instrumental.drivers.daq.ni.
AnalogOut
(daq, chan_name)¶ -
__init__
(daq, chan_name)¶
-
read
(duration=None, fsamp=None, n_samples=None)¶ Read one or more analog output samples.
Not supported by all DAQ models; requires the appropriate internal channel.
By default, reads and returns a single sample. If two of
duration
,fsamp
, andn_samples
are given, an array of samples is read and returned.Parameters: - duration (Quantity) – How long to read from the analog output, specified as a Quantity.
Use with
fsamp
orn_samples
. - fsamp (Quantity) – The sample frequency, specified as a Quantity. Use with
duration
orn_samples
. - n_samples (int) – The number of samples to read. Use with
duration
orfsamp
.
Returns: data – The data that was read from analog output.
Return type: scalar or array Quantity
- duration (Quantity) – How long to read from the analog output, specified as a Quantity.
Use with
-
write
(data, duration=None, reps=None, fsamp=None, freq=None, onboard=True)¶ Write a value or array to the analog output.
If
data
is a scalar value, it is written to output and the function returns immediately. Ifdata
is an array of values, a buffered write is performed, writing each value in sequence at the rate determined byduration
andfsamp
orfreq
. You must specify eitherfsamp
orfreq
.When writing an array, this function blocks until the output sequence has completed.
Parameters: - data (scalar or array Quantity) – The value or values to output, passed in Volt-compatible units.
- duration (Quantity, optional) – Used when writing arrays of data. This is how long the entirety of
the output lasts, specified as a second-compatible Quantity. If
duration
is longer than a single period of data, the waveform will repeat. Use either this orreps
, not both. If neither is given, waveform is output once. - reps (int or float, optional) – Used when writing arrays of data. This is how many times the
waveform is repeated. Use either this or
duration
, not both. If neither is given, waveform is output once. - fsamp (Quantity, optional) – Used when writing arrays of data. This is the sample frequency,
specified as a Hz-compatible Quantity. Use either this or
freq
, not both. - freq (Quantity, optional) – Used when writing arrays of data. This is the frequency of the
overall waveform, specified as a Hz-compatible Quantity. Use
either this or
fsamp
, not both. - onboard (bool, optional) – Use only onboard memory. Defaults to True. If False, all data will be continually buffered from the PC memory, even if it is only repeating a small number of samples many times.
-
type
= 'AO'¶
-
-
class
instrumental.drivers.daq.ni.
VirtualDigitalChannel
(daq, line_pairs)¶ -
__init__
(daq, line_pairs)¶
-
as_input
()¶
-
as_output
()¶
-
read
()¶
-
write
(value)¶ Write a value to the digital output channel
Parameters: value (int or bool) – An int representing the digital values to write. The lowest bit of the int is written to the first digital line, the second to the second, and so forth. For a single-line DO channel, can be a bool.
-
write_sequence
(data, duration=None, reps=None, fsamp=None, freq=None, onboard=True, clock='')¶ Write an array of samples to the digital output channel
Outputs a buffered digital waveform, writing each value in sequence at the rate determined by
duration
andfsamp
orfreq
. You must specify eitherfsamp
orfreq
.This function blocks until the output sequence has completed.
Parameters: - data (array or list of ints or bools) – The sequence of samples to output. For a single-line DO channel, samples can be bools.
- duration (Quantity, optional) – How long the entirety of the output lasts, specified as a
second-compatible Quantity. If
duration
is longer than a single period of data, the waveform will repeat. Use either this orreps
, not both. If neither is given, waveform is output once. - reps (int or float, optional) – How many times the waveform is repeated. Use either this or
duration
, not both. If neither is given, waveform is output once. - fsamp (Quantity, optional) – This is the sample frequency, specified as a Hz-compatible
Quantity. Use either this or
freq
, not both. - freq (Quantity, optional) – This is the frequency of the overall waveform, specified as a
Hz-compatible Quantity. Use either this or
fsamp
, not both. - onboard (bool, optional) – Use only onboard memory. Defaults to True. If False, all data will be continually buffered from the PC memory, even if it is only repeating a small number of samples many times.
-
type
= 'DIO'¶
-
-
class
instrumental.drivers.daq.ni.
SampleMode
¶ -
continuous
= 'ContSamps'¶
-
finite
= 'FiniteSamps'¶
-
hwtimed
= 'HWTimedSinglePoint'¶
-
-
class
instrumental.drivers.daq.ni.
TerminalConfig
¶ -
NRSE
= 'NRSE'¶
-
RSE
= 'RSE'¶
-
default
= 'Cfg_Default'¶
-
diff
= 'Diff'¶
-
pseudo_diff
= 'PseudoDiff'¶
-
-
class
instrumental.drivers.daq.ni.
RelativeTo
¶ -
CurrReadPos
= 'CurrReadPos'¶
-
FirstPretrigSamp
= 'FirstPretrigSamp'¶
-
FirstSample
= 'FirstSample'¶
-
MostRecentSamp
= 'MostRecentSamp'¶
-
RefTrig
= 'RefTrig'¶
-
-
class
instrumental.drivers.daq.ni.
ProductCategory
¶ -
AOSeries
= 'AOSeries'¶
-
BSeriesDAQ
= 'BSeriesDAQ'¶
-
CSeriesModule
= 'CSeriesModule'¶
-
CompactDAQChassis
= 'CompactDAQChassis'¶
-
DigitalIO
= 'DigitalIO'¶
-
DynamicSignalAcquisition
= 'DynamicSignalAcquisition'¶
-
ESeriesDAQ
= 'ESeriesDAQ'¶
-
MSeriesDAQ
= 'MSeriesDAQ'¶
-
NIELVIS
= 'NIELVIS'¶
-
NetworkDAQ
= 'NetworkDAQ'¶
-
SCCConnectorBlock
= 'SCCConnectorBlock'¶
-
SCCModule
= 'SCCModule'¶
-
SCExpress
= 'SCExpress'¶
-
SCSeriesDAQ
= 'SCSeriesDAQ'¶
-
SCXIModule
= 'SCXIModule'¶
-
SSeriesDAQ
= 'SSeriesDAQ'¶
-
Switches
= 'Switches'¶
-
TIOSeries
= 'TIOSeries'¶
-
USBDAQ
= 'USBDAQ'¶
-
Unknown
= 'Unknown'¶
-
XSeriesDAQ
= 'XSeriesDAQ'¶
-
Function Generators¶
Create FunctionGenerator
objects using instrument()
.
Tektronix Function Generators¶
Driver module for Tektronix function generators. Currently supports:
- AFG 3000 series
-
class
instrumental.drivers.funcgenerators.tektronix.
AFG_3000
(visa_inst)¶ -
AM_enabled
(channel=1)¶ Returns whether amplitude modulation is enabled.
Returns: Whether AM is enabled. Return type: bool
-
FM_enabled
(channel=1)¶ Returns whether frequency modulation is enabled.
Returns: Whether FM is enabled. Return type: bool
-
FSK_enabled
(channel=1)¶ Returns whether frequency-shift keying modulation is enabled.
Returns: Whether FSK is enabled. Return type: bool
-
PM_enabled
(channel=1)¶ Returns whether phase modulation is enabled.
Returns: Whether PM is enabled. Return type: bool
-
PWM_enabled
(channel=1)¶ Returns whether pulse width modulation is enabled.
Returns: Whether PWM is enabled. Return type: bool
-
__init__
(visa_inst)¶ Constructor for an AFG 3000 Function Generator object. End users should not use this directly, and should instead use
instrument()
-
burst_enabled
(channel=1)¶ Returns whether burst mode is enabled.
Returns: Whether burst mode is enabled. Return type: bool
-
disable_AM
(channel=1)¶ Disable amplitude modulation mode.
-
disable_FM
(channel=1)¶ Disable frequency modulation mode.
-
disable_FSK
(channel=1)¶ Disable frequency-shift keying mode.
-
disable_PM
(channel=1)¶ Disable phase modulation mode.
-
disable_PWM
(channel=1)¶ Disable pulse width modulation mode.
-
disable_burst
(channel=1)¶ Disable burst mode.
-
enable_AM
(enable=True, channel=1)¶ Enable amplitude modulation mode.
Parameters: enable (bool, optional) – Whether to enable or disable AM
-
enable_FM
(enable=True, channel=1)¶ Enable frequency modulation mode.
Parameters: enable (bool, optional) – Whether to enable or disable FM
-
enable_FSK
(enable=True, channel=1)¶ Enable frequency-shift keying mode.
Parameters: enable (bool, optional) – Whether to enable or disable FSK
-
enable_PM
(enable=True, channel=1)¶ Enable phase modulation mode.
Parameters: enable (bool, optional) – Whether to enable or disable PM
-
enable_PWM
(enable=True, channel=1)¶ Enable pulse width modulation mode.
Parameters: enable (bool, optional) – Whether to enable or disable PWM
-
enable_burst
(enable=True, channel=1)¶ Enable burst mode.
Parameters: enable (bool, optional) – Whether to enable or disable burst mode.
-
get_dbm
(channel=1)¶ Get the amplitude of the current waveform in dBm.
Note that this returns a float, not a pint.Quantity
Returns: dbm – The current waveform’s dBm amplitude Return type: float
-
get_ememory
()¶ Get array of data from edit memory.
Returns: Data retrieved from the AFG’s edit memory. Return type: numpy.array
-
get_frequency
(channel=1)¶ Get the frequency to be used in fixed frequency mode.
-
get_frequency_mode
(channel=1)¶ Get the frequency mode.
Returns: The frequency mode Return type: ‘fixed’ or ‘sweep’
-
get_vpp
(channel=1)¶ Get the peak-to-peak voltage of the current waveform.
Returns: vpp – The current waveform’s peak-to-peak voltage Return type: pint.Quantity
-
get_vrms
(channel=1)¶ Get the RMS voltage of the current waveform.
Returns: vrms – The current waveform’s RMS voltage Return type: pint.Quantity
-
set_am_depth
(depth, channel=1)¶ Set depth of amplitude modulation.
Parameters: depth (number) – Depth of modulation in percent. Must be between 0.0% and 120.0%. Has resolution of 0.1%.
-
set_arb_func
(data, interp=None, num_pts=10000)¶ Write arbitrary waveform data to EditMemory.
Parameters: - data (array_like) – A 1D array of real values to be used as evenly-spaced points. The values will be normalized to extend from 0 t0 16382. It must have a length in the range [2, 131072]
- interp (str or int, optional) – Interpolation to use for smoothing out data. None indicates no interpolation. Values include (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’), or an int to specify the order of spline interpolation. See scipy.interpolate.interp1d for details.
- num_pts (int) – Number of points to use in interpolation. Default is 10000. Must
be greater than or equal to the number of points in
data
, and at most 131072.
-
set_dbm
(dbm, channel=1)¶ Set the amplitude of the current waveform in dBm.
Note that this returns a float, not a pint.Quantity
Parameters: dbm (float) – The current waveform’s dBm amplitude
-
set_frequency
(freq, change_mode=True, channel=1)¶ Set the frequency to be used in fixed frequency mode.
Parameters: - freq (pint.Quantity) – The frequency to be used in fixed frequency mode.
- change_mode (bool, optional) – If True, will set the frequency mode to
fixed
.
-
set_frequency_mode
(mode, channel=1)¶ Set the frequency mode.
In fixed mode, the waveform’s frequency is kept constant. In sweep mode, it is swept according to the sweep settings.
Parameters: mode ({'fixed', 'sweep'}) – Mode to switch to.
-
set_function
(**kwargs)¶ Set selected function parameters. Useful for setting multiple parameters at once. See individual setters for more details.
When setting the waveform amplitude, you may use up to two of
high
,low
,offset
, andvpp
/vrms
/dbm
.Parameters: - shape ({'SINusoid', 'SQUare', 'PULSe', 'RAMP', 'PRNoise', 'DC', 'SINC', 'GAUSsian', 'LORentz', 'ERISe', 'EDECay', 'HAVersine',) –
- 'USER2', 'USER3', 'USER4', 'EMEMory'}, optional ('USER1',) – Shape of the waveform. Case-insenitive, abbreviation or full string.
- phase (pint.Quantity or string or number, optional) – Phase of the waveform in radian-compatible units.
- vrms, dbm (vpp,) – Amplitude of the waveform in volt-compatible units.
- offset (pint.Quantity or string, optional) – Offset of the waveform in volt-compatible units.
- high (pint.Quantity or string, optional) – High level of the waveform in volt-compatible units.
- low (pint.Quantity or string, optional) – Low level of the waveform in volt-compatible units.
- channel ({1, 2}, optional) – Output channel to modify. Some models may have only one channel.
-
set_function_shape
(shape, channel=1)¶ Set shape of output function.
Parameters: - shape ({'SINusoid', 'SQUare', 'PULSe', 'RAMP', 'PRNoise', 'DC', 'SINC', 'GAUSsian', 'LORentz', 'ERISe', 'EDECay', 'HAVersine', 'USER1', 'USER2', 'USER3', 'USER4', 'EMEMory'}, optional) – Shape of the waveform. Case-insenitive string that contains a valid
shape or its abbreviation. The abbreviations are indicated above by
capitalization. For example,
sin
,SINUSOID
, andSiN
are all valid inputs, whilesinus
is not. - channel ({1, 2}, optional) – Output channel to modify. Some models may have only one channel.
- shape ({'SINusoid', 'SQUare', 'PULSe', 'RAMP', 'PRNoise', 'DC', 'SINC', 'GAUSsian', 'LORentz', 'ERISe', 'EDECay', 'HAVersine', 'USER1', 'USER2', 'USER3', 'USER4', 'EMEMory'}, optional) – Shape of the waveform. Case-insenitive string that contains a valid
shape or its abbreviation. The abbreviations are indicated above by
capitalization. For example,
-
set_high
(high, channel=1)¶ Set the high voltage level of the current waveform.
This changes the high level while keeping the low level fixed.
Parameters: high (pint.Quantity) – The new high level in volt-compatible units
-
set_low
(low, channel=1)¶ Set the low voltage level of the current waveform.
This changes the low level while keeping the high level fixed.
Parameters: low (pint.Quantity) – The new low level in volt-compatible units
-
set_offset
(offset, channel=1)¶ Set the voltage offset of the current waveform.
This changes the offset while keeping the amplitude fixed.
Parameters: offset (pint.Quantity) – The new voltage offset in volt-compatible units
-
set_phase
(phase, channel=1)¶ Set the phase offset of the current waveform.
Parameters: phase (pint.Quantity or number) – The new low level in radian-compatible units. Unitless numbers are treated as radians.
-
set_sweep
(channel=1, **kwargs)¶ Set selected sweep parameters.
Automatically enables sweep mode.
Parameters: - start (pint.Quantity) – The start frequency of the sweep in Hz-compatible units
- stop (pint.Quantity) – The stop frequency of the sweep in Hz-compatible units
- span (pint.Quantity) – The frequency span of the sweep in Hz-compatible units
- center (pint.Quantity) – The center frequency of the sweep in Hz-compatible units
- sweep_time (pint.Quantity) – The sweep time in second-compatible units. Must be between 1 ms and 300 s
- hold_time (pint.Quantity) – The hold time in second-compatible units
- return_time (pint.Quantity) – The return time in second-compatible units
- spacing ({'linear', 'lin', 'logarithmic', 'log'}) – The spacing in time of the sweep frequencies
-
set_sweep_center
(center, channel=1)¶ Set the sweep frequency center.
This sets the sweep center frequency while keeping the sweep frequency span fixed. The start and stop frequencies will be changed.
Parameters: center (pint.Quantity) – The center frequency of the sweep in Hz-compatible units
-
set_sweep_hold_time
(time, channel=1)¶ Set the hold time of the sweep.
The hold time is the amount of time that the frequency is held constant after reaching the stop frequency.
Parameters: time (pint.Quantity) – The hold time in second-compatible units
-
set_sweep_return_time
(time, channel=1)¶ Set the return time of the sweep.
The return time is the amount of time that the frequency spends sweeping from the stop frequency back to the start frequency. This does not include hold time.
Parameters: time (pint.Quantity) – The return time in second-compatible units
-
set_sweep_spacing
(spacing, channel=1)¶ Set whether a sweep is linear or logarithmic.
Parameters: spacing ({'linear', 'lin', 'logarithmic', 'log'}) – The spacing in time of the sweep frequencies
-
set_sweep_span
(span, channel=1)¶ Set the sweep frequency span.
This sets the sweep frequency span while keeping the center frequency fixed. The start and stop frequencies will be changed.
Parameters: span (pint.Quantity) – The frequency span of the sweep in Hz-compatible units
-
set_sweep_start
(start, channel=1)¶ Set the sweep start frequency.
This sets the start frequency while keeping the stop frequency fixed. The span and center frequencies will be changed.
Parameters: start (pint.Quantity) – The start frequency of the sweep in Hz-compatible units
-
set_sweep_stop
(stop, channel=1)¶ Set the sweep stop frequency.
This sets the stop frequency while keeping the start frequency fixed. The span and center frequencies will be changed.
Parameters: stop (pint.Quantity) – The stop frequency of the sweep in Hz-compatible units
-
set_sweep_time
(time, channel=1)¶ Set the sweep time.
The sweep time does not include hold time or return time. Sweep time must be between 1 ms and 300 s.
Parameters: time (pint.Quantity) – The sweep time in second-compatible units. Must be between 1 ms and 200 s
-
set_vpp
(vpp, channel=1)¶ Set the peak-to-peak voltage of the current waveform.
Parameters: vpp (pint.Quantity) – The new peak-to-peak voltage
-
set_vrms
(vrms, channel=1)¶ Set the amplitude of the current waveform in dBm.
Parameters: vrms (pint.Quantity) – The new RMS voltage
-
Lasers¶
Create Laser
objects using instrument()
.
Toptica FemtoFErb 1560 Laser¶
Driver for Tobtica FemtoFiber Lasers.
The femtofiber drivers, which among other things make the usb connection appear as a serial port, must be installed (available from http://www.toptica.com/products/ultrafast_fiber_lasers/femtofiber_smart/femtosecond_erbium_fiber_laser_1560_nm_femtoferb)
-
class
instrumental.drivers.lasers.femto_ferb.
FemtoFiber
(port)¶ A femtoFiber laser.
Lasers can only be accessed by their serial port address.
-
__init__
(port)¶
-
close
()¶ Closes the connection to the laser.
-
is_control_on
()¶ Returns the status of the hardware input control.
Hardware input control must be on in order for the laser to be controlled by usb connection.
Returns: message – If True, hardware input conrol is on. Return type: bool
-
is_on
()¶ Indicates if the laser is on (True) or off (False).
-
set_control
(control)¶ Sets the status of the hardware input control.
Hardware input control must be on in order for the laser to be controlled by usb connection.
Parameters: control (bool) – If True, hardware input conrol is turned on. Returns: error – Zero is returned if the hardware input control status was set correctly. Otherwise, the error string returned by the laser is returned. Return type: int or str
-
Lock-in Amplifiers¶
Create Lockin
objects using instrument()
.
SRS Model SR850 Lock-in Amplifier¶
Driver for SRS model SR850 lock-in amplifier.
-
class
instrumental.drivers.lockins.sr850.
Ch1OutputSource
¶ -
R
= 1¶
-
X
= 0¶
-
theta
= 2¶
-
trace_1
= 3¶
-
trace_2
= 4¶
-
trace_3
= 5¶
-
trace_4
= 6¶
-
-
class
instrumental.drivers.lockins.sr850.
Ch2OutputSource
¶ -
R
= 1¶
-
Y
= 0¶
-
theta
= 2¶
-
trace_1
= 3¶
-
trace_2
= 4¶
-
trace_3
= 5¶
-
trace_4
= 6¶
-
-
class
instrumental.drivers.lockins.sr850.
Divide
¶ -
AuxIn1
= 8¶
-
AuxIn1_2
= 20¶
-
AuxIn2
= 9¶
-
AuxIn2_2
= 21¶
-
AuxIn3
= 10¶
-
AuxIn3_2
= 22¶
-
AuxIn4
= 11¶
-
AuxIn4_2
= 23¶
-
F
= 12¶
-
F_2
= 24¶
-
R
= 3¶
-
R_2
= 15¶
-
R_n
= 7¶
-
Rn_2
= 19¶
-
X
= 1¶
-
X_2
= 13¶
-
X_n
= 5¶
-
Xn_2
= 17¶
-
Y
= 2¶
-
Y_2
= 14¶
-
Y_n
= 6¶
-
Yn_2
= 18¶
-
theta
= 4¶
-
theta_2
= 16¶
-
unity
= 0¶
-
-
class
instrumental.drivers.lockins.sr850.
LineFilter
¶ -
both_filters
= 3¶
-
line_2x_notch
= 2¶
-
line_notch
= 1¶
-
no_filters
= 0¶
-
-
class
instrumental.drivers.lockins.sr850.
LowPassSlope
¶ -
eighteen_dB_per_octave
= 2¶
-
six_dB_per_octave
= 0¶
-
twelve_dB_per_octave
= 1¶
-
twentyfour_dB_per_octave
= 3¶
-
-
class
instrumental.drivers.lockins.sr850.
Multiply
¶ -
AuxIn1
= 8¶
-
AuxIn2
= 9¶
-
AuxIn3
= 10¶
-
AuxIn4
= 11¶
-
F
= 12¶
-
R
= 3¶
-
R_n
= 7¶
-
X
= 1¶
-
X_n
= 5¶
-
Y
= 2¶
-
Y_n
= 6¶
-
theta
= 4¶
-
unity
= 0¶
-
-
class
instrumental.drivers.lockins.sr850.
Parameter
¶ -
units
(parameter)¶
-
AuxIn_1
= 5¶
-
AuxIn_2
= 6¶
-
AuxIn_3
= 7¶
-
AuxIn_4
= 8¶
-
R
= 3¶
-
X
= 1¶
-
Y
= 2¶
-
reference_frequency
= 9¶
-
theta
= 4¶
-
trace_1
= 10¶
-
trace_2
= 11¶
-
trace_3
= 12¶
-
trace_4
= 13¶
-
-
class
instrumental.drivers.lockins.sr850.
ReferenceSlope
¶ -
sine_zero
= 0¶
-
ttl_falling
= 2¶
-
ttl_rising
= 1¶
-
-
class
instrumental.drivers.lockins.sr850.
ReferenceSource
¶ -
external
= 2¶
-
internal
= 0¶
-
internal_sweep
= 1¶
-
-
class
instrumental.drivers.lockins.sr850.
SR850
(inst, rs232_interface=True)¶ Interfaces with the SRS model SR850 Lock-in Amplifier
-
__init__
(inst, rs232_interface=True)¶ Connects to SRS850
rs232_interface is a bool which indicates which communication mode (RS-232 or GPIB) the sr850 is connected to.
-
auto_gain
()¶ Performs the auto-gain function.
Note that this function does not return until the process has completed.
-
auto_offset
(offset_selector)¶ Automatically offsets the selected quadrature to zero
offset_selector should be of type OffsetSelector
-
auto_phase
()¶ Performs the auto-phase function
-
auto_reserve
()¶ Performs the auto-reserve function
-
clear_registers
()¶ Clears all status registers, except for status enable registers.
-
close
()¶
-
command_execution_in_progress
()¶ Indicates if a command is currently being executed.
-
get_alarm_mode
()¶ Returns whether the audible alarm is on or off.
-
get_aux_in
(aux_in)¶ Returns the voltage of the specified auxillary input.
aux_in should be of type AuxIn
-
get_ch1_output_source
()¶ Returns the output source for channel 1.
-
get_ch2_output_source
()¶ Returns the output source for channel 2.
-
get_current_gain
()¶ Returns the conversion gain of the input current
-
get_detection_harmonic
()¶ Returns the detection harmonic
-
get_frequency_sweep_type
()¶ Returns whether a sweep is linear or logarithmic.
Returns type SweepType
-
get_input_configuration
()¶ Returns the input configuration.
-
get_input_coupling
()¶ Returns the input couplig mode
-
get_input_ground
()¶ Returns the input shield grounding mode.
-
get_line_filter_status
()¶ Returns the configuratin of the line filters
-
get_low_pass_slope
()¶ Returns the slope of the low pass filter.
-
get_output_offsets_and_expands
(offset_selector)¶ Returns the offsets and expands for the selected quadrature.
offset_selector should be of type OffsetSelector
-
get_reference_frequency
()¶ Returns the frequency of the reference source
-
get_reference_phase
()¶ Returns the phase shift of the reference source
-
get_reference_slope
()¶ Returns the mode with wich the reference source is discriminated.
-
get_reference_source
()¶ Returns the source used for the reference frequency.
Returns type ReferenceSource
-
get_reserve
()¶ Returns the current value of the dynamic reserve.
-
get_reserve_mode
()¶ Returns the reserve mode of the instrument.
-
get_scan_length
()¶ Returns the scan length.
-
get_scan_mode
()¶ Returns the scan mode.
-
get_scan_sample_rate
()¶ Sets the sampling rate of a scan.
-
get_sensitivity
()¶ Returns the sensitivity setting of the instrument
-
get_sine_amplitude
()¶ Returns the amplitude of the sine output, in Volts.
-
get_start_frequency
()¶ Returns the freqeuncy that a sweep starts at
-
get_stop_frequency
()¶ Returns the frequency that a sweep stops at
-
get_synchronous_filter
()¶ Returns the state of the synchronous filter.
-
get_time_constant
()¶ Get the current time constant of the instrument.
-
get_trace
(trace_number, points=None, units=None, binary=True)¶ Returns a vector of the values stored in the indicated trace
If get_trace times out while transferring data, the constants BINARY_TIME_PER_POINT and or ASCII_TIME_PER_POINT may need to be increased
Parameters: - should be an element of TraceNumber. (trace_number) –
- is a list of two integers - the first indicates the position (points) –
- the first value to be read, while the second indicates the number (of) –
- values to be read. By default, all points are read. (of) –
- - string indicating the proper units of the trace (units) –
- - boolean indicating the method of data transfer. Using binary (binary) –
- usually about 4 times faster. (is) –
-
get_trace_definitions
(trace)¶ Returns the definition of the given trace.
Trace should be an enumerator of Trace. The trace definition is of the form m1*m2/d
Returns: - m1, m2 of type Multiply
- d of type Divide
- store of type Store
-
get_trigger_start_scan_mode
()¶ Returns the mode in which the trigger initiates a scan.
-
pause_scan
()¶ Pauses a scan or sweep.
Has no effect is no scans are in progress.
-
read_aux_input
(aux_input)¶ Returns the value of the specified aux input
use type AuxInput
-
read_output
(output_type)¶ Returns the value of the indicated output
use type OutputType.
-
read_simultaneously
(parameters)¶ Returns simultaneosly the values the given parameters
the list parameters should have between two and 6 elements of the type Parameter
-
read_trace_value
(trace_number, units=None)¶ Returns the current value of indicated trace
trace_number should be of enumeraror class TraceNumber. If specified, units are added to the returned value. units should be a string.
-
reset_scan
()¶ Resets a scan.
This works whether a scan is in progress, finished, or paused. Note that the data buffer is erased.
-
scan_in_progress
()¶ Indicates if a scan is in progress.
Note that a paused scan is counted as being in progress
-
set_alarm_mode
(alarm_mode)¶ Sets the audible alarm on or off.
Use the enumerator AlarmMode.
-
set_ch1_output_source
(ch1_output_source)¶ Sets the output source for channel 1.
Use the enumerator Ch1OutputSource.
-
set_ch2_output_source
(ch2_output_source)¶ Sets the output source for channel 2
Use the enumerator Ch2OutputSource.
-
set_current_gain
(current_gain)¶ Sets the conversion gain of the input current.
Use the enumerator CurrentGain
-
set_detection_harmonic
(harmonic)¶ Sets the detection harmonic
-
set_frequency_sweep_type
(sweep_type)¶ Sets whether a sweep is linear or logarithmic.
sweep_type should be of type SweepType
-
set_input_configuration
(input_configuration)¶ Sets the input configuration.
input_conusing should be of type InputConfiguration
-
set_input_coupling
(input_coupling)¶ Sets the input coupling mode Use the enumerator InputCoupling
-
set_input_ground
(input_ground)¶ Sets the input shield grounding mode.
Use the enumerator InputGround
-
set_line_filter_status
(line_filter)¶ Sets the configuration of the line filters.
Use the enumerator LineFilter
-
set_low_pass_slope
(low_pass_slope)¶ Sets the slope for the low pass filter
Use the enumerator LowPassSlope
-
set_output_interface
(rs232_interface=True)¶ Sets the output interface.
Default is serial (rs232_insterface=True) Set rs232_interface to False for GPIB
-
set_output_offsets_and_expands
(offset_selector, offset, expand)¶ Sets the offsets and expands for the selected quadrature.
offset_selector is of type OffsetSelector, and indicates which quadrature to use. Note that offset_selector should be in percent, and expand should be an integer between 1 and 256
-
set_reference_frequency
(frequency)¶ Sets the freqeuncy of the reference source
-
set_reference_phase
(phase)¶ Sets the phase shift of the reference source
-
set_reference_slope
(reference_slope)¶ Sets the mode with wich the reference source is discriminated.
This is only relevant when an external source is used.
reference_slope should be of type ReferenceSlope
-
set_reference_source
(reference_source)¶ Sets the source used for the reference frequency.
reference_source should be of type ReferenceSource
-
set_reserve
(reserve)¶ Sets the manual dynamic reserve.
Reserve should be an integer between 0 and 5, inclusive. 0 sets the minimum reserve for the current time constant and sensitivity. Each increment increases the reserve by 10dB.
-
set_reserve_mode
(reserve_mode)¶ Sets the reserve mode of the instrument
Use the enumerator ReserveMode
-
set_scan_length
(scan_length)¶ Sets the scan length.
-
set_scan_mode
(scan_mode)¶ Sets the scan mode. Use the enumerator ScanMode.
-
set_scan_sample_rate
(scan_sample_rate)¶ Sets the sampling rate of a scan.
Use the enumerator ScanSampleRate.
-
set_sensitivity
(sensitivity)¶ Sets the sensitivity of the instrument.
Use the enumerator Sensitivity
-
set_sine_amplitude
(amplitude)¶ Sets the amplitude of the sine output.
Must be between 0.004 and 5V. (Rounds to nearest 0.002 V)
-
set_start_frequency
(frequency)¶ Sets the frequency a sweep starts at
-
set_stop_frequency
(frequency)¶ Sets the frequency that a sweep stops at
-
set_synchronous_filter
(synchronous_filter)¶ Sets the state of the synchronous filter.
Use the enumerator SynchronousFilter. Note that the synchronous filter only operates if the detection frequency is below 200Hz
-
set_time_constant
(time_constant)¶ Sets the time constant of the instrument
Use the enumerator TimeConstant
-
set_trace_definitions
(trace, m1, m2=<Multiply.unity: 0>, d=<Divide.unity: 0>, store=<Store.stored: 1>)¶ Sets the definition of the given trace ‘trace’ to be m1*m2/d.
Trace should be an enumerator of Trace, m1 and m2 should be enumerators of Multiply, d should be an enumerator of Divide, and store should be an enumerator of Store.
-
set_trigger_start_scan_mode
(trigger_start_scan_mode)¶ Sets the mode in which the trigger initiates a scan.
Use the enumerator TriggerStartScanMode.
-
start_scan
()¶ Starts or resumes a scan/sweep.
Has no effect if a scan is already in progress.
-
trace_length
(trace_number)¶ Returns the number of points in the specified trace
use the enumerator TraceNumber
-
trigger
()¶ Initiates a trigger event.
-
-
class
instrumental.drivers.lockins.sr850.
ScanSampleRate
¶ -
trigger
= 14¶
-
x125mHz
= 1¶
-
x128Hz
= 11¶
-
x16Hz
= 8¶
-
x1Hz
= 4¶
-
x250mHz
= 2¶
-
x256Hz
= 12¶
-
x2Hz
= 5¶
-
x32Hz
= 9¶
-
x4Hz
= 6¶
-
x500mHz
= 3¶
-
x512Hz
= 13¶
-
x62_5mHz
= 0¶
-
x64Hz
= 10¶
-
x8Hz
= 7¶
-
-
class
instrumental.drivers.lockins.sr850.
Sensitivity
¶ -
x100mV_nA
= 23¶
-
x100nV_fA
= 5¶
-
x100uV_pA
= 14¶
-
x10mV_nA
= 20¶
-
x10nV_fA
= 2¶
-
x10uV_pA
= 11¶
-
x1V_uA
= 26¶
-
x1mV_nA
= 17¶
-
x1uV_pA
= 8¶
-
x200mV_nA
= 24¶
-
x200nV_fA
= 6¶
-
x200uV_pA
= 15¶
-
x20mV_nA
= 21¶
-
x20nV_fA
= 3¶
-
x20uV_pA
= 12¶
-
x2mV_nA
= 18¶
-
x2nV_fA
= 0¶
-
x2uV_pA
= 9¶
-
x500mV_nA
= 25¶
-
x500nV_fA
= 7¶
-
x500uV_pA
= 16¶
-
x50mV_nA
= 22¶
-
x50nV_fA
= 4¶
-
x50uV_pA
= 13¶
-
x5mV_nA
= 19¶
-
x5nV_fA
= 1¶
-
x5uV_pA
= 10¶
-
-
class
instrumental.drivers.lockins.sr850.
StatusByte
¶ -
enabled_bit_in_LIA_status_set
= 3¶
-
enabled_bit_in_error_status_set
= 2¶
-
enabled_bit_in_standard_status_set
= 5¶
-
no_command_execution_in_progress
= 1¶
-
no_scan_in_progress
= 0¶
-
output_buffer_non_empty
= 4¶
-
service_request
= 6¶
-
Motion Control¶
Create Motion
objects using instrument()
.
Thorlabs Motorized Filter Flip Mount (MFF10X)¶
Driver for controlling Thorlabs Flipper Filters using the Kinesis SDK.
One must place Thorlabs.MotionControl.DeviceManager.dll and Thorlabs.MotionControl.FilterFlipper.dll in the path
-
exception
instrumental.drivers.motion.filter_flipper.
FilterFlipperError
¶
-
class
instrumental.drivers.motion.filter_flipper.
Filter_Flipper
(serial, polling_period='200ms')¶ Driver for controlling Thorlabs Filter Flippers
Takes the serial number of the device as a string.
The polling period, which is how often the device updates its status, is passed as a pint quantity with units of time and is optional argument, with a default of 200ms
-
__init__
(serial, polling_period='200ms')¶ Parameters: - serial_number (str) –
- polling_period (pint quantity with units of time) –
-
close
()¶
-
flip
()¶ Flips the position of the filter.
-
get_position
()¶ Get the position of the flipper.
Returns an instance of Position. Note that this represents the position at the most recent polling event.
-
get_transit_time
()¶ Returns the transit time.
The transit time is the time to transition from one filter position to the next.
-
home
()¶ Homes the device
-
isValidPosition
(position)¶ Indicates if it is possible to move to the given position.
Parameters: position (instance of Position) –
-
move_and_wait
(position, delay='100ms')¶ Moves to the indicated position and waits until that position is reached.
Parameters: - position (instance of Position) – should not be ‘Position.moving’
- delay (pint quantity with units of time) – the period with which the position of the flipper is checked.
-
move_to
(position)¶ Moves the flipper to the indicated position.
Returns immediatley.
Parameters: position (instance of Position) – should not be ‘Position.moving’
-
set_transit_time
(transit_time='500ms')¶ Sets the transit time. The transit time is the time to transition from one filter position to the next.
Parameters: transit_time (pint quantity with units of time) –
-
-
class
instrumental.drivers.motion.filter_flipper.
Position
¶ The position of the flipper.
-
moving
= 0¶
-
one
= 1¶
-
two
= 2¶
-
-
instrumental.drivers.motion.filter_flipper.
list_instruments
()¶
Thorlabs K10CR1 Rotation Stage¶
Driver for controlling Thorlabs Kinesis devices. Currently only directs the K10CR1 rotation stage.
-
class
instrumental.drivers.motion.kinesis.
K10CR1
(serial, gear_box_ratio=120, steps_per_rev=200, micro_steps_per_step=2048, polling_period='200 ms', offset='0 deg')¶ Class for controlling Thorlabs K10CR1 integrated stepper rotation stages
Takes the serial number of the device as a string as well as the gear box ratio, steps per revolution and microsteps per step as integers. It also takes the polling period as a pint quantity.
The polling period, which is how often the device updates its status, is passed as a pint pint quantity with units of time and is optional argument, with a default of 200ms
-
class
K10CR1.
MessageType
¶ -
GenericDCMotor
= 3¶
-
GenericDevice
= 0¶
-
GenericMotor
= 2¶
-
GenericPiezo
= 1¶
-
GenericSimpleMotor
= 4¶
-
Laser
= 6¶
-
NanoTrak
= 9¶
-
Quad
= 8¶
-
RackDevice
= 5¶
-
Solenoid
= 11¶
-
Specialized
= 10¶
-
TECCtlr
= 7¶
-
-
K10CR1.
__init__
(serial, gear_box_ratio=120, steps_per_rev=200, micro_steps_per_step=2048, polling_period='200 ms', offset='0 deg')¶ Parameters: - serial (str) –
- polling_period (pint quantity with units of time) –
-
K10CR1.
close
()¶
-
K10CR1.
get_messages
()¶
-
K10CR1.
get_next_message
()¶
-
K10CR1.
home
(wait=False)¶ Home the stage
Parameters: wait (bool, optional) – Wait until the stage has finished homing to return
-
K10CR1.
homing_finished
()¶ Check if the most recent homing operation has finished
-
K10CR1.
move_finished
()¶ Check if the most recent move has finished
-
K10CR1.
move_to
(angle, wait=False)¶ Rotate the stage to the given angle
Parameters: angle (Quantity) – Angle that the stage will rotate to. Takes the stage offset into account.
-
K10CR1.
wait_for_home
()¶ Wait for the most recent homing operation to complete
-
K10CR1.
wait_for_move
()¶ Wait for the most recent move to complete
-
K10CR1.
is_homing
¶
-
K10CR1.
is_moving
¶
-
K10CR1.
needs_homing
¶ True if the device needs to be homed before a move can be performed
-
K10CR1.
offset
¶
-
K10CR1.
position
¶
-
class
T-Cube DC Servo Motor Controller (TDC001)¶
Driver for controlling Thorlabs TDC001 T-Cube DC Servo Motor Controllers using the Kinesis SDK.
One must place Thorlabs.MotionControl.DeviceManager.dll and Thorlabs.MotionControl.TCube.DCServo.dll in the path.
-
exception
instrumental.drivers.motion.tdc_001.
TDC001Error
¶
-
class
instrumental.drivers.motion.tdc_001.
SoftwareApproachPolicy
¶ -
AllowAll
= 3¶
-
DisableFarOutsideRange
= 1¶
-
DisableOutsideRange
= 0¶
-
TruncateBeyondLimit
= 2¶
-
-
class
instrumental.drivers.motion.tdc_001.
TDC001
(serial, polling_period=<Mock object>, allow_all_moves=True)¶ Controlling Thorlabs TDC001 T-Cube DC Servo Motor Controllers
Takes the serial number of the device as a string.
The polling period, which is how often the device updates its status, is passed as a pint pint quantity with units of time and is optional argument, with a default of 200ms
-
class
Status
(status_bits)¶ Stores information about the status of the device from the status bits.
-
__init__
(status_bits)¶
-
-
TDC001.
__init__
(serial, polling_period=<Mock object>, allow_all_moves=True)¶ Parameters: - serial_number (str) –
- polling_period (pint quantity with units of time) –
-
TDC001.
at_position
(position, tol=1)¶ Indicates whether the motor is at the given position.
Parameters: - position (pint quantity of units self.real_world_units) –
- tol (int representing the number of encoder counts within which the) –
- is considered to be at position (motor) –
-
TDC001.
close
()¶ Closes the connectin to the device
-
TDC001.
get_motor_params
()¶ Gets the stage motor parameters.
Returns: - (steps_per_rev (int,)
- gearbox_ratio (int,)
- pitch (float))
-
TDC001.
get_position
()¶ Returns the position of the motor.
Note that this represents the position at the most recent polling event.
-
TDC001.
get_status
()¶ Returns the status registry bits from the device.
-
TDC001.
home
()¶ Homes the device
-
TDC001.
move_and_wait
(position, delay='100ms', tol=1)¶ Moves to the indicated position and waits until that position is reached.
Parameters: - position (pint quantity of units self.real_world_units) –
- delay (pint quantity with units of time) – the period with which the position of the motor is checked.
- tol (int) – the tolerance, in encoder units, to which the motor is considered at position
-
TDC001.
move_to
(position)¶ Moves to the indicated position
Returns immediately.
Parameters: position (pint quantity of units self.real_world_units) –
-
class
-
instrumental.drivers.motion.tdc_001.
list_instruments
()¶
Attocube ECC100 Motion Controller¶
Driver module for Attocube stages.
- Interfaces with the ECC100 controller, which has support for various stages:
- ECS3030
- ECS3040
- ECS3050
- ECS3060
- ECS3070
- ECS3080
- ECS5050
- ECGp5050
- ECGt5050
- ECR3030
Note that ecc.dll must be on the system path, and that this is a windows only driver.
-
class
instrumental.drivers.motion.ecc100.
Actor
(controller, axis)¶ -
__init__
(controller, axis)¶
-
at_target
(delta_pos=None)¶ Indicates whether the stage is at the target position.
delta_pos is the tolerance within which the stage is considered ‘at position’
-
disable
()¶ Disables communication from the controller to the stage.
-
enable
()¶ Enables communication from the controller to the stage.
-
enable_feedback
(enable=True)¶ Control the positioning feedback-control loop
enable: bool, where False corresponds to OFF and True corresponds to ON
-
get_amplitude
()¶ Gets the amplitude of the actuator signal.
-
get_frequency
()¶ Gets the frequency of the actuator signal.
-
get_position
()¶ Returns the current postion
-
get_ref_position
()¶ Returns the current reference positoin
-
get_target
()¶ Returns the target position of the feedback control loop.
-
is_enabled
()¶ Returns whether communication to the stage is enabled.
-
is_feedback_on
()¶ Indicates if the feedback-control loop is ON (True) or OFF (False)
-
is_ref_position_valid
()¶ Returns whether the reference position is valid.
-
is_stepping_backward
()¶
-
is_stepping_forward
()¶
-
move_to
(pos, wait=False)¶ Moves to a location using closed loop control.
-
set_amplitude
(amplitude)¶ Sets the amplitude of the actuator signal.
This modifies the step size of the positioner.
Parameters: amplitude (pint.Quantity) – amplitude of the actuator signal in volt-compatible units. The allowed range of inputs is from 0 V to 45 V.
-
set_frequency
(frequency)¶ Sets the frequency of the actuation voltage applied to the stage.
The frequency is proportional to the travel speed of the positioner.
Parameters: frequency (pint.Quantity) – frequency of the actuator signal in Hz-compatible units. The allowed range of inputs is from 1 Hz to 2 kHz.
-
set_target
(target)¶ Sets the target position of the feedback control loop.
target: target position, in nm for linear stages, in micro radians for goniometers
-
start_stepping
(backward=False)¶ Step continously until stopped.
This will stop any ongoing motion in the opposite direction.
-
step_once
(backward=False)¶ Step once.
-
stop_stepping
()¶ Stop any continuous stepping.
-
timed_move
(direction, duration)¶ Moves in the specified direction for the specified duration.
direction: bool controlling the direciton of movement. True corresponds to the positive direction for linear stages and the negative direction for goniometers
duration: duration of motion, a pint quantity with units of time
-
wait_until_at_position
(update_interval='10 ms', delta_pos=None)¶ Waits to return until the actor is at the target position
delta_pos is the margin within which the device is considered to be at the target position
-
-
class
instrumental.drivers.motion.ecc100.
ActorType
¶ -
Goniometer
= 1¶
-
LinearStage
= 0¶
-
RotationStage
= 2¶
-
-
class
instrumental.drivers.motion.ecc100.
ECC100
(device_id=None)¶ Interfaces with the Attocube ECC100 controller. Windows-only.
-
__init__
(device_id=None)¶ Connects to the attocube controller.
id is the id of the device to be connected to
-
close
()¶ Closes the connection to the controller.
-
get_position
(actors=None)¶ Gets the positions of the actors in the list actors.
actors is a list of type Actor, or one can use the default actors, set by set_default_actors
-
get_target
(actors=None)¶ Gets the target positions of the actors in the list actors.
Returns a list of target positions.
actors is a list of type Actor, or one can use the default actors, set by set_default_actors
-
move_to
(positions, actors=None, wait=False)¶ Moves to the positions in the list positions.
actors is a list of type Actor, or one can use the default actors, set by set_default_actors
-
set_default_actors
(actors)¶ Sets the default list of actors used in various functions.
Actors should be a list of instances of Actor
-
set_target
(target, actors=None)¶ Sets the target positions of the actors in the list actors.
target is a list of position that are unitful pint quantities
actors is a list of type Actor, or one can use the default actors, set by set_default_actors
-
wait_until_at_position
(actors=None, delta_pos=None)¶ Waits to return until all actors are at the target position
If actors is None, then the default actors are used. The default actors are set using set_default_actors
-
-
class
instrumental.drivers.motion.ecc100.
RotationStage
(controller, axis)¶
-
instrumental.drivers.motion.ecc100.
check_for_devices
()¶ Checks for devices, returns their info and how many there are.
Returns: - num (int) – number of devices connected
- info (list of EccInfo) – info list. Each EccInfo object has the attributes ‘id’, and ‘locked’
-
instrumental.drivers.motion.ecc100.
list_instruments
()¶
Multimeters¶
Create Multimeter
objects using instrument()
.
HP 34401A Multimeter¶
-
exception
instrumental.drivers.multimeters.hp.
MultimeterError
¶
-
class
instrumental.drivers.multimeters.hp.
HPMultimeter
(visa_inst)¶ -
__init__
(visa_inst)¶
-
clear
()¶
-
config_voltage_dc
(range=None, resolution=None)¶ Configure the multimeter to perform a DC voltage measurement.
Parameters: - range (Quantity, 'min', 'max', or 'def') – Expected value of the input signal
- resolution (Quantity, 'min', 'max', or 'def') – Resolution of the measurement, in measurement units
-
fetch
()¶
-
initiate
()¶
-
trigger
()¶ Emit the software trigger
To use this function, the device must be in the ‘wait-for-trigger’ state and its
trigger_source
must be set to ‘bus’.
-
npl_cycles
¶
-
trigger_source
¶
-
Power Meters¶
Create PowerMeter
objects using instrument()
.
Newport Power Meters¶
Driver module for Newport power meters. Supports:
- 1830-C
-
class
instrumental.drivers.powermeters.newport.
Newport_1830_C
(inst)¶ A Newport 1830-C power meter
-
__init__
(inst)¶
-
attenuator_enabled
()¶ Whether the attenuator is enabled
Returns: enabled – whether the attenuator is enabled Return type: bool
-
disable_attenuator
()¶ Disable the power meter attenuator
-
disable_auto_range
()¶ Disable auto-range
Leaves the signal range at its current position.
-
disable_hold
()¶ Disable hold mode
-
disable_zero
()¶ Disable the zero function
-
enable_attenuator
(enabled=True)¶ Enable the power meter attenuator
-
enable_auto_range
()¶ Enable auto-range
-
enable_hold
(enable=True)¶ Enable hold mode
-
enable_zero
(enable=True)¶ Enable the zero function
When enabled, the next power reading is stored as a background value and is subtracted off of all subsequent power readings.
-
get_filter
()¶ Get the current setting for the averaging filter
Returns: the current averaging filter Return type: SLOW_FILTER, MEDIUM_FILTER, NO_FILTER
-
get_power
()¶ Get the current power measurement
Returns: power – Power in units of watts, regardless of the power meter’s current ‘units’ setting. Return type: Quantity
-
get_range
()¶ Return the current range setting as an int
1 corresponds to the lowest range, while 8 is the highest range (least amplifier gain).
Note that this does not query the status of auto-range.
Returns: range – the current range setting. Possible values are from 1-8. Return type: int
-
get_status_byte
()¶ Query the status byte register and return it as an int
-
get_units
()¶ Get the units used for displaying power measurements
Returns: units – ‘watts’, ‘db’, ‘dbm’, or ‘rel’ Return type: str
-
get_wavelength
()¶ Get the input wavelength setting
-
hold_enabled
()¶ Whether hold mode is enabled
Returns: enabled – True if in hold mode, False if in run mode Return type: bool
-
is_measurement_valid
()¶ Whether the current measurement is valid
The measurement is considered invalid if the power meter is saturated, over-range or busy.
-
set_medium_filter
()¶ Set the averaging filter to medium mode
The medium filter uses a 4-measurement running average.
-
set_no_filter
()¶ Set the averaging filter to fast mode, i.e. no averaging
-
set_range
(range_num)¶ Set the range for power measurements
range_num = 0 for auto-range range_num = 1 to 8 for manual signal range (1 is lowest, and 8 is highest)
Parameters: n (int) – Sets the signal range for the input signal.
-
set_slow_filter
()¶ Set the averaging filter to slow mode
The slow filter uses a 16-measurement running average.
-
set_units
(units)¶ Set the units for displaying power measurements
The different unit modes are watts, dB, dBm, and REL. Each displays the power in a different way.
‘watts’ displays absolute power in watts
‘dBm’ displays power in dBm (i.e. dBm = 10 * log(P / 1mW))
‘dB’ displays power in dB relative to the current reference power (i.e. dB = 10 * log(P / Pref). At power-up, the reference power is set to 1mW.
‘REL’ displays power relative to the current reference power (i.e. REL = P / Pref)
The current reference power can be set using
store_reference()
.Parameters: units ('watts', 'dBm', 'dB', or 'REL') – Case-insensitive str indicating which units mode to enter.
-
set_wavelength
(wavelength)¶ Set the input signal wavelength setting
Parameters: wavelength (Quantity) – wavelength of the input signal, in units of [length]
-
store_reference
()¶ Store the current power input as a reference
Sets the current power measurement as the reference power for future dB or relative measurements.
-
zero_enabled
()¶ Whether the zero function is enabled
-
MEDIUM_FILTER
= 2¶
-
NO_FILTER
= 3¶
-
SLOW_FILTER
= 1¶
-
Thorlabs Power Meters¶
Driver module for Thorlabs power meters. Supports:
- PM100D
-
class
instrumental.drivers.powermeters.thorlabs.
PM100D
(visa_inst)¶ A Thorlabs PM100D series power meter
-
__init__
(visa_inst)¶
-
auto_range_enabled
()¶ Whether auto-ranging is enabled
Returns: bool Return type: enabled
-
close
()¶
-
disable_auto_range
()¶ Disable auto-ranging
-
enable_auto_range
(enable=True)¶ Enable auto-ranging
-
get_num_averaged
()¶ Get the number of samples to average
Returns: num_averaged – number of samples that are averaged Return type: int
-
get_power
()¶ Get the current power measurement
Returns: power – the current power measurement Return type: Quantity
-
get_range
()¶ Get the current input range’s max power
-
get_wavelength
()¶ Get the input signal wavelength setting
Returns: wavelength – the input signal wavelength in units of [length] Return type: Quantity
-
measure
(n_samples=100)¶ Make a multi-sample power measurement
Parameters: n_samples (int) – Number of samples to take Returns: Measured power, with units and uncertainty, as a pint.Measurement
objectReturn type: pint.Measurement
-
set_num_averaged
(num_averaged)¶ Set the number of samples to average
Each sample takes approximately 3ms. Thus, averaging over 1000 samples would take about a second.
Parameters: num_averaged (int) – number of samples to average
-
set_wavelength
(wavelength)¶ Set the input signal wavelength setting
Parameters: wavelength (Quantity) – the input signal wavelength in units of [length]
-
Scopes¶
Create Scope
objects using instrument()
.
Tektronix Oscilloscopes¶
Driver module for Tektronix oscilloscopes. Currently supports
- TDS 3000 series
- MSO/DPO 4000 series
-
class
instrumental.drivers.scopes.tektronix.
MSO_DPO_4000
(name=None, visa_inst=None)¶ A Tektronix MSO/DPO 4000 series oscilloscope.
-
class
instrumental.drivers.scopes.tektronix.
TDS_3000
(name=None, visa_inst=None)¶ A Tektronix TDS 3000 series oscilloscope.
-
class
instrumental.drivers.scopes.tektronix.
TekScope
(name=None, visa_inst=None)¶ A base class for Tektronix scopes. Supports at least TDS 3000 series as well as MSO/DPO 4000 series scopes.
-
__init__
(name=None, visa_inst=None)¶ Create a scope object that has the given VISA name name and connect to it. You can find available instrument names using the VISA Instrument Manager.
-
are_measurement_stats_on
()¶ Returns whether measurement statistics are currently enabled
-
disable_measurement_stats
()¶ Disables measurement statistics
-
enable_measurement_stats
(enable=True)¶ Enables measurement statistics.
When enabled, measurement statistics are kept track of, including ‘mean’, ‘stddev’, ‘minimum’, ‘maximum’, and ‘nsamps’.
Parameters: enable (bool) – Whether measurement statistics should be enabled
-
get_data
(channel=1)¶ Retrieve a trace from the scope.
Pulls data from channel
channel
and returns it as a tuple(t,y)
of unitful arrays.Parameters: channel (int, optional) – Channel number to pull trace from. Defaults to channel 1. Returns: t, y – Unitful arrays of data from the scope. t
is in seconds, whiley
is in volts.Return type: pint.Quantity arrays
-
get_math_function
()¶
-
read_measurement_stats
(num)¶ Read the value and statistics of a measurement.
Parameters: num (int) – Number of the measurement to read from, from 1-4 Returns: stats – Dictionary of measurement statistics. Includes value, mean, stddev, minimum, maximum, and nsamps. Return type: dict
-
read_measurement_value
(num)¶ Read the value of a measurement.
Parameters: num (int) – Number of the measurement to read from, from 1-4 Returns: value – Value of the measurement Return type: pint.Quantity
-
run_acquire
()¶ Sets the acquire state to ‘run’
-
set_math_function
(expr)¶ Set the expression used by the MATH channel.
Parameters: expr (str) – a string representing the MATH expression, using channel variables CH1, CH2, etc. eg. ‘CH1/CH2+CH3’
-
set_measurement_nsamps
(nsamps)¶ Sets the number of samples used to compute measurements.
Parameters: nsamps (int) – Number of samples used to compute measurements
-
set_measurement_params
(num, mtype, channel)¶ Set the parameters for a measurement.
Parameters:
-
stop_acquire
()¶ Sets the acquire state to ‘stop’
-
Spectrometers¶
Create Spectrometer
objects using instrument()
.
Bristol Spectrum Analyzers¶
This module is for controlling Bristol model 721 spectrum analyzers.
Driver for Bristol 721 spectrum analyzers.
-
class
instrumental.drivers.spectrometers.bristol.
Bristol_721
(port=None)¶ -
__init__
(port=None)¶
-
close
()¶
-
get_spectrum
()¶ Get a spectrum.
Returns: - x (array Quantity) – Wavelength of the bins, in nm
- y (array) – Power in each bin, in arbitrary units
-
get_wavelength
()¶ Get the vacuum wavelength of the tallest peak in the spectrum
Returns: wavelength – The peak wavelength, in nm Return type: Quantity
-
-
instrumental.drivers.spectrometers.bristol.
bin_index
(fft_size, dec, fold, lamb)¶
-
instrumental.drivers.spectrometers.bristol.
ignore_stderr
(f)¶
-
instrumental.drivers.spectrometers.bristol.
list_instruments
()¶
-
instrumental.drivers.spectrometers.bristol.
stderr_redirected
(*args, **kwds)¶
Thorlabs CCS Spectrometers¶
This module is for controlling Thorlabs CCS spectrometers.
The Thorlabs OSA software provided on Thorlabs website must be installed. This driver is currently windows only.
Driver Module for Thorlabs CCSXXX series spectrometers. Currently Windows only.
Copyright Christopher Rogers 2016
-
exception
instrumental.drivers.spectrometers.thorlabs_ccs.
ThorlabsCCSError
¶
-
class
instrumental.drivers.spectrometers.thorlabs_ccs.
CCS
(spectrometer_attributes=None)¶ A CCS-series Thorlabs spectrometer.
If this construcor is called, it will connect to the first available spectrometer (if there is at least one). It can also be accessed by calling get_spectrometer using any one of the parameters ‘address’, ‘serial’, or ‘model’. Calling the function
instrument()
, using any one of the parameters ‘ccs_usb_address’, ‘ccs_serial_number’, or ‘ccs_model’ will also return a CCS instance (if successful).-
__init__
(spectrometer_attributes=None)¶ Create a spectrometer object by connecting to the spectrometer has the serial number in spectrometer_attributes.
-
calibrate_wavelength
(calibration_type=<Calibration.User: 1>, wavelength_array=None, pixel_array=None)¶ Sets a custom pixel-wavelength calibration.
The wavelength and pixel points are used to interpolate the correlation between pixel and wavelength.
Note that the given values must be strictly increasing as a function of wavelength, and that the lenght of the arrays must be equal and be between 4 and 10 (inclusive). Note that there are also some other requirements, that seem to have something with the calibration data points being somewhat’smooth’ that are not specified in the documentation and may result in the not very descriptive ‘Invalid user wavelength adjustment data’ error.
If calibration_type is Calibration.User, then the last 3 arguments must be given, and are used to set the wavelength calibration.
If calibration_type is Calibration.Factory, then the last three arguments are ignored, and the default factory wavelength calibration is used.
Parameters: - pixel_data (array of int) – The pixel indices for the interpolation.
- wavelength_data (array of float) – The wavelengths (in nm) to be used in the interpolation.
- calibration_type (Calibration) –
-
close
()¶ Closes the spectrometer.
-
cont_scan_in_progress
()¶ Indicates if a continuous scan is in progress
-
get_amplitude_data
(mode=<CorrectionType.Store: 2>)¶ Gets the amplitude correction factors.
Parameters: mode (str) – This parameter can be either ‘stored’ or ‘one_time’. If set to ‘one_time’, the correction factors for the current data are returned. If set to ‘stored’, the correction factors stored in the spectrometers non-volatile memory will be returned. Returns: correction_factors – Array of pixel correction factors, of length NUM_RAW_PIXELS. Return type: array of float
-
get_device_info
()¶ Returns and instance of ID_Infor, containing various device information.
-
get_integration_time
()¶ Returns the integration time.
-
get_scan_data
()¶ Returns the processed scan data.
Contains the pixel values from the last completed scan.
Returns: data Return type: numpy array of type float with of length NUM_RAW_PIXELS = 3648,
-
get_status
(status=None)¶ Returns a list instance containing strings indicating the status of the device. :param status: :type status: int, optional :param An int representing the state of the byte register. If ‘None’: :param (default), the method gets the current status directly from the: :param spectrometer.:
-
is_data_ready
()¶ Indicates if the spectrometer has data ready to transmit.
-
is_idle
()¶ Supposedly returns ‘True’ if the spectrometer is idle.
The status bit on the spectrometer this driver was tested with did not seem to work properly. This may or may not be a genereal issue.
-
reset
()¶ Resets the device.
-
set_amplitude_data
(correction_factors, start_index=0, mode=<CorrectionType.Store: 2>)¶ Sets the amplitude correction factors.
These factors multiply the pixels intensities to correct for variations between pixels.
On start-up, these are all set to unity. The factors are set by the values in correction_factors, starting with pixel start_index.
Parameters: - correction_factors (array of float) – Correction factors for the pixels.
- num_points (int) – The number of pixels to apply the correction factors (typically the length of correction_factors).
- start_index (int) – The index of the first pixel to which the correction factors will be applied.
- mode (CorrectionType) – Can be either ‘store’ or ‘one_time’. If set to OneTime, the correction factors are only applied to the current data. If set to Store, the correction factors will be applied to the current data and all future data.
-
set_background
(integration_time=None, num_avg=1)¶ Collects a background spectrum using the given settings.
Both the integration time and the number of spectra to average over can be specified as paramters. The background spectra itself is returned.
Parameters:
-
set_integration_time
(integration_time, stop_scan=True)¶ Sets the integration time.
-
start_cont_scan_trg
()¶ Arms spectrometer for continuous external triggering.
The spectrometer will wait for a signal from the external trigger before executing a scan, will rearm immediatley after that scan has completed, and so on.
Note that the function returns immediately, and does not wait for the trigger or for the scan to finish.
Note also that this cancels other scans in progress.
-
start_continuous_scan
()¶
-
start_scan_trg
()¶ Arms spectrometer to wait for a signal from the external trigger before executing scan.
Note that the function returns immediately, and does not wait for the trigger or for the scan to finish.
Note also that this cancels other scans in progress.
-
start_single_scan
()¶
-
stop_and_clear
()¶ Stops any scans in progress, and clears any data waiting to transmit.
-
stop_scan
()¶
-
take_data
(integration_time=None, num_avg=1, use_background=False)¶ Returns scan data.
The data can be averaged over a number of trials ‘num_Avg’ if desired. The stored backgorund spectra can also be subtracted from the data.
Parameters: - integration_time (float, optional) –
The integration time in seconds. If not specified, the current integration time is used.
Note that in practice, times greater than 50 seconds do not seem to work properly.
- num_avg (int, Default=1) – The number of spectra to average over.
- use_background (bool, Default=False) – If true, the spectrometer subtracts the current background spectra (stored in self._background) from the data.
Returns: - data (numpy array of float of size (self.num_pixels, 1)) – The amplitude data from the spectrometer, given in arbitrary units.
- wavelength_data (numpy array of float of size (self.numpixel, 1)) – The wavelength (in nm) corresponding to each pixel.
- integration_time (float, optional) –
-
waiting_for_trig
()¶ Indicates if the spectrometer is waiting for an external trigger signal.
-
-
class
instrumental.drivers.spectrometers.thorlabs_ccs.
ID_Info
(manufacturer, device_name, serial_number, firmware_version, driver_version)¶ -
__init__
(manufacturer, device_name, serial_number, firmware_version, driver_version)¶
-
-
class
instrumental.drivers.spectrometers.thorlabs_ccs.
SpecTypes
¶ -
CCS100
¶
-
CCS125
¶
-
CCS150
¶
-
CCS175
¶
-
CCS200
¶
-
-
instrumental.drivers.spectrometers.thorlabs_ccs.
list_instruments
()¶ Get a list of all spectrometers currently attached.
Wavemeters¶
Create Wavemeter
objects using instrument()
.
Burleigh Wavemeters¶
Driver module for Burleigh wavemeters. Supports:
- WA-1000/1500
-
class
instrumental.drivers.wavemeters.burleigh.
WA_1000
(inst)¶ A Burleigh WA-1000/1500 wavemeter
-
__init__
(inst)¶
-
averaging_enabled
()¶ Whether averaging mode is enabled
-
disable_averaging
()¶ Disable averaging mode
-
enable_averaging
(enable=True)¶ Enable averaging mode
-
get_deviation
()¶ Get the current deviation
Returns: deviation – The wavelength difference between the current input wavelength and the fixed setpoint. Return type: Quantity
-
get_num_averaged
()¶ Get the number of samples used in averaging mode
-
get_pressure
()¶ Get the barometric pressure inside the wavemeter
Returns: pressure – The barometric pressure inside the wavemeter Return type: Quantity
-
get_setpoint
()¶ Get the wavelength setpoint
Returns: setpoint – the wavelength setpoint Return type: Quantity
-
get_temperature
()¶ Get the temperature inside the wavemeter
Returns: temperature – The temperature inside the wavemeter Return type: Quantity
-
get_wavelength
()¶ Get the wavelength
Returns: wavelength – The current input wavelength measurement Return type: Quantity
-
is_locked
()¶ Whether the front panel is locked or not
-
lock
(lock=True)¶ Lock the front panel of the wavemeter, preventing manual input
When locked, the wavemeter can only be controlled remotely by a computer. To unlock, use
unlock()
or hit the ‘Remote’ button on the wavemeter’s front panel.
-
set_num_averaged
(num)¶ Set the number of samples used in averaging mode
When averaging mode is enabled, the wavemeter calculates a running average of the last
num
samples.Parameters: num (int) – Number of samples to average. Must be between 2 and 50.
-
set_setpoint
(setpoint)¶ Set the wavelength setpoint
The setpoint is a fixed wavelength used to compute the deviation. It is used for display and to determine the analog output voltage.
Parameters: setpoint (Quantity) – Wavelength of the setpoint, in units of [length]
-
unlock
()¶ Unlock the front panel of the wavemeter, allowing manual input
-
Functions¶
-
class
instrumental.drivers.
Instrument
¶ Base class for all instruments.
-
save_instrument
(name, force=False)¶ Save an entry for this instrument in the config file.
Parameters: - name (str) – The name to give the instrument, e.g. ‘myCam’
- force (bool, optional) – Force overwrite of the old entry for instrument
name
. By default, Instrumental will raise an exception if you try to write to a name that’s already taken. Ifforce
is True, the old entry will be commented out (with a warning given) and a new entry will be written.
-
-
class
instrumental.drivers.
InstrumentMeta
¶ Instrument metaclass.
Implements inheritance of method and property docstrings for subclasses of Instrument. That way e.g. you don’t have to repeat the docstring of an abstract method, though you can provide a docstring in case more specific documentation is useful.
If the child’s docstring contains only a single-line function signature, it is prepended to its parent’s docstring rather than overriding it comopletely. This is useful for the explicitly specifying signatures for methods that are wrapped by a decorator.
-
instrumental.drivers.
instrument
(inst=None, **kwargs)¶ Create any Instrumental instrument object from an alias, parameters, or an existing instrument.
>>> inst1 = instrument('MYAFG') >>> inst2 = instrument(visa_address='TCPIP::192.168.1.34::INSTR') >>> inst3 = instrument({'visa_address': 'TCPIP:192.168.1.35::INSTR'}) >>> inst4 = instrument(inst1)
-
instrumental.drivers.
list_instruments
(server=None, module=None)¶ Returns a list of info about available instruments.
May take a few seconds because it must poll hardware devices.
It actually returns a list of specialized dict objects that contain parameters needed to create an instance of the given instrument. You can then get the actual instrument by passing the dict to
instrument()
.>>> inst_list = get_instruments() >>> print(inst_list) [<NIDAQ 'Dev1'>, <TEKTRONIX 'TDS 3032'>, <TEKTRONIX 'AFG3021B'>] >>> inst = instrument(inst_list[0])
Parameters: server (str, optional) – The remote Instrumental server to query. It can be an alias from your instrumental.conf file, or a str of the form (hostname|ip-address)[:port]
, e.g. ‘192.168.1.10:12345’. Is None by default, meaning search on the local machine.
-
instrumental.drivers.
list_visa_instruments
()¶ Returns a list of info about available VISA instruments.
May take a few seconds because it must poll the network.
It actually returns a list of specialized dict objects that contain parameters needed to create an instance of the given instrument. You can then get the actual instrument by passing the dict to
instrument()
.>>> inst_list = get_visa_instruments() >>> print(inst_list) [<TEKTRONIX 'TDS 3032'>, <TEKTRONIX 'AFG3021B'>] >>> inst = instrument(inst_list[0])
Example¶
>>> from instrumental import instrument
>>> scope = instrument('my_scope_alias')
>>> x, y = scope.get_data()
Fitting¶
Module containing utilities related to fitting.
Still very much a work in progress...
-
instrumental.fitting.
curve_fit
(f, xdata, ydata, p0=None, sigma=None, **kw)¶ Wrapper for scipy’s curve_fit that works with pint Quantities.
-
instrumental.fitting.
guided_decay_fit
(data_x, data_y)¶ Guided fit of a ringdown. Takes data_x and data_y as
pint
Quantities with dimensions of time and voltage, respectively. Plots the data and asks user to manually crop to select the region to fit.It then does a rough linear fit to find initial parameters and performs a nonlinear fit.
Finally, it plots the data with the curve fit overlayed and returns the full-width at half-max (FWHM) with units.
-
instrumental.fitting.
guided_ringdown_fit
(data_x, data_y)¶ Guided fit of a ringdown. Takes data_x and data_y as
pint
Quantities with dimensions of time and voltage, respectively. Plots the data and asks user to manually crop to select the region to fit.It then does a rough linear fit to find initial parameters and performs a nonlinear fit.
Finally, it plots the data with the curve fit overlayed and returns the full-width at half-max (FWHM) with units.
-
instrumental.fitting.
guided_trace_fit
(data_x, data_y, EOM_freq)¶ Guided fit of a cavity scan trace that has sidebands. Takes data_x and data_y as
pint
Quantities, and the EOM frequency EOM_freq can be anything that thepint.Quantity
constructor understands, like an existingpint.Quantity
or a string, e.g.'5 Mhz'
.It plots the data then asks the user to identify the three maxima by by clicking on them in left-to-right order. It then uses that input to estimate and then do a nonlinear fit of the parameters.
Finally, it plots the data with the curve fit overlayed and returns the parameters in a map.
The parameters are
A0
,B0
,FWHM
,nu0
, anddnu
.
-
instrumental.fitting.
lorentzian
(x, A, x0, FWHM)¶ Lorentzian curve. Takes an array
x
and returns an array
-
instrumental.fitting.
triple_lorentzian
(nu, A0, B0, FWHM, nu0, dnu, y0)¶ Triple lorentzian curve. Takes an array
nu
and returns an array that is the sum of three lorentzianslorentzian(nu, A0, nu0, FWHM) + lorentzian(nu, B0, nu0-dnu, FWHM) + lorentzian(nu, B0, nu0+dnu, FWHM)
.
Plotting¶
Module that provides unit-aware plotting functions that can be used as a drop-in replacement for matplotlib.pyplot.
Also acts as a repository for useful plotting tools, like slider-plots.
-
instrumental.plotting.
param_plot
(x, func, params, **kwargs)¶ Plot a function with user-adjustable parameters.
Parameters: - x (array_like) – Independent (x-axis) variable.
- func (function) – Function that takes as its first argument an independent variable and
as subsequent arguments takes parameters. It should return an output
array the same dimension as
x
, which is plotted as the y-variable. - params (dict) – Dictionary whose keys are strings named exactly as the parameter
arguments to
func
are. [More info on options]
Returns: final_params – A dict whose keys are the same as
params
and whose values correspond to the values selected by the slider.final_params
will continue to change until the figure is closed, at which point it has the final parameter values the user chose. This is useful for hand-fitting curves.Return type:
-
instrumental.plotting.
plot
(*args, **kwargs)¶ Quantity-aware wrapper of pyplot.plot
-
instrumental.plotting.
xlabel
(s, *args, **kwargs)¶ Quantity-aware wrapper of pyplot.xlabel
Automatically adds parenthesized units to the end of
s
.
-
instrumental.plotting.
ylabel
(s, *args, **kwargs)¶ Quantity-aware wrapper of pyplot.ylabel.
Automatically adds parenthesized units to the end of
s
.
Tools¶
-
class
instrumental.tools.
DataSession
(name, meas_gen, overwrite=False)¶ A data-taking session.
Useful for organizing, saving, and live-plotting data while (automatically or manually) taking it.
-
__init__
(name, meas_gen, overwrite=False)¶ Create a DataSession.
Parameters: - name (str) – The name of the session. Used for naming the saved data file.
- meas_gen (generator) – A generator that, when iterated through, returns individual measurements as dicts. Each dict key is a string that is the name of what’s being measured, and its matching value is the corresponding quantity. Most often you’ll want to create this generator by writing a generator function.
- overwrite (bool) – If True, data with the same filename will be overwritten. Defaults to False.
-
create_plot
(vars, **kwargs)¶ Create a plot of the DataSession.
This plot is live-updated with data points as you take them.
Parameters: - vars (list of tuples) – vars to plot. Each tuple corresponds to a data series, with x-data, y-data, and optional format string. This is meant to be reminiscent of matplotlib’s plot function. The x and y data can each either be a string (representing the variable in the measurement dict with that name) or a function that takes kwargs with the name of those in the measurement dict and returns its computed value.
- **kwargs (keyword arguments) – used for formatting the plot. These are passed directly to the plot function. Useful for e.g. setting the linewidth.
-
save_summary
(overwrite=None)¶
-
start
()¶ Start collecting data.
This function blocks until all data has been collected.
-
-
instrumental.tools.
FSRs_from_mode_wavelengths
(wavelengths)¶
-
instrumental.tools.
diff
(unitful_array)¶
-
instrumental.tools.
do_ringdown_set
(set_name, base_dir=None)¶
-
instrumental.tools.
find_FSR
()¶
-
instrumental.tools.
fit_ringdown
(scope, channel=1, FSR=None)¶
-
instrumental.tools.
fit_ringdown_save
(subdir='', trace_num=0, base_dir=None)¶ Read a trace from the scope, save it and fit a ringdown curve.
Parameters:
-
instrumental.tools.
fit_scan
(EOM_freq, scope, channel=1)¶
-
instrumental.tools.
fit_scan_save
(EOM_freq, subdir='', trace_num=0, base_dir=None)¶
-
instrumental.tools.
get_photo_fnames
()¶
-
instrumental.tools.
load_data
(fname, delimiter='\t')¶
-
instrumental.tools.
qappend
(arr, values, axis=None)¶ Append values to the end of an array-valued Quantity.
Developer’s Guide¶
The Manifesto¶
A major goal of Instrumental is to try to unify and simplify a lot of common, useful operations. Essential to that is a consistent and coherent interface.
- Simple and common tasks should be simple to perform
- Provide options for more complex tasks
- Documentation is an essential, not a luxury
- Make units standard
Simple and common tasks should be simple to perform¶
Tasks that are conceptually simple or commonly performed should be made easy. This means having sane defaults.
Provide options for more complex tasks¶
Along with sane defaults, provide options. Often this means using optional parameters in functions and methods.
Documentation is an essential, not a luxury¶
Documentation can be hard or boring to provide, but without it your carefully constructed interfaces are rendered useless. In particular, all functions and methods should have brief summary sentences, detailed explanations, and descriptions of their parameters and return values.
This also includes providing useful error messages and warnings that the average user can actually understand and do something with.
Make units standard¶
Units in scientific code can be a big issue. Look no further than the commonly-cited Mars Climate Orbiter mishap. Instrumental incorporates unitful quantities using the very nice Pint module. While units are great, it can seem like extra work to start using them. Instrumental strives to use units everywhere to encourage their widespread use. Part of this is making units a joy to use with matplotlib.
Coding Conventions¶
As with most Python projects, you should be keeping in mind the style suggestions in PEP8. In particular:
- Use 4 spaces per indent (not tabs!)
- Classes should be named using
CapWords
capitalization - Functions and methods should be named using
lower_case_with_underscores
- As an exception, python wrapper (e.g. cffi/ctypes) code used as a _thin_ wrapper to an underlying library may stick with its naming convention for functions/methods. (See the docs for Attocube stages for an example of this)
- Modules and packages should have short, all-lowercase names, e.g.
drivers
- Use a
_leading_underscore
for non-public functions, methods, variables, etc. - Module-level constants are written in
ALL_CAPS
Strongly consider using a plugin for your text editor (e.g. vim-flake8) to check your PEP8 compliance.
It is OK to have lines over 80 characters, though they should almost always be 100 characters or less.
Docstrings¶
Code in Instrumental is primarily documented using python docstrings. Specifically, we follow the numpydoc conventions. In general, you should also follow the guidelines of pep 257.
- No spaces after the opening triple-quote
- One-line docstrings should be on a single line, e.g. “”“Does good stuff”“”
- Multi-liners have a summary line, followed by a blank line, followed by the rest of the doc. The closing quote should be on its own line
Python 2/3 Compatibility¶
Currently Instrumental is developed and tested using Python 2.7, with an eye towards Python 3 compatibility. The ultimate goal is to to have a code base that runs unmodified on Python 2 and 3. Moving straight to 3 would be nice, but there is still much code in the universe that has not yet been ported.
There are a number of backwards-incompatible changes that occurred, but perhaps the biggest and peskiest for Instrumental was the switchover to using unicode strings by default. This is probably the largest source of Python 3 incompatibility in the existing code.
Other notable changes include:
print
is now a function, no longer a statement- All division now uses “true” division (e.g.
3/4 == 0.75
). Use//
to denote integer division (e.g.3//4 == 0
)
To help alleviate these transition pains, you should use python’s built-in
__future__
module. E.g.:
>>> from __future__ import division, print_function, unicode_literals
Some useful links about Py2/3 compatibility¶
Developing Drivers¶
If you’re considering writing a driver, thank you! Check out Developing Drivers for details.