Pysweepme

From SweepMe! Wiki
Jump to navigation Jump to search

pysweepme is the open-source Python package that exposes parts of SweepMe! as an MIT-licensed library. It lets you load SweepMe! instrument drivers (formerly called "Device Classes") in your own Python scripts, open the required communication ports, and reuse SweepMe!'s folder and logging helpers, all without running the SweepMe! application.

The source code is hosted on the pysweepme GitHub repository.

Introduction

SweepMe! communicates with instruments through drivers that are small, self-contained Python code snippets. With pysweepme you can import those same drivers into an independent project and drive an instrument directly from Python. The package bundles the parts of SweepMe! that the drivers rely on:

  • DeviceManager: loads a driver and returns a ready-to-use instance (get_driver); see below.
  • EmptyDeviceClass: the base class of every driver, defining the semantic standard functions; see below.
  • FolderManager: resolves the standard SweepMe! folders and manages the driver library search path; documented on Folder system.
  • PortManager / Ports: create and manage interface ports (COM, GPIB, USBTMC, TCPIP, SOCKET, ...); documented on Port manager and Supported ports.
  • ErrorMessage: the debug and error logging helpers; see below and Debugging.

Installation

pysweepme is published on PyPI and is installed with pip from the command line (cmd):

:: install
pip install pysweepme

:: upgrade
pip install pysweepme --upgrade

So far, only Windows is fully supported. Other operating systems might work, but some modifications are usually needed (several drivers rely on Windows DLLs or Windows-only third-party packages).

Python version and environment

We recommend Python 3.14, 64-bit together with pysweepme 1.6.1.x, because this is the Python version targeted by SweepMe! 1.6 and by the dependencies bundled in the instrument-driver repository. If you work with SweepMe! 1.5.x, use Python 3.9, 64-bit and pysweepme 1.5.8.x.

pysweepme only declares the packages that pysweepme itself needs. Many SweepMe! drivers use additional Python packages:

  • Packages that are part of SweepMe! but not shipped with pysweepme have to be installed with pip by resolving the resulting ImportErrors. The full package list is the requirements.txt in the libs folder of your SweepMe! installation (it also includes pysweepme itself).
  • Packages that are not part of SweepMe!'s requirements.txt are typically shipped inside the driver folder (see External libraries and dependencies).

Version numbering

The version number of pysweepme correlates with the version number of SweepMe!. For example, pysweepme 1.6.1.x relates to SweepMe! 1.6.1.x, although the last digit of the version number can differ. The list of changes is available on the releases page on GitHub.

Getting started

The typical workflow is: copy the driver into your project, load it with get_driver, connect, and start communicating.

  1. Copy the driver(s) into a folder of your project, e.g. Devices, or use the public CustomDevices folder of a SweepMe! installation.
  2. Import pysweepme.
  3. Load a driver with get_driver.
  4. Look at the driver source code to see which communication commands are available, or call pysweepme.commands.describe_commands(driver) (see below). A general overview of the semantic functions of a driver is given on the Sequencer procedure page.
import pysweepme

# Retrieve the path to SweepMe!'s public CustomDevices directory (optional)
custom_devices_folder = pysweepme.get_path("CUSTOMDEVICES")

# folder      : path from which the instrument driver will be loaded
# port_string : resource string of the port, e.g. "COM1" or "GPIB0::24::INSTR"
mouse = pysweepme.get_driver("Logger-PC_Mouse", folder=".", port_string="")

mouse.connect()
print(mouse.read())

Loading drivers: get_driver / DeviceManager

The central entry point is pysweepme.get_driver (implemented in the DeviceManager submodule). It loads the driver module, instantiates its Device class, sets the default parameters, and, if the driver uses the port manager and a port_string is given, opens the port and attaches it to the driver.

driver = pysweepme.get_driver(name, folder=None, port_string="")
Argument Description
name Name of the driver, which is the name of the driver folder (e.g. SMU-Keithley_2400).
folder (optional) Folder in which to look for the driver. If the argument is not given (None), the driver version that is selected in the Version Manager of the matching SweepMe! version is loaded (pysweepme 1.6.1.3 or newer). If it is an empty string, the driver is loaded from the current working directory. In pysweepme 1.5.8.x, the default is ".", i.e. the current working directory, and there is no Version Manager lookup.
port_string (optional) A port resource name as used in SweepMe!, e.g. COM1, GPIB0::1::INSTR. Required when the driver connects to an instrument via the port manager.

The returned object is an instance of the driver's Device class (a subclass of EmptyDevice, see below). You must always call connect() yourself, even when the port was already opened by get_driver.

Lower-level helpers are available in the DeviceManager submodule if you need finer control:

from pysweepme import DeviceManager

module = DeviceManager.get_driver_module(folder, name)    # loads the .py module
cls    = DeviceManager.get_driver_class(folder, name)     # returns the Device class
driver = DeviceManager.get_driver_instance(folder, name)  # bare instance, no parameters set

The EmptyDevice class

Every driver's Device class inherits from EmptyDevice (submodule EmptyDeviceClass, also exposed as pysweepme.EmptyDevice). A driver implements a set of semantic standard functions that SweepMe! calls in a defined order during a measurement. In your own scripts you can either call these functions directly or use the convenience wrappers.

Semantic standard functions

Drivers override the functions that are relevant for the instrument. The main ones, in call order, are: connect, initialize, configure, poweron, signin, start, apply, reach, adapt, adapt_ready, trigger_ready, measure, request_result, read_result, process_data, call, finish, signout, poweroff, unconfigure, deinitialize, disconnect. A full description is given on the Sequencer procedure page. The semantic functions call the communication commands of the driver, one public method per command of the instrument (e.g. set_voltage, get_voltage), which a script can call as well. Drivers converted to the Driver API declare these commands with @command (see below); older drivers offer plain methods, and some only the semantic functions.

