diff --git a/README.rst b/README.rst index 6cc013b..15ab912 100644 --- a/README.rst +++ b/README.rst @@ -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 diff --git a/docs/source/user_guide.rst b/docs/source/user_guide.rst index cad1225..44840fd 100644 --- a/docs/source/user_guide.rst +++ b/docs/source/user_guide.rst @@ -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. diff --git a/docs/source/user_guide/waveform_output_use.rst b/docs/source/user_guide/waveform_output_use.rst new file mode 100644 index 0000000..6afd910 --- /dev/null +++ b/docs/source/user_guide/waveform_output_use.rst @@ -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. diff --git a/pyproject.toml b/pyproject.toml index a86a056..7e33461 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", ] diff --git a/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_Waveform.py b/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_Waveform.py new file mode 100644 index 0000000..83b4615 --- /dev/null +++ b/src/pymodaq_plugins_daqmx/daq_move_plugins/daq_move_NIDAQmx_Waveform.py @@ -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__) diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/system.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/system.py index ca07bdb..ed45a3e 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/system.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/system.py @@ -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 diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/timing.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/timing.py index c8dcbcf..5af5e00 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/timing.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/timing.py @@ -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, diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/waveform_player.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/waveform_player.py new file mode 100644 index 0000000..3d44290 --- /dev/null +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/waveform_player.py @@ -0,0 +1,106 @@ +"""Plays arrays of samples on several analog outputs of one NI device, with one task (one clock, one trigger).""" +from typing import Callable, Optional, Sequence + +import numpy as np +from pymodaq.utils.logger import get_module_name, set_logger +from pymodaq_plugins_utils.hardware.waveform_output import OutputMode + +from pymodaq_plugins_daqmx.hardware.national_instruments.api import ( + AOVoltage, AnalogOutputTask, ClockSettings, TaskConfig) +from pymodaq_plugins_daqmx.hardware.national_instruments.qt_task_bridge import QtTaskBridge + +logger = set_logger(get_module_name(__file__)) + + +class WaveformPlayer: + """The analog outputs ``channels`` (all of the same device: a NI task cannot span several), driven by one task. + + Between two waveforms (and before the first) the outputs are held at 0 V by a task without clock. A waveform is + played by a new task, the previous one being closed: there is no seamless update, the outputs go through 0 V + between two waveforms (the capability ``live_update`` of the plugin is False). When a finite waveform ends, its + task stays open so that the outputs keep the last sample until the next waveform, ``park`` or ``close``. + """ + + def __init__(self, channels: Sequence[AOVoltage]): + if not channels: + raise ValueError('no analog output chosen') + devices = {channel.name.partition('/')[0] for channel in channels} + if len(devices) > 1: + raise ValueError(f'the outputs of one task belong to one device, got {", ".join(sorted(devices))}') + self.channels = list(channels) + self.task: Optional[AnalogOutputTask] = None + self.bridge: Optional[QtTaskBridge] = None + self.playing = False # a waveform is being generated (a continuous one until stopped) + + @property + def n_channels(self) -> int: + return len(self.channels) + + def play(self, samples: np.ndarray, rate: float, mode: OutputMode, repetitions: int = 1, clock_source: str = '', + trigger=None, on_done: Optional[Callable[[int], None]] = None) -> None: + """Generate ``samples`` (volts, one row per channel) at ``rate`` Hz, in the ``mode`` of the output. + + ``on_done(status)`` is called, in the thread that calls ``play`` (it needs an event loop), when a finite + or repeated generation has ended: status 0, or the code of the driver error. It is not called for a + continuous generation. Must be called from the thread of the plugin. + """ + samples = np.asarray(samples, dtype=float) + if samples.ndim != 2 or samples.shape[0] != self.n_channels: + raise ValueError(f'{self.n_channels} channels: the samples should be shaped ({self.n_channels}, N), ' + f'got {samples.shape}') + mode = OutputMode(mode) + n = samples.shape[1] + if mode == OutputMode.FINITE: + data, timing = samples, ClockSettings(rate, samples=n, source=clock_source) + elif mode == OutputMode.REPEAT: + data = np.tile(samples, (1, int(repetitions))) + timing = ClockSettings(rate, samples=data.shape[1], source=clock_source) + else: # the driver repeats the buffer: its size is the signal + data, timing = samples, ClockSettings(rate, buffer=n, source=clock_source) + self._release() + task = AnalogOutputTask(TaskConfig(channels=self.channels, timing=timing, trigger=trigger)) + try: + task.write_analog(data) + if on_done is not None and mode != OutputMode.CONTINUOUS: + self.bridge = QtTaskBridge(task) + self.bridge.done.connect(lambda status: self._ended(status, on_done)) + task.start() + except Exception: + self._close_task(task) + self.bridge = None + raise + self.task, self.playing = task, True + + def _ended(self, status: int, on_done: Callable[[int], None]) -> None: + self.playing = False + on_done(status) + + def park(self) -> None: + """Stop what is played and hold every output at 0 V.""" + self._release() + self.task = AnalogOutputTask(TaskConfig(channels=self.channels)) + self.task.write_levels([0.] * self.n_channels) + + def close(self) -> None: + """Set the outputs to 0 V and release them (the channels are only this task's while it is open).""" + try: + self.park() + except Exception: # closing must go on: the channels have to be released + logger.warning('The outputs could not be set to 0 V', exc_info=True) + self._release() + + def _release(self) -> None: + self.playing = False + if self.bridge is not None: + self.bridge.close() + self.bridge = None + if self.task is not None: + self._close_task(self.task) + self.task = None + + @staticmethod + def _close_task(task: AnalogOutputTask) -> None: + try: + task.stop() + finally: + task.close() diff --git a/tests/api/test_system.py b/tests/api/test_system.py index 6e475ea..4839608 100644 --- a/tests/api/test_system.py +++ b/tests/api/test_system.py @@ -55,6 +55,8 @@ def test_maximum_rates_and_the_lack_of_one(system_driver): assert system.ai_max_rate('Dev2', multi_channel=False) == 2000000.0 assert system.ao_max_rate('Dev2') == pytest.approx(2857142.857) assert system.ao_max_rate('Dev1') is None # the PCI-6133 has no analog output + assert system.ao_min_rate('Dev2') == pytest.approx(0.1) + assert system.ao_min_rate('Dev1') is None def test_tells_whether_a_device_can_be_started_by_a_trigger(system_driver): @@ -62,6 +64,8 @@ def test_tells_whether_a_device_can_be_started_by_a_trigger(system_driver): assert system.supports_start_trigger('Dev2', ChannelKind.AI) is True assert system.supports_start_trigger('Dev2', ChannelKind.DI) is True + assert system.supports_start_trigger('Dev2', ChannelKind.AO) is True + assert system.supports_start_trigger('Dev1', ChannelKind.AO) is False assert system.supports_start_trigger('Dev1', ChannelKind.DI) is False diff --git a/tests/api/test_timing_and_triggers.py b/tests/api/test_timing_and_triggers.py index 3559159..f981987 100644 --- a/tests/api/test_timing_and_triggers.py +++ b/tests/api/test_timing_and_triggers.py @@ -31,7 +31,8 @@ def test_the_sample_clock_can_come_from_another_device(driver): @pytest.mark.parametrize('kwargs', [dict(rate=0., samples=10), dict(rate=-1., samples=10), - dict(rate=100., samples=0)]) + dict(rate=100., samples=0), dict(rate=100., samples=10, buffer=10), + dict(rate=100., buffer=0)]) def test_a_clock_that_cannot_run_is_refused(kwargs): with pytest.raises(ValueError): ClockSettings(**kwargs) @@ -66,6 +67,14 @@ def test_only_a_counter_has_a_terminal_of_pulses(): counter_output_terminal('Dev2/ao0') +def test_the_buffer_of_a_continuous_task_can_be_the_samples_to_repeat(driver): + task, nidaqmx_task = open_task(driver, timing=ClockSettings(rate=2000., buffer=50)) + + (call,) = nidaqmx_task.timing_calls + assert call[2]['sample_mode'] == AcquisitionType.CONTINUOUS + assert call[2]['samps_per_chan'] == 50 + + def test_without_a_number_of_samples_the_acquisition_is_continuous(driver): task, nidaqmx_task = open_task(driver, timing=ClockSettings(rate=2000.)) diff --git a/tests/nidaqmx_double.py b/tests/nidaqmx_double.py index 3b2bcdc..8b7fb42 100644 --- a/tests/nidaqmx_double.py +++ b/tests/nidaqmx_double.py @@ -320,6 +320,8 @@ def _get(self, key): ai_max_multi_chan_rate = property(lambda self: self._get('ai_max_multi')) ai_max_single_chan_rate = property(lambda self: self._get('ai_max_single')) ao_max_rate = property(lambda self: self._get('ao_max')) + ao_min_rate = property(lambda self: self._get('ao_min')) + ao_trig_usage = property(lambda self: self._get('ao_trig')) ai_trig_usage = property(lambda self: self._get('ai_trig')) ai_meas_types = property(lambda self: self._properties.get('ai_meas', [UsageTypeAI.VOLTAGE, UsageTypeAI.CURRENT])) di_trig_usage = property(lambda self: self._get('di_trig')) @@ -338,7 +340,8 @@ def _pcie_6363(): '/Dev2/ai/SampleClock', '/Dev2/ao/SampleClock', '/Dev2/ai/ConvertClock', '/Dev2/ctr0', '/Dev2/port0/line0'], ai_ranges=[(-0.1, 0.1), (-0.2, 0.2), (-0.5, 0.5), (-1.0, 1.0), (-2.0, 2.0), (-5.0, 5.0), (-10.0, 10.0)], ao_ranges=[(-5.0, 5.0), (-10.0, 10.0)], ai_max_multi=1000000.0, ai_max_single=2000000.0, - ao_max=2857142.8571428573, ai_trig=start_pause_reference, di_trig=start_pause_reference) + ao_max=2857142.8571428573, ao_min=0.1, # ao_min: a value of the tests, not recorded + ao_trig=[TriggerUsage.PAUSE, TriggerUsage.START], ai_trig=start_pause_reference, di_trig=start_pause_reference) def _pci_6133(): @@ -351,6 +354,8 @@ def _pci_6133(): ai_ranges=[(-1.25, 1.25), (-2.5, 2.5), (-5.0, 5.0), (-10.0, 10.0)], ao_ranges=[], ai_max_multi=2500000.0, ai_max_single=2500000.0, ao_max=nidaqmx.DaqError('Device does not support this property.', -200197), + ao_min=nidaqmx.DaqError('Device does not support this property.', -200197), + ao_trig=nidaqmx.DaqError('Device does not support this property.', -200197), ai_trig=[TriggerUsage.PAUSE, TriggerUsage.REFERENCE, TriggerUsage.START], di_trig=[]) diff --git a/tests/test_waveform_plugin.py b/tests/test_waveform_plugin.py new file mode 100644 index 0000000..a26fd28 --- /dev/null +++ b/tests/test_waveform_plugin.py @@ -0,0 +1,189 @@ +"""Behaviour of the waveform output actuator (several analog outputs, one task), with the driver doubled.""" +import types + +import numpy as np +import pytest + +pytest.importorskip('nidaqmx') +pytest.importorskip('pymodaq') +pytest.importorskip('pymodaq_plugins_utils') + +from nidaqmx.constants import AcquisitionType, Edge +from pymodaq.utils.data import DataActuator +from pymodaq.utils.plugin_testing import make_actuator +from pymodaq_plugins_utils.hardware.waveform_output import WaveformOutput + +from pymodaq_plugins_daqmx.daq_move_plugins.daq_move_NIDAQmx_Waveform import DAQ_Move_NIDAQmx_Waveform + +from nidaqmx_double import driver, system_driver # noqa: F401 (pytest fixtures) + +CHANNELS = ['Dev2/ao0', 'Dev2/ao1'] + + +def chosen(*names): + return dict(all_items=['Dev2/ao0', 'Dev2/ao1', 'Dev2/ao2', 'Dev2/ao3'], selected=list(names)) + + +@pytest.fixture +def plugin(qapp, driver, system_driver): + plugin = make_actuator(DAQ_Move_NIDAQmx_Waveform, channels=chosen(*CHANNELS)) + yield plugin + plugin.close() + + +def position(*rows): + return DataActuator(data=[np.asarray(row, dtype=float) for row in rows], units='V') + + +def waveform_tasks(driver, kind='ao_voltage'): + return [t for t in driver if t.channels and t.channels[0][0] == kind and t.timing_calls] + + +def set_output(plugin, **choices): + for name, value in choices.items(): + plugin.settings.child('waveform_output', name).setValue(value) + + +def test_the_outputs_are_offered_and_held_at_zero_at_start(plugin, driver): + assert 'Dev2/ao3' in plugin.settings['channels']['all_items'] + (task,) = [t for t in driver if t.channels] + assert [c[1] for c in task.channels] == CHANNELS and task.writes == [([[0.], [0.]], True)] + assert plugin.axis_unit == 'V' + + +def test_the_capabilities_follow_the_device_and_the_contract(plugin): + waveform_output = WaveformOutput.from_module(_Module(plugin)) + assert waveform_output.n_channels == 2 + assert (waveform_output.min_rate, waveform_output.max_rate) == (pytest.approx(0.1), pytest.approx(2857142.857)) + assert (waveform_output.min_voltage, waveform_output.max_voltage) == (-10., 10.) + assert [mode.value for mode in waveform_output.modes] == ['finite', 'repeat', 'continuous'] + assert '/Dev2/PFI0' in waveform_output.triggers and waveform_output.live_update is False + assert waveform_output.max_samples == 1000000 + + +class _Module: + """What an application has: a control module whose settings hold the ones of the plugin""" + _hw_settings_name = 'hw' + + def __init__(self, plugin): + self.settings = types.SimpleNamespace(child=lambda name: plugin.settings) + + +def test_a_finite_waveform_is_one_task_with_one_clock_for_all_the_outputs(plugin, driver): + set_output(plugin, sample_rate=1e4, mode='finite') + plugin.move_abs(position(np.linspace(0, 1, 100), np.linspace(1, 0, 100))) + + (task,) = waveform_tasks(driver) + assert [c[1] for c in task.channels] == CHANNELS + (call,) = task.timing_calls + assert call[1] == 1e4 and call[2]['sample_mode'] == AcquisitionType.FINITE and call[2]['samps_per_chan'] == 100 + data, auto_start = task.writes[-1] + assert np.array(data).shape == (2, 100) and auto_start is False + assert task.started and plugin.ispolling is False + assert [len(row) for row in plugin.get_actuator_value().data] == [100, 100] + + +def test_a_repeated_waveform_is_the_samples_several_times(plugin, driver): + set_output(plugin, sample_rate=1e4, mode='repeat', repetitions=3) + plugin.move_abs(position([0., 1., 2.], [3., 4., 5.])) + + (task,) = waveform_tasks(driver) + assert task.timing_calls[0][2]['samps_per_chan'] == 9 + assert np.array(task.writes[-1][0]).tolist() == [[0., 1., 2.] * 3, [3., 4., 5.] * 3] + + +def test_a_continuous_waveform_regenerates_a_buffer_of_its_size(plugin, driver): + set_output(plugin, sample_rate=1e4, mode='continuous') + plugin.move_abs(position(np.zeros(50), np.ones(50))) + + (task,) = waveform_tasks(driver) + call = task.timing_calls[0] + assert call[2]['sample_mode'] == AcquisitionType.CONTINUOUS and call[2]['samps_per_chan'] == 50 + + +def test_what_the_instrument_cannot_do_is_refused_with_a_reason_and_nothing_is_played(plugin, driver): + set_output(plugin, sample_rate=1e4) + with pytest.raises(ValueError, match='2 channels'): + plugin.move_abs(position(np.zeros(10))) + with pytest.raises(ValueError, match='V to 20 V'): + plugin.move_abs(position(np.full(10, 20.), np.zeros(10))) + set_output(plugin, sample_rate=1e8) + with pytest.raises(ValueError, match='Sample rate'): + plugin.move_abs(position(np.zeros(10), np.zeros(10))) + assert not waveform_tasks(driver) + + +def test_the_samples_are_cut_by_the_max_samples_setting_with_a_clear_error(plugin, driver): + plugin.settings.child('max_samples').setValue(20) + plugin.commit_settings(plugin.settings.child('max_samples')) # what the Dashboard does when a setting is edited + with pytest.raises(ValueError, match='at most 20'): + plugin.move_abs(position(np.zeros(30), np.zeros(30))) + + +def test_a_start_trigger_and_an_external_clock_are_given_to_the_task(plugin, driver): + plugin.settings.child('trigger').setValue('/Dev2/PFI0') + plugin.settings.child('trigger_edge').setValue('falling') + plugin.settings.child('clock_source').setValue('/Dev2/PFI1') + plugin.move_abs(position(np.zeros(10), np.zeros(10))) + + (task,) = waveform_tasks(driver) + assert task.trigger_calls == [('dig_edge', '/Dev2/PFI0', Edge.FALLING)] + assert task.timing_calls[0][2]['source'] == '/Dev2/PFI1' + + +def test_a_new_waveform_replaces_the_previous_one(plugin, driver): + plugin.move_abs(position(np.zeros(10), np.zeros(10))) + plugin.move_abs(position(np.ones(20), np.ones(20))) + + first, second = waveform_tasks(driver) + assert first.closed and not second.closed and second.timing_calls[0][2]['samps_per_chan'] == 20 + + +def test_the_end_of_a_finite_waveform_is_announced(plugin, driver, qtbot): + sent = [] + plugin.emit_status = lambda status: status.command != 'update_settings' and sent.append(status) + plugin.move_abs(position(np.zeros(10), np.zeros(10))) + (task,) = waveform_tasks(driver) + + task.fire_done(0) + + qtbot.waitUntil(lambda: any(s.command == 'generation_done' and s.attribute == 0 for s in sent), timeout=2000) + + +def test_a_continuous_waveform_has_no_end(plugin, driver, qtbot): + sent = [] + plugin.emit_status = lambda status: status.command != 'update_settings' and sent.append(status) + set_output(plugin, mode='continuous') + plugin.move_abs(position(np.zeros(10), np.zeros(10))) + (task,) = waveform_tasks(driver) + + task.fire_done(0) + qtbot.wait(200) + + assert not [status for status in sent if status.command == 'generation_done'] + + +def test_stop_and_close_bring_the_outputs_to_zero(plugin, driver): + plugin.move_abs(position(np.ones(10), np.ones(10))) + (played,) = waveform_tasks(driver) + + plugin.stop_motion() + + assert played.closed + holder = [t for t in driver if t.channels and not t.timing_calls][-1] + assert holder.writes[-1] == ([[0.], [0.]], True) and not holder.closed + plugin.close() + assert holder.closed + + +def test_a_choice_of_outputs_on_several_devices_or_none_is_refused(qapp, driver, system_driver): + with pytest.raises(ValueError, match='no analog output'): + make_actuator(DAQ_Move_NIDAQmx_Waveform, channels=chosen()) + with pytest.raises(ValueError, match='one device'): + make_actuator(DAQ_Move_NIDAQmx_Waveform, channels=dict(all_items=['Dev2/ao0', 'Dev1/ao0'], + selected=['Dev2/ao0', 'Dev1/ao0'])) + + +def test_a_relative_move_makes_no_sense_for_a_waveform(plugin): + with pytest.raises(ValueError, match='no relative move'): + plugin.move_rel(position(np.zeros(2), np.zeros(2)))