From 621819057399a5b92034a7170a9ec5daebcf6eb3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 09:40:16 +0000 Subject: [PATCH 1/8] Per-module clock source and start trigger in the generic AI viewer Each module has its own frequency, clock (internal, a terminal or the clock of another module) and start trigger. Tasks start in the order the sources require; with an external clock the 1D axis is in samples. The TOML format gains per-module clock and [modules..trigger]. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../source/examples/config_daqmx_example.toml | 12 +- docs/source/user_guide/config_files.rst | 16 +- docs/source/user_guide/nidaqmx_viewer_use.rst | 39 ++-- .../plugins_0D/daq_0Dviewer_NIDAQmx.py | 193 +++++++++++------- .../national_instruments/NIDAQmx_AI.py | 57 ++++-- .../national_instruments/config_files.py | 66 ++++-- tests/test_config_files.py | 38 ++-- tests/test_generic_ai_configuration.py | 50 +++-- tests/test_generic_ai_plugin.py | 174 +++++++++------- 9 files changed, 397 insertions(+), 248 deletions(-) diff --git a/docs/source/examples/config_daqmx_example.toml b/docs/source/examples/config_daqmx_example.toml index bc9bda9..48c0abc 100644 --- a/docs/source/examples/config_daqmx_example.toml +++ b/docs/source/examples/config_daqmx_example.toml @@ -29,6 +29,13 @@ product = "NI 9217" [modules.cDAQ1Mod3] product = "NI 9205" +frequency = 1000 +clock = "/cDAQ1/PFI1" + +[modules.cDAQ1Mod3.trigger] +type = "digital edge" +terminal = "/cDAQ1/PFI0" +edge = "rising" [modules.cDAQ1Mod3.ai.ai0] type = "voltage" @@ -46,8 +53,3 @@ info = "Example of AI voltage channel" [modules.cDAQ1Mod4] product = "NI 9203" - -[trigger] -type = "digital edge" -terminal = "/cDAQ1/PFI0" -edge = "rising" diff --git a/docs/source/user_guide/config_files.rst b/docs/source/user_guide/config_files.rst index ea38434..a8b65be 100644 --- a/docs/source/user_guide/config_files.rst +++ b/docs/source/user_guide/config_files.rst @@ -40,13 +40,15 @@ Format its module and its key: ``[modules.cDAQ1Mod3.ai.ai0]`` is the channel ``cDAQ1Mod3/ai0``, so the module of a channel is the device its name starts with. ``product`` is the product type of the module, informative. ``frequency`` is optional: the sampling frequency of the module in Hz, a positive - integer. The generic viewer acquires each module with its own task, so each has its own frequency. - -``[trigger]`` - Optional: what starts the tasks. A digital trigger starts the task of every module; an analog one watches a channel of - the file and starts only the task of its module. ``type`` is ``digital edge`` (``terminal``, such as - ``/cDAQ1/PFI0``, and ``edge``) or ``analog edge`` (``channel``, a channel of the file such as ``cDAQ1Mod3/ai0`` or a dedicated analog trigger - terminal such as ``/Dev1/APFI0``, ``level`` in volts, inside the range of the channel, and ``edge``). ``edge`` is ``rising`` (the default) or ``falling``. Without this table the tasks start at once. + integer. The generic viewer acquires each module with its own task, so each has its own frequency (with an external + clock, the highest frequency of that clock). ``clock`` is optional: a terminal such as ``/cDAQ1/PFI1`` or + ``/cDAQ1Mod1/ai/SampleClock`` (the clock of another module); without it the module uses its own clock. + +``[modules..trigger]`` + Optional: what starts the task of the module; without it the task starts at once. ``type`` is ``digital edge`` + (``terminal``, such as ``/cDAQ1/PFI0``, and ``edge``) or ``analog edge`` (``channel``, a channel of the module such + as ``cDAQ1Mod3/ai0`` or a dedicated analog trigger terminal such as ``/Dev1/APFI0``, ``level`` in volts, inside the + range of the channel, and ``edge``). ``edge`` is ``rising`` (the default) or ``falling``. ``[modules..ai.]`` One table for each analog input channel. The channel is ``/`` (``cDAQ1Mod3/ai0``) and the order of diff --git a/docs/source/user_guide/nidaqmx_viewer_use.rst b/docs/source/user_guide/nidaqmx_viewer_use.rst index 01a8ba8..02b39d4 100644 --- a/docs/source/user_guide/nidaqmx_viewer_use.rst +++ b/docs/source/user_guide/nidaqmx_viewer_use.rst @@ -31,7 +31,7 @@ How to use it The channels are acquired by one task for each module (the device their name starts with, ``cDAQ1Mod1`` for ``cDAQ1Mod1/ai0``), because the modules of a chassis cannot always share a clock (the delta-sigma modules such as the NI 9211 and NI 9217 cannot be timed with others). Each task gives its own data, named ``NI AI `` (``NI AI cDAQ1Mod1``), and the tasks -start one after the other, without any alignment of their samples. A start trigger shared by the tasks (see below) is +start one after the other, without any alignment of their samples. A common clock or start trigger (see below) is the way to align them when the hardware allows it. The driver refuses to put in one task modules that cannot share a clock (error -201425, which the plugin turns into a message naming the devices): the generic viewer avoids it, as each module has its own task. @@ -44,14 +44,25 @@ Settings * **Display type**: ``0D`` gives the mean of the samples of each channel (with its standard error), ``1D`` gives the trace as a function of time. * **Frequency Acq.**: the sampling rate that a module starts with. -* **Module frequencies**: one frequency for each module of the channels (they appear and disappear with the - channels), as a module can need a rate of its own. Each module is acquired at its frequency. -* **Start trigger**: ``none`` (the tasks start at once), ``digital edge`` (a *Terminal* such as ``/Dev1/PFI0`` and - an *Edge*) or ``analog edge`` (a *Channel*, a *Level* in volts and an *Edge*). A digital trigger starts the task of - every module. An analog trigger watches one of the channels of the tree, which the driver requires to be a channel of - the task, so it starts only the task of that channel's module (the others start at once); the channel is acquired - like the others. The list also offers the dedicated analog trigger terminals (``/Dev1/APFI0``) of the devices of the - channels, for the devices that have some: such a terminal is not acquired, and starts the task of its device. +* **Modules**: one group for each module of the channels (they appear and disappear with the channels), as a module + can need a rate, a clock and a start of its own. Each module is acquired by its own task, with: + + * **Frequency**: the sampling rate of the module. With an external clock it is the highest frequency that clock + can have (the driver needs it to size its buffer), not the real one. + * **Clock**: ``internal`` (the module times itself), a terminal wired to the device (``/Dev1/PFI1``), or the clock + exported by another module (``/Dev1/ai/SampleClock``), which makes the modules share one clock. Any module may + follow an external clock. A module cannot be offered its own clock. + * **Start trigger**: ``none`` (the task starts at once), ``digital edge`` (a *Terminal* such as ``/Dev1/PFI0``, or + the start trigger exported by another module, and an *Edge*) or ``analog edge`` (a *Channel*, a *Level* in volts + and an *Edge*). An analog trigger watches one of the channels of the module, which the driver requires to be a + channel of the task (set its ``read`` box off if you do not want its samples); the list also offers the dedicated + analog trigger terminals (``/Dev1/APFI0``) of the module, if it has some: such a terminal is not acquired. + + The tasks start in the order that their sources require: a module that waits for the clock or the trigger of another + one starts first and the one that provides the signal starts last. Two modules that wait for each other cannot be + started: the plugin says so, and one of them has to use its own clock. + With an external clock the time between samples is not known, so the 1D axis is the sample index (no unit) and not + the time in seconds. * **Nsamples** (``1D`` only): the length of the trace. In ``0D`` the number of points averaged is the *Naverage* of the viewer, and in ``1D`` *Naverage* is the number of traces averaged. The driver needs at least two samples for a clocked acquisition: *Nsamples* cannot be below 2, and with *Naverage* = 1 two samples are acquired and the first @@ -77,16 +88,16 @@ The parameters below are in the ``NIDAQmx config`` group of the settings. the state manager of the Dashboard, which sets the menu again, and so loads the same file. The list is read when the plugin starts, and again after a save. * **Configuration** also loads the channels: choosing a file replaces the channels of the tree by the ones of the - file, in the order of the file (which is the order of the data), the frequency of each module and the start trigger - (none if the file has none). You can then add, remove or change channels as + file, in the order of the file (which is the order of the data), the frequency, the clock and the start trigger of each module + (internal clock and no trigger if the file has none). You can then add, remove or change channels as usual, also from several devices: the file is only read, never changed, unless you save. One file is one configuration: to work with another set of channels, save it under another suffix. -* As soon as the tree is not what the file describes any more (a channel added, removed or changed, a frequency or - the trigger modified), the menu goes back to ``(manual)``, so that it never shows a configuration that is not in the tree. To get the +* As soon as the tree is not what the file describes any more (a channel added, removed or changed, a frequency, a clock or + a trigger modified), the menu goes back to ``(manual)``, so that it never shows a configuration that is not in the tree. To get the file back, choose it again in the menu. * **Save as...**: a button with a LED. A click opens a small dialog asking the *Suffix* of the file (``config_daqmx_.toml``; ``default`` is the file without suffix), proposed with the configuration loaded. - The file then describes exactly the channels of the tree, the frequency of each module and the start trigger + The file then describes exactly the channels of the tree, the frequency, the clock and the start trigger of each module (those of an existing file that are not in the tree are removed). The format of the file groups the channels by module, so each channel is written in the module its name starts with (``Dev1`` for ``Dev1/ai1``, ``cDAQ1Mod3`` for ``cDAQ1Mod3/ai0``): channels of several devices can be diff --git a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py index 21e50b9..c29e188 100644 --- a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py +++ b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py @@ -18,9 +18,36 @@ MANUAL = '(manual)' # no configuration file: the channels are the ones of the tree TRIGGER_TYPES = ['none', 'digital edge', 'analog edge'] +CLOCK_INTERNAL = 'internal' # the sample clock of the module itself DEFAULT = 'default' # the name of the configuration of the file without suffix +def _exporting_module(terminal: str) -> Optional[str]: + """The module that produces the signal ``terminal`` (``/Dev1/ai/SampleClock``), None for any other terminal.""" + parts = (terminal or '').split('/') + return parts[1] if len(parts) > 3 and parts[0] == '' and parts[2] == 'ai' else None + + +def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str]) -> dict: + """The settings of a module: its frequency, its clock and its start trigger.""" + return {'title': module, 'name': module, 'type': 'group', 'children': [ + {'title': 'Frequency:', 'name': 'frequency', 'type': 'int', 'value': frequency, 'min': 1, + 'tip': 'Sampling rate; with an external clock, the real frequency of that clock (the highest it may have)'}, + {'title': 'Clock:', 'name': 'clock', 'type': 'list', 'limits': clocks, 'value': CLOCK_INTERNAL, + 'tip': 'The clock of the module, or a terminal (a clock wired in, or the clock that another module exports)'}, + {'title': 'Start trigger:', 'name': 'trigger', 'type': 'group', 'children': [ + {'title': 'Type:', 'name': 'type', 'type': 'list', 'limits': TRIGGER_TYPES, 'value': 'none'}, + {'title': 'Terminal:', 'name': 'terminal', 'type': 'list', 'limits': terminals, 'visible': False}, + {'title': 'Channel:', 'name': 'channel', 'type': 'list', 'limits': channels, 'visible': False, + 'tip': 'A channel of this module (it is acquired) or a dedicated analog trigger terminal'}, + {'title': 'Edge:', 'name': 'edge', 'type': 'list', 'limits': ['rising', 'falling'], 'value': 'rising', + 'visible': False}, + {'title': 'Level (V):', 'name': 'level', 'type': 'float', 'value': 0., 'visible': False, + 'tip': 'Inside the range of the channel'}, + ]}, + ]} + + def _label(suffix: str) -> str: return suffix or DEFAULT @@ -40,15 +67,7 @@ class DAQ_0DViewer_NIDAQmx(DAQ_Viewer_AIBase): 'value': MANUAL}, save_param(), ]}, - {'title': 'Start trigger:', 'name': 'trigger', 'type': 'group', 'children': [ - {'title': 'Type:', 'name': 'type', 'type': 'list', 'limits': TRIGGER_TYPES, 'value': 'none'}, - {'title': 'Terminal:', 'name': 'terminal', 'type': 'list', 'limits': [], 'visible': False}, - {'title': 'Channel:', 'name': 'channel', 'type': 'list', 'limits': [], 'visible': False}, - {'title': 'Edge:', 'name': 'edge', 'type': 'list', 'limits': ['rising', 'falling'], 'value': 'rising', - 'visible': False}, - {'title': 'Level (V):', 'name': 'level', 'type': 'float', 'value': 0., 'visible': False}, - ]}, - {'title': 'Module frequencies:', 'name': 'frequencies', 'type': 'group', 'children': []}, + {'title': 'Modules:', 'name': 'modules', 'type': 'group', 'children': []}, {'title': 'Channels:', 'name': 'channels', 'type': 'ni_channels', 'kind': ChannelKind.AI.value, 'limits': [], 'children': []}, ] @@ -58,8 +77,7 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) system = NIDAQSystem() self.settings.child('channels').setLimits(system.all_channels(ChannelKind.AI)) - self.settings.child('trigger', 'terminal').setLimits( - [terminal for device in system.devices() for terminal in system.terminals(device)]) + self.terminals = [terminal for device in system.devices() for terminal in system.terminals(device)] self.files = ConfigFiles() self.loaded = MANUAL # the configuration whose channels are in the tree self.in_file = () # what the file describes (see `snapshot`), to tell if the tree still is the file @@ -91,12 +109,12 @@ def _load(self, label: str) -> None: channels = [channel for module in configuration.modules for channel in configuration.channels(module)] unread = {name for module in configuration.modules for name in configuration.unread(module)} self.settings.child('channels').setChannels(channels, unread) - self.sync_frequencies() - self.sync_trigger_channels() - for module in self.modules(): # a module that the file gives no frequency to goes back to the global one - frequency = configuration.frequency(module) or self.settings['frequency'] - self.settings.child('frequencies', module).setValue(frequency) - self.set_trigger(configuration.trigger) + self.sync_modules() + for module in self.modules(): # what the file does not give goes back to the default + group = self.settings.child('modules', module) + group.child('frequency').setValue(configuration.frequency(module) or self.settings['frequency']) + group.child('clock').setValue(configuration.clock(module) or CLOCK_INTERNAL) + self.set_module_trigger(module, configuration.trigger(module)) self.loaded = label self.in_file = self.snapshot() self.settings.child('config', 'save').setOpts(suffix=label) # what the dialog of the save button proposes @@ -110,7 +128,7 @@ def save_configuration(self, button: Parameter) -> None: existing file the description, the devices and the notes of the channels that stay are kept. """ suffix = _suffix(button.opts['suffix']) - self.sync_frequencies() + self.sync_modules() channels = self.channels() if not channels: raise ValueError('There is no channel to save') @@ -124,8 +142,11 @@ def save_configuration(self, button: Parameter) -> None: for module, module_channels in by_module.items(): configuration = configuration.with_channels( module, module_channels, unread=[c.name for c in module_channels if c.name in unread]) - configuration = configuration.with_frequency(module, self.settings['frequencies', module]) - self.files.save(suffix, configuration.with_trigger(self.trigger_keys())) + group = self.settings.child('modules', module) + configuration = configuration.with_frequency(module, group['frequency']) + configuration = configuration.with_clock(module, '' if group['clock'] == CLOCK_INTERNAL else group['clock']) + configuration = configuration.with_trigger(module, self.trigger_keys(module)) + self.files.save(suffix, configuration) self.refresh_menu() self.loaded, self.in_file = _label(suffix), self.snapshot() # the tree is that file now self.settings.child('config', 'configuration').setValue(self.loaded) @@ -147,47 +168,55 @@ def modules(self) -> List[str]: names = [child.opts['title'].split('/')[0] for child in self.settings.child('channels').children()] return list(dict.fromkeys(names)) - def sync_trigger_channels(self) -> None: - """What an analog trigger can watch: the channels of the tree (the driver only accepts a channel of the task) - and the dedicated analog trigger terminals (``/Dev1/APFI0``) of the devices of the tree, which are not read.""" - names = [child.opts['title'] for child in self.settings.child('channels').children()] - system = NIDAQSystem() - for module in self.modules(): - try: - names += [t for t in system.terminals(module) if '/APFI' in t] - except ValueError: # a module that is not a device of the system - pass - channel = self.settings.child('trigger', 'channel') - if channel.opts['limits'] != names: - channel.setLimits(names) - - def sync_frequencies(self) -> None: - """One frequency for each module of the channels: a new module starts at the global frequency.""" - group = self.settings.child('frequencies') + def sync_modules(self) -> None: + """One group of settings for each module of the channels (frequency, clock, start trigger): a new module + starts at the global frequency, on its own clock, without trigger. The lists of terminals follow the modules: + a module can use the clock or the start trigger that another module of the tree exports.""" + group = self.settings.child('modules') modules = self.modules() for child in group.children(): if child.name() not in modules: group.removeChild(child) for module in modules: + lists = self.module_lists(module) if module not in group.names: - group.addChild({'title': f'{module}:', 'name': module, 'type': 'int', 'min': 1, - 'value': self.settings['frequency']}) - - def trigger_for(self, acquisition: Acquisition): - """The start trigger chosen in the settings for the task of ``acquisition``, or None. A digital trigger starts - every task; an analog one watches a channel of its task, so it starts only the task of that channel.""" - settings = self.settings.child('trigger') - kind = settings['type'] - if kind == 'digital edge': - return DigitalEdgeTrigger(settings['terminal'], Edge[settings['edge'].upper()]) - source = settings['channel'] - if kind == 'analog edge' and (source in acquisition.labels or source.startswith(f'/{acquisition.name}/')): - return AnalogEdgeTrigger(settings['channel'], settings['level'], Slope[settings['edge'].upper()]) - return None - - def trigger_keys(self) -> Optional[dict]: - """The start trigger of the tree as the keys of the ``[trigger]`` table of a file, or None.""" - settings = self.settings.child('trigger') + group.addChild(module_group(module, self.settings['frequency'], **lists)) + continue + self.set_limits(group.child(module, 'clock'), lists['clocks']) + self.set_limits(group.child(module, 'trigger', 'terminal'), lists['terminals']) + self.set_limits(group.child(module, 'trigger', 'channel'), lists['channels']) + + @staticmethod + def set_limits(param: Parameter, limits: List[str]) -> None: + if param.opts['limits'] != limits: + param.setLimits(limits) + + def module_lists(self, module: str) -> dict: + """What the settings of ``module`` choose among. A terminal of its own ``ai`` subsystem cannot time it.""" + others = [m for m in self.modules() if m != module] + own = f'/{module}/ai/' + terminals = [t for t in self.terminals if not t.startswith(own)] + names = [child.opts['title'] for child in self.settings.child('channels').children() + if child.opts['title'].split('/')[0] == module] + try: # the dedicated analog trigger terminals of the device, which are not read + apfi = [t for t in NIDAQSystem().terminals(module) if '/APFI' in t] + except ValueError: # a module that is not a device of the system + apfi = [] + return {'clocks': [CLOCK_INTERNAL] + terminals + [f'/{m}/ai/SampleClock' for m in others], + 'terminals': terminals + [f'/{m}/ai/StartTrigger' for m in others], 'channels': names + apfi} + + def module_trigger(self, module: str): + """The start trigger of ``module`` as the API describes it, None if it starts at once.""" + keys = self.trigger_keys(module) + if keys is None: + return None + if keys['type'] == 'digital edge': + return DigitalEdgeTrigger(keys['terminal'], Edge[keys['edge'].upper()]) + return AnalogEdgeTrigger(keys['channel'], keys['level'], Slope[keys['edge'].upper()]) + + def trigger_keys(self, module: str) -> Optional[dict]: + """The start trigger of ``module`` as the keys of the ``trigger`` table of a file, or None.""" + settings = self.settings.child('modules', module, 'trigger') if settings['type'] == 'digital edge': return {'type': 'digital edge', 'terminal': settings['terminal'], 'edge': settings['edge']} if settings['type'] == 'analog edge': @@ -195,27 +224,20 @@ def trigger_keys(self) -> Optional[dict]: 'edge': settings['edge']} return None - def set_trigger(self, keys: Optional[dict]) -> None: + def set_module_trigger(self, module: str, keys: Optional[dict]) -> None: """Put the trigger of a file in the tree (no trigger if the file has none).""" - settings = self.settings.child('trigger') + settings = self.settings.child('modules', module, 'trigger') keys = keys or {'type': 'none'} settings.child('type').setValue(keys['type']) for key in ('terminal', 'channel', 'level'): if key in keys: settings.child(key).setValue(keys[key]) settings.child('edge').setValue(keys.get('edge', 'rising')) - self.show_trigger() - - def snapshot(self) -> tuple: - """What a configuration file describes in the tree: the channels, the frequency of each module and the - trigger.""" - self.sync_frequencies() - frequencies = tuple((child.name(), child.value()) for child in self.settings.child('frequencies').children()) - return tuple(self.channels()), tuple(unread_of(self.settings.child('channels'))), frequencies, self.trigger_keys() + self.show_trigger(module) - def show_trigger(self) -> None: + def show_trigger(self, module: str) -> None: """Only the parameters of the chosen type of trigger are visible.""" - settings = self.settings.child('trigger') + settings = self.settings.child('modules', module, 'trigger') kind = settings['type'] settings.child('terminal').setOpts(visible=kind == 'digital edge') settings.child('channel').setOpts(visible=kind == 'analog edge') @@ -223,16 +245,34 @@ def show_trigger(self) -> None: settings.child('edge').setOpts(visible=kind != 'none') def acquisitions(self) -> List[Acquisition]: - """One task for each module: the channels of a module are acquired together, at its own frequency.""" - self.sync_frequencies() # the channels may have been added without the GUI telling the plugin - self.sync_trigger_channels() + """One task for each module: its channels are acquired together, at its frequency, on its clock, started by + its trigger.""" + self.sync_modules() # the channels may have been added without the GUI telling the plugin by_module = {} for channel in self.channels(): by_module.setdefault(channel.name.split('/')[0], []).append(channel) unread = unread_of(self.settings.child('channels')) - return [Acquisition(module, channels, self.settings['frequencies', module], - tuple(c.name for c in channels if c.name in unread)) - for module, channels in by_module.items()] + acquisitions = [] + for module, channels in by_module.items(): + group = self.settings.child('modules', module) + clock = '' if group['clock'] == CLOCK_INTERNAL else group['clock'] + trigger = self.module_trigger(module) + key = {'digital edge': 'terminal', 'analog edge': 'channel'}.get(group['trigger', 'type']) + sources = [clock] + ([group['trigger', key]] if key is not None else []) + waits = tuple(dict.fromkeys(m for m in (_exporting_module(source) for source in sources) + if m not in (None, module) and m in by_module)) + acquisitions.append(Acquisition(module, channels, group['frequency'], + tuple(c.name for c in channels if c.name in unread), clock, trigger, waits)) + return acquisitions + + def snapshot(self) -> tuple: + """What a configuration file describes in the tree: the channels and, for each module, its frequency, clock + and trigger.""" + self.sync_modules() + modules = tuple((module, self.settings['modules', module, 'frequency'], + self.settings['modules', module, 'clock'], self.trigger_keys(module)) + for module in self.modules()) + return tuple(self.channels()), tuple(unread_of(self.settings.child('channels'))), modules def leave_configuration_if_modified(self) -> None: """The menu goes back to ``(manual)`` as soon as the tree is not what the file describes any more: its @@ -281,11 +321,10 @@ def commit_settings(self, param: Parameter) -> None: if param.name() == 'type' and param.parent() is not None and param.parent().parent() is self.settings.child( 'channels'): # the type of a channel: its group is rebuilt set_type(ChannelKind.AI, param.parent(), param.value()) - if param.name() == 'type' and param.parent() is self.settings.child('trigger'): - self.show_trigger() + if param.name() == 'type' and param.parent() is not None and param.parent().name() == 'trigger': + self.show_trigger(param.parent().parent().name()) self.leave_configuration_if_modified() - self.sync_frequencies() - self.sync_trigger_channels() + self.sync_modules() super().commit_settings(param) diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py index 7cd3078..28807db 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py @@ -39,6 +39,9 @@ class Acquisition: channels: list frequency: int unread: tuple = () # names of the channels that are in the task but not in the data + clock: str = '' # terminal of the sample clock, empty for the onboard clock of the module + trigger: Optional[object] = None # what starts the task (a trigger of the API), None to start it at once + waits_for: tuple = () # the other modules whose signals the task waits for (their clock, their trigger...) @property def rows(self) -> List[int]: @@ -51,6 +54,31 @@ def labels(self) -> List[str]: return [self.channels[i].name for i in self.rows] +def trace_axis(acquisition: 'Acquisition', points: int, index: int) -> Axis: + """The axis along a trace: time in seconds, or the number of the sample if the clock is external, as the rate that + is given to the driver is then only the highest the clock may have, so a time computed with it could be false.""" + if acquisition.clock: + return Axis('sample', '', data=np.arange(points, dtype=float), index=index) + return Axis('time', 's', data=np.arange(points) / acquisition.frequency, index=index) + + +def start_order(acquisitions: List['Acquisition']) -> List[int]: + """The order in which to start the tasks: a task that waits for a signal of another module (its clock, its + trigger) is armed before the module that gives it. A loop of such waits is a ``ValueError`` naming the modules.""" + names = [a.name for a in acquisitions] + pending = list(range(len(acquisitions))) + order = [] + while pending: + # a task can start once no pending task waits for it + ready = [i for i in pending if not any(names[i] in acquisitions[j].waits_for for j in pending if j != i)] + if not ready: + raise ValueError('The modules ' + ', '.join(names[i] for i in pending) + ' wait for each other\'s signals ' + '(clock or trigger): one of them has to use its own clock') + order.append(ready[0]) + pending.remove(ready[0]) + return order + + class DAQ_Viewer_AIBase(DAQ_Viewer_base): """Acquire points at `frequency` on one or several analog inputs, as 0D (mean) or 1D data. @@ -72,6 +100,7 @@ class DAQ_Viewer_AIBase(DAQ_Viewer_base): def ini_attributes(self): self.controller = None # the task of this plugin, or the group of its tasks when it has several self.tasks: List[AnalogInputTask] = [] # one per acquisition + self.start_order: List[int] = [] # the indexes of the tasks in the order they start self.acquisitions_done: List[Acquisition] = [] # what each task acquires, in the order of the tasks self._signature = None # what the tasks were built for, to rebuild them when the settings changed self.live: bool = False @@ -97,10 +126,6 @@ def acquisitions(self) -> List[Acquisition]: channels = self.channels() return [Acquisition('', channels, self.settings['frequency'])] if channels else [] - def trigger_for(self, acquisition: Acquisition): - """What starts the task of ``acquisition`` (a trigger of the API), or None to start it at once.""" - return None - def data_names(self, acquisitions: List[Acquisition]) -> List[str]: return [f'{self.data_name} {a.name}' if a.name else self.data_name for a in acquisitions] @@ -111,6 +136,7 @@ def ini_detector(self, controller=None) -> Tuple[str, bool]: else: # a slave uses the task of its master, which owns it: it neither replaces nor closes it self.controller = controller self.tasks = [controller] + self.start_order = [0] self.acquisitions_done = [Acquisition('', self.channels(), self.settings['frequency'])] self._signature = self.signature() return 'Analog input ready', True @@ -132,8 +158,7 @@ def task_samples(self) -> int: def signature(self, streaming: bool = False): """What the tasks are built for: the channels and the frequency of each, and the samples of finite tasks.""" samples = None if streaming else self.task_samples() - return tuple((tuple(a.channels), a.frequency, samples, self.trigger_for(a), a.unread) - for a in self.acquisitions()) + return tuple(self.acquisitions()), samples def update_tasks(self, streaming: bool = False) -> None: """Replace the tasks by ones that follow the settings: finite for a snap, continuous for the live mode.""" @@ -142,25 +167,31 @@ def update_tasks(self, streaming: bool = False) -> None: if not acquisitions: # a task needs a channel: they are built when the first one is added return samples = None if streaming else self.task_samples() + order = start_order(acquisitions) # before the tasks: a loop of waits must not leave tasks open tasks = [] try: for acquisition in acquisitions: - clock = ClockSettings(rate=acquisition.frequency, samples=samples) + clock = ClockSettings(rate=acquisition.frequency, samples=samples, source=acquisition.clock) tasks.append(AnalogInputTask(TaskConfig(channels=acquisition.channels, timing=clock, - trigger=self.trigger_for(acquisition)))) + trigger=acquisition.trigger))) except Exception: for task in reversed(tasks): task.close() raise self.tasks, self.acquisitions_done = tasks, acquisitions + self.start_order = order self.controller = tasks[0] if len(tasks) == 1 else TaskGroup(*tasks) self._signature = self.signature(streaming) + def ordered_tasks(self) -> List[AnalogInputTask]: + """The tasks in the order they start: the ones that wait for the signal of another module come first.""" + return [self.tasks[i] for i in self.start_order] + def read_samples(self) -> List[np.ndarray]: """Run one finite acquisition of each task, together, and return their arrays (nchannels, Nsamples).""" started = [] try: - for task in self.tasks: + for task in self.ordered_tasks(): task.start() started.append(task) return [task.read_analog() for task in self.tasks] @@ -200,7 +231,7 @@ def start_live(self) -> None: self._bridges.append(bridge) started = [] try: - for task in self.tasks: + for task in self.ordered_tasks(): task.start(notify_every=self.samples_per_block()) started.append(task) except Exception: @@ -250,17 +281,17 @@ def emit_traces(self, traces: List[List[np.ndarray]], indexes: Optional[List[int if not acquisition.rows: continue series = [trace[acquisition.rows] for trace in series] # the channels that are read - times = np.arange(series[0].shape[1]) / acquisition.frequency + points = series[0].shape[1] if len(series) == 1: # nothing to average, so no error either data.append(DataFromPlugins(name=names[index], data=[row for row in series[0]], dim='Data1D', labels=acquisition.labels, - axes=[Axis('time', 's', data=times, index=0)])) + axes=[trace_axis(acquisition, points, 0)])) continue stack = np.stack(series) # (traces, channels, points): the traces are the first, navigation, axis acquisitions = Axis('acquisition', data=np.arange(float(len(series))), index=0) averaged = DataFromPlugins(name=names[index], data=[stack[:, ch, :] for ch in range(stack.shape[1])], dim='DataND', nav_indexes=(0,), labels=acquisition.labels, - axes=[acquisitions, Axis('time', 's', data=times, index=1)]) + axes=[acquisitions, trace_axis(acquisition, points, 1)]) data.append(averaged.mean_with_errors(axis=0)) self.dte_signal.emit(DataToExport(self.data_name, data=data)) diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/config_files.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/config_files.py index eb69fc7..7f35587 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/config_files.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/config_files.py @@ -19,7 +19,7 @@ FORMAT_VERSION = 1 -#: the keys of the ``[trigger]`` table for each type of start trigger (``edge`` is optional) +#: the keys of the ``trigger`` table of a module for each type of start trigger (``edge`` is optional) TRIGGER_KEYS = {'digital edge': ('terminal', 'edge'), 'analog edge': ('channel', 'level', 'edge')} #: channel types of a configuration file, by the ``type`` key, for each kind of channel @@ -45,6 +45,8 @@ class _Module: notes: Dict[str, str] = field(default_factory=dict) # channel name -> free text of the file frequency: Optional[int] = None # sampling frequency of the module, None if not given unread: set = field(default_factory=set) # names of the channels in the task but not in the data + clock: str = '' # terminal of the sample clock, '' for the onboard clock + trigger: Optional[dict] = None # the start trigger, as the keys of its table, or None class Configuration: @@ -54,7 +56,6 @@ def __init__(self, description: str = ''): self.description = description self.devices: Dict[str, str] = {} # device name -> product self.modules: Dict[str, _Module] = {} # module name -> its content - self.trigger: Optional[dict] = None # the start trigger, as the keys of the [trigger] table, or None def channels(self, module: str) -> list: return list(self.modules[module].channels) if module in self.modules else [] @@ -65,19 +66,19 @@ def _copy(self) -> 'Configuration': new.modules = {name: dataclasses.replace(mod, channels=list(mod.channels), notes=dict(mod.notes), unread=set(mod.unread)) for name, mod in self.modules.items()} - new.trigger = self.trigger return new def with_channels(self, module: str, channels: list, product: str = '', unread=None) -> 'Configuration': """A copy where ``module`` has these channels (the notes of the channels that stay, and its frequency, are - kept). ``unread`` names the channels that are in the task but not in the data; by default the ones that were + kept, and so are its clock and trigger). ``unread`` names the channels that are in the task but not in the data; by default the ones that were not read stay so.""" new = self._copy() previous = new.modules.get(module, _Module(product)) kept = {channel.name: previous.notes.get(channel.name, '') for channel in channels} names = {channel.name for channel in channels} not_read = {name for name in (previous.unread if unread is None else unread) if name in names} - new.modules[module] = _Module(product or previous.product, list(channels), kept, previous.frequency, not_read) + new.modules[module] = _Module(product or previous.product, list(channels), kept, previous.frequency, not_read, + previous.clock, previous.trigger) return new def unread(self, module: str) -> set: @@ -94,11 +95,24 @@ def with_frequency(self, module: str, frequency: Optional[int]) -> 'Configuratio new.modules[module].frequency = frequency return new - def with_trigger(self, trigger: Optional[dict]) -> 'Configuration': - """A copy with the start trigger ``trigger`` (``None``, or the keys of the ``[trigger]`` table), shared by - the tasks of all the modules.""" - new = self._copy() - new.trigger = trigger + def clock(self, module: str) -> str: + """The terminal of the sample clock of ``module`` (such as ``/Dev1/PFI1``); empty for its onboard clock.""" + return self.modules[module].clock if module in self.modules else '' + + def with_clock(self, module: str, clock: str) -> 'Configuration': + """A copy where ``module`` is timed by the terminal ``clock`` (empty for its onboard clock).""" + new = self.with_channels(module, self.channels(module)) + new.modules[module].clock = clock + return new + + def trigger(self, module: str) -> Optional[dict]: + """The start trigger of ``module`` as the keys of its ``trigger`` table, ``None`` if it starts at once.""" + return self.modules[module].trigger if module in self.modules else None + + def with_trigger(self, module: str, trigger: Optional[dict]) -> 'Configuration': + """A copy where ``module`` starts on ``trigger`` (``None``, or the keys of its ``trigger`` table).""" + new = self.with_channels(module, self.channels(module)) + new.modules[module].trigger = trigger return new @@ -216,11 +230,13 @@ def load(self, suffix: str) -> Configuration: module = configuration.modules[name] = _Module(entry.get('product', '')) if 'frequency' in entry: module.frequency = self._frequency(path, name, entry['frequency']) + if 'clock' in entry: + module.clock = self._clock(path, name, entry['clock']) + if 'trigger' in entry: + module.trigger = self._trigger(path, name, entry['trigger']) for kind in ChannelKind: for key, channel_entry in entry.get(kind.value, {}).items(): self._add(path, module, name, kind, key, channel_entry) - if 'trigger' in content: - configuration.trigger = self._trigger(path, content['trigger']) return configuration @staticmethod @@ -230,26 +246,32 @@ def _frequency(path, module, value) -> int: return value @staticmethod - def _trigger(path, table: dict) -> Optional[dict]: - """The ``[trigger]`` table, checked: the keys of its type are required and the others are dropped.""" + def _clock(path, module, value) -> str: + if not isinstance(value, str): + raise ConfigFileError(f'{path}: [modules.{module}] clock must be the text of a terminal, got {value!r}') + return value + + @staticmethod + def _trigger(path, module, table: dict) -> Optional[dict]: + """The ``[modules..trigger]`` table, checked: the keys of its type are required and the others are dropped.""" kind = table.get('type') if kind not in TRIGGER_KEYS: - raise ConfigFileError(f"{path}: [trigger] type must be one of {sorted(TRIGGER_KEYS)}, got {kind!r}") + raise ConfigFileError(f"{path}: [modules.{module}.trigger] type must be one of {sorted(TRIGGER_KEYS)}, got {kind!r}") trigger = {'type': kind} for key in TRIGGER_KEYS[kind]: if key not in table: if key == 'edge': continue # rising by default - raise ConfigFileError(f'{path}: [trigger] of type {kind!r} needs a {key!r}') + raise ConfigFileError(f'{path}: [modules.{module}.trigger] of type {kind!r} needs a {key!r}') trigger[key] = table[key] if trigger.get('edge', 'rising') not in ('rising', 'falling'): - raise ConfigFileError(f"{path}: [trigger] edge must be 'rising' or 'falling', got {trigger['edge']!r}") + raise ConfigFileError(f"{path}: [modules.{module}.trigger] edge must be 'rising' or 'falling', got {trigger['edge']!r}") for key in ('terminal', 'channel'): if key in trigger and not isinstance(trigger[key], str): - raise ConfigFileError(f'{path}: [trigger] {key} must be a text, got {trigger[key]!r}') + raise ConfigFileError(f'{path}: [modules.{module}.trigger] {key} must be a text, got {trigger[key]!r}') if 'level' in trigger: if isinstance(trigger['level'], bool) or not isinstance(trigger['level'], (int, float)): - raise ConfigFileError(f"{path}: [trigger] level must be a number, got {trigger['level']!r}") + raise ConfigFileError(f"{path}: [modules.{module}.trigger] level must be a number, got {trigger['level']!r}") trigger['level'] = float(trigger['level']) return trigger @@ -301,13 +323,15 @@ def save(self, suffix: str, configuration: Configuration) -> None: entry = content['modules'][name] = {'product': module.product} if module.frequency is not None: entry['frequency'] = module.frequency + if module.clock: + entry['clock'] = module.clock + if module.trigger is not None: + entry['trigger'] = module.trigger if module.channels: entry[ChannelKind.AI.value] = { channel.name.split('/')[-1]: _encode(channel, module.notes.get(channel.name, ''), channel.name not in module.unread) for channel in module.channels} - if configuration.trigger is not None: - content['trigger'] = configuration.trigger self.folder.mkdir(parents=True, exist_ok=True) self.path(suffix).write_text(toml.dumps(content)) diff --git a/tests/test_config_files.py b/tests/test_config_files.py index 515426c..dc10fa9 100644 --- a/tests/test_config_files.py +++ b/tests/test_config_files.py @@ -158,45 +158,53 @@ def test_the_example_of_the_user_guide_is_a_file_the_loader_accepts(tmp_path): 'cDAQ1Mod3/ai0', terminal_config=TerminalConfiguration.RSE) -def test_the_frequency_of_a_module_and_the_start_trigger_survive_a_round_trip(folder): +def test_the_frequency_clock_and_trigger_of_a_module_survive_a_round_trip(folder): files = ConfigFiles(folder) - configuration = files.load('').with_frequency('cDAQ1Mod1', 14).with_trigger( - {'type': 'digital edge', 'terminal': '/cDAQ1/PFI0', 'edge': 'falling'}) + configuration = (files.load('').with_frequency('cDAQ1Mod1', 14).with_clock('cDAQ1Mod1', '/cDAQ1/PFI1') + .with_trigger('cDAQ1Mod1', {'type': 'digital edge', 'terminal': '/cDAQ1/PFI0', 'edge': 'falling'})) files.save('timed', configuration) loaded = files.load('timed') assert loaded.frequency('cDAQ1Mod1') == 14 and loaded.frequency('cDAQ1Mod3') is None - assert loaded.trigger == {'type': 'digital edge', 'terminal': '/cDAQ1/PFI0', 'edge': 'falling'} + assert loaded.clock('cDAQ1Mod1') == '/cDAQ1/PFI1' and loaded.clock('cDAQ1Mod3') == '' # '' is the onboard clock + assert loaded.trigger('cDAQ1Mod1') == {'type': 'digital edge', 'terminal': '/cDAQ1/PFI0', 'edge': 'falling'} + assert loaded.trigger('cDAQ1Mod3') is None assert loaded.channels('cDAQ1Mod1') == files.load('').channels('cDAQ1Mod1') -def test_changing_the_channels_of_a_module_keeps_its_frequency(folder): - configuration = ConfigFiles(folder).load('').with_frequency('cDAQ1Mod3', 250) +def test_changing_the_channels_of_a_module_keeps_its_frequency_clock_and_trigger(folder): + trigger = {'type': 'analog edge', 'channel': 'cDAQ1Mod3/ai0', 'level': 1.0, 'edge': 'rising'} + configuration = (ConfigFiles(folder).load('').with_frequency('cDAQ1Mod3', 250).with_clock('cDAQ1Mod3', '/x/PFI0') + .with_trigger('cDAQ1Mod3', trigger)) channels = configuration.channels('cDAQ1Mod3')[:1] - assert configuration.with_channels('cDAQ1Mod3', channels).frequency('cDAQ1Mod3') == 250 + changed = configuration.with_channels('cDAQ1Mod3', channels) + assert (changed.frequency('cDAQ1Mod3'), changed.clock('cDAQ1Mod3'), changed.trigger('cDAQ1Mod3')) == ( + 250, '/x/PFI0', trigger) -def test_a_file_without_frequency_nor_trigger_loads_as_before_and_is_saved_without_them(folder): + +def test_a_file_without_frequency_clock_nor_trigger_loads_as_before_and_is_saved_without_them(folder): files = ConfigFiles(folder) files.save('plain', files.load('')) text = files.path('plain').read_text() - assert 'frequency' not in text and '[trigger]' not in text - assert files.load('plain').trigger is None + assert 'frequency' not in text and 'clock' not in text and 'trigger' not in text + assert files.load('plain').trigger('cDAQ1Mod1') is None @pytest.mark.parametrize('text, where', [ ('[modules.Dev1]\nfrequency = 0\n', "frequency"), ('[modules.Dev1]\nfrequency = "fast"\n', "frequency"), - ('[trigger]\ntype = "magic"\n', "type"), - ('[trigger]\ntype = "digital edge"\n', "terminal"), - ('[trigger]\ntype = "analog edge"\nchannel = "Dev1/ai0"\n', "level"), - ('[trigger]\ntype = "digital edge"\nterminal = "/Dev1/PFI0"\nedge = "sideways"\n', "edge"), + ('[modules.Dev1]\nclock = 3\n', "clock"), + ('[modules.Dev1.trigger]\ntype = "magic"\n', "type"), + ('[modules.Dev1.trigger]\ntype = "digital edge"\n', "terminal"), + ('[modules.Dev1.trigger]\ntype = "analog edge"\nchannel = "Dev1/ai0"\n', "level"), + ('[modules.Dev1.trigger]\ntype = "digital edge"\nterminal = "/Dev1/PFI0"\nedge = "sideways"\n', "edge"), ]) -def test_a_wrong_frequency_or_trigger_is_reported_with_the_file_and_the_key(tmp_path, text, where): +def test_a_wrong_frequency_clock_or_trigger_is_reported_with_the_file_and_the_key(tmp_path, text, where): (tmp_path / 'config_daqmx.toml').write_text('version = 1\n' + text) with pytest.raises(ConfigFileError, match=where) as error: diff --git a/tests/test_generic_ai_configuration.py b/tests/test_generic_ai_configuration.py index c6670ba..175d9d9 100644 --- a/tests/test_generic_ai_configuration.py +++ b/tests/test_generic_ai_configuration.py @@ -322,15 +322,17 @@ def test_switching_configurations_chosen_in_the_gui_is_replayed_by_the_gui(qapp, plugin.close() -def test_the_frequencies_of_the_modules_and_the_trigger_are_saved_and_loaded_with_the_channels( +def test_the_frequency_clock_and_trigger_of_each_module_are_saved_and_loaded_with_the_channels( qapp, driver, system_driver, folder): plugin = make_detector(DAQ_0DViewer_NIDAQmx) group = plugin.settings.child('channels') group.addNew('Dev1/ai0') group.addNew('Dev2/ai3') plugin.commit_settings(group) - plugin.settings.child('frequencies', 'Dev2').setValue(500) - trigger = plugin.settings.child('trigger') + modules = plugin.settings.child('modules') + modules.child('Dev2', 'frequency').setValue(500) + modules.child('Dev2', 'clock').setValue('/Dev1/ai/SampleClock') + trigger = modules.child('Dev1', 'trigger') trigger.child('type').setValue('analog edge') plugin.commit_settings(trigger.child('type')) trigger.child('channel').setValue('Dev1/ai0') @@ -338,16 +340,20 @@ def test_the_frequencies_of_the_modules_and_the_trigger_are_saved_and_loaded_wit trigger.child('edge').setValue('falling') plugin.settings.child('config', 'save').opts.update(suffix='timed') press(plugin, 'config', 'save') - assert ConfigFiles(folder).load('timed').frequency('Dev2') == 500 + saved = ConfigFiles(folder).load('timed') + assert saved.frequency('Dev2') == 500 and saved.clock('Dev2') == '/Dev1/ai/SampleClock' + assert saved.clock('Dev1') == '' and saved.trigger('Dev2') is None - plugin.settings.child('frequencies', 'Dev2').setValue(10) + modules.child('Dev2', 'frequency').setValue(10) trigger.child('type').setValue('none') plugin.commit_settings(trigger.child('type')) - choose(plugin, 'configuration', 'lab') # another file, with other channels and no frequency nor trigger + choose(plugin, 'configuration', 'lab') # another file, with other channels and no frequency, clock nor trigger choose(plugin, 'configuration', 'timed') - assert [(c.name(), c.value()) for c in plugin.settings.child('frequencies').children()] == [ - ('Dev1', 1000), ('Dev2', 500)] + assert plugin.settings['modules', 'Dev2', 'frequency'] == 500 + assert plugin.settings['modules', 'Dev2', 'clock'] == '/Dev1/ai/SampleClock' + assert plugin.settings['modules', 'Dev1', 'clock'] == 'internal' + trigger = plugin.settings.child('modules', 'Dev1', 'trigger') assert trigger['type'] == 'analog edge' and trigger['channel'] == 'Dev1/ai0' assert trigger['level'] == 2.5 and trigger['edge'] == 'falling' assert trigger.child('level').opts['visible'] @@ -356,26 +362,26 @@ def test_the_frequencies_of_the_modules_and_the_trigger_are_saved_and_loaded_wit def test_loading_a_file_without_trigger_clears_the_trigger(qapp, driver, system_driver, folder): plugin = make_detector(DAQ_0DViewer_NIDAQmx) - trigger = plugin.settings.child('trigger') - trigger.child('type').setValue('digital edge') - plugin.commit_settings(trigger.child('type')) + plugin.settings.child('channels').addNew('cDAQ1Mod3/ai0') + plugin.commit_settings(plugin.settings.child('channels')) + trigger = plugin.settings.child('modules', 'cDAQ1Mod3', 'trigger', 'type') + trigger.setValue('digital edge') + plugin.commit_settings(trigger) choose(plugin, 'configuration', 'lab') - assert trigger['type'] == 'none' + assert plugin.settings['modules', 'cDAQ1Mod3', 'trigger', 'type'] == 'none' plugin.close() -def test_the_menu_goes_back_to_manual_when_a_frequency_or_the_trigger_is_changed(qapp, driver, system_driver, folder): +def test_the_menu_goes_back_to_manual_when_a_frequency_a_clock_or_a_trigger_is_changed( + qapp, driver, system_driver, folder): plugin = make_detector(DAQ_0DViewer_NIDAQmx) choose(plugin, 'configuration', 'lab') - frequency = plugin.settings.child('frequencies', 'cDAQ1Mod3') - frequency.setValue(frequency.value() + 1) - plugin.commit_settings(frequency) - assert menu(plugin) == '(manual)' - choose(plugin, 'configuration', 'lab') - trigger = plugin.settings.child('trigger', 'type') - trigger.setValue('digital edge') - plugin.commit_settings(trigger) - assert menu(plugin) == '(manual)' + for path, value in ((('frequency',), 7), (('clock',), '/Dev1/PFI0'), (('trigger', 'type'), 'digital edge')): + changed = plugin.settings.child('modules', 'cDAQ1Mod3', *path) + changed.setValue(value) + plugin.commit_settings(changed) + assert menu(plugin) == '(manual)' + choose(plugin, 'configuration', 'lab') plugin.close() diff --git a/tests/test_generic_ai_plugin.py b/tests/test_generic_ai_plugin.py index 42fb284..7099644 100644 --- a/tests/test_generic_ai_plugin.py +++ b/tests/test_generic_ai_plugin.py @@ -79,134 +79,160 @@ def test_each_module_is_acquired_by_its_own_task_and_gives_its_own_data(qapp, dr plugin.close() -def test_each_module_has_its_own_frequency_that_starts_at_the_global_one(qapp, driver, system_driver): + + + + + + + + + + + + +def test_a_channel_that_is_not_read_stays_in_the_task_but_not_in_the_data(qapp, driver, system_driver): plugin = make_detector(DAQ_0DViewer_NIDAQmx) group = plugin.settings.child('channels') group.addNew('Dev1/ai0') + group.addNew('Dev1/ai1') group.addNew('Dev2/ai3') - plugin.commit_settings(group) - frequencies = plugin.settings.child('frequencies') - assert [(c.name(), c.value()) for c in frequencies.children()] == [('Dev1', 1000), ('Dev2', 1000)] - frequencies.child('Dev2').setValue(500) - plugin.commit_settings(frequencies.child('Dev2')) - grab_and_wait(plugin) - assert [task.timing_calls[0][1] for task in driver] == [1000, 500] - group.removeChild(group.child('Dev1_ai0')) - plugin.commit_settings(group) - assert [c.name() for c in frequencies.children()] == ['Dev2'] + assert group.child('Dev1_ai1', 'read').value() is True # read by default + group.child('Dev1_ai1', 'read').setValue(False) + plugin.commit_settings(group.child('Dev1_ai1', 'read')) + dte = grab_and_wait(plugin) + assert [name for _, name, _ in driver[0].channels] == ['Dev1/ai0', 'Dev1/ai1'] # the task has it (a trigger) + assert [data.labels for data in dte] == [['Dev1/ai0'], ['Dev2/ai3']] plugin.close() -def test_the_1d_viewer_gives_a_trace_per_module_at_the_frequency_of_the_module(qapp, driver, system_driver): - from pymodaq_plugins_daqmx.daq_viewer_plugins.plugins_1D.daq_1Dviewer_NIDAQmx import DAQ_1DViewer_NIDAQmx - plugin = make_detector(DAQ_1DViewer_NIDAQmx, Nsamples=10) +def test_a_module_without_channel_to_read_gives_no_data(qapp, driver, system_driver): + plugin = make_detector(DAQ_0DViewer_NIDAQmx) group = plugin.settings.child('channels') group.addNew('Dev1/ai0') group.addNew('Dev2/ai3') - plugin.commit_settings(group) - plugin.settings.child('frequencies', 'Dev2').setValue(500) + group.child('Dev1_ai0', 'read').setValue(False) dte = grab_and_wait(plugin) - assert [data.dim for data in dte] == ['Data1D', 'Data1D'] - assert [data.axes[0].get_data()[1] for data in dte] == pytest.approx([1 / 1000, 1 / 500]) + assert [data.labels for data in dte] == [['Dev2/ai3']] plugin.close() -def test_a_digital_edge_trigger_starts_every_task(qapp, driver, system_driver): - from nidaqmx.constants import Edge +def test_changing_the_type_of_a_channel_keeps_whether_it_is_read(qapp, driver, system_driver): plugin = make_detector(DAQ_0DViewer_NIDAQmx) + group = plugin.settings.child('channels') + group.addNew('Dev1/ai0') + group.child('Dev1_ai0', 'read').setValue(False) + group.child('Dev1_ai0', 'type').setValue('current') + plugin.commit_settings(group.child('Dev1_ai0', 'type')) + assert group.child('Dev1_ai0', 'read').value() is False + plugin.close() + + +def two_modules(plugin, display=None): group = plugin.settings.child('channels') group.addNew('Dev1/ai0') group.addNew('Dev2/ai3') - trigger = plugin.settings.child('trigger') + plugin.commit_settings(group) + return plugin.settings.child('modules') + + +def test_each_module_has_its_own_settings_that_start_at_the_defaults(qapp, driver, system_driver): + plugin = make_detector(DAQ_0DViewer_NIDAQmx) + modules = two_modules(plugin) + assert [child.name() for child in modules.children()] == ['Dev1', 'Dev2'] + assert modules['Dev1', 'frequency'] == 1000 and modules['Dev1', 'clock'] == 'internal' + assert modules['Dev1', 'trigger', 'type'] == 'none' + modules.child('Dev2', 'frequency').setValue(500) + plugin.commit_settings(modules.child('Dev2', 'frequency')) + grab_and_wait(plugin) + assert [task.timing_calls[0][1] for task in driver] == [1000, 500] + plugin.settings.child('channels').removeChild(plugin.settings.child('channels', 'Dev1_ai0')) + plugin.commit_settings(plugin.settings.child('channels')) + assert [child.name() for child in modules.children()] == ['Dev2'] + plugin.close() + + +def test_a_digital_edge_trigger_starts_the_task_of_its_module_only(qapp, driver, system_driver): + from nidaqmx.constants import Edge + plugin = make_detector(DAQ_0DViewer_NIDAQmx) + modules = two_modules(plugin) + trigger = modules.child('Dev1', 'trigger') trigger.child('type').setValue('digital edge') plugin.commit_settings(trigger.child('type')) assert trigger.child('terminal').opts['visible'] and not trigger.child('level').opts['visible'] trigger.child('terminal').setValue('/Dev1/PFI1') trigger.child('edge').setValue('falling') grab_and_wait(plugin) - assert [task.trigger_calls for task in driver] == [[('dig_edge', '/Dev1/PFI1', Edge.FALLING)]] * 2 + assert [task.trigger_calls for task in driver] == [[('dig_edge', '/Dev1/PFI1', Edge.FALLING)], []] plugin.close() -def test_an_analog_edge_trigger_waits_for_the_level_of_a_channel_of_the_tree_and_starts_the_task_of_its_module( - qapp, driver, system_driver): +def test_an_analog_edge_trigger_watches_a_channel_or_an_apfi_terminal_of_its_own_module(qapp, driver, system_driver): from nidaqmx.constants import Slope plugin = make_detector(DAQ_0DViewer_NIDAQmx) - group = plugin.settings.child('channels') - group.addNew('Dev1/ai0') - group.addNew('Dev1/ai1') - group.addNew('Dev2/ai3') - plugin.commit_settings(group) - trigger = plugin.settings.child('trigger') + modules = two_modules(plugin) + trigger = modules.child('Dev2', 'trigger') trigger.child('type').setValue('analog edge') plugin.commit_settings(trigger.child('type')) assert trigger.child('channel').opts['visible'] and not trigger.child('terminal').opts['visible'] - assert trigger.child('channel').opts['limits'][:3] == ['Dev1/ai0', 'Dev1/ai1', 'Dev2/ai3'] # the channels first - trigger.child('channel').setValue('Dev1/ai1') + assert trigger.child('channel').opts['limits'] == ['Dev2/ai3', '/Dev2/APFI0', '/Dev2/APFI1'] + trigger.child('channel').setValue('/Dev2/APFI0') trigger.child('level').setValue(1.5) grab_and_wait(plugin) - assert [task.trigger_calls for task in driver] == [[('anlg_edge', 'Dev1/ai1', Slope.RISING, 1.5)], []] + assert [task.trigger_calls for task in driver] == [[], [('anlg_edge', '/Dev2/APFI0', Slope.RISING, 1.5)]] plugin.close() -def test_without_trigger_the_tasks_start_at_once(qapp, driver, system_driver): +def test_a_module_can_be_timed_by_the_clock_of_another_which_then_starts_last(qapp, driver, system_driver): + from nidaqmx_double import DoubleTask plugin = make_detector(DAQ_0DViewer_NIDAQmx) - plugin.settings.child('channels').addNew('Dev1/ai0') + modules = two_modules(plugin) + clock = modules.child('Dev2', 'clock') + assert '/Dev1/ai/SampleClock' in clock.opts['limits'] and '/Dev2/ai/SampleClock' not in clock.opts['limits'] + clock.setValue('/Dev1/ai/SampleClock') grab_and_wait(plugin) - assert driver[0].trigger_calls == [] + assert [call[2]['source'] for call in (task.timing_calls[0] for task in driver)] == ['', '/Dev1/ai/SampleClock'] + starts = [name for what, name in DoubleTask.log if what == 'start'] + assert starts == ['Dev2/ai3', 'Dev1/ai0'] # the one that waits for the clock is armed before the one that gives it plugin.close() -def test_a_dedicated_analog_trigger_terminal_can_be_the_source_and_starts_the_task_of_its_device( - qapp, driver, system_driver): - from nidaqmx.constants import Slope +def test_all_the_modules_can_follow_an_external_clock_in_any_order(qapp, driver, system_driver): plugin = make_detector(DAQ_0DViewer_NIDAQmx) - group = plugin.settings.child('channels') - group.addNew('Dev1/ai0') - group.addNew('Dev2/ai3') - plugin.commit_settings(group) - trigger = plugin.settings.child('trigger') - trigger.child('type').setValue('analog edge') - plugin.commit_settings(trigger.child('type')) - assert trigger.child('channel').opts['limits'] == ['Dev1/ai0', 'Dev2/ai3', '/Dev2/APFI0', '/Dev2/APFI1'] - trigger.child('channel').setValue('/Dev2/APFI0') + modules = two_modules(plugin) + for module in ('Dev1', 'Dev2'): + modules.child(module, 'clock').setValue('/Dev1/PFI0') grab_and_wait(plugin) - assert [task.trigger_calls for task in driver] == [[], [('anlg_edge', '/Dev2/APFI0', Slope.RISING, 0.)]] + assert [task.timing_calls[0][2]['source'] for task in driver] == ['/Dev1/PFI0'] * 2 plugin.close() -def test_a_channel_that_is_not_read_stays_in_the_task_but_not_in_the_data(qapp, driver, system_driver): +def test_modules_that_wait_for_each_other_are_refused_with_a_message_naming_them(qapp, driver, system_driver): plugin = make_detector(DAQ_0DViewer_NIDAQmx) - group = plugin.settings.child('channels') - group.addNew('Dev1/ai0') - group.addNew('Dev1/ai1') - group.addNew('Dev2/ai3') - assert group.child('Dev1_ai1', 'read').value() is True # read by default - group.child('Dev1_ai1', 'read').setValue(False) - plugin.commit_settings(group.child('Dev1_ai1', 'read')) - dte = grab_and_wait(plugin) - assert [name for _, name, _ in driver[0].channels] == ['Dev1/ai0', 'Dev1/ai1'] # the task has it (a trigger) - assert [data.labels for data in dte] == [['Dev1/ai0'], ['Dev2/ai3']] + modules = two_modules(plugin) + modules.child('Dev1', 'clock').setValue('/Dev2/ai/SampleClock') + modules.child('Dev2', 'clock').setValue('/Dev1/ai/SampleClock') + with pytest.raises(ValueError, match='Dev1.*Dev2'): + plugin.grab_data() plugin.close() -def test_a_module_without_channel_to_read_gives_no_data(qapp, driver, system_driver): - plugin = make_detector(DAQ_0DViewer_NIDAQmx) - group = plugin.settings.child('channels') - group.addNew('Dev1/ai0') - group.addNew('Dev2/ai3') - group.child('Dev1_ai0', 'read').setValue(False) +def test_the_1d_axis_is_in_samples_with_an_external_clock_and_in_seconds_otherwise(qapp, driver, system_driver): + from pymodaq_plugins_daqmx.daq_viewer_plugins.plugins_1D.daq_1Dviewer_NIDAQmx import DAQ_1DViewer_NIDAQmx + plugin = make_detector(DAQ_1DViewer_NIDAQmx, Nsamples=10) + modules = two_modules(plugin) + modules.child('Dev2', 'frequency').setValue(500) + modules.child('Dev2', 'clock').setValue('/Dev2/PFI0') dte = grab_and_wait(plugin) - assert [data.labels for data in dte] == [['Dev2/ai3']] + seconds, samples = dte[0].axes[0], dte[1].axes[0] + assert seconds.get_data()[1] == pytest.approx(1 / 1000) and seconds.units == 's' + assert list(samples.get_data()[:3]) == [0, 1, 2] and samples.label == 'sample' plugin.close() -def test_changing_the_type_of_a_channel_keeps_whether_it_is_read(qapp, driver, system_driver): +def test_without_trigger_the_tasks_start_at_once(qapp, driver, system_driver): plugin = make_detector(DAQ_0DViewer_NIDAQmx) - group = plugin.settings.child('channels') - group.addNew('Dev1/ai0') - group.child('Dev1_ai0', 'read').setValue(False) - group.child('Dev1_ai0', 'type').setValue('current') - plugin.commit_settings(group.child('Dev1_ai0', 'type')) - assert group.child('Dev1_ai0', 'read').value() is False + plugin.settings.child('channels').addNew('Dev1/ai0') + grab_and_wait(plugin) + assert driver[0].trigger_calls == [] plugin.close() From 75abe84a3added7bfb672967490d74ad9d99f395 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:50:41 +0000 Subject: [PATCH 2/8] Offer only signal terminals as clock or trigger sources, not channels Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../plugins_0D/daq_0Dviewer_NIDAQmx.py | 18 +++++++++++++++--- tests/nidaqmx_double.py | 6 ++++-- tests/test_generic_ai_plugin.py | 11 +++++++++++ 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py index c29e188..18fe635 100644 --- a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py +++ b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py @@ -1,3 +1,4 @@ +import re from typing import List, Optional from pymodaq.control_modules.thread_commands import ThreadStatus @@ -28,6 +29,15 @@ def _exporting_module(terminal: str) -> Optional[str]: return parts[1] if len(parts) > 3 and parts[0] == '' and parts[2] == 'ai' else None +_NOT_A_SOURCE = re.compile(r'^/[^/]+/((ai|ao)\d+|ctr\d+|port\d+(/line\d+)?|APFI\d+)$', re.IGNORECASE) + + +def is_signal_terminal(terminal: str) -> bool: + """Whether ``terminal`` carries a signal that can be a clock or a trigger: not a channel (``/Dev1/ai0``), nor an + analog trigger terminal (``/Dev1/APFI0``), which has its own list.""" + return _NOT_A_SOURCE.match(terminal) is None + + def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str]) -> dict: """The settings of a module: its frequency, its clock and its start trigger.""" return {'title': module, 'name': module, 'type': 'group', 'children': [ @@ -195,15 +205,17 @@ def module_lists(self, module: str) -> dict: """What the settings of ``module`` choose among. A terminal of its own ``ai`` subsystem cannot time it.""" others = [m for m in self.modules() if m != module] own = f'/{module}/ai/' - terminals = [t for t in self.terminals if not t.startswith(own)] + terminals = [t for t in self.terminals if not t.startswith(own) and is_signal_terminal(t)] names = [child.opts['title'] for child in self.settings.child('channels').children() if child.opts['title'].split('/')[0] == module] try: # the dedicated analog trigger terminals of the device, which are not read apfi = [t for t in NIDAQSystem().terminals(module) if '/APFI' in t] except ValueError: # a module that is not a device of the system apfi = [] - return {'clocks': [CLOCK_INTERNAL] + terminals + [f'/{m}/ai/SampleClock' for m in others], - 'terminals': terminals + [f'/{m}/ai/StartTrigger' for m in others], 'channels': names + apfi} + clocks = [CLOCK_INTERNAL] + terminals + [f'/{m}/ai/SampleClock' for m in others] + starts = terminals + [f'/{m}/ai/StartTrigger' for m in others] + return {'clocks': list(dict.fromkeys(clocks)), 'terminals': list(dict.fromkeys(starts)), + 'channels': names + apfi} def module_trigger(self, module: str): """The start trigger of ``module`` as the API describes it, None if it starts at once.""" diff --git a/tests/nidaqmx_double.py b/tests/nidaqmx_double.py index 55aa0c9..f8920b2 100644 --- a/tests/nidaqmx_double.py +++ b/tests/nidaqmx_double.py @@ -327,7 +327,8 @@ def _pcie_6363(): 'Dev2', ai=[f'Dev2/ai{c}' for c in range(32)], ao=[f'Dev2/ao{c}' for c in range(4)], ci=[f'Dev2/ctr{c}' for c in range(4)], co=[f'Dev2/ctr{c}' for c in range(4)] + ['Dev2/freqout'], di=[f'Dev2/port0/line{c}' for c in range(4)], do=[f'Dev2/port0/line{c}' for c in range(4)], - terminals=[f'/Dev2/PFI{c}' for c in range(6)] + ['/Dev2/APFI0', '/Dev2/APFI1'], + terminals=[f'/Dev2/PFI{c}' for c in range(6)] + ['/Dev2/APFI0', '/Dev2/APFI1', '/Dev2/ai0', '/Dev2/ao0', + '/Dev2/ai/SampleClock', '/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) @@ -338,7 +339,8 @@ def _pci_6133(): return DoubleDevice( 'Dev1', ai=[f'Dev1/ai{c}' for c in range(8)], ao=[], ci=['Dev1/ctr0', 'Dev1/ctr1'], co=['Dev1/ctr0', 'Dev1/ctr1', 'Dev1/freqout'], di=[f'Dev1/port0/line{c}' for c in range(4)], - do=[f'Dev1/port0/line{c}' for c in range(4)], terminals=[f'/Dev1/PFI{c}' for c in range(6)], + do=[f'Dev1/port0/line{c}' for c in range(4)], + terminals=[f'/Dev1/PFI{c}' for c in range(6)] + ['/Dev1/ai0', '/Dev1/ai/SampleClock', '/Dev1/ctr0'], 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), diff --git a/tests/test_generic_ai_plugin.py b/tests/test_generic_ai_plugin.py index 7099644..cd8ee98 100644 --- a/tests/test_generic_ai_plugin.py +++ b/tests/test_generic_ai_plugin.py @@ -152,6 +152,17 @@ def test_each_module_has_its_own_settings_that_start_at_the_defaults(qapp, drive plugin.close() +def test_the_clock_and_terminal_lists_offer_terminals_not_channels(qapp, driver, system_driver): + plugin = make_detector(DAQ_0DViewer_NIDAQmx) + modules = two_modules(plugin) + for module in ('Dev1', 'Dev2'): + for offered in (modules.child(module, 'clock').opts['limits'], + modules.child(module, 'trigger', 'terminal').opts['limits']): + assert '/Dev1/PFI1' in offered or '/Dev2/PFI1' in offered + assert not [t for t in offered if t.split('/')[-1].startswith(('ai0', 'ao0', 'ctr0', 'line0', 'APFI'))] + plugin.close() + + def test_a_digital_edge_trigger_starts_the_task_of_its_module_only(qapp, driver, system_driver): from nidaqmx.constants import Edge plugin = make_detector(DAQ_0DViewer_NIDAQmx) From 714a3246af75d52f2ebb97bd3a0d1b74cd7dcb3e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:52:46 +0000 Subject: [PATCH 3/8] Channel range shown with its unit, and not kept across quantities Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- docs/source/user_guide/nidaqmx_viewer_use.rst | 2 +- .../plugins_0D/daq_0Dviewer_NIDAQmx.py | 5 ++- .../national_instruments/channel_tree.py | 40 +++++++++++++++++-- tests/test_channel_group.py | 4 +- tests/test_channel_tree.py | 39 ++++++++++++++++-- 5 files changed, 78 insertions(+), 12 deletions(-) diff --git a/docs/source/user_guide/nidaqmx_viewer_use.rst b/docs/source/user_guide/nidaqmx_viewer_use.rst index 02b39d4..71e3a4d 100644 --- a/docs/source/user_guide/nidaqmx_viewer_use.rst +++ b/docs/source/user_guide/nidaqmx_viewer_use.rst @@ -70,7 +70,7 @@ Settings * **Channels**: the group described above. Each channel has a ``read`` box (checked by default): unchecked, the channel stays in the task but its samples are not in the data, which is what an analog trigger on that channel needs. A module whose channels are all unchecked gives no data. The parameters of a channel are the fields of its channel class of the - API (``AIVoltage``, ``AICurrent``, ``AIThermocouple``, ``AIRtd``), with the same names; see :doc:`config_files` + API (``AIVoltage``, ``AICurrent``, ``AIThermocouple``, ``AIRtd``), with the same names (the range, ``min_val`` and ``max_val``, is shown in the unit of its quantity: V, A or the temperature units). Changing the type of a channel keeps the values that still make sense: the range is kept only between types that measure the same quantity (thermocouple and RTD), and takes the default of the new type otherwise; see :doc:`config_files` for the list. Loading and saving a configuration diff --git a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py index 18fe635..6960903 100644 --- a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py +++ b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py @@ -12,7 +12,7 @@ from pymodaq_plugins_daqmx.hardware.national_instruments.api import ( AnalogEdgeTrigger, ChannelKind, DigitalEdgeTrigger, NIDAQSystem) from pymodaq_plugins_daqmx.hardware.national_instruments.channel_group import channels_of, unread_of -from pymodaq_plugins_daqmx.hardware.national_instruments.channel_tree import set_type +from pymodaq_plugins_daqmx.hardware.national_instruments.channel_tree import set_type, update_suffixes from pymodaq_plugins_daqmx.hardware.national_instruments.config_files import Configuration, ConfigFiles from pymodaq_plugins_daqmx.hardware.national_instruments.save_button import save_param from pymodaq_gui.utils.status_palette import Status @@ -333,6 +333,9 @@ def commit_settings(self, param: Parameter) -> None: if param.name() == 'type' and param.parent() is not None and param.parent().parent() is self.settings.child( 'channels'): # the type of a channel: its group is rebuilt set_type(ChannelKind.AI, param.parent(), param.value()) + if param.name() == 'units' and param.parent() is not None and param.parent().parent() is self.settings.child( + 'channels'): # the units of a temperature: the range follows + update_suffixes(param.parent()) if param.name() == 'type' and param.parent() is not None and param.parent().name() == 'trigger': self.show_trigger(param.parent().parent().name()) self.leave_configuration_if_modified() diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/channel_tree.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/channel_tree.py index 57fc68a..0217721 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/channel_tree.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/channel_tree.py @@ -15,26 +15,55 @@ def _is_enum(field) -> bool: return isinstance(field.type, type) and issubclass(field.type, enum.Enum) -def _parameter(field, value=None) -> dict: +_TEMPERATURE_SUFFIXES = {'DEG_C': '°C', 'DEG_F': '°F', 'K': 'K', 'DEG_R': '°R'} +_RANGE = ('min_val', 'max_val') + + +def _quantity(type_: str) -> str: + """What the range of a type of channel measures: a range is meaningful only for that quantity.""" + return {'voltage': 'V', 'current': 'A'}.get(type_, 'temperature') + + +def _suffix(type_: str, units: str = None) -> str: + quantity = _quantity(type_) + return _TEMPERATURE_SUFFIXES.get(units, '') if quantity == 'temperature' else quantity + + +def _parameter(field, value=None, suffix: str = '') -> dict: """The settings parameter of a field of a channel, valued by ``value`` or the default of the field.""" if value is None: value = field.default if _is_enum(field): return {'title': field.name, 'name': field.name, 'type': 'list', 'limits': [member.name for member in field.type], 'value': value.name} - return {'title': field.name, 'name': field.name, 'type': 'float', 'value': float(value)} + parameter = {'title': field.name, 'name': field.name, 'type': 'float', 'value': float(value)} + if field.name in _RANGE and suffix: + parameter['suffix'] = suffix + return parameter def _children(kind: ChannelKind, type_: str, channel=None, previous: dict = None, read: bool = True) -> List[dict]: types = CHANNEL_TYPES[kind] children = [{'title': 'type', 'name': 'type', 'type': 'list', 'limits': list(types), 'value': type_}, {'title': 'read', 'name': 'read', 'type': 'bool', 'value': read}] # in the data, or only in the task - for field in channel_fields(types[type_]): + fields = channel_fields(types[type_]) + units = next((getattr(channel, f.name).name if channel is not None else + (previous or {}).get(f.name) for f in fields if f.name == 'units'), None) + if units is None: # a temperature channel that is new has the default units of its class + units = next((f.default.name for f in fields if f.name == 'units'), None) + for field in fields: value = getattr(channel, field.name) if channel is not None else (previous or {}).get(field.name) - children.append(_parameter(field, value)) + children.append(_parameter(field, value, _suffix(type_, units))) return children +def update_suffixes(group) -> None: + """Put the unit of the range (the temperature units can be changed) on the range of the channel of ``group``.""" + suffix = _suffix(group.child('type').value(), group.child('units').value() if group.names.get('units') else None) + for name in _RANGE: + group.child(name).setOpts(suffix=suffix) + + def channel_params(kind: ChannelKind, channel, read: bool = True) -> dict: """The settings group (as a dictionary for ``Parameter.create``) of a channel of the API. @@ -68,6 +97,9 @@ def set_type(kind: ChannelKind, group, type_: str) -> None: are kept.""" kept = {child.name(): child.value() for child in group.children() if child.name() != 'type'} read = kept.pop('read', True) + if _quantity(type_) != _quantity(group.child('type').value()): # a range in volts means nothing in amperes + for name in _RANGE: + kept.pop(name, None) for child in list(group.children()): group.removeChild(child) previous = {} diff --git a/tests/test_channel_group.py b/tests/test_channel_group.py index e2ee76d..1d0d07b 100644 --- a/tests/test_channel_group.py +++ b/tests/test_channel_group.py @@ -45,8 +45,8 @@ def test_the_channels_of_the_group_are_channels_of_the_api_in_the_order_of_the_g group.addNew('Dev1/ai0') set_type(ChannelKind.AI, group.children()[1], 'thermocouple') # what the plugin does when the type changes - # the range of the voltage channel, which the two types share, is kept - assert channels_of(group) == [AIVoltage('Dev1/ai1'), AIThermocouple('Dev1/ai0', min_val=-10., max_val=10.)] + # a range in volts means nothing in degrees: the thermocouple gets its own default range + assert channels_of(group) == [AIVoltage('Dev1/ai1'), AIThermocouple('Dev1/ai0')] def test_the_group_takes_new_limits(qtbot): diff --git a/tests/test_channel_tree.py b/tests/test_channel_tree.py index e3f9ad5..f4f1077 100644 --- a/tests/test_channel_tree.py +++ b/tests/test_channel_tree.py @@ -7,7 +7,7 @@ from pymodaq_plugins_daqmx.hardware.national_instruments.api import (AICurrent, AIRtd, AIThermocouple, AIVoltage, ChannelKind) from pymodaq_plugins_daqmx.hardware.national_instruments.channel_tree import (channel_from_params, channel_params, - set_type) + set_type, update_suffixes) CHANNELS = [ AIVoltage('Dev1/ai0', -5., 5., TerminalConfiguration.DIFF), @@ -41,12 +41,43 @@ def test_a_channel_group_has_the_parameters_of_its_type_only(qtbot): def test_changing_the_type_replaces_the_parameters_and_keeps_the_ones_in_common(qtbot): channel = group(AIThermocouple('Dev1/ai2', min_val=5., max_val=60.)) + set_type(ChannelKind.AI, channel, 'rtd') + + assert channel.child('type').value() == 'rtd' + assert (channel.child('min_val').value(), channel.child('max_val').value()) == (5., 60.) + assert channel_from_params(ChannelKind.AI, channel).units == AIThermocouple('x').units + + +def test_changing_the_type_replaces_the_parameters(qtbot): + channel = group(AIThermocouple('Dev1/ai2')) + set_type(ChannelKind.AI, channel, 'voltage') assert [child.name() for child in channel.children()] == ['type', 'read', 'min_val', 'max_val', 'terminal_config'] - assert channel.child('type').value() == 'voltage' - assert (channel.child('min_val').value(), channel.child('max_val').value()) == (5., 60.) - assert channel_from_params(ChannelKind.AI, channel) == AIVoltage('Dev1/ai2', 5., 60.) + + +def test_the_range_is_not_kept_when_the_quantity_changes(qtbot): + channel = group(AIVoltage('Dev1/ai0', -5., 5.)) + + set_type(ChannelKind.AI, channel, 'current') + assert channel_from_params(ChannelKind.AI, channel) == AICurrent('Dev1/ai0') # the default range of a current + + set_type(ChannelKind.AI, channel, 'voltage') + assert channel_from_params(ChannelKind.AI, channel) == AIVoltage('Dev1/ai0') + + +def test_the_range_has_the_unit_of_its_quantity(qtbot): + voltage, current = group(AIVoltage('Dev1/ai0')), group(AICurrent('Dev1/ai1')) + thermocouple = group(AIThermocouple('Dev1/ai2', units=TemperatureUnits.DEG_F)) + for parameter in (voltage, current, thermocouple): + assert parameter.child('min_val').opts['suffix'] == parameter.child('max_val').opts['suffix'] + assert voltage.child('min_val').opts['suffix'] == 'V' + assert current.child('min_val').opts['suffix'] == 'A' + assert thermocouple.child('min_val').opts['suffix'] == '°F' + + thermocouple.child('units').setValue('K') + update_suffixes(thermocouple) + assert thermocouple.child('max_val').opts['suffix'] == 'K' def test_a_range_that_makes_no_sense_names_the_channel(qtbot): From 9f16006e88bb0079773284fe5f19b7d4bf44ee71 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 11:58:48 +0000 Subject: [PATCH 4/8] Reset the channel range when the type changes the quantity Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../hardware/national_instruments/channel_tree.py | 4 +++- tests/test_channel_tree.py | 12 +++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/channel_tree.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/channel_tree.py index 0217721..1124ec6 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/channel_tree.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/channel_tree.py @@ -97,7 +97,9 @@ def set_type(kind: ChannelKind, group, type_: str) -> None: are kept.""" kept = {child.name(): child.value() for child in group.children() if child.name() != 'type'} read = kept.pop('read', True) - if _quantity(type_) != _quantity(group.child('type').value()): # a range in volts means nothing in amperes + # the value of the type has already changed: the previous quantity is the one the range is shown in + previous = group.child('min_val').opts.get('suffix', '') + if _quantity(type_) != ('temperature' if previous not in ('V', 'A') else previous): # volts mean nothing in amperes for name in _RANGE: kept.pop(name, None) for child in list(group.children()): diff --git a/tests/test_channel_tree.py b/tests/test_channel_tree.py index f4f1077..536a7e6 100644 --- a/tests/test_channel_tree.py +++ b/tests/test_channel_tree.py @@ -59,10 +59,16 @@ def test_changing_the_type_replaces_the_parameters(qtbot): def test_the_range_is_not_kept_when_the_quantity_changes(qtbot): channel = group(AIVoltage('Dev1/ai0', -5., 5.)) - set_type(ChannelKind.AI, channel, 'current') - assert channel_from_params(ChannelKind.AI, channel) == AICurrent('Dev1/ai0') # the default range of a current + def switch(type_): # the plugin is told after the value of the type has changed + channel.child('type').setValue(type_) + set_type(ChannelKind.AI, channel, type_) - set_type(ChannelKind.AI, channel, 'voltage') + switch('current') + assert channel_from_params(ChannelKind.AI, channel) == AICurrent('Dev1/ai0') # the default range of a current + switch('thermocouple') + assert channel_from_params(ChannelKind.AI, channel) == AIThermocouple('Dev1/ai0') + assert channel.child('max_val').opts['suffix'] == '°C' + switch('voltage') assert channel_from_params(ChannelKind.AI, channel) == AIVoltage('Dev1/ai0') From 7e2ab1f9728d501e686f1f726362e24e67d293c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:00:30 +0000 Subject: [PATCH 5/8] Clean up and document the generic AI viewer No change of behaviour: module and section comments, one helper for the channels grouped by module, a clearer commit_settings. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../plugins_0D/daq_0Dviewer_NIDAQmx.py | 95 ++++++++++++++----- .../national_instruments/NIDAQmx_AI.py | 37 ++++++-- 2 files changed, 100 insertions(+), 32 deletions(-) diff --git a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py index 6960903..71a0e1b 100644 --- a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py +++ b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py @@ -1,34 +1,48 @@ +"""Generic viewer of the analog inputs of any NI device, on the ``nidaqmx`` API. + +How this module is organised: + +* helpers on terminals (``_exporting_module``, ``is_signal_terminal``) and the settings of one module (``module_group``); +* ``DAQ_0DViewer_NIDAQmx``, whose sections are, in order: configuration files (menu, load, save), the channels and + the module groups of the tree (``sync_modules``), the start trigger of a module, what is acquired + (``acquisitions``), and the reaction to a change of a setting (``commit_settings``). + +The acquisition itself (tasks, clocks, order of start, emission of the data) is in ``DAQ_Viewer_AIBase``. +""" import re -from typing import List, Optional +from typing import Dict, List, Optional +from nidaqmx.constants import Edge, Slope from pymodaq.control_modules.thread_commands import ThreadStatus from pymodaq.control_modules.viewer_utility_classes import main from pymodaq.utils.daq_utils import ThreadCommand +from pymodaq_gui.utils.status_palette import Status from pyqtgraph.parametertree import Parameter from pymodaq_plugins_daqmx.hardware.national_instruments.NIDAQmx_AI import Acquisition, DAQ_Viewer_AIBase -from nidaqmx.constants import Edge, Slope - from pymodaq_plugins_daqmx.hardware.national_instruments.api import ( AnalogEdgeTrigger, ChannelKind, DigitalEdgeTrigger, NIDAQSystem) from pymodaq_plugins_daqmx.hardware.national_instruments.channel_group import channels_of, unread_of from pymodaq_plugins_daqmx.hardware.national_instruments.channel_tree import set_type, update_suffixes from pymodaq_plugins_daqmx.hardware.national_instruments.config_files import Configuration, ConfigFiles from pymodaq_plugins_daqmx.hardware.national_instruments.save_button import save_param -from pymodaq_gui.utils.status_palette import Status MANUAL = '(manual)' # no configuration file: the channels are the ones of the tree -TRIGGER_TYPES = ['none', 'digital edge', 'analog edge'] +TRIGGER_TYPES = ['none', 'digital edge', 'analog edge'] # the types of start trigger of a module CLOCK_INTERNAL = 'internal' # the sample clock of the module itself DEFAULT = 'default' # the name of the configuration of the file without suffix +# --- terminals -------------------------------------------------------------------------------------------------- + def _exporting_module(terminal: str) -> Optional[str]: - """The module that produces the signal ``terminal`` (``/Dev1/ai/SampleClock``), None for any other terminal.""" + """The module that produces the signal ``terminal`` (``/Dev1/ai/SampleClock`` is produced by ``Dev1``), None for + any other terminal (``/Dev1/PFI0``, a wire). It tells which task has to be started before another one.""" parts = (terminal or '').split('/') return parts[1] if len(parts) > 3 and parts[0] == '' and parts[2] == 'ai' else None +# what the driver lists as terminals but cannot be a clock or a trigger source _NOT_A_SOURCE = re.compile(r'^/[^/]+/((ai|ao)\d+|ctr\d+|port\d+(/line\d+)?|APFI\d+)$', re.IGNORECASE) @@ -38,6 +52,8 @@ def is_signal_terminal(terminal: str) -> bool: return _NOT_A_SOURCE.match(terminal) is None +# --- settings of a module --------------------------------------------------------------------------------------- + def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str]) -> dict: """The settings of a module: its frequency, its clock and its start trigger.""" return {'title': module, 'name': module, 'type': 'group', 'children': [ @@ -93,7 +109,10 @@ def __init__(self, *args, **kwargs): self.in_file = () # what the file describes (see `snapshot`), to tell if the tree still is the file self.refresh_menu() + # --- configuration files: menu, load, save ------------------------------------------------------------------ + def refresh_menu(self) -> None: + """List the files of the configuration folder in the menu, after ``(manual)``.""" self.settings.child('config', 'configuration').setLimits([MANUAL] + [_label(s) for s in self.files.suffixes()]) def load_configuration(self) -> None: @@ -143,9 +162,7 @@ def save_configuration(self, button: Parameter) -> None: if not channels: raise ValueError('There is no channel to save') unread = unread_of(self.settings.child('channels')) - by_module = {} - for channel in channels: - by_module.setdefault(channel.name.split('/')[0], []).append(channel) + by_module = self.channels_by_module() configuration = self.files.load(suffix) if self.files.path(suffix).exists() else Configuration() for module in [name for name in configuration.modules if name not in by_module]: del configuration.modules[module] @@ -162,6 +179,8 @@ def save_configuration(self, button: Parameter) -> None: self.settings.child('config', 'configuration').setValue(self.loaded) self.notify(f'Channels saved in the configuration {_label(suffix)}') + # --- feedback to the control module ------------------------------------------------------------------------- + def notify(self, message: str) -> None: """Tell the control module that the action succeeded: its LED is back to normal.""" self.emit_status(ThreadCommand('Update_Status', [message, 'log'])) @@ -170,9 +189,19 @@ def fail(self, error: Exception) -> None: """Tell the control module that the action failed: its LED shows the error and its message.""" self.emit_status(ThreadCommand(ThreadStatus.ERROR, str(error))) + # --- channels and module groups of the tree ----------------------------------------------------------------- + def channels(self) -> list: + """The channels of the API that the tree describes, in the order of the tree.""" return channels_of(self.settings.child('channels')) + def channels_by_module(self) -> Dict[str, list]: + """The channels of the tree grouped by module (the device their name starts with), in order of appearance.""" + by_module = {} + for channel in self.channels(): + by_module.setdefault(channel.name.split('/')[0], []).append(channel) + return by_module + def modules(self) -> List[str]: """The modules of the channels of the tree (the device a channel name starts with), in order of appearance.""" names = [child.opts['title'].split('/')[0] for child in self.settings.child('channels').children()] @@ -198,6 +227,7 @@ def sync_modules(self) -> None: @staticmethod def set_limits(param: Parameter, limits: List[str]) -> None: + """Change the limits only when they differ: setting them sends them to the GUI and resets its combo box.""" if param.opts['limits'] != limits: param.setLimits(limits) @@ -217,6 +247,8 @@ def module_lists(self, module: str) -> dict: return {'clocks': list(dict.fromkeys(clocks)), 'terminals': list(dict.fromkeys(starts)), 'channels': names + apfi} + # --- start trigger of a module ------------------------------------------------------------------------------ + def module_trigger(self, module: str): """The start trigger of ``module`` as the API describes it, None if it starts at once.""" keys = self.trigger_keys(module) @@ -256,19 +288,23 @@ def show_trigger(self, module: str) -> None: settings.child('level').setOpts(visible=kind == 'analog edge') settings.child('edge').setOpts(visible=kind != 'none') + # --- what is acquired --------------------------------------------------------------------------------------- + def acquisitions(self) -> List[Acquisition]: """One task for each module: its channels are acquired together, at its frequency, on its clock, started by - its trigger.""" + its trigger. + + ``waits_for`` lists the other modules whose exported signal (clock or start trigger) this module uses: the + base class starts those that wait first and the provider last.""" self.sync_modules() # the channels may have been added without the GUI telling the plugin - by_module = {} - for channel in self.channels(): - by_module.setdefault(channel.name.split('/')[0], []).append(channel) + by_module = self.channels_by_module() unread = unread_of(self.settings.child('channels')) acquisitions = [] for module, channels in by_module.items(): group = self.settings.child('modules', module) - clock = '' if group['clock'] == CLOCK_INTERNAL else group['clock'] + clock = '' if group['clock'] == CLOCK_INTERNAL else group['clock'] # '' = the module's own clock trigger = self.module_trigger(module) + # the parameter of the trigger that names its source depends on the type of trigger key = {'digital edge': 'terminal', 'analog edge': 'channel'}.get(group['trigger', 'type']) sources = [clock] + ([group['trigger', key]] if key is not None else []) waits = tuple(dict.fromkeys(m for m in (_exporting_module(source) for source in sources) @@ -288,8 +324,9 @@ def snapshot(self) -> tuple: def leave_configuration_if_modified(self) -> None: """The menu goes back to ``(manual)`` as soon as the tree is not what the file describes any more: its - channels, the frequencies of the modules or the trigger (a value that cannot be a channel is a modification too), so that it never shows a configuration that is not - in the tree, and that choosing the file again reloads it.""" + channels, the frequency, clock or trigger of a module (a value that cannot be a channel is a modification + too). The menu thus never shows a configuration that is not in the tree, and choosing the file again reloads + it.""" if self.loaded == MANUAL: return try: @@ -317,10 +354,20 @@ def own(self, param: Parameter) -> Parameter: return param return self.settings.child(*reversed(names)) if names else self.settings + # --- reaction to a change of a setting ---------------------------------------------------------------------- + def commit_settings(self, param: Parameter) -> None: + """What the plugin does when a setting changed (in the GUI or by code). + + The first branch handles the configuration actions (load, save); then the rebuilding of the tree that a + parameter requires (a type of channel, the units of a range, a type of trigger). Any change finally checks + that the tree still is the loaded configuration and updates the groups of the modules. + """ button = param # the one of the GUI: it holds what its dialog returned param = self.own(param) - if param.name() == 'configuration' and param.parent() is self.settings.child('config'): + parent = param.parent() + in_a_channel = parent is not None and parent.parent() is self.settings.child('channels') + if param.name() == 'configuration' and parent is self.settings.child('config'): self.load_configuration() elif param.opts['type'] == 'ni_save': # the button has been clicked, after the dialog of the GUI param.opts.update(suffix=button.opts['suffix']) @@ -330,14 +377,12 @@ def commit_settings(self, param: Parameter) -> None: except (ValueError, OSError) as error: param.setValue(Status.ERROR) self.fail(error) - if param.name() == 'type' and param.parent() is not None and param.parent().parent() is self.settings.child( - 'channels'): # the type of a channel: its group is rebuilt - set_type(ChannelKind.AI, param.parent(), param.value()) - if param.name() == 'units' and param.parent() is not None and param.parent().parent() is self.settings.child( - 'channels'): # the units of a temperature: the range follows - update_suffixes(param.parent()) - if param.name() == 'type' and param.parent() is not None and param.parent().name() == 'trigger': - self.show_trigger(param.parent().parent().name()) + if param.name() == 'type' and in_a_channel: # the type of a channel: its group is rebuilt + set_type(ChannelKind.AI, parent, param.value()) + if param.name() == 'units' and in_a_channel: # the units of a temperature: the range follows + update_suffixes(parent) + if param.name() == 'type' and parent is not None and parent.name() == 'trigger': + self.show_trigger(parent.parent().name()) # only the parameters of that type of trigger are visible self.leave_configuration_if_modified() self.sync_modules() super().commit_settings(param) diff --git a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py index 28807db..b2be98d 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/NIDAQmx_AI.py @@ -1,4 +1,14 @@ -"""Base class of the thin analog input viewers (AI and DualAI) built on top of the NIDAQmx wrapper.""" +"""Base class of the analog input viewers, built on the ``nidaqmx`` API of this package. + +Overview: + +* ``Acquisition`` describes what one task acquires (a module: channels, frequency, clock, start trigger); +* ``start_order`` and ``trace_axis`` are the two rules that depend on the clocks (which task starts first, what the + axis of a trace is); +* ``DAQ_Viewer_AIBase`` builds one task for each acquisition (``update_tasks``), grabs finite blocks (``grab_data``) + or streams them in live mode (``start_live``), and emits the data (``emit_points``, ``emit_traces``). Subclasses + only tell *what* to acquire by overriding ``channels`` or ``acquisitions``. +""" from typing import List, Optional, Tuple from dataclasses import dataclass @@ -85,7 +95,9 @@ class DAQ_Viewer_AIBase(DAQ_Viewer_base): In 0D, the Naverage of the viewer is the number of points averaged by the acquisition (`Nsamples` is hidden). In 1D, `Nsamples` is the length of the trace and Naverage the number of traces averaged. - Subclasses declare in `params` one list parameter per channel and give their names in `channel_names`. + Subclasses give the channels (`channels`, or `channel_names` for voltages) or, to acquire with several tasks, the + list of `acquisitions`. Each acquisition has its task and gives its own data, so the tasks can differ in + frequency, clock and start trigger. """ params = comon_parameters + [ {'title': 'Display type:', 'name': 'display', 'type': 'list', 'limits': ['0D', '1D'], @@ -156,12 +168,16 @@ def task_samples(self) -> int: return max(self.samples_per_block(), MIN_CLOCKED_SAMPLES) def signature(self, streaming: bool = False): - """What the tasks are built for: the channels and the frequency of each, and the samples of finite tasks.""" + """What the tasks are built for: the acquisitions (channels, frequency, clock, trigger) and the samples of + finite tasks. When it differs from the one the tasks were built with, the tasks are rebuilt at the next grab.""" samples = None if streaming else self.task_samples() return tuple(self.acquisitions()), samples def update_tasks(self, streaming: bool = False) -> None: - """Replace the tasks by ones that follow the settings: finite for a snap, continuous for the live mode.""" + """Replace the tasks by ones that follow the settings: finite for a snap, continuous for the live mode. + + All tasks are built, or none is: a failure closes those already built (a task keeps its channels reserved). + """ self.close() acquisitions = self.acquisitions() if not acquisitions: # a task needs a channel: they are built when the first one is added @@ -183,12 +199,17 @@ def update_tasks(self, streaming: bool = False) -> None: self.controller = tasks[0] if len(tasks) == 1 else TaskGroup(*tasks) self._signature = self.signature(streaming) + def no_channel_message(self) -> None: + self.emit_status(ThreadCommand('Update_Status', ['No channel to acquire: add one to the channels', 'log'])) + def ordered_tasks(self) -> List[AnalogInputTask]: """The tasks in the order they start: the ones that wait for the signal of another module come first.""" return [self.tasks[i] for i in self.start_order] def read_samples(self) -> List[np.ndarray]: - """Run one finite acquisition of each task, together, and return their arrays (nchannels, Nsamples).""" + """Run one finite acquisition of each task, together, and return their arrays (nchannels, Nsamples), in the + order of the tasks. The tasks start in `start_order` (those that wait for a signal first) and are stopped + whatever happens, so that their channels are free for the next acquisition.""" started = [] try: for task in self.ordered_tasks(): @@ -208,7 +229,7 @@ def grab_data(self, Naverage: int = 1, live: bool = False, **kwargs) -> None: if self.controller is None or self._signature != self.signature(): self.update_tasks() # follow the Naverage of the viewer in 0D, and the channels added or changed if self.controller is None: - self.emit_status(ThreadCommand('Update_Status', ['No channel to acquire: add one to the channels', 'log'])) + self.no_channel_message() return if self.settings['display'] == '0D': # the surplus sample of Naverage=1 is dropped @@ -222,7 +243,7 @@ def start_live(self) -> None: self.stop_live() self.update_tasks(streaming=True) # a stopped task still reserves its channels: no snap task in parallel if self.controller is None: - self.emit_status(ThreadCommand('Update_Status', ['No channel to acquire: add one to the channels', 'log'])) + self.no_channel_message() return self._traces = [[] for _ in self.tasks] for index, task in enumerate(self.tasks): @@ -247,6 +268,8 @@ def stop_live(self) -> None: self.update_tasks() # back to the tasks of the snaps def _on_block(self, index: int, block: np.ndarray) -> None: + """A block of samples of the task ``index`` arrived in live mode: emit it (0D), or add it to the series of + traces being averaged and emit the mean when the series is complete (1D).""" if self.settings['display'] == '0D': self.emit_points([block], [index]) return From f97e2ff799473e9b6e4dc4c39be95f92a69d77df Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:04:30 +0000 Subject: [PATCH 6/8] The clock list offers clock sources only, from all the devices Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../plugins_0D/daq_0Dviewer_NIDAQmx.py | 13 ++++++++++++- tests/nidaqmx_double.py | 2 +- tests/test_generic_ai_plugin.py | 11 +++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py index 71a0e1b..a807e29 100644 --- a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py +++ b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py @@ -54,6 +54,15 @@ def is_signal_terminal(terminal: str) -> bool: # --- settings of a module --------------------------------------------------------------------------------------- +# the terminals that can time a task: a wire in (PFI, RTSI, PXI), or the sample clock or the timebase of a subsystem +_CLOCK_SOURCE = re.compile(r'^/[^/]+/((PFI|RTSI|PXI_Trig)\d+(/.+)?|\w+/SampleClock(Timebase)?|\w*Timebase\w*)$', re.IGNORECASE) + + +def is_clock_source(terminal: str) -> bool: + """Whether ``terminal`` can be the sample clock of a task (``/Dev1/PFI1``, ``/Dev1/ao/SampleClock``).""" + return _CLOCK_SOURCE.match(terminal) is not None + + def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str]) -> dict: """The settings of a module: its frequency, its clock and its start trigger.""" return {'title': module, 'name': module, 'type': 'group', 'children': [ @@ -242,7 +251,9 @@ def module_lists(self, module: str) -> dict: apfi = [t for t in NIDAQSystem().terminals(module) if '/APFI' in t] except ValueError: # a module that is not a device of the system apfi = [] - clocks = [CLOCK_INTERNAL] + terminals + [f'/{m}/ai/SampleClock' for m in others] + # the clock sources of all the devices, and the sample clock that another module of the tree exports + clocks = ([CLOCK_INTERNAL] + [t for t in terminals if is_clock_source(t)] + + [f'/{m}/ai/SampleClock' for m in others]) starts = terminals + [f'/{m}/ai/StartTrigger' for m in others] return {'clocks': list(dict.fromkeys(clocks)), 'terminals': list(dict.fromkeys(starts)), 'channels': names + apfi} diff --git a/tests/nidaqmx_double.py b/tests/nidaqmx_double.py index f8920b2..332bdb2 100644 --- a/tests/nidaqmx_double.py +++ b/tests/nidaqmx_double.py @@ -328,7 +328,7 @@ def _pcie_6363(): ci=[f'Dev2/ctr{c}' for c in range(4)], co=[f'Dev2/ctr{c}' for c in range(4)] + ['Dev2/freqout'], di=[f'Dev2/port0/line{c}' for c in range(4)], do=[f'Dev2/port0/line{c}' for c in range(4)], terminals=[f'/Dev2/PFI{c}' for c in range(6)] + ['/Dev2/APFI0', '/Dev2/APFI1', '/Dev2/ai0', '/Dev2/ao0', - '/Dev2/ai/SampleClock', '/Dev2/ctr0', '/Dev2/port0/line0'], + '/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) diff --git a/tests/test_generic_ai_plugin.py b/tests/test_generic_ai_plugin.py index cd8ee98..36eec0c 100644 --- a/tests/test_generic_ai_plugin.py +++ b/tests/test_generic_ai_plugin.py @@ -163,6 +163,17 @@ def test_the_clock_and_terminal_lists_offer_terminals_not_channels(qapp, driver, plugin.close() +def test_the_clock_list_offers_clock_sources_of_all_the_devices(qapp, driver, system_driver): + plugin = make_detector(DAQ_0DViewer_NIDAQmx) + modules = two_modules(plugin) + offered = modules.child('Dev1', 'clock').opts['limits'] + assert offered[0] == 'internal' + assert {'/Dev1/PFI1', '/Dev2/PFI1', '/Dev2/ai/SampleClock', '/Dev2/ao/SampleClock'} <= set(offered) + assert '/Dev1/ai/SampleClock' not in offered # a module cannot be timed by its own clock + assert '/Dev2/ai/ConvertClock' not in offered # not a clock of the samples + plugin.close() + + def test_a_digital_edge_trigger_starts_the_task_of_its_module_only(qapp, driver, system_driver): from nidaqmx.constants import Edge plugin = make_detector(DAQ_0DViewer_NIDAQmx) From 6103048c3c65da99c4b26b75af78836685b5d358 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:06:54 +0000 Subject: [PATCH 7/8] Offer only the terminals that can reach a module as clock or digital trigger source Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- docs/source/user_guide/nidaqmx_viewer_use.rst | 5 +++- .../plugins_0D/daq_0Dviewer_NIDAQmx.py | 30 ++++++++++++++++--- .../national_instruments/api/system.py | 4 +++ tests/nidaqmx_double.py | 7 +++++ tests/test_generic_ai_plugin.py | 13 ++++++++ 5 files changed, 54 insertions(+), 5 deletions(-) diff --git a/docs/source/user_guide/nidaqmx_viewer_use.rst b/docs/source/user_guide/nidaqmx_viewer_use.rst index 71e3a4d..1d1a182 100644 --- a/docs/source/user_guide/nidaqmx_viewer_use.rst +++ b/docs/source/user_guide/nidaqmx_viewer_use.rst @@ -51,7 +51,10 @@ Settings can have (the driver needs it to size its buffer), not the real one. * **Clock**: ``internal`` (the module times itself), a terminal wired to the device (``/Dev1/PFI1``), or the clock exported by another module (``/Dev1/ai/SampleClock``), which makes the modules share one clock. Any module may - follow an external clock. A module cannot be offered its own clock. + follow an external clock. A module cannot be offered its own clock. The list offers only the terminals + that can reach the module: those of its device, and for a module of a chassis the terminals of the chassis and of + the other modules of that chassis (a board cannot be wired by software to another device). The terminal of the + digital trigger follows the same rule. * **Start trigger**: ``none`` (the task starts at once), ``digital edge`` (a *Terminal* such as ``/Dev1/PFI0``, or the start trigger exported by another module, and an *Edge*) or ``analog edge`` (a *Channel*, a *Level* in volts and an *Edge*). An analog trigger watches one of the channels of the module, which the driver requires to be a diff --git a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py index a807e29..da1de89 100644 --- a/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py +++ b/src/pymodaq_plugins_daqmx/daq_viewer_plugins/plugins_0D/daq_0Dviewer_NIDAQmx.py @@ -112,7 +112,7 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) system = NIDAQSystem() self.settings.child('channels').setLimits(system.all_channels(ChannelKind.AI)) - self.terminals = [terminal for device in system.devices() for terminal in system.terminals(device)] + self.terminals = {device: system.terminals(device) for device in system.devices()} # of each device self.files = ConfigFiles() self.loaded = MANUAL # the configuration whose channels are in the tree self.in_file = () # what the file describes (see `snapshot`), to tell if the tree still is the file @@ -240,11 +240,33 @@ def set_limits(param: Parameter, limits: List[str]) -> None: if param.opts['limits'] != limits: param.setLimits(limits) + def reachable_devices(self, module: str) -> List[str]: + """The devices whose terminals can reach ``module``: itself and, for a module of a chassis, the chassis and the + other modules of that chassis (a board cannot be wired to another device by software).""" + try: + chassis = NIDAQSystem().chassis(module) + except ValueError: # not a device of the system + chassis = '' + if not chassis: + return [module] + return [device for device in self.terminals + if device in (module, chassis) or self.chassis_of(device) == chassis] + + @staticmethod + def chassis_of(device: str) -> str: + try: + return NIDAQSystem().chassis(device) + except ValueError: + return '' + def module_lists(self, module: str) -> dict: - """What the settings of ``module`` choose among. A terminal of its own ``ai`` subsystem cannot time it.""" - others = [m for m in self.modules() if m != module] + """What the settings of ``module`` choose among. A terminal of its own ``ai`` subsystem cannot time it, and + only the devices that can reach the module offer terminals (see ``reachable_devices``).""" + reachable = self.reachable_devices(module) + others = [m for m in self.modules() if m != module and m in reachable] own = f'/{module}/ai/' - terminals = [t for t in self.terminals if not t.startswith(own) and is_signal_terminal(t)] + terminals = [t for device in reachable for t in self.terminals.get(device, []) + if not t.startswith(own) and is_signal_terminal(t)] names = [child.opts['title'] for child in self.settings.child('channels').children() if child.opts['title'].split('/')[0] == module] try: # the dedicated analog trigger terminals of the device, which are not read 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 7723237..ca07bdb 100644 --- a/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/system.py +++ b/src/pymodaq_plugins_daqmx/hardware/national_instruments/api/system.py @@ -61,6 +61,10 @@ def terminals(self, device): """Terminals of ``device`` (``/Dev1/PFI0``...), usable as clock or trigger sources.""" return list(self._device_property(device, 'terminals', list, [])) + def chassis(self, device): + """Name of the chassis that holds ``device`` (``cDAQ1`` for ``cDAQ1Mod3``), empty for a device that is not in one.""" + return self._device_property(device, 'compact_daq_chassis_device', lambda chassis: chassis.name, '') + def ai_voltage_ranges(self, device): """Voltage ranges of the analog inputs as ``(min, max)`` pairs.""" return self._device_property(device, 'ai_voltage_rngs', _pairs, []) diff --git a/tests/nidaqmx_double.py b/tests/nidaqmx_double.py index 332bdb2..1ac752c 100644 --- a/tests/nidaqmx_double.py +++ b/tests/nidaqmx_double.py @@ -290,6 +290,11 @@ def _flat(ranges): return [value for pair in ranges for value in pair] +class _Named: + def __init__(self, name): + self.name = name + + class DoubleDevice: """Values copied from the reports of a PCIe-6363 (``Dev2``) and of a PCI-6133 without analog output.""" @@ -318,6 +323,8 @@ def _get(self, key): 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')) + # the chassis of a module (a device without one gives an empty name); the double puts its devices in 'cDAQ1' + compact_daq_chassis_device = property(lambda self: _Named(self._properties.get('chassis', 'cDAQ1'))) def _pcie_6363(): diff --git a/tests/test_generic_ai_plugin.py b/tests/test_generic_ai_plugin.py index 36eec0c..3839968 100644 --- a/tests/test_generic_ai_plugin.py +++ b/tests/test_generic_ai_plugin.py @@ -174,6 +174,19 @@ def test_the_clock_list_offers_clock_sources_of_all_the_devices(qapp, driver, sy plugin.close() +def test_sources_come_from_the_chassis_of_the_module_not_from_other_devices(qapp, driver, system_driver): + system_driver.installed_devices[1]._properties['chassis'] = '' # Dev2 is a board of its own, Dev1 is in cDAQ1 + plugin = make_detector(DAQ_0DViewer_NIDAQmx) + modules = two_modules(plugin) + for offered in (modules.child('Dev1', 'clock').opts['limits'], modules.child('Dev1', 'trigger', 'terminal').opts['limits']): + assert '/Dev1/PFI1' in offered + assert not [t for t in offered if t.startswith('/Dev2/')] + for offered in (modules.child('Dev2', 'clock').opts['limits'], modules.child('Dev2', 'trigger', 'terminal').opts['limits']): + assert '/Dev2/PFI1' in offered + assert not [t for t in offered if t.startswith('/Dev1/')] + plugin.close() + + def test_a_digital_edge_trigger_starts_the_task_of_its_module_only(qapp, driver, system_driver): from nidaqmx.constants import Edge plugin = make_detector(DAQ_0DViewer_NIDAQmx) From de861ed922a8b3f692ad880559ea7404f1a3ffa4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 12:11:10 +0000 Subject: [PATCH 8/8] Update the viewer documentation: clock sources, reach of the sources, channel ranges Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- docs/source/user_guide/nidaqmx_viewer_use.rst | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/source/user_guide/nidaqmx_viewer_use.rst b/docs/source/user_guide/nidaqmx_viewer_use.rst index 1d1a182..62fe727 100644 --- a/docs/source/user_guide/nidaqmx_viewer_use.rst +++ b/docs/source/user_guide/nidaqmx_viewer_use.rst @@ -22,8 +22,9 @@ How to use it its device can measure (``voltage``, then ``current``, ``thermocouple`` and ``rtd``) and its default parameters; a voltage channel gets the widest voltage range of the device. 3. **Choose the type of each channel** (``voltage``, ``current``, ``thermocouple``, ``rtd``). The group is rebuilt with - only the parameters of the new type; the values that the two types share, such as the range, are kept. - Remove a channel with the remove button of its group. + only the parameters of the new type. The range is kept only between types that measure the same quantity + (thermocouple and RTD): changing from a voltage to a current or a temperature gives the default range of the new + type, as a range in volts means nothing in amperes. Remove a channel with the remove button of its group. 4. **Set the acquisition**: the display, the frequency and, for the traces, the number of samples (see below). 5. **Grab or start the live mode.** The task is built from the channels when the first one is available, and rebuilt at the next grab when the channels changed (in live mode, at the next start). @@ -49,14 +50,17 @@ Settings * **Frequency**: the sampling rate of the module. With an external clock it is the highest frequency that clock can have (the driver needs it to size its buffer), not the real one. - * **Clock**: ``internal`` (the module times itself), a terminal wired to the device (``/Dev1/PFI1``), or the clock - exported by another module (``/Dev1/ai/SampleClock``), which makes the modules share one clock. Any module may - follow an external clock. A module cannot be offered its own clock. The list offers only the terminals - that can reach the module: those of its device, and for a module of a chassis the terminals of the chassis and of - the other modules of that chassis (a board cannot be wired by software to another device). The terminal of the - digital trigger follows the same rule. + * **Clock**: ``internal`` (the module times itself) or a clock source, which makes the modules share one clock. + Any module may follow an external clock. The list offers only real clock sources: the terminals wired to the + device (``/Dev1/PFI1``, RTSI, PXI), the sample clocks and timebases of the subsystems of the device + (``/Dev1/ao/SampleClock``) and the sample clock that another module exports (``/Dev1/ai/SampleClock``). A module + is never offered its own sample clock. + * **Reach of the sources**: a clock source or a digital trigger terminal has to be reachable by the module. The + lists offer the terminals of the device of the module and, for a module of a cDAQ chassis, the terminals of the + chassis (``/cDAQ1/PFI0``) and of the other modules of the same chassis. A card or a USB device only has its own + terminals, as a device cannot be wired to another one by software. * **Start trigger**: ``none`` (the task starts at once), ``digital edge`` (a *Terminal* such as ``/Dev1/PFI0``, or - the start trigger exported by another module, and an *Edge*) or ``analog edge`` (a *Channel*, a *Level* in volts + the start trigger exported by another module of the same chassis, and an *Edge*) or ``analog edge`` (a *Channel*, a *Level* in volts and an *Edge*). An analog trigger watches one of the channels of the module, which the driver requires to be a channel of the task (set its ``read`` box off if you do not want its samples); the list also offers the dedicated analog trigger terminals (``/Dev1/APFI0``) of the module, if it has some: such a terminal is not acquired. @@ -73,8 +77,8 @@ Settings * **Channels**: the group described above. Each channel has a ``read`` box (checked by default): unchecked, the channel stays in the task but its samples are not in the data, which is what an analog trigger on that channel needs. A module whose channels are all unchecked gives no data. The parameters of a channel are the fields of its channel class of the - API (``AIVoltage``, ``AICurrent``, ``AIThermocouple``, ``AIRtd``), with the same names (the range, ``min_val`` and ``max_val``, is shown in the unit of its quantity: V, A or the temperature units). Changing the type of a channel keeps the values that still make sense: the range is kept only between types that measure the same quantity (thermocouple and RTD), and takes the default of the new type otherwise; see :doc:`config_files` - for the list. + API (``AIVoltage``, ``AICurrent``, ``AIThermocouple``, ``AIRtd``), with the same names; the range (``min_val`` and ``max_val``) is shown in the unit of its quantity: V, A, or the + temperature units of the channel. See :doc:`config_files` for the list. Loading and saving a configuration ----------------------------------