Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ Actuators

* **NIDAQmx**: One analog output (voltage / current) of a National Instrument device, set one point at a time
* **NIDAQmx_DO**: One digital output line (0 / 1, or a pulse to trigger an acquisition)
* **NIDAQmx_Waveform**: Waveforms (arrays of samples) played on several analog outputs of one device, with one clock; the
samples come from an application such as the waveform extension of ``pymodaq_plugins_waveform``
* **NIDAQmx_RampOutput**: A quantity driven by an analog output, changed by voltage ramps timed by a counter used as a
clock (value = voltage x conversion factor); several axes (x, y, z) can share the clock

Expand Down
1 change: 1 addition & 0 deletions docs/source/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ This user guide will first explain how to use these plugins, and then detail how
user_guide/ramp_output_use
user_guide/nidaqmx_viewer_use
user_guide/nidaqmx_actuator_use
user_guide/waveform_output_use
user_guide/config_files

For any other use, you will need to create your own move or viewer based on this plugin. See the :ref:`create_plugin` guide for a detailed procedure.
Expand Down
52 changes: 52 additions & 0 deletions docs/source/user_guide/waveform_output_use.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
Waveform output NIDAQmx_Waveform
================================

The actuator ``NIDAQmx_Waveform`` (``DAQ_Move_NIDAQmx_Waveform``) plays **waveforms**, arrays of samples, on several
analog outputs of one NI device at once. The outputs are driven by one task, so they share a sample clock and start
together. For one output set a level at a time, see ``NIDAQmx``; for voltage ramps timed by a counter, see
``NIDAQmx_RampOutput``.

The position of the actuator is a ``DataActuator`` holding one array of samples (in volts) for each chosen output, all
of the same length. The arrays are given in the order of the chosen outputs. The plugin follows the contract of
``pymodaq_plugins_utils.hardware.waveform_output``: the applications that design waveforms, such as the extension of
``pymodaq_plugins_waveform``, read what this device can do and check what they send before they send it.

How to use it
-------------

1. Choose the **Outputs** (the analog outputs of one device, ticked in the list) and their range (**Min**, **Max**).
Outputs of several devices cannot be in one task: the plugin refuses them. Change them while the actuator runs and
the outputs go to 0 V before the new ones are driven.
2. In **Waveform output** choose the **Sample rate**, the **Mode** and the number of **Repetitions**:

* ``finite``: the samples are generated once;
* ``repeat``: the samples are generated *Repetitions* times;
* ``continuous``: the samples are generated again and again until the actuator is stopped. The driver repeats the
samples that were written, so the waveform should hold a whole number of periods.

3. Optionally give an external **Sample clock** (a terminal such as ``/Dev1/PFI1``) and a **Start trigger** (a PFI
terminal and its edge): the generation then waits for the edge. Without trigger it starts at once.
4. Move the actuator to the samples.

The move is done when the generation has started. The end of a finite or repeated generation is announced by the status
command ``generation_done`` (0 if all went well, else the code of the driver error). The outputs are at 0 V when the
actuator starts, after **stop** and when it closes. When a finite waveform ends, the outputs keep its last sample until
the next waveform or the stop.

Limits
------

The settings group **Waveform capabilities** (read only) shows what the plugin tells to the applications: the
number of outputs, the range of sample rates (``ao_min_rate`` and ``ao_max_rate`` of the device), the voltage range
(the intersection of **Min**, **Max** and the ranges of the device), the modes, the PFI terminals if the device accepts a
start trigger, and **Max samples**.

* The device may be slower than its ``ao_max_rate`` when several outputs are used (some modules share their converter
between outputs): the driver then refuses the rate and its message is shown.
* **Max samples** is a limit of the plugin (samples per output, to protect the memory), not a figure of the device.
Set it as you need; a longer waveform is refused with a message.
* A new waveform replaces the one being played **with a break**: the outputs go through 0 V in between
(``live_update`` is False). To change a waveform without a break, a device that can update its buffer on the fly is
needed.
* The samples are written to the buffer of the driver before the generation starts: there is no streaming of waveforms
longer than the buffer.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ dependencies = [
"pymodaq_utils>=5.3.1",
"pymodaq_gui>=5.3.0",
"pymodaq_data>=5.3.0",
"pymodaq_plugins_utils>=5.3.6",
"nidaqmx",
"aenum",
]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
"""Several analog outputs of a NI device playing waveforms (arrays of samples), from one task with one clock.

The position of the actuator is a ``DataActuator`` holding one array of samples (volts) per chosen output, all of the
same length. The sample rate, the mode (finite, repeated, continuous) and the repetitions are the ``Waveform output``
settings of the plugin, which also lists what the device can do (``Waveform capabilities``): they follow the contract
of ``pymodaq_plugins_utils.hardware.waveform_output``, so the applications that design waveforms (the Dashboard
extension of ``pymodaq_plugins_waveform``) can send to this actuator and check what they send.

The move is done once the generation has started. The end of a finite or repeated generation is announced with the
status command ``generation_done`` (its value is the status of the driver, 0 if all went well). A new waveform replaces
the one being played with a break: the outputs go through 0 V in between (``live_update`` is False). The outputs are at
0 V at the start, after ``stop`` and at the close.
"""
import numpy as np
from nidaqmx.constants import Edge
from pymodaq.control_modules.move_utility_classes import (DAQ_Move_base, DataActuator, DataActuatorType,
comon_parameters_fun, main)
from pymodaq.utils.daq_utils import ThreadCommand
from pymodaq_data import Q_
from pymodaq_plugins_utils.hardware.waveform_output import (CAPABILITIES_NAME, OUTPUT_NAME, OutputMode,
WaveformOutput, fill_waveform_output_settings,
waveform_output_params)

