diff --git a/AGENTS.md b/AGENTS.md index 8d6ed9b..1f75542 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ Guidance for AI coding assistants (and humans) building on **PyMoDAQ 5.3.x** from this template. PyMoDAQ is a Qt framework that drives lab experiments: hardware is added through small *plugins*, and PyMoDAQ -provides the GUI, threading, data model, scans and HDF5 saving. Python 3.10 to 3.13. +provides the GUI, threading, data model, scans and HDF5 saving. Python 3.11 to 3.14. This repository is a plugin package named `pymodaq_plugins_`. Rename everything that still says `template` before publishing. diff --git a/README.rst b/README.rst index 3292f82..4a2b8e4 100644 --- a/README.rst +++ b/README.rst @@ -20,14 +20,33 @@ pymodaq_plugins_waveform Design waveforms and send them to the analog outputs and arbitrary waveform generators of the Dashboard. -This package holds the Dashboard extension that builds a waveform from the factory of ``pymodaq_plugins_utils`` -(sine, square, triangle, ramp, pulse, piecewise linear, array...), shows it, and sends it to any actuator whose plugin -follows the waveform output contract of ``pymodaq_plugins_utils.hardware.waveform_output`` (NI-DAQmx analog outputs, -Red Pitaya...). It is under development: nothing is released yet. - -This branch targets **PyMoDAQ 5.3.x** (Python 3.10 to 3.13). - Authors ======= * Sebastien Weber + +Instruments +=========== + +Actuators ++++++++++ + +* **WaveformParameter**: virtual actuator, created by the Waveform designer extension, that a scan moves to change one + parameter of a waveform. + +Extensions +++++++++++ + +* **Waveform designer**: builds one waveform per channel, shows them, and sends them to any actuator whose plugin + follows the waveform output contract of ``pymodaq_plugins_utils.hardware.waveform_output`` (NI-DAQmx analog outputs, + Red Pitaya...). Sets of waveforms can be saved by name. + +The package also holds the factory of waveforms (sine, square, triangle, ramp, pulse, piecewise linear, file...). +It is under development: nothing is released yet. + +Requirements +============ + +This package needs **PyMoDAQ 5.4** (``pymodaq``, ``pymodaq_gui``, ``pymodaq_data`` ``>=5.4.0a0``) and Python 3.11 to +3.14: the virtual actuator relies on ``move_failed_signal`` of the actuator modules, only in PyMoDAQ 5.4. Until 5.4.0 is +released, install the alpha (``pip install --pre pymodaq``). diff --git a/pyproject.toml b/pyproject.toml index 933e64f..a927e3b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [features] # defines the plugin features contained into this plugin -instruments = false # true if plugin contains instrument classes (else false, notice the lowercase for toml files) -extensions = false # true if plugins contains dashboard extensions +instruments = true # true if plugin contains instrument classes (else false, notice the lowercase for toml files) +extensions = true # true if plugins contains dashboard extensions models = false # true if plugins contains models of the extensions (PID, optimizers, data mixer, sequencer, ...) h5exporters = false # true if plugin contains custom h5 file exporters scanners = false # true if plugin contains custom scan layout (daq_scan extensions) @@ -21,11 +21,11 @@ keywords = [ "arbitrary waveform generator", ] dependencies = [ - "pymodaq>=5.3.7", + "pymodaq>=5.4.0a0", # the alpha is accepted since the specifier names a pre-release; replace by >=5.4.0 at the release "pymodaq_utils>=5.3.1", - "pymodaq_gui>=5.3.0", - "pymodaq_data>=5.3.0", - "pymodaq_plugins_utils", + "pymodaq_gui>=5.4.0a0", + "pymodaq_data>=5.4.0a0", + "pymodaq_plugins_utils>=5.3.6", ] authors = [ @@ -40,7 +40,7 @@ maintainers = [ dynamic = ["version", "urls", "entry-points", "classifiers"] readme = "README.rst" license = { file="LICENSE" } -requires-python = ">=3.10" +requires-python = ">=3.11" [build-system] requires = [ diff --git a/src/pymodaq_plugins_waveform/daq_move_plugins/daq_move_WaveformParameter.py b/src/pymodaq_plugins_waveform/daq_move_plugins/daq_move_WaveformParameter.py new file mode 100644 index 0000000..11daa3c --- /dev/null +++ b/src/pymodaq_plugins_waveform/daq_move_plugins/daq_move_WaveformParameter.py @@ -0,0 +1,80 @@ +"""The actuator that a scan moves to change a parameter of a waveform of the Waveform designer extension""" +from typing import TYPE_CHECKING + +from pymodaq_utils.utils import ThreadCommand + +from pymodaq.control_modules.move_utility_classes import ( + DAQ_Move_base, DataActuator, DataActuatorType, comon_parameters_fun) + +if TYPE_CHECKING: + from pymodaq_plugins_waveform.extensions.waveform_designer import WaveformDesigner + + +class DAQ_Move_WaveformParameter(DAQ_Move_base): + """A virtual actuator, created by the Waveform designer extension (and closed with it) + + Its position is the value of one parameter of one waveform (the ``parameter`` setting, whose choices are set by the + extension). Moving it asks the extension to compute the waveform with this value and to send it to the output + actuator, and the move is done when the output actuator has loaded it. + """ + _controller_units = '' + is_multiaxes = False + _epsilon = 1e-12 + data_actuator_type = DataActuatorType.DataActuator + params = [{'title': 'Parameter:', 'name': 'parameter', 'type': 'list', 'limits': [], + 'tip': 'The parameter of a waveform that this actuator drives, listed by the extension'}, + ] + comon_parameters_fun(is_multiaxes, epsilon=_epsilon) + + def ini_attributes(self): + self.controller: 'WaveformDesigner' = None + self.value = DataActuator(data=0.) + + def ini_stage(self, controller=None): + """The controller is the extension that created this actuator: nothing to initialize""" + self.controller = controller + return 'Waveform parameter of the Waveform designer', True + + def get_actuator_value(self) -> DataActuator: + """The value of the chosen parameter, as it is in the settings of the extension""" + self._take_value() + return self.value + + def _take_value(self): + """The value of the chosen parameter, read in the settings of the extension (the controller)""" + value = self.controller.parameter_values().get(self.settings['parameter']) + if value is not None: + self.value = DataActuator(data=value) + + def close(self): + pass + + def commit_settings(self, param): + if param.name() == 'parameter': + self.emit_value(self.get_actuator_value()) + + def move_abs(self, position: DataActuator): + """Ask the extension (the controller, by a signal as this plugin runs in its own thread) to build and send the + waveform; ``waveform_loaded`` answers when it is done""" + position = self.check_bound(position) + self.target_value = position + self.value = position + self.controller.parameter_requested.emit(self._title, self.settings['parameter'], float(position.value())) + + def waveform_loaded(self, ok: bool = True, message: str = ''): + """Command sent by the extension once the output actuator has loaded the waveform, or refused it + + A refusal is raised: the module is marked in error with the reason and the move is not done (``move_done`` is + not called), as for any actuator that cannot reach a position. + """ + if not ok: + raise ValueError(message or 'The waveform was not loaded by the output actuator') + self.move_done() + + def move_rel(self, position: DataActuator): + self.move_abs(self.value + position) + + def move_home(self): + self.emit_status(ThreadCommand('Update_Status', ['A waveform parameter has no home position'])) + + def stop_motion(self): + self.move_done() diff --git a/src/pymodaq_plugins_waveform/extensions/waveform_designer.py b/src/pymodaq_plugins_waveform/extensions/waveform_designer.py new file mode 100644 index 0000000..929f128 --- /dev/null +++ b/src/pymodaq_plugins_waveform/extensions/waveform_designer.py @@ -0,0 +1,496 @@ +"""Dashboard extension to design waveforms and send them to a waveform output actuator + +The waveforms are the ones of the :class:`~pymodaq_plugins_waveform.waveform_factory.WaveformFactory`. The target is one +of the actuators of the Dashboard that follow the contract of +:mod:`pymodaq_plugins_utils.hardware.waveform_output`. The extension can also create virtual actuators +(``Waveform parameter``) that a scan moves to change one parameter of a waveform: they ask the extension to compute and +send the waveform, and they are closed with it. +""" +from dataclasses import dataclass +from functools import partial +from typing import Optional, TYPE_CHECKING + +import numpy as np +from qtpy import QtCore, QtWidgets + +from pymodaq.control_modules.enums import DAQTypesEnum # noqa: F401 (kept for the ones that subclass) +from pymodaq.control_modules.thread_commands import ThreadStatus +from pymodaq.control_modules.utils import ControllerAndThread, QThreadProxy +from pymodaq.utils.custom_ext import CustomExt +from pymodaq.utils.managers.modules import ModuleType +from pymodaq.utils.managers.modules.loader import PluginInfo +from pymodaq.utils.data import Axis, DataRaw, DataToExport, DataActuator +from pymodaq_gui import utils as gutils +from pymodaq_gui.plotting.data_viewers.viewer import ViewerDispatcher +from pymodaq_utils.logger import set_logger, get_module_name +from pymodaq_utils.utils import ThreadCommand +from pymodaq_plugins_utils.hardware.waveform_output import ( + WaveformOutput, OutputMode, OUTPUT_NAME, waveform_output_settings_params) + +from pymodaq_plugins_waveform import waveforms # noqa: F401 (registers the waveforms) +from pymodaq_plugins_waveform.waveform_factory import Waveform, WaveformFactory +from pymodaq_plugins_waveform.waveform_manager import WaveformManager + +if TYPE_CHECKING: + from pymodaq.control_modules.daq_move import DAQ_Move + +logger = set_logger(get_module_name(__file__)) + +EXTENSION_NAME = 'Waveform designer' # the name displayed in the extension list of the dashboard +CLASS_NAME = 'WaveformDesigner' +PARAMETER_ACTUATOR = 'Waveform parameter' # name of the virtual actuators +PARAMETER_PLUGIN = 'WaveformParameter' # the instrument plugin of these actuators +DEFAULT_WAVEFORM = 'sine' + + +def channel_group(index: int, waveform: str = DEFAULT_WAVEFORM) -> dict: + """Settings of one channel: the choice of the waveform and its parameters, from the factory""" + return {'title': f'Channel {index + 1}', 'name': f'ch{index}', 'type': 'group', 'children': [ + {'title': 'Waveform:', 'name': 'waveform', 'type': 'list', 'limits': WaveformFactory.names(), + 'value': waveform}, + {'title': 'Parameters:', 'name': 'parameters', 'type': 'group', + 'children': WaveformFactory.get_class(waveform).params()}]} + + +@dataclass +class PendingMove: + """A waveform upload asked by a virtual actuator, until the target loaded it, failed, or was stopped""" + requester: str # title of the virtual actuator + target: str # title of the target that received the waveforms + + +def parameter_key(channel: int, name: str) -> str: + """What the ``parameter`` setting of a virtual actuator holds""" + return f'Channel {channel + 1}: {name}' + + +class WaveformDesigner(CustomExt): + # emitted by the virtual actuators (they run in their own thread, the settings and the send are of the GUI thread: + # the connection is queued): the text of their ``parameter`` setting and the position asked + # the title of the requesting actuator, the text of its ``parameter`` setting and the position asked + parameter_requested = QtCore.Signal(str, str, float) + settings_name = 'WaveformDesignerSettings' + h5_base_group_name = 'WaveformDesigner' + params = [ + {'title': 'Target:', 'name': 'target', 'type': 'list', 'limits': [], + 'tip': 'Actuators of the Dashboard that are waveform outputs'}, + waveform_output_settings_params(), + {'title': 'Channels:', 'name': 'channels', 'type': 'group', 'children': []}, + ] + + def __init__(self, parent: gutils.DockArea, dashboard): + super().__init__(parent, dashboard, add_toolbar_break=False) + self._parameter_actuators: list[str] = [] + self._connected_targets: dict[str, tuple] = {} # title -> (module, its slots), to tell a replaced module + self._pending: Optional[PendingMove] = None + self.refusal = '' # why the last waveforms were not sent + self._silent = False # True while the settings are changed by the extension: no preview for each change + self.setup_ui() + self.show_repetitions() + self.dashboard.modules_manager.modules_added_signal.connect(self.on_modules_added) + self.parameter_requested.connect(self.on_parameter_request) + self.refresh_targets() + self.setup_waveform_manager() + + def setup_waveform_manager(self): + """The manager of the saved waveforms: its actions are in a toolbar of the extension, its window is not shown. + It is made once the channels exist, as it saves them in its default entry.""" + self.waveform_manager = WaveformManager(designer=self) + self.waveform_manager.add_to_toolbar(self.add_toolbar('waveform_manager', 'Waveforms', parent=self.mainwindow, add_break=False)) + + # ---- the interface + def setup_docks_and_widgets(self): + self.docks['settings'] = gutils.Dock('Settings') + self.dockarea.addDock(self.docks['settings']) + self.docks['settings'].addWidget(self.settings_tree) + + self.docks['preview'] = gutils.Dock('Preview') + self.dockarea.addDock(self.docks['preview'], 'right') + area_preview = gutils.DockArea() + self.docks['preview'].addWidget(area_preview) + self.preview = ViewerDispatcher(area_preview, direction='bottom') + + def setup_actions(self): + self.add_action('refresh', 'Refresh targets', 'refresh', 'Look again for the waveform output actuators') + self.add_action('preview', 'Preview', 'visibility', 'Compute the waveforms and show them') + self.add_action('send', 'Send', 'start', 'Send the waveforms to the target actuator') + self.add_action('stop', 'Stop', 'stop', 'Stop the output of the target actuator') + self.toolbar.addSeparator() + self.add_action('create_parameter_actuator', 'Create a parameter actuator', 'add_circle', + tip=f'Create a "{PARAMETER_ACTUATOR}" actuator that a scan can move to change a parameter', + icon_color=self.get_theme().blue) + + def connect_things(self): + self.connect_action('refresh', self.refresh_targets) + self.connect_action('preview', self.show_preview) + self.connect_action('send', self.send) + self.connect_action('stop', self.stop) + self.connect_action('create_parameter_actuator', self.create_parameter_actuator) + + def setup_menus_and_toolbars(self, menubar: QtWidgets.QMenuBar = None): + self.create_dashboard_toolbar(add_break=False) + def get_app_toolbars(self) -> list[QtWidgets.QToolBar]: + """The toolbars shown in the window of the extension: also the one of the manager""" + return [self.toolbar, self.get_toolbar('waveform_manager')] + + def validate_config(self) -> bool: + return True + + @property + def config_path(self): + return None + + # ---- the target + def target_modules(self) -> dict[str, 'DAQ_Move']: + """The actuators of the Dashboard that follow the contract of the waveform outputs""" + return {module.title: module for module in self.modules_manager.actuators_all + if WaveformOutput.from_module(module) is not None} + + def refresh_targets(self): + """Update the list of targets, and the channels if the target changed""" + modules = self.target_modules() + replaced = self._connect_targets(modules) + targets = list(modules) + target = self.settings.child('target') + current = target.value() + target.setLimits(targets) + if current in targets: + target.setValue(current) + if current in replaced: # a new module under the same title: its channels may be different + self.target_changed() + elif targets: + target.setValue(targets[0]) + self.target_changed() + else: + self.target_changed() + + def _connect_targets(self, modules: dict[str, 'DAQ_Move']) -> list[str]: + """Listen to the targets: returns the titles of the ones that are a new module under a known title""" + replaced = [] + for title in list(self._connected_targets): + module, slots = self._connected_targets[title] + if modules.get(title) is not module: # removed or replaced + self._disconnect_target(title) + if title in modules: + replaced.append(title) + for title, module in modules.items(): + if title not in self._connected_targets: + slots = (partial(self._on_target_done, title), self._on_target_failed, self._on_target_status) + module.move_done_signal.connect(slots[0]) + module.custom_sig.connect(slots[2]) + if hasattr(module, 'move_failed_signal'): # PyMoDAQ >= 5.4 + module.move_failed_signal.connect(slots[1]) + self._connected_targets[title] = (module, slots) + return replaced + + def _disconnect_target(self, title: str): + module, slots = self._connected_targets.pop(title) + if self._pending is not None and self._pending.target == title: + self._finish_pending(False, f'The target {title} was removed') + for signal, slot in ((getattr(module, 'move_done_signal', None), slots[0]), + (getattr(module, 'move_failed_signal', None), slots[1]), + (getattr(module, 'custom_sig', None), slots[2])): + try: + signal.disconnect(slot) + except (TypeError, RuntimeError, AttributeError): # the module is already deleted + pass + + def on_modules_added(self): + """Instruments were added to the Dashboard after the experiment was set: the manager of the extension does not + see them (it takes the list of the Dashboard when an experiment is set, and a new list is made when modules are + added), so take it again. A removal changes the list that both share.""" + self.modules_manager.actuators_all = self.dashboard.modules_manager.actuators_all + self.refresh_targets() + + def do_things_after_experiment_set(self, experiment_name: str, show_dashboard: bool = None): + """The instruments changed: look again for the targets""" + super().do_things_after_experiment_set(experiment_name, show_dashboard) + self.refresh_targets() + + @property + def target(self) -> Optional['DAQ_Move']: + return self.target_modules().get(self.settings['target']) + + def target_changed(self): + """One group of settings per channel of the target (one without target), and the output choices of the target""" + module = self.target + output = WaveformOutput.from_module(module) if module is not None else None + self._silent = True + try: + self._build_channels(output) + finally: + self._silent = False + self.show_preview() + + def _build_channels(self, output: Optional[WaveformOutput]): + """Create the settings of the channels (and take the output choices) for the capabilities of the target""" + channels = self.settings.child('channels') + if output is None: # no target: one channel to design and preview waveforms, kept if there already are some + if not channels.children(): + channels.addChild(channel_group(0)) + self.update_parameter_choices() + return + existing = channels.children() + for group in existing[output.n_channels:]: # beyond the channels of the target + channels.removeChild(group) + for index in range(len(existing), output.n_channels): # the channels already designed are kept + channels.addChild(channel_group(index)) + for name, value in (('sample_rate', output.sample_rate), ('mode', output.mode.value), + ('repetitions', output.repetitions)): + self.settings.child(OUTPUT_NAME, name).setValue(value) + self.settings.child(OUTPUT_NAME, 'mode').setLimits([mode.value for mode in output.modes]) + self.show_repetitions() + self.update_parameter_choices() + + def show_repetitions(self): + """The repetitions are only used by the ``repeat`` mode""" + self.settings.child(OUTPUT_NAME, 'repetitions').setOpts( + visible=self.settings[OUTPUT_NAME, 'mode'] == OutputMode.REPEAT.value) + + def value_changed(self, param): + """The preview follows every change of a waveform or of the sample rate""" + if self._silent: + return + if param.name() == 'target': + self.target_changed() + elif param.name() == 'waveform' and param.parent().name().startswith('ch'): + self._silent = True + try: + parameters = param.parent().child('parameters') + parameters.clearChildren() + parameters.addChildren(WaveformFactory.get_class(param.value()).params()) + self.update_parameter_choices() + finally: + self._silent = False + path = self.settings.childPath(param) or [] + if path == [OUTPUT_NAME, 'mode']: + self.show_repetitions() + if len(path) == 4 and path[0] == 'channels' and path[2] == 'parameters': + self.update_parameter_actuators(parameter_key(int(path[1][2:]), path[3])) + if path and (path[0] == 'channels' or path[:2] == [OUTPUT_NAME, 'sample_rate']): + self.show_preview() + + def update_parameter_actuators(self, key: str): + """A parameter changed in the settings: the virtual actuators set on it show its new value""" + for module in self.parameter_modules(): + if module.settings[module._hw_settings_name, 'parameter'] == key: + module.get_actuator_value() + + # ---- the waveforms + def channel_waveforms(self) -> list[Waveform]: + """The waveform of each channel, as set in the settings""" + waveforms_ = [] + for group in self.settings.child('channels').children(): + cls = WaveformFactory.get_class(group['waveform']) + waveforms_.append(cls.from_settings(group.child('parameters'))) + return waveforms_ + + def load_channels(self, descriptions: list[dict]): + """Set the waveforms of the channels from their descriptions (see :meth:`Waveform.to_dict`) + + A description beyond the channels of the target is ignored, a channel without description is left as it is. + """ + waveforms_ = [Waveform.from_dict(description) for description in descriptions] # all valid before any change + groups = self.settings.child('channels').children() + if len(waveforms_) != len(groups): + logger.warning(f'{len(waveforms_)} waveforms for {len(groups)} channels') + self._silent = True + try: + for group, waveform in zip(groups, waveforms_): + parameters = group.child('parameters') + if group['waveform'] != waveform.name: + group.child('waveform').setValue(waveform.name) + parameters.clearChildren() + parameters.addChildren(type(waveform).params()) + for name, value in waveform.to_dict().items(): + if name != 'name': + parameters.child(name).setValue(value) + self.update_parameter_choices() + finally: + self._silent = False + self.show_preview() + + def sampled_waveforms(self): + rate = self.settings[OUTPUT_NAME, 'sample_rate'] + sampled = [] + for index, waveform in enumerate(self.channel_waveforms()): + try: + sampled.append(waveform.to_samples(rate)) + except OSError as e: # a file of the waveform cannot be read + raise ValueError(f'Channel {index + 1}: cannot read {e.filename or "the file"}: {e.strerror or e}') + return sampled + + def show_preview(self): + """Show the channels, one viewer under the other, with the time in seconds as axis""" + try: + sampled = self.sampled_waveforms() + except ValueError as e: + logger.error(str(e)) + return + dte = DataToExport('preview') + for index, wave in enumerate(sampled): + time = np.arange(len(wave.samples)) / wave.sample_rate + label = f'Channel {index + 1}' + if wave.frequency is not None: + label += f' ({wave.frequency:.6g} Hz, error {wave.frequency_error:.2g} Hz)' + dte.append(DataRaw(label, data=[wave.samples], units='V', labels=['V'], + axes=[Axis('time', 's', data=time)])) + self.preview.show_data(dte) + + def send(self) -> bool: + """Check the waveforms against the capabilities of the target and send them as its position + + Returns False if they cannot be sent: the reason is logged and kept in ``refusal``. + """ + module = self.target + self.refusal = '' + if module is None: + self.refusal = 'No waveform output actuator to send the waveforms to' + logger.error(self.refusal) + return False + try: + sampled = self.sampled_waveforms() + samples = [wave.samples for wave in sampled] + for index, array in enumerate(samples): + if not np.all(np.isfinite(array)): + raise ValueError(f'Channel {index + 1}: the samples must be finite numbers (NaN or inf found)') + output = WaveformOutput.from_module(module) + output.check(samples, sample_rate=self.settings[OUTPUT_NAME, 'sample_rate'], + mode=self.settings[OUTPUT_NAME, 'mode']) + except ValueError as e: + self.refusal = str(e) + logger.error(self.refusal) + return False + hardware = module.settings.child(module._hw_settings_name, OUTPUT_NAME) + for name in ('sample_rate', 'mode', 'repetitions'): + hardware.child(name).setValue(self.settings[OUTPUT_NAME, name]) + module.move_abs(DataActuator(module.title, data=samples, units='V')) + return True + + def stop(self): + module = self.target + if module is not None: + if self._pending is not None and self._pending.target == module.title: + self._finish_pending(False, f'The output of {module.title} was stopped') + module.stop_motion() + + # ---- the virtual actuators that a scan moves + def scannable_keys(self) -> dict[str, tuple[int, str]]: + """The scannable parameters of the waveforms: the text of the ``parameter`` setting of the actuators, and the + channel and the name of the parameter""" + keys = {} + for index, group in enumerate(self.settings.child('channels').children()): + for name in WaveformFactory.get_class(group['waveform']).scannable_parameters(): + keys[parameter_key(index, name)] = (index, name) + return keys + + def parameter_values(self) -> dict[str, float]: + """The value in the settings of each scannable parameter, by the text of the ``parameter`` setting""" + return {key: float(self.settings['channels', f'ch{channel}', 'parameters', name]) + for key, (channel, name) in self.scannable_keys().items()} + + def parameter_modules(self) -> list['DAQ_Move']: + mods = [] + for name in self._parameter_actuators: + module = self.dashboard.modules_manager.get_mod_from_name(name, ModuleType.Actuator) + if module is not None: + mods.append(module) + return mods + + def update_parameter_choices(self): + """Tell the virtual actuators which parameters can be scanned""" + keys = list(self.scannable_keys()) + for module in self.parameter_modules(): + module.settings.child(module._hw_settings_name, 'parameter').setLimits(keys) + + def create_parameter_actuator(self): + name = f'{PARAMETER_ACTUATOR} {len(self._parameter_actuators) + 1}' + id_ = self.dashboard.modules_manager.get_random_id() + plugin = PluginInfo( + id=id_, name=name, class_name=PARAMETER_PLUGIN, type=ModuleType.Actuator, is_master=False, + controller=ControllerAndThread(name=name, id=id_, is_master=False, controller=self, + thread=QThreadProxy(thread=self.thread()))) + self._parameter_actuators.append(name) + self.dashboard.module_creator.add_move_from_extension(modules=[plugin], callback=self._on_actuator_added) + + def _on_actuator_added(self, modules: list['DAQ_Move']): + self.dashboard.module_creator.forget_callback(self._on_actuator_added) + self.update_parameter_choices() + + def on_parameter_request(self, requester: str, parameter: str, position: float): + """A virtual actuator was moved: set the parameter, then compute and send the waveforms""" + try: + channel, name = self.scannable_keys()[parameter] + except KeyError: + message = f'Unknown waveform parameter {parameter}: choose one in the actuator' + logger.error(message) + self._answer(requester, False, message) + return + if self._pending is not None: # one upload at a time: the earlier request is over + self._finish_pending(False, 'Replaced by a new request') + self._silent = True # the preview is shown once, below + try: + self.settings.child('channels', f'ch{channel}', 'parameters', name).setValue(position) + finally: + self._silent = False + self.show_preview() # also when the waveforms cannot be sent + module = self.target + if module is None: # nothing to load them in: setting the parameter and the preview is all there is, ok to test + self._answer(requester, True) + return + self._pending = PendingMove(requester, module.title) + if not self.send(): + self._finish_pending(False, self.refusal) + + def _answer(self, requester: str, ok: bool, message: str = ''): + """Tell the virtual actuator that asked for the waveform (only this one) how it went""" + for module in self.parameter_modules(): + if module.title == requester: + module.command_hardware.emit(ThreadCommand('waveform_loaded', dict(ok=ok, message=message))) + + def _finish_pending(self, ok: bool, message: str = ''): + """End the request waiting for the target, if any; late signals of its upload are then ignored""" + pending, self._pending = self._pending, None + if pending is not None: + self._answer(pending.requester, ok, message) + + def _on_target_status(self, status: ThreadCommand): + """The target raised an error while the waveform was being loaded""" + if status.command == ThreadStatus.ERROR and self._pending is not None: + self._finish_pending(False, str(status.attribute)) + + def _on_target_failed(self, title: str, message: str): + """The plugin of the target raised an exception while moving (``move_failed_signal`` of the module)""" + if self._pending is not None and self._pending.target == title: + self._finish_pending(False, message) + + def _on_target_done(self, title: str, data): + """A target has loaded the waveforms: finish the move of the virtual actuator waiting for this one""" + if self._pending is not None and self._pending.target == title: + self._finish_pending(True) + + def _quit_fun(self) -> bool: + self.waveform_manager.quit_fun() + self.waveform_manager.mainwindow.deleteLater() # its window is never shown but it is not deleted by its quit + if self._parameter_actuators: + self.dashboard.remove_modules(self._parameter_actuators) + return True + + +def main(): + """Start a Dashboard with the Waveform designer extension""" + import sys + from pymodaq_gui.qt_utils import mkQApp + from pymodaq.dashboard import load_dashboard_with_arguments + from pymodaq.utils.gui_utils.loader_utils import create_extension + + app = mkQApp(EXTENSION_NAME) + + win, dashboard, _ = load_dashboard_with_arguments(show_dashboard=False, load_extension=False) + win.mainwindow.setVisible(False) + win_ext, extension = create_extension(dashboard, WaveformDesigner, show_extension=True) + sys.exit(app.exec()) + + +if __name__ == '__main__': + main() diff --git a/src/pymodaq_plugins_waveform/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py index f0113eb..b2c694b 100644 --- a/src/pymodaq_plugins_waveform/waveform_factory.py +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -63,7 +63,7 @@ def waveform_field(default: Any, unit: Optional[str] = None, title: str = '', mi scannable = type in ('float', 'int') if scannable and type not in ('float', 'int'): raise ValueError(f'A {type} parameter cannot be scanned') - if type not in ('float', 'str', 'int', 'bool', 'list'): + if type not in ('float', 'str', 'int', 'bool', 'list', 'browsepath'): raise ValueError(f'Unknown parameter type {type}') if type == 'list' and not limits: raise ValueError('A list parameter needs its limits') diff --git a/src/pymodaq_plugins_waveform/waveform_manager.py b/src/pymodaq_plugins_waveform/waveform_manager.py new file mode 100644 index 0000000..7822e02 --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveform_manager.py @@ -0,0 +1,96 @@ +"""Manager of the named sets of waveforms (one waveform per channel) of the Waveform designer + +It is a :class:`~pymodaq_gui.managers.manager_base.ManagerBase` whose window is never shown: its actions (list of the +entries, new, copy, delete, save, reload, execute) are placed in the toolbar of the extension, that holds the settings. +An entry is a toml file of the ``waveforms`` folder of the PyMoDAQ configuration folder. +""" +from pathlib import Path +from typing import TYPE_CHECKING + +import os +import tempfile + +import toml + +from qtpy import QtWidgets + +from pymodaq_gui.managers.manager_base import ManagerBase, ManagerActions +from pymodaq_gui.utils.widgets.combo import ComboBox +from pymodaq_utils.config import get_set_config_dir +from pymodaq_utils.logger import set_logger, get_module_name + +if TYPE_CHECKING: + from pymodaq_plugins_waveform.extensions.waveform_designer import WaveformDesigner + +logger = set_logger(get_module_name(__file__)) + +FORMAT_VERSION = 1 # of the toml files: ``version``, then one ``[[channels]]`` table per channel + + +class WaveformManager(ManagerBase): + """Save, name, and load the waveforms of the channels of a Waveform designer""" + entry_type = 'waveform' + entry_extension = '.toml' + icon_name = 'graphic_eq' + + def init_extra(self, designer: 'WaveformDesigner' = None, **kwargs): + super().init_extra(**kwargs) + self.designer = designer + + def finish_init(self): + self.enable_actions(True) + + def add_to_toolbar(self, toolbar: QtWidgets.QToolBar): + """Put the combo of the entries and the actions in the toolbar of the extension (the window stays hidden)""" + self.add_widget(ManagerActions.LIST_EXTERNAL, ComboBox(), toolbar=toolbar, tip='The saved waveforms') + self.sync_entries_with(self.get_action(ManagerActions.LIST_EXTERNAL).widget) + for action in (ManagerActions.EXECUTE, ManagerActions.NEW, ManagerActions.COPY, ManagerActions.SAVE, + ManagerActions.RELOAD, ManagerActions.DELETE): + self.affect_to(action, toolbar) + + def get_entry_folder(self, **kwargs_to_entry_folder) -> Path: + return get_set_config_dir('waveforms') + + def save_entries(self, entry_path: Path = None): + """Write the waveforms of the channels of the designer""" + if entry_path is None: + entry_path = self.entry_filepath + content = {'version': FORMAT_VERSION, + 'channels': [waveform.to_dict() for waveform in self.designer.channel_waveforms()]} + entry_path = Path(entry_path) + # written aside then moved: a failure (full disk...) leaves the previous entry as it was + fd, temporary = tempfile.mkstemp(dir=entry_path.parent, prefix=entry_path.name, suffix='.tmp') + try: + with os.fdopen(fd, 'w') as file: + file.write(toml.dumps(content)) + os.replace(temporary, entry_path) + except BaseException: + Path(temporary).unlink(missing_ok=True) + raise + + def read_entry(self, entry_path: Path) -> list[dict]: + """The description of the waveforms of an entry, refusing the files of an unknown version""" + content = toml.loads(Path(entry_path).read_text()) + if content.get('version') != FORMAT_VERSION: + raise ValueError(f'{Path(entry_path).name}: waveform file of version {content.get("version")}, ' + f'only version {FORMAT_VERSION} is known') + channels = content.get('channels') + if not isinstance(channels, list) or not all(isinstance(channel, dict) for channel in channels): + raise ValueError(f'{Path(entry_path).name}: "channels" must be a list of tables, one per channel') + return channels + + def can_execute_entry(self) -> bool: + return self.designer is not None + + def _update_entry(self, entry_path: Path): + """Set the waveforms of the entry in the channels of the designer""" + self._loaded = False + try: + self.designer.load_channels(self.read_entry(entry_path)) + self._loaded = True + except (ValueError, KeyError, TypeError, OSError) as e: + logger.error(f'Cannot load the waveforms of {Path(entry_path).name}: {e}') + + def _execute_entry(self, entry_path: Path = None, **kwargs) -> bool: + """Executing an entry is loading it in the channels (done when it is updated): the designer sends them""" + return getattr(self, '_loaded', True) # False if the entry was refused: nothing was applied diff --git a/src/pymodaq_plugins_waveform/waveforms/__init__.py b/src/pymodaq_plugins_waveform/waveforms/__init__.py index b7a48ab..1641bc6 100644 --- a/src/pymodaq_plugins_waveform/waveforms/__init__.py +++ b/src/pymodaq_plugins_waveform/waveforms/__init__.py @@ -9,7 +9,7 @@ for _module in pkgutil.iter_modules(__path__): importlib.import_module(f'{__name__}.{_module.name}') -from pymodaq_plugins_waveform.waveforms.array import Array # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.file import File # noqa: E402,F401 from pymodaq_plugins_waveform.waveforms.dc import DC # noqa: E402,F401 from pymodaq_plugins_waveform.waveforms.piecewise import Piecewise, parse_breakpoints # noqa: E402,F401 from pymodaq_plugins_waveform.waveforms.pulse import Pulse # noqa: E402,F401 diff --git a/src/pymodaq_plugins_waveform/waveforms/array.py b/src/pymodaq_plugins_waveform/waveforms/file.py similarity index 70% rename from src/pymodaq_plugins_waveform/waveforms/array.py rename to src/pymodaq_plugins_waveform/waveforms/file.py index 0f56bc8..51aa55a 100644 --- a/src/pymodaq_plugins_waveform/waveforms/array.py +++ b/src/pymodaq_plugins_waveform/waveforms/file.py @@ -1,4 +1,4 @@ -"""Samples from a file or an array""" +"""Samples read from a file""" import dataclasses from pathlib import Path from typing import ClassVar, Optional @@ -10,18 +10,18 @@ @WaveformFactory.register() @dataclasses.dataclass -class Array(Waveform): - """Samples taken as they are, from a file (``.npy`` or text) or given as ``values``; they are played at the sample +class File(Waveform): + """Samples taken as they are, from a file (``.npy`` or text, chosen with a browse button) or given as ``values``; they are played at the sample rate of the output""" - name: ClassVar[str] = 'array' - path: str = waveform_field('', None, 'File', tip='.npy file or text file (csv) with one column of samples in V') + name: ClassVar[str] = 'file' + path: str = waveform_field('', None, 'File', type='browsepath', tip='.npy file or text file (csv) with one column of samples in V') values: Optional[np.ndarray] = None # not a parameter: the samples when no file is given def _to_samples(self, sample_rate): values = self.values if values is None: if not self.path: - raise ValueError('No file and no values for the array waveform') + raise ValueError('No file and no values for the file waveform') path = Path(self.path) values = np.load(path) if path.suffix == '.npy' else np.loadtxt(path, delimiter=',') values = np.asarray(values, dtype=float) diff --git a/tests/fake_waveform_output.py b/tests/fake_waveform_output.py new file mode 100644 index 0000000..4d75705 --- /dev/null +++ b/tests/fake_waveform_output.py @@ -0,0 +1,80 @@ +"""A waveform output actuator without hardware, to test the applications of the contract""" +import time +import types + +import numpy as np +from qtpy import QtWidgets + +from pymodaq.control_modules import instruments +from pymodaq.control_modules.move_utility_classes import DAQ_Move_base, comon_parameters_fun, DataActuatorType +from pymodaq.utils.data import DataActuator +from pymodaq_plugins_utils.hardware.waveform_output import waveform_output_params, fill_waveform_output_settings, OutputMode + + +class DAQ_Move_FakeWaveformOutput(DAQ_Move_base): + is_multiaxes = False + _controller_units = 'V' + _epsilon = 0.01 + data_actuator_type = DataActuatorType.DataActuator + params = waveform_output_params() + comon_parameters_fun(is_multiaxes, epsilon=_epsilon) + n_channels = 2 + + def ini_attributes(self): + self.controller = None + self.loaded = None + + def ini_stage(self, controller=None): + self.controller = object() + self.loaded = DataActuator(data=[np.zeros(10)] * self.n_channels, units='V') + fill_waveform_output_settings(self.settings, self.n_channels, 1., 1e5, 100000, -10., 10., + modes=(OutputMode.FINITE, OutputMode.REPEAT)) + return 'ok', True + + def get_actuator_value(self): + return self.loaded + + def close(self): + pass + + def commit_settings(self, param): + pass + + def move_abs(self, position): + self.target_value = position + self.loaded = position + self.move_done() + + def move_rel(self, position): + pass + + def move_home(self): + pass + + def stop_motion(self): + pass + + +def register(name, plugin_class): + if name not in instruments.ACTUATOR_NAMES: + module = types.SimpleNamespace(**{f'daq_move_{name}': types.SimpleNamespace(**{f'DAQ_Move_{name}': plugin_class})}) + instruments.ACTUATOR_TYPES.append({'name': name, 'module': module, 'type': 'daq_move'}) + instruments.ACTUATOR_NAMES.append(name) + + +def make_module(name: str, title: str, timeout=10.): + """An initialized DAQ_Move of a registered plugin""" + import pymodaq.control_modules.daq_move as dm + dm.find_actuator_class_from_name = instruments.find_actuator_class_from_name + module = dm.DAQ_Move(None, title=title) # no UI + module.actuator = name + inited = [] + module.init_signal.connect(inited.append) + module.init_hardware(True) + t0 = time.time() + while not inited and time.time() - t0 < timeout: + QtWidgets.QApplication.processEvents() + time.sleep(0.01) + if not (inited and inited[0]): + module.quit_fun() # the caller never gets the module to close it + raise AssertionError(f'{name} did not initialize') + return module diff --git a/tests/test_waveform_designer.py b/tests/test_waveform_designer.py new file mode 100644 index 0000000..1dbf699 --- /dev/null +++ b/tests/test_waveform_designer.py @@ -0,0 +1,391 @@ +"""The Waveform designer extension, in an empty Dashboard with a fake waveform output actuator""" +import pytest + +pytest.importorskip('pymodaq.utils.plugin_testing') + +from pymodaq.utils.plugin_testing import loaded_extension + +from pymodaq_plugins_waveform.extensions.waveform_designer import WaveformDesigner +from pymodaq_plugins_waveform.waveform_manager import WaveformManager + + +def test_the_extension_loads_and_closes_without_target(): + with loaded_extension(WaveformDesigner) as (dashboard, extension): + assert extension.settings['target'] in (None, '') + assert [group.name() for group in extension.settings.child('channels').children()] == ['ch0'] + assert 'sine' in extension.settings.child('channels', 'ch0', 'waveform').opts['limits'] + + +import time + +import numpy as np +from qtpy import QtWidgets + +from pymodaq.utils.data import DataActuator +from fake_waveform_output import DAQ_Move_FakeWaveformOutput, register, make_module +from pymodaq_plugins_waveform.daq_move_plugins.daq_move_WaveformParameter import DAQ_Move_WaveformParameter + + +def wait_for(condition, timeout=5.): + t0 = time.time() + while not condition() and time.time() - t0 < timeout: + QtWidgets.QApplication.processEvents() + time.sleep(0.005) + return condition() + + +@pytest.fixture(autouse=True) +def waveform_folder(tmp_path, monkeypatch): + """The saved waveforms of the tests are not the ones of the user: set before the extension is made""" + monkeypatch.setattr(WaveformManager, 'get_entry_folder', lambda self, **kw: tmp_path) + + +@pytest.fixture +def designer(): + register('FakeWaveformOutput', DAQ_Move_FakeWaveformOutput) + register('WaveformParameter', DAQ_Move_WaveformParameter) + with loaded_extension(WaveformDesigner) as (dashboard, extension): + output = make_module('FakeWaveformOutput', 'ao') + dashboard.modules_manager.add_modules([output]) + extension.refresh_targets() + yield extension, output + output.quit_fun() + + +def test_the_channels_of_the_target_become_groups_of_settings(designer): + extension, output = designer + + assert extension.settings['target'] == 'ao' + assert [group.name() for group in extension.settings.child('channels').children()] == ['ch0', 'ch1'] + + +def test_sending_loads_the_waveforms_in_the_target(designer): + extension, output = designer + extension.settings.child('channels', 'ch1', 'waveform').setValue('dc') + + done = [] + output.move_done_signal.connect(done.append) + + assert extension.send() + + assert wait_for(lambda: done) + sine, dc = done[0].data + assert 0.9 < np.max(sine) <= 1. # the sine of amplitude 1 V + assert np.allclose(dc, dc[0]) # the DC of the other channel + + +def test_a_waveform_that_exceeds_the_target_is_not_sent(designer, caplog): + extension, output = designer + extension.settings.child('channels', 'ch0', 'parameters', 'amplitude').setValue(50.) + + assert not extension.send() + + +def test_the_parameters_to_scan_are_listed_by_the_waveforms(designer): + extension, output = designer + + keys = extension.scannable_keys() + + assert keys['Channel 1: frequency'] == (0, 'frequency') + assert 'Channel 2: amplitude' in keys + + +def test_moving_a_parameter_actuator_loads_the_waveform_and_ends_the_move(designer): + extension, output = designer + extension.create_parameter_actuator() + assert wait_for(lambda: extension.parameter_modules()) + (actuator,) = extension.parameter_modules() + assert wait_for(lambda: 'Channel 1: amplitude' in actuator.settings.child( + actuator._hw_settings_name, 'parameter').opts['limits']) + actuator.settings.child(actuator._hw_settings_name, 'parameter').setValue('Channel 1: amplitude') + done, loaded = [], [] + actuator.move_done_signal.connect(done.append) + output.move_done_signal.connect(loaded.append) + + actuator.move_abs(DataActuator('amplitude', data=3.)) + + assert wait_for(lambda: done and loaded) + assert extension.settings['channels', 'ch0', 'parameters', 'amplitude'] == 3. + assert 2.5 < np.max(loaded[0].data[0]) <= 3. + + +def test_an_actuator_added_to_the_dashboard_becomes_a_target(designer): + extension, output = designer + other = make_module('FakeWaveformOutput', 'ao2') + try: + extension.dashboard.modules_manager.add_modules([other]) + + assert set(extension.settings.child('target').opts['limits']) == {'ao', 'ao2'} + finally: + other.quit_fun() + + +def test_without_target_a_waveform_can_be_previewed_but_not_sent(): + with loaded_extension(WaveformDesigner) as (dashboard, extension): + extension.settings.child('channels', 'ch0', 'waveform').setValue('square') + + extension.show_preview() + + assert not extension.send() + + +def test_the_preview_follows_the_changes_of_the_settings(designer, monkeypatch): + extension, output = designer + previews = [] + monkeypatch.setattr(extension, 'show_preview', lambda: previews.append(1)) + + extension.settings.child('channels', 'ch0', 'parameters', 'amplitude').setValue(2.) + assert len(previews) == 1 + + extension.settings.child('channels', 'ch1', 'waveform').setValue('square') + assert len(previews) == 2 # once for the new waveform, not for each of its parameters + + extension.settings.child('waveform_output', 'sample_rate').setValue(2e4) + assert len(previews) == 3 + + +def test_the_repetitions_are_shown_for_the_repeat_mode_only(designer): + extension, output = designer + repetitions = extension.settings.child('waveform_output', 'repetitions') + + assert not repetitions.opts['visible'] + + extension.settings.child('waveform_output', 'mode').setValue('repeat') + assert repetitions.opts['visible'] + + extension.settings.child('waveform_output', 'mode').setValue('finite') + assert not repetitions.opts['visible'] + + +def test_the_waveforms_are_saved_and_loaded_by_name(designer, tmp_path, monkeypatch): + extension = designer[0] + manager = extension.waveform_manager + extension.settings.child('channels', 'ch0', 'parameters', 'frequency').setValue(7.) + manager.create_entry('seven', bypass_dialog=True) + extension.settings.child('channels', 'ch0', 'parameters', 'frequency').setValue(3.) + + manager.execute_entry('seven') + + assert extension.settings['channels', 'ch0', 'parameters', 'frequency'] == 7. + assert (tmp_path / 'seven.toml').is_file() + + +def test_a_file_of_an_unknown_version_is_refused(designer, tmp_path, monkeypatch): + extension = designer[0] + manager = extension.waveform_manager + (tmp_path / 'future.toml').write_text('version = 99\nchannels = []\n') + + with pytest.raises(ValueError): + manager.read_entry(tmp_path / 'future.toml') + + +def test_a_parameter_actuator_reads_and_sets_the_value_of_the_extension(designer): + extension, output = designer + extension.create_parameter_actuator() + assert wait_for(lambda: extension.parameter_modules()) + (actuator,) = extension.parameter_modules() + assert wait_for(lambda: 'Channel 1: amplitude' in actuator.settings.child( + actuator._hw_settings_name, 'parameter').opts['limits']) + actuator.settings.child(actuator._hw_settings_name, 'parameter').setValue('Channel 1: amplitude') + extension.settings.child('channels', 'ch0', 'parameters', 'amplitude').setValue(2.) + actuator.get_actuator_value() + assert wait_for(lambda: actuator._current_value.value() == 2.) # not current_value: it recurses when the origin is empty + done = [] + actuator.move_done_signal.connect(done.append) + + actuator.move_abs(DataActuator('amplitude', data=0.)) + + assert wait_for(lambda: done) + assert extension.settings['channels', 'ch0', 'parameters', 'amplitude'] == 0. + assert extension.parameter_values()['Channel 1: amplitude'] == 0. + + +def test_the_toolbar_of_the_manager_is_in_the_window_of_the_extension(designer): + extension, _ = designer + toolbar = extension.get_toolbar('waveform_manager') + + assert toolbar in extension.get_app_toolbars() + assert len(toolbar.actions()) >= 7 # the entries, execute, new, copy, save, reload, delete + + +def test_changing_a_parameter_updates_the_actuator_set_on_it(designer): + extension, output = designer + extension.create_parameter_actuator() + assert wait_for(lambda: extension.parameter_modules()) + (actuator,) = extension.parameter_modules() + assert wait_for(lambda: 'Channel 1: amplitude' in actuator.settings.child( + actuator._hw_settings_name, 'parameter').opts['limits']) + actuator.settings.child(actuator._hw_settings_name, 'parameter').setValue('Channel 1: amplitude') + + extension.settings.child('channels', 'ch0', 'parameters', 'amplitude').setValue(1.5) + + assert wait_for(lambda: actuator._current_value.value() == 1.5) + + +def test_moving_a_parameter_actuator_updates_the_preview_even_if_the_waveform_is_refused(designer, monkeypatch): + extension, output = designer + previews = [] + monkeypatch.setattr(extension, 'show_preview', lambda: previews.append(1)) + + extension.on_parameter_request('x', 'Channel 1: amplitude', 1000.) # beyond the limits of the target + + assert previews + assert extension.settings['channels', 'ch0', 'parameters', 'amplitude'] == 1000. + + +def _actuator_on_amplitude(extension): + extension.create_parameter_actuator() + assert wait_for(lambda: extension.parameter_modules()) + (actuator,) = extension.parameter_modules() + assert wait_for(lambda: 'Channel 1: amplitude' in actuator.settings.child( + actuator._hw_settings_name, 'parameter').opts['limits']) + actuator.settings.child(actuator._hw_settings_name, 'parameter').setValue('Channel 1: amplitude') + return actuator + + +def test_a_refused_waveform_is_an_error_of_the_actuator_and_its_move_is_not_done(designer): + extension, output = designer + actuator = _actuator_on_amplitude(extension) + done = [] + actuator.move_done_signal.connect(done.append) + + actuator.move_abs(DataActuator('amplitude', data=1000.)) # beyond the limits of the target + + assert wait_for(lambda: actuator._in_error) + assert not done + + +def test_a_failure_of_the_target_while_loading_is_an_error_of_the_actuator(designer, monkeypatch): + extension, output = designer + actuator = _actuator_on_amplitude(extension) + done = [] + actuator.move_done_signal.connect(done.append) + + def refuse(self, position): + raise RuntimeError('the board refused') + monkeypatch.setattr(DAQ_Move_FakeWaveformOutput, 'move_abs', refuse) + + actuator.move_abs(DataActuator('amplitude', data=0.7)) + + assert wait_for(lambda: actuator._in_error) + assert not done + assert extension._pending is None + + +def test_only_the_actuator_that_asked_is_answered(designer): + extension, output = designer + first = _actuator_on_amplitude(extension) + extension.create_parameter_actuator() + assert wait_for(lambda: len(extension.parameter_modules()) == 2) + second = [m for m in extension.parameter_modules() if m is not first][0] + done_first, done_second = [], [] + first.move_done_signal.connect(done_first.append) + second.move_done_signal.connect(done_second.append) + + first.move_abs(DataActuator('amplitude', data=0.4)) + + assert wait_for(lambda: done_first) + QtWidgets.QApplication.processEvents() + assert not done_second + + +def test_a_done_of_another_target_does_not_end_the_move(designer): + from pymodaq_plugins_waveform.extensions.waveform_designer import PendingMove + extension, output = designer + actuator = _actuator_on_amplitude(extension) + done = [] + actuator.move_done_signal.connect(done.append) + extension._pending = PendingMove(actuator.title, 'ao') + + extension._on_target_done('ao2', None) + QtWidgets.QApplication.processEvents() + assert not done and extension._pending is not None + + extension._on_target_done('ao', None) + assert wait_for(lambda: done) + + +def test_stopping_the_target_ends_the_pending_move_in_error(designer): + from pymodaq_plugins_waveform.extensions.waveform_designer import PendingMove + extension, output = designer + actuator = _actuator_on_amplitude(extension) + done = [] + actuator.move_done_signal.connect(done.append) + extension._pending = PendingMove(actuator.title, 'ao') + + extension.stop() + + assert wait_for(lambda: actuator._in_error) + assert not done and extension._pending is None + + +def test_non_finite_samples_are_not_sent(designer): + extension, output = designer + extension.settings.child('channels', 'ch0', 'parameters', 'amplitude').setValue(float('nan')) + + assert not extension.send() + assert 'finite' in extension.refusal + + +def test_a_missing_file_is_a_refusal_not_an_exception(designer, tmp_path): + extension, output = designer + extension.settings.child('channels', 'ch0', 'waveform').setValue('file') + extension.settings.child('channels', 'ch0', 'parameters', 'path').setValue(str(tmp_path / 'gone.csv')) + + assert not extension.send() + assert 'Channel 1' in extension.refusal + + +def test_the_draft_made_without_target_is_kept_when_a_target_appears(): + register('FakeWaveformOutput', DAQ_Move_FakeWaveformOutput) + with loaded_extension(WaveformDesigner) as (dashboard, extension): + extension.settings.child('channels', 'ch0', 'waveform').setValue('square') + output = make_module('FakeWaveformOutput', 'ao') + try: + dashboard.modules_manager.add_modules([output]) + extension.refresh_targets() + + assert extension.settings['channels', 'ch0', 'waveform'] == 'square' + assert len(extension.settings.child('channels').children()) == 2 + finally: + output.quit_fun() + + +def test_a_refused_entry_is_not_reported_as_executed(designer, tmp_path): + extension = designer[0] + manager = extension.waveform_manager + (tmp_path / 'future.toml').write_text('version = 99\nchannels = []\n') + (tmp_path / 'broken.toml').write_text('version = 1\nchannels = 42\n') + + for name in ('future', 'broken'): + manager._update_entry(tmp_path / f'{name}.toml') + assert not manager._execute_entry(tmp_path / f'{name}.toml') + + +def test_a_failed_save_keeps_the_previous_entry(designer, tmp_path, monkeypatch): + extension = designer[0] + manager = extension.waveform_manager + target = tmp_path / 'keep.toml' + target.write_text('version = 1\nchannels = []\n') + monkeypatch.setattr('pymodaq_plugins_waveform.waveform_manager.toml.dumps', + lambda content: (_ for _ in ()).throw(OSError('disk full'))) + + with pytest.raises(OSError): + manager.save_entries(target) + + assert target.read_text() == 'version = 1\nchannels = []\n' + assert [p.name for p in tmp_path.iterdir() if p.name.endswith('.tmp')] == [] + + +def test_without_target_a_parameter_actuator_sets_the_parameter_and_its_move_is_done(): + register('WaveformParameter', DAQ_Move_WaveformParameter) + with loaded_extension(WaveformDesigner) as (dashboard, extension): + actuator = _actuator_on_amplitude(extension) + done = [] + actuator.move_done_signal.connect(done.append) + + actuator.move_abs(DataActuator('amplitude', data=0.5)) + + assert wait_for(lambda: done) + assert extension.settings['channels', 'ch0', 'parameters', 'amplitude'] == 0.5 + assert not actuator._in_error diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py index 4b70034..013b5fb 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -17,7 +17,7 @@ def create_waveform(name, **parameters): def test_registry_has_the_standard_forms(): assert {'dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise', - 'array'} <= set(WaveformFactory.names()) + 'file'} <= set(WaveformFactory.names()) assert WaveformFactory.get_class('sine') is wf.Sine and wf.Sine.name == 'sine' with pytest.raises(KeyError, match='Unknown waveform'): create_waveform('nope') @@ -135,13 +135,13 @@ def test_breakpoints_errors(text, message): def test_array_from_values_and_from_files(tmp_path): values = np.array([0., 1., 0.5]) - assert create_waveform('array', values=values).to_samples(100.).samples.tolist() == values.tolist() + assert create_waveform('file', values=values).to_samples(100.).samples.tolist() == values.tolist() np.save(tmp_path / 'wave.npy', values) - assert create_waveform('array', path=str(tmp_path / 'wave.npy')).to_samples(100.).samples.tolist() == values.tolist() + assert create_waveform('file', path=str(tmp_path / 'wave.npy')).to_samples(100.).samples.tolist() == values.tolist() (tmp_path / 'wave.csv').write_text('0\n1\n0.5\n') - assert create_waveform('array', path=str(tmp_path / 'wave.csv')).to_samples(100.).samples.tolist() == values.tolist() + assert create_waveform('file', path=str(tmp_path / 'wave.csv')).to_samples(100.).samples.tolist() == values.tolist() with pytest.raises(ValueError, match='No file'): - create_waveform('array').to_samples(100.) + create_waveform('file').to_samples(100.) def test_pint_quantities_are_converted(): @@ -158,7 +158,7 @@ def test_limits(): @pytest.mark.parametrize('name', ['dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise', - 'array']) + 'file']) def test_settings_roundtrip(name): """The params make a settings group and the waveform is read back from it""" cls = WaveformFactory.get_class(name) @@ -213,7 +213,7 @@ def test_waveform_field_refuses_inconsistent_arguments(): def test_only_the_numbers_are_scannable_by_default(): assert WaveformFactory.get_class('sine').scannable_parameters() == ['amplitude', 'frequency', 'offset', 'phase'] - assert 'path' not in WaveformFactory.get_class('array').scannable_parameters() + assert 'path' not in WaveformFactory.get_class('file').scannable_parameters() def test_a_text_parameter_cannot_be_declared_scannable():