Instrument classes

class pymeasure.instruments.common_base.CommonBase(preprocess_reply=None, **kwargs)

Base class for instruments and channels.

This class contains everything needed for pymeasure’s property creator control() and its derivatives measurement() and setting().

Parameters

preprocess_reply

An optional callable used to preprocess strings received from the instrument. The callable returns the processed string.

Deprecated since version 0.11: Implement it in the instrument’s read method instead.

class BaseChannelCreator(cls, **kwargs)

Base class for ChannelCreator and MultiChannelCreator.

Parameters
  • cls – Class for all children or tuple/list of classes, one for each child.

  • **kwargs – Keyword arguments for all children.

class ChannelCreator(cls, id=None, **kwargs)

Add a single channel to the parent class.

The child will be added to the parent instance at instantiation with CommonBase.add_child(). The attribute name that ChannelCreator was assigned to in the Instrument class will be the name of the channel interface.

class Extreme5000(Instrument):
    # Two output channels, accessible by their property names
    # and both are accessible through the 'channels' collection
    output_A = Instrument.ChannelCreator(Extreme5000Channel, "A")
    output_B = Instrument.ChannelCreator(Extreme5000Channel, "B")
    # A channel without a channel accessible through the 'motor' collection
    motor = Instrument.ChannelCreator(MotorControl)

inst = SomeInstrument()
# Set the extreme_temp for channel A of Extreme5000 instrument
inst.output_A.extreme_temp = 42
Parameters
  • cls – Channel class for channel interface

  • id – The id of the channel on the instrument, integer or string.

  • **kwargs – Keyword arguments for all children.

class MultiChannelCreator(cls, id=None, prefix='ch_', **kwargs)

Add channels to the parent class.

The children will be added to the parent instance at instantiation with CommonBase.add_child(). The attribute name (e.g. channels) will be used as the collection of the children. You may define the attribute prefix. If there are no other pressing reasons, use channels as the attribute name and leave the prefix at the default "ch_".

class Extreme5000(Instrument):
    # Three channels of the same type: 'ch_A', 'ch_B', 'ch_C'
    # and add them to the 'channels' collection
    channels = Instrument.MultiChannelCreator(Extreme5000Channel, ["A", "B", "C"])
    # Two channel interfaces of different types: 'fn_power', 'fn_voltage'
    # and add them to the 'functions' collection
    functions = Instrument.MultiChannelCreator((PowerChannel, VoltageChannel),
                                    ["power", "voltage"], prefix="fn_")
Parameters
  • cls – Class for all children or tuple/list of classes, one for each child.

  • id – tuple/list of ids of the channels on the instrument.

  • prefix – Collection prefix for the attributes, e.g. “ch_” creates attribute self.ch_A. If prefix evaluates False, the child will be added directly under the variable name. Required if id is tuple/list.

  • **kwargs – Keyword arguments for all children.

add_child(cls, id=None, collection='channels', prefix='ch_', attr_name='', **kwargs)

Add a child to this instance and return its index in the children list.

The newly created child may be accessed either by the id in the children dictionary or by the created attribute, e.g. the fifth channel of instrument with id “F” has two access options: instrument.channels["F"] == instrument.ch_F

Note

Do not change the default collection or prefix parameter, unless you have to distinguish several collections of different children, e.g. different channel types (analog and digital).

Parameters
  • cls – Class of the channel.

  • id – Child id how it is used in communication, e.g. “A”.

  • collection – Name of the collection of children, used for dictionary access to the channel interfaces.

  • prefix – For creating multiple channel interfaces, the prefix e.g. “ch_” is prepended to the attribute name of the channel interface self.ch_A. If prefix evaluates False, the child will be added directly under the collection name.

  • attr_name – For creating a single channel interface, the attr_name argument is used when setting the attribute name of the channel interface.

  • **kwargs – Keyword arguments for the channel creator.

Returns

Instance of the created child.

ask(command, query_delay=0)

Write a command to the instrument and return the read response.

Parameters
  • command – Command string to be sent to the instrument.

  • query_delay – Delay between writing and reading in seconds.

Returns

String returned by the device without read_termination.

binary_values(command, query_delay=0, **kwargs)

Write a command to the instrument and return a numpy array of the binary data.

Parameters
  • command – Command to be sent to the instrument.

  • query_delay – Delay between writing and reading in seconds.

  • kwargs – Arguments for read_binary_values().

Returns

NumPy array of values.

check_errors()

Read all errors from the instrument and log them.

Returns

List of error entries.

check_get_errors()

Check for errors after having gotten a property and log them.

Called if check_get_errors=True is set for that property.

If you override this method, you may choose to raise an Exception for certain errors.

Returns

List of error entries.

check_set_errors()