from pymodaq_plugins_daqmx.hardware.national_instruments.api import (
AOVoltage, ChannelKind, DigitalEdgeTrigger, NIDAQSystem)
from pymodaq_plugins_daqmx.hardware.national_instruments.waveform_player import WaveformPlayer

NO_TRIGGER = 'none'
EDGES = {'rising': Edge.RISING, 'falling': Edge.FALLING}


class DAQ_Move_NIDAQmx_Waveform(DAQ_Move_base):
"""Analog outputs of one NI device that play waveforms, started on demand or on a trigger."""
is_multiaxes = False
_axis_names = ['waveform']
_controller_units = 'V'
_epsilons = [1e-3]
data_actuator_type = DataActuatorType.DataActuator
has_encoder = False # an output cannot be read back: the move is done once the samples are playing
rebuild_on = ('channels', 'min_val', 'max_val', 'max_samples', 'trigger', 'trigger_edge')
params = [
{'title': 'Outputs:', 'name': 'channels', 'type': 'itemselect', 'checkbox': True,
'value': dict(all_items=[], selected=[]),
'tip': 'Analog outputs played together, all of the same device. The waveforms are given in this order'},
{'title': 'Min:', 'name': 'min_val', 'type': 'float', 'value': -10., 'suffix': 'V',
'tip': 'Lowest voltage of the outputs'},
{'title': 'Max:', 'name': 'max_val', 'type': 'float', 'value': 10., 'suffix': 'V'},
{'title': 'Sample clock:', 'name': 'clock_source', 'type': 'str', 'value': '',
'tip': 'Terminal of an external sample clock such as /Dev1/PFI1. Empty: the clock of the device'},
{'title': 'Start trigger:', 'name': 'trigger', 'type': 'list', 'limits': [NO_TRIGGER], 'value': NO_TRIGGER,
'tip': 'Terminal whose edge starts the generation, or none to start it at once'},
{'title': 'Trigger edge:', 'name': 'trigger_edge', 'type': 'list', 'limits': list(EDGES),
'value': 'rising'},
{'title': 'Max samples:', 'name': 'max_samples', 'type': 'int', 'value': 1000000, 'min': 2,
'tip': 'Samples per output accepted by the actuator: a limit of the plugin to protect the memory, '
'not a figure of the device'},
] + waveform_output_params() + comon_parameters_fun(False, axis_names=_axis_names, epsilon=_epsilons)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings.child('channels').setValue(dict(all_items=NIDAQSystem().all_channels(ChannelKind.AO),
selected=[]))

def ini_attributes(self):
self.controller: WaveformPlayer = None
self.last_samples = None # what was sent last, as the position

# --- settings ----------------------------------------------------------------------------------------------

@property
def channel_names(self) -> list:
return list(self.settings['channels']['selected'])

def _device_limits(self, device: str) -> tuple:
"""The range of voltages, and the lowest and highest rates that the outputs of the device can do"""
system = NIDAQSystem()
ranges = system.ao_voltage_ranges(device)
low = min((r[0] for r in ranges), default=self.settings['min_val'])
high = max((r[1] for r in ranges), default=self.settings['max_val'])
return low, high, system.ao_min_rate(device) or 0., system.ao_max_rate(device) or 0.

def _fill_capabilities(self, device: str) -> None:
system = NIDAQSystem()
low, high, min_rate, max_rate = self._device_limits(device)
triggers = [t for t in system.terminals(device) if 'PFI' in t] \
if system.supports_start_trigger(device, ChannelKind.AO) else []
self.settings.child('trigger').setLimits([NO_TRIGGER] + triggers)
fill_waveform_output_settings(
self.settings, n_channels=len(self.channel_names), min_rate=min_rate, max_rate=max_rate,
max_samples=self.settings['max_samples'], min_voltage=max(low, self.settings['min_val']),
max_voltage=min(high, self.settings['max_val']),
modes=[OutputMode.FINITE, OutputMode.REPEAT, OutputMode.CONTINUOUS], triggers=triggers,
live_update=False)

def _make_player(self) -> WaveformPlayer:
channels = [AOVoltage(name, self.settings['min_val'], self.settings['max_val'])
for name in self.channel_names]
player = WaveformPlayer(channels) # refuses no output and outputs of several devices
self._fill_capabilities(channels[0].name.partition('/')[0])
player.park()
self.last_samples = [np.zeros(1) for _ in channels]
return player