Convenience functions for pysweepme

For quick use from a script, EmptyDevice offers convenience wrappers that call several semantic functions in one step:

Function Description
driver.connect() Open the communication. Always call this, even when the port was opened by get_driver.
driver.disconnect() Close the communication.
driver.write(value) Apply value as a new sweep value: calls start, apply_value and reach.
driver.apply_value(value) Set self.value and call apply.
driver.read() Run the measurement chain (adapt → measure → ... → call) and return a list of values.
driver.get_variables() / driver.get_units() Names and units of the returned values.
driver.get_variables_units() Mapping of variable name to unit.
driver.set_parameters(dict) / driver.get_parameters() Set/read the GUI parameters of the driver.
driver.set_port(port) / driver.get_port() Attach or read the port object.

A minimal source-meter example:

import pysweepme

smu = pysweepme.get_driver("SMU-Keithley_2400", folder=".", port_string="GPIB0::24::INSTR")
smu.set_parameters({
    "SweepMode": "Voltage in V",
    "Compliance": 0.1,
})
try:
    smu.connect()
    smu.initialize()
    smu.configure()
    smu.poweron()

    for voltage in [0.0, 0.5, 1.0]:
        smu.write(voltage)          # apply the value
        print(smu.read())           # measure and read back
finally:
    smu.poweroff()
    smu.unconfigure()
    smu.deinitialize()
    smu.disconnect()
    pysweepme.close_port(smu.get_port())  # the port that get_driver opened for this driver

The finally block brings the instrument back to a safe state even if the script fails. The port that get_driver opened is closed by the script, not by the driver; when several drivers share one port (channels of one instrument), close it once after the last of them disconnected.

Note: The available parameters and communication commands differ per driver. Check the driver source code (the main.py of the driver folder) for the exact parameter names and functions, or call describe_commands as described below.

Communication commands: pysweepme.commands

pysweepme 1.6.1.4 or newer; complete with pysweepme 1.6.1.5, which SweepMe! 1.6.1.9 ships.

The submodule pysweepme.commands is the Driver API: a driver declares its communication commands with the decorator @command and the markers Unit, Label, Range, Selector and Elements in standard Python annotations. Every call of a declared command is checked against the declaration, whoever calls it, and a value outside the declared choices or range raises a ValueError that names the command, the parameter and what is allowed. A command raises {{{1}}} when the instrument or its library answers an error code.

describe_commands(driver) returns one CommandSpec per command, with its name, description, kind (set, read or run), parameters with type, choices, unit, label, range and selector, and the quantities it answers. This is what SweepMe! and its Instrument Control tool read; a script can use it to see what a driver offers:

from pysweepme.commands import describe_commands

for spec in describe_commands(smu):
    print(spec.name, spec.kind, [p.name for p in spec.parameters])

How to write and declare commands is described in section 7 of the driver guide and on Driver Programming.


Use with CustomFunction

You can use pysweepme to load drivers in scripts for the Pro module CustomFunction. This allows you to run specialized measurement tasks where for example multiple driver tightly interact with each other. In this case, you can use the get_driver method without any folder argument. pysweepme then loads the driver from the origin selected in the SweepMe! Version Manager.

Loading a driver without a folder argument from the Version Manager selection requires SweepMe! 1.6.1.6 or newer (pysweepme 1.6.1.3). In SweepMe! 1.5.x, pass the folder explicitly, e.g. pysweepme.get_path("CUSTOMDEVICES").

import pysweepme
smu = pysweepme.get_driver("SMU-Keithley_2400", port_string="GPIB0::24::INSTR")


Logging

The ErrorMessage submodule provides the logging helpers used throughout SweepMe! and its drivers. They are also exposed at the top level:

import pysweepme

pysweepme.debug("connection established")             # timestamped message
pysweepme.debug("verbose only", debugmode_only=True)  # printed only in debug mode

try:
    ...
except Exception:
    pysweepme.error("reading failed")   # message + full traceback
Function Description
debug(*args, debugmode_only=False) Print a timestamped message. With debugmode_only=True the message is only printed when debug mode is on (environment variable SWEEPME_DEBUGMODE set to "True").
error(*args) Print the message together with the traceback of the most recent exception.

When running standalone, these functions print to the console (standard output) instead of the SweepMe! debug log. See Debugging for more on the SweepMe! debug output.

Submodules

The submodules for folders and ports are shared with SweepMe! and are documented on their own pages so the information stays in one place:

  • Folders: use the FolderManager submodule to resolve SweepMe!'s standard folders (pysweepme.get_path / set_path) and to add a driver's library folder to the search path (addFolderToPATH). See Folder system.
  • Ports: open and use interface ports standalone with pysweepme.get_port / close_port, or via the PortManager instance. See Port manager for usage and port properties, and Supported ports for port types and troubleshooting.

pysweepme versus SweepMe!

pysweepme reuses SweepMe! code, but a few behaviours differ when running standalone:

  • Folder keys derived from MAIN point at your script's folder, not a SweepMe! installation (see Folder system).
  • debug and error print to the console instead of the SweepMe! debug log.
  • Some drivers require additional Python packages or Windows-only components that are shipped with SweepMe! but not with pysweepme.
  • Drivers that do not wrap their communication commands into methods can still be loaded, but only their semantic functions are available.

See also

Source code and support