Check for errors after having set a property and log them.

Called if check_set_errors=True is set for that property.

If you override this method, you may choose to raise an Exception for certain errors.

Returns

List of error entries.

static control(get_command, set_command, docs, validator=<function CommonBase.<lambda>>, values=(), map_values=False, get_process=<function CommonBase.<lambda>>, set_process=<function CommonBase.<lambda>>, command_process=None, check_set_errors=False, check_get_errors=False, dynamic=False, preprocess_reply=None, separator=', ', maxsplit=-1, cast=<class 'float'>, values_kwargs=None, **kwargs)

Return a property for the class based on the supplied commands. This property may be set and read from the instrument. See also measurement() and setting().

Parameters
  • get_command – A string command that asks for the value, set to None if get is not supported (see also setting()).

  • set_command – A string command that writes the value, set to None if set is not supported (see also measurement()).

  • docs – A docstring that will be included in the documentation

  • validator – A function that takes both a value and a group of valid values and returns a valid value, while it otherwise raises an exception

  • values – A list, tuple, range, or dictionary of valid values, that can be used as to map values if map_values is True.

  • map_values – A boolean flag that determines if the values should be interpreted as a map

  • get_process – A function that take a value and allows processing before value mapping, returning the processed value

  • set_process – A function that takes a value and allows processing before value mapping, returning the processed value

  • command_process

    A function that takes a command and allows processing before executing the command

    Deprecated since version 0.12: Use a dynamic property instead.

  • check_set_errors – Toggles checking errors after setting

  • check_get_errors – Toggles checking errors after getting

  • dynamic – Specify whether the property parameters are meant to be changed in instances or subclasses.

  • preprocess_reply – Optional callable used to preprocess the string received from the instrument, before splitting it. The callable returns the processed string.

  • separator – A separator character to split the string returned by the device into a list.

  • maxsplit – The string returned by the device is splitted at most maxsplit times. -1 (default) indicates no limit.

  • cast – A type to cast each element of the splitted string.

  • values_kwargs (dict) – Further keyword arguments for values().

  • **kwargs

    Keyword arguments for values().

    Deprecated since version 0.12: Use values_kwargs dictionary parameter instead.

Example of usage of dynamic parameter is as follows:

class GenericInstrument(Instrument):
    center_frequency = Instrument.control(
        ":SENS:FREQ:CENT?;", ":SENS:FREQ:CENT %e GHz;",
        " A floating point property that represents the frequency ... ",
        validator=strict_range,
        # Redefine this in subclasses to reflect actual instrument value:
        values=(1, 20),
        dynamic=True  # enable changing property parameters on-the-fly
    )

class SpecificInstrument(GenericInstrument):
    # Identical to GenericInstrument, except for frequency range
    # Override the "values" parameter of the "center_frequency" property
    center_frequency_values = (1, 10) # Redefined at subclass level

instrument = SpecificInstrument()
instrument.center_frequency_values = (1, 6e9) # Redefined at instance level

Warning

Unexpected side effects when using dynamic properties

Users must pay attention when using dynamic properties, since definition of class and/or instance attributes matching specific patterns could have unwanted side effect. The attribute name pattern property_param, where property is the name of the dynamic property (e.g. center_frequency in the example) and param is any of this method parameters name except dynamic and docs (e.g. values in the example) has to be considered reserved for dynamic property control.

static get_channel_pairs(cls)

Return a list of all the Instrument’s channel pairs

static get_channels(cls)

Return a list of all the Instrument’s ChannelCreator and MultiChannelCreator instances

static measurement(get_command, docs, values=(), map_values=None, get_process=<function CommonBase.<lambda>>, command_process=None, check_get_errors=False, dynamic=False, preprocess_reply=None, separator=', ', maxsplit=-1, cast=<class 'float'>, values_kwargs=None, **kwargs)

Return a property for the class based on the supplied commands. This is a measurement quantity that may only be read from the instrument, not set.

Parameters
  • get_command – A string command that asks for the value

  • docs – A docstring that will be included in the documentation

  • values – A list, tuple, range, or dictionary of valid values, that can be used as to map values if map_values is True.

  • map_values – A boolean flag that determines if the values should be interpreted as a map

  • get_process – A function that take a value and allows processing before value mapping, returning the processed value

  • command_process

    A function that take a command and allows processing before executing the command, for getting

    Deprecated since version 0.12: Use a dynamic property instead.

  • check_get_errors – Toggles checking errors after getting

  • dynamic – Specify whether the property parameters are meant to be changed in instances or subclasses. See control() for an usage example.

  • preprocess_reply – Optional callable used to preprocess the string received from the instrument, before splitting it. The callable returns the processed string.

  • separator – A separator character to split the string returned by the device into a list.

  • maxsplit – The string returned by the device is splitted at most maxsplit times. -1 (default) indicates no limit.

  • cast – A type to cast each element of the splitted string.

  • values_kwargs (dict) – Further keyword arguments for values().

  • **kwargs

    Keyword arguments for values().

    Deprecated since version 0.12: Use values_kwargs dictionary parameter instead.