# --- the actuator ------------------------------------------------------------------------------------------

def ini_stage(self, controller=None):
self.controller = self._make_player()
return 'NI waveform output ready', True

def close(self):
if self.controller is not None:
self.controller.close()
self.controller = None

def commit_settings(self, param):
if param.name() in self.rebuild_on and self.controller is not None:
self.controller.close()
self.controller = self._make_player()

def get_actuator_value(self) -> DataActuator:
return DataActuator(data=[np.array(channel) for channel in self.last_samples], units='V')

def _volts(self, value: DataActuator) -> np.ndarray:
"""The samples of a position in volts, one row per output"""
factor = Q_(1, value.units).m_as('V') if value.units else 1.
return np.array([np.asarray(channel, dtype=float) * factor for channel in value.data])

def move_abs(self, value: DataActuator):
try:
samples = self._volts(value)
capabilities, output = (self.settings.child(name) for name in (CAPABILITIES_NAME, OUTPUT_NAME))
WaveformOutput.from_settings(capabilities, output).check(samples)
trigger = None
if self.settings['trigger'] != NO_TRIGGER:
trigger = DigitalEdgeTrigger(self.settings['trigger'], EDGES[self.settings['trigger_edge']])
self.controller.play(samples, output['sample_rate'], OutputMode(output['mode']), output['repetitions'],
self.settings['clock_source'], trigger,
on_done=lambda status: self.emit_status(ThreadCommand('generation_done', status)))
except Exception as error: # the move cannot be done: tell it, a move_done would claim a success
self.emit_status(ThreadCommand('Update_Status', [f'The waveform was not played: {error}', 'log']))
raise
self.last_samples = list(samples)
self.target_value = value
self.ispolling = False # the move is done once the generation has started: no polling (set for each move)

def move_rel(self, value: DataActuator):
raise ValueError('a waveform has no relative move: send the samples with an absolute move')

def move_home(self):
self.stop_motion()

def stop_motion(self):
"""Stop the generation and bring the outputs to 0 V"""
if self.controller is not None:
self.controller.park()


if __name__ == '__main__':
main(__file__)
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,14 @@ def ao_max_rate(self, device):
"""Maximum update rate (Hz) of the analog outputs; ``None`` if the device has none."""
return self._device_property(device, 'ao_max_rate', float, None)

def ao_min_rate(self, device):
"""Minimum update rate (Hz) of the analog outputs; ``None`` if the device has none."""
return self._device_property(device, 'ao_min_rate', float, None)

def supports_start_trigger(self, device, kind):
"""Whether a ``kind`` (``ChannelKind.AI`` or ``ChannelKind.DI``) task on ``device`` can wait for a start trigger."""
if kind not in (ChannelKind.AI, ChannelKind.DI):
raise ValueError(f"unknown kind {kind!r}: triggers are supported by AI and DI tasks")
"""Whether a ``kind`` (``ChannelKind.AI``, ``AO`` or ``DI``) task on ``device`` can wait for a start trigger."""
if kind not in (ChannelKind.AI, ChannelKind.AO, ChannelKind.DI):
raise ValueError(f"unknown kind {kind!r}: triggers are supported by AI, AO and DI tasks")
usage = self._device_property(device, f'{kind}_trig_usage', list, [])
return TriggerUsage.START in usage

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,30 @@ class ClockSettings:
``source`` is a terminal such as ``/Dev1/PFI1`` to use an external clock; empty means the onboard clock.
A continuous acquisition (no ``samples``) is read through ``on_samples_ready`` (``start(notify_every=n)``),
with a driver buffer holding at least one second of data.

``buffer`` is the number of samples per channel of the driver buffer of a continuous task. Leave it to None for
an acquisition. For a generation that repeats the samples of its buffer (analog output), give the number of samples
of the signal: the driver then regenerates exactly these samples again and again.
"""
rate: float
samples: Optional[int] = None
source: str = ''
edge: Edge = Edge.RISING
buffer: Optional[int] = None

def __post_init__(self):
if not self.rate > 0:
raise ValueError(f'rate must be positive, got {self.rate}')
if self.samples is not None and not self.samples >= 1:
raise ValueError(f'samples must be at least 1, got {self.samples}')
if self.buffer is not None and (self.samples is not None or not self.buffer >= 1):
raise ValueError(f'buffer is the size of the buffer of a continuous task (no samples), at least 1, '
f'got samples={self.samples}, buffer={self.buffer}')

def apply_to(self, task):
if self.samples is None:
mode, per_channel = AcquisitionType.CONTINUOUS, max(1000, int(self.rate))
mode = AcquisitionType.CONTINUOUS
per_channel = max(1000, int(self.rate)) if self.buffer is None else self.buffer
else:
mode, per_channel = AcquisitionType.FINITE, self.samples
task.timing.cfg_samp_clk_timing(self.rate, source=self.source, active_edge=self.edge,
Expand Down
Loading
Loading