remove_child(child)

Remove the child from the instrument and the corresponding collection.

Parameters

child – Instance of the child to delete.

static setting(set_command, docs, validator=<function CommonBase.<lambda>>, values=(), map_values=False, set_process=<function CommonBase.<lambda>>, check_set_errors=False, dynamic=False)

Return a property for the class based on the supplied commands. This property may be set, but raises an exception when being read from the instrument.

Parameters
  • set_command – A string command that writes the value

  • docs – A docstring that will be included in the documentation

  • validator – A function that takes both a value and a group of valid values and returns a valid value, while it otherwise raises an exception

  • values – A list, tuple, range, or dictionary of valid values, that can be used as to map values if map_values is True.

  • map_values – A boolean flag that determines if the values should be interpreted as a map

  • set_process – A function that takes a value and allows processing before value mapping, returning the processed value

  • check_set_errors – Toggles checking errors after setting

  • dynamic – Specify whether the property parameters are meant to be changed in instances or subclasses. See control() for an usage example.

values(command, separator=', ', cast=<class 'float'>, preprocess_reply=None, maxsplit=-1, **kwargs)

Write a command to the instrument and return a list of formatted values from the result.

Parameters
  • command – SCPI command to be sent to the instrument.

  • preprocess_reply – Optional callable used to preprocess the string received from the instrument, before splitting it. The callable returns the processed string.

  • separator – A separator character to split the string returned by the device into a list.

  • maxsplit – The string returned by the device is splitted at most maxsplit times. -1 (default) indicates no limit.

  • cast – A type to cast each element of the splitted string.

  • **kwargs – Keyword arguments to be passed to the ask() method.

Returns

A list of the desired type, or strings where the casting fails.

wait_for(query_delay=0)

Wait for some time. Used by ‘ask’ to wait before reading.

Implement in subclass!

Parameters

query_delay – Delay between writing and reading in seconds.

class pymeasure.instruments.Instrument(adapter, name, includeSCPI=None, preprocess_reply=None, **kwargs)

The base class for all Instrument definitions.

It makes use of one of the Adapter classes for communication with the connected hardware device. This decouples the instrument/command definition from the specific communication interface used.

When adapter is a string, this is taken as an appropriate resource name. Depending on your installed VISA library, this can be something simple like COM1 or ASRL2, or a more complicated VISA resource name defining the target of your connection.

When adapter is an integer, a GPIB resource name is created based on that. In either case a VISAAdapter is constructed based on that resource name. Keyword arguments can be used to further configure the connection.

Otherwise, the passed Adapter object is used and any keyword arguments are discarded.

This class defines basic SCPI commands by default. This can be disabled with includeSCPI for instruments not compatible with the standard SCPI commands.

Parameters
  • adapter – A string, integer, or Adapter subclass object

  • name (string) – The name of the instrument. Often the model designation by default.

  • includeSCPI

    An obligatory boolean, which toggles the inclusion of standard SCPI commands

    Deprecated since version 0.14: If True, inherit the SCPIMixin class instead.

  • preprocess_reply

    An optional callable used to preprocess strings received from the instrument. The callable returns the processed string.

    Deprecated since version 0.11: Implement it in the instrument’s read method instead.

  • **kwargs – In case adapter is a string or integer, additional arguments passed on to VISAAdapter (check there for details). Discarded otherwise.

check_errors()

Read all errors from the instrument and log them.

Returns

List of error entries.

check_get_errors()

Check for errors after having gotten a property and log them.

Called if check_get_errors=True is set for that property.

If you override this method, you may choose to raise an Exception for certain errors.

Returns

List of error entries.

check_set_errors()

Check for errors after having set a property and log them.

Called if check_set_errors=True is set for that property.

If you override this method, you may choose to raise an Exception for certain errors.

Returns

List of error entries.

clear()

Clears the instrument status byte

property complete

Get the synchronization bit.

This property allows synchronization between a controller and a device. The Operation Complete query places an ASCII character 1 into the device’s Output Queue when all pending selected device operations have been finished.

property id

Get the identification of the instrument.

property next_error

Get the next error of the instrument (tuple of code and message).

property options

Get the device options installed.

read(**kwargs)

Read up to (excluding) read_termination or the whole read buffer.

read_binary_values(**kwargs)

Read binary values from the device.

read_bytes(count, **kwargs)

Read a certain number of bytes from the instrument.

Parameters
  • count (int) – Number of bytes to read. A value of -1 indicates to read the whole read buffer.

  • kwargs – Keyword arguments for the adapter.

Returns bytes

Bytes response of the instrument (including termination).

reset()

Resets the instrument.

shutdown()

Brings the instrument to a safe and stable state

property status

Get the status byte and Master Summary Status bit.

wait_for(query_delay=0)

Wait for some time. Used by ‘ask’ to wait before reading.

Parameters

query_delay – Delay between writing and reading in seconds.

write(command, **kwargs)

Write a string command to the instrument appending write_termination.

Parameters
  • command – command string to be sent to the instrument

  • kwargs – Keyword arguments for the adapter.

write_binary_values(command, values, *args, **kwargs)

Write binary values to the device.

Parameters
  • command – Command to send.

  • values – The values to transmit.

  • **kwargs (*args,) – Further arguments to hand to the Adapter.

write_bytes(content, **kwargs)

Write the bytes content to the instrument.

class pymeasure.instruments.Channel(parent, id)

The base class for channel definitions.

This class supports dynamic properties like Instrument, but requires an Instrument instance as a parent for communication.

insert_id() inserts the channel id into the command string sent to the instrument. The default implementation replaces the Channel’s placeholder (default “ch”) with the channel id in all command strings (e.g. “CHANnel{ch}:foo”).

Parameters
  • parent – The instrument (an instance of Instrument) to which the channel belongs.

  • id – Identifier of the channel, as it is used for the communication.

check_errors()

Read all errors from the instrument and log them.

Returns

List of error entries.

check_get_errors()

Check for errors after having gotten a property and log them.

Called if check_get_errors=True is set for that property.

If you override this method, you may choose to raise an Exception for certain errors.

Returns

List of error entries.

check_set_errors()

Check for errors after having set a property and log them.

Called if check_set_errors=True is set for that property.

If you override this method, you may choose to raise an Exception for certain errors.

Returns

List of error entries.

insert_id(command)

Insert the channel id in a command replacing placeholder.

Subclass this method if you want to do something else, like always prepending the channel id.

read(**kwargs)

Read up to (excluding) read_termination or the whole read buffer.

read_binary_values(**kwargs)

Read binary values from the instrument.

read_bytes(count, **kwargs)

Read a certain number of bytes from the instrument.

Parameters
  • count (int) – Number of bytes to read. A value of -1 indicates to read the whole read buffer.

  • kwargs – Keyword arguments for the adapter.

Returns bytes

Bytes response of the instrument (including termination).

wait_for(query_delay=0)

Wait for some time. Used by ‘ask’ to wait before reading.

Parameters

query_delay – Delay between writing and reading in seconds.

write(command, **kwargs)

Write a string command to the instrument appending write_termination.

Parameters
  • command – command string to be sent to the instrument. ‘{ch}’ is replaced by the channel id.

  • kwargs – Keyword arguments for the adapter.

write_binary_values(command, values, *args, **kwargs)

Write binary values to the instrument.

Parameters
  • command – Command to send.

  • values – The values to transmit.

  • **kwargs (*args,) – Further arguments to hand to the Adapter.

write_bytes(content, **kwargs)

Write the bytes content to the instrument.

class pymeasure.instruments.fakes.FakeInstrument(adapter=None, name='Fake Instrument', includeSCPI=False, **kwargs)

Bases: Instrument

Provides a fake implementation of the Instrument class for testing purposes.

static control(get_command, set_command, docs, validator=<function FakeInstrument.<lambda>>, values=(), map_values=False, get_process=<function FakeInstrument.<lambda>>, set_process=<function FakeInstrument.<lambda>>, check_set_errors=False, check_get_errors=False, **kwargs)

Fake Instrument.control.

Strip commands and only store and return values indicated by format strings to mimic many simple commands. This is analogous how the tests in test_instrument are handled.

class pymeasure.instruments.fakes.SwissArmyFake(name='Mock instrument', wait=0.1, **kwargs)

Bases: FakeInstrument

Dummy instrument class useful for testing.

Like a Swiss Army knife, this class provides multi-tool functionality in the form of streams of multiple types of fake data. Data streams that can currently be generated by this class include ‘voltages’, sinusoidal ‘waveforms’, and mono channel ‘image data’.

property frame

Get a new image frame.

property frame_format

Control the format for image data returned from the get_frame() method. Allowed values are: mono_8: single channel 8-bit image. mono_16: single channel 16-bit image.

property frame_height

Control frame height in pixels.

property frame_width

Control frame width in pixels.

property output_voltage

Control the voltage.

property time

Control the elapsed time.

property voltage

Measure the voltage.

property wave

Measure a waveform.