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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/source/user_guide/nidaqmx_viewer_use.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,22 @@ written, and is back to normal when it worked. After a failure the menu goes bac
that is not in the tree.

A file that cannot be read gives an error that names the file and the entry that is wrong.

Digital input lines (``NIDAQmx_DI``)
------------------------------------

``DAQ_1DViewer_NIDAQmx_DI`` (in the 1D viewers, as ``NIDAQmx_DI``) is the same viewer for the digital input lines of
a device (``Dev1/port0/line0``), as 1D traces: a line is 0 or 1, so there is no mean and no 0D display. It differs
from the analog viewer in a few points:

* The group ``Lines`` replaces ``Channels``: *Add* lists the lines of the computer, and a line has no type nor range,
only its ``read`` box.
* The group of each module (``Modules``) is the same, with the frequency and the clock, but the start trigger is
``none`` or ``digital edge`` only: a digital input has no analog trigger. ``internal`` is the sample clock of the
digital task itself (``/Dev1/di/SampleClock``), which exists on the devices that can time their digital lines. If the
driver refuses it, choose a clock source: a PFI terminal wired to a clock, or the clock of another module. The
sample clock of an analog input (``/Dev1/ai/SampleClock``) is a different clock: it only runs while an analog
task of that device runs, at its rate, which is what you want to read lines in step with analog channels.
* Each module has its own task and gives its own data, named ``NI DI <module>``, with the lines as traces labelled
with their names.
* There is no live mode and no configuration file in this version.
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@

# --- terminals --------------------------------------------------------------------------------------------------

def _exporting_module(terminal: str) -> Optional[str]:
"""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."""
def _exporting_module(terminal: str, subsystem: str = 'ai') -> Optional[str]:
"""The module that produces the signal ``terminal`` (``/Dev1/ai/SampleClock`` is produced by ``Dev1`` for the
subsystem ``ai``), 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
return parts[1] if len(parts) > 3 and parts[0] == '' and parts[2] == subsystem else None


# what the driver lists as terminals but cannot be a clock or a trigger source
Expand All @@ -63,15 +64,16 @@ def is_clock_source(terminal: str) -> bool:
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:
def module_group(module: str, frequency: int, clocks: List[str], terminals: List[str], channels: List[str],
trigger_types: List[str] = TRIGGER_TYPES) -> 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': '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'},
Expand Down Expand Up @@ -107,16 +109,28 @@ class DAQ_0DViewer_NIDAQmx(DAQ_Viewer_AIBase):
'limits': [], 'children': []},
]
data_name = 'NI AI'
# what distinguishes the subclasses for other inputs (the digital lines): the kind of channels of the tree (it
# also names the subsystem of the driver that exports the clock and the trigger of a module: ``/Dev1/ai/...``),
# the types of start trigger, and whether there are files
kind = ChannelKind.AI
trigger_types = TRIGGER_TYPES
has_configuration = True

@property
def subsystem(self) -> str:
"""The part of the terminal names that the driver gives to the subsystem of the channels (``ai``, ``di``)."""
return self.kind.value

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
system = NIDAQSystem()
self.settings.child('channels').setLimits(system.all_channels(ChannelKind.AI))
self.settings.child('channels').setLimits(system.all_channels(self.kind))
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
self.refresh_menu()
if self.has_configuration:
self.refresh_menu()

# --- configuration files: menu, load, save ------------------------------------------------------------------

Expand Down Expand Up @@ -228,7 +242,7 @@ def sync_modules(self) -> None:
for module in modules:
lists = self.module_lists(module)
if module not in group.names:
group.addChild(module_group(module, self.settings['frequency'], **lists))
group.addChild(module_group(module, self.settings['frequency'], trigger_types=self.trigger_types, **lists))
continue
self.set_limits(group.child(module, 'clock'), lists['clocks'])
self.set_limits(group.child(module, 'trigger', 'terminal'), lists['terminals'])
Expand Down Expand Up @@ -264,7 +278,7 @@ def module_lists(self, module: str) -> dict:
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/'
own = f'/{module}/{self.subsystem}/'
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()
Expand All @@ -275,8 +289,8 @@ def module_lists(self, module: str) -> dict:
apfi = []
# 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]
+ [f'/{m}/{self.subsystem}/SampleClock' for m in others])
starts = terminals + [f'/{m}/{self.subsystem}/StartTrigger' for m in others]
return {'clocks': list(dict.fromkeys(clocks)), 'terminals': list(dict.fromkeys(starts)),
'channels': names + apfi}

Expand Down Expand Up @@ -340,7 +354,7 @@ def acquisitions(self) -> List[Acquisition]:
# 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)
waits = tuple(dict.fromkeys(m for m in (_exporting_module(source, self.subsystem) 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))
Expand Down Expand Up @@ -400,9 +414,9 @@ def commit_settings(self, param: Parameter) -> None:
param = self.own(param)
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'):
if self.has_configuration and 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
elif self.has_configuration and param.opts['type'] == 'ni_save': # the button has been clicked, after the dialog of the GUI
param.opts.update(suffix=button.opts['suffix'])
try:
self.save_configuration(param)
Expand All @@ -411,7 +425,7 @@ def commit_settings(self, param: Parameter) -> None:
param.setValue(Status.ERROR)
self.fail(error)
if param.name() == 'type' and in_a_channel: # the type of a channel: its group is rebuilt
set_type(ChannelKind.AI, parent, param.value())
set_type(self.kind, 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':
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Generic viewer of the digital input lines of any NI device, as 1D traces.

It is the generic analog viewer with lines in place of channels: the same settings for each module (frequency,
clock, start trigger) and one clocked digital task for each module. A line is 0 or 1, so the data are traces and
never a mean (there is no 0D display). There is no live mode and no configuration file in this version.
"""
from copy import deepcopy

import numpy as np
from pymodaq.control_modules.viewer_utility_classes import main

from pymodaq_plugins_daqmx.daq_viewer_plugins.plugins_0D.daq_0Dviewer_NIDAQmx import DAQ_0DViewer_NIDAQmx
from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind, DigitalTask


def _digital_params() -> list:
params = []
for param in deepcopy(DAQ_0DViewer_NIDAQmx.params):
if param['name'] == 'config': # the files describe analog inputs
continue
if param['name'] == 'display': # traces only
param.update(limits=['1D'], value='1D', visible=False)
if param['name'] == 'channels':
param.update(title='Lines:', kind=ChannelKind.DI.value)
params.append(param)
return params


class DAQ_1DViewer_NIDAQmx_DI(DAQ_0DViewer_NIDAQmx):
"""Digital input lines (``Dev1/port0/line0``) of any NI device, as 1D traces, one data for each module."""
params = _digital_params()
data_name = 'NI DI'
kind = ChannelKind.DI
trigger_types = ['none', 'digital edge'] # there is no analog start trigger on a digital input
has_configuration = False
live_mode_available = False
task_class = DigitalTask

def read_block(self, task) -> np.ndarray:
"""The levels of the lines as floats (0. or 1.), shaped (lines, Nsamples)."""
return task.read_digital(self.task_samples()).astype(float)


if __name__ == '__main__':
main(__file__, init=False)
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ class DAQ_Viewer_AIBase(DAQ_Viewer_base):
hardware_averaging = True
live_mode_available = True # with live=True: one continuous task, one data per block of samples
data_name = 'NI AI'
task_class = AnalogInputTask # the kind of task of an acquisition; a subclass for other inputs gives its own

def read_block(self, task) -> np.ndarray:
"""Run the finite acquisition of a started task: its samples as floats, shaped (nchannels, Nsamples)."""
return task.read_analog()

def ini_attributes(self):
self.controller = None # the task of this plugin, or the group of its tasks when it has several
Expand Down Expand Up @@ -188,7 +193,7 @@ def update_tasks(self, streaming: bool = False) -> None:
try:
for acquisition in acquisitions:
clock = ClockSettings(rate=acquisition.frequency, samples=samples, source=acquisition.clock)
tasks.append(AnalogInputTask(TaskConfig(channels=acquisition.channels, timing=clock,
tasks.append(self.task_class(TaskConfig(channels=acquisition.channels, timing=clock,
trigger=acquisition.trigger)))
except Exception:
for task in reversed(tasks):
Expand All @@ -215,7 +220,7 @@ def read_samples(self) -> List[np.ndarray]:
for task in self.ordered_tasks():
task.start()
started.append(task)
return [task.read_analog() for task in self.tasks]
return [self.read_block(task) for task in self.tasks]
finally:
for task in reversed(started):
task.stop()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from nidaqmx.constants import TerminalConfiguration, ThermocoupleType, UsageTypeAI

from pymodaq_plugins_daqmx.hardware.national_instruments.api import (
AICurrent, AIRtd, AIThermocouple, AIVoltage, ChannelKind)
AICurrent, AIRtd, AIThermocouple, AIVoltage, ChannelKind, DigitalIn)

FORMAT_VERSION = 1

Expand All @@ -25,6 +25,7 @@
#: channel types of a configuration file, by the ``type`` key, for each kind of channel
CHANNEL_TYPES = {
ChannelKind.AI: {'voltage': AIVoltage, 'current': AICurrent, 'thermocouple': AIThermocouple, 'rtd': AIRtd},
ChannelKind.DI: {'line': DigitalIn}, # in the settings tree only: the files describe analog inputs
}


Expand Down
2 changes: 1 addition & 1 deletion tests/nidaqmx_double.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

KNOWN_COUNTERS = {f"Dev2/ctr{c}" for c in range(4)}
KNOWN_AO_CHANNELS = {f"Dev2/ao{c}" for c in range(4)}
KNOWN_LINES = {f"Dev2/port0/line{c}" for c in range(8)}
KNOWN_LINES = {f"Dev2/port0/line{c}" for c in range(8)} | {f"Dev1/port0/line{c}" for c in range(4)}
KNOWN_AI_CHANNELS = {f"Dev{d}/ai{c}" for d in (1, 2) for c in range(8)}


Expand Down
3 changes: 2 additions & 1 deletion tests/test_config_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,12 @@ def test_a_file_of_an_unknown_version_is_refused(tmp_path):
def test_the_user_guide_describes_every_type_key_and_value_of_the_format():
import dataclasses
import enum
from pymodaq_plugins_daqmx.hardware.national_instruments.api import ChannelKind
from pymodaq_plugins_daqmx.hardware.national_instruments.config_files import CHANNEL_TYPES, channel_fields
page = (Path(__file__).parent.parent / 'docs' / 'source' / 'user_guide' / 'config_files.rst').read_text()

missing = []
for types in CHANNEL_TYPES.values():
for types in [CHANNEL_TYPES[ChannelKind.AI]]: # the files describe analog inputs
for name, cls in types.items():
missing += [f'type {name}'] if f'``{name}``' not in page else []
for f in channel_fields(cls):
Expand Down
62 changes: 62 additions & 0 deletions tests/test_generic_di_plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Behaviour of the generic NI digital input viewer (1D traces of lines, no hardware needed)."""
import pytest

pytest.importorskip('nidaqmx')
pytest.importorskip('pymodaq')

from pymodaq.utils.plugin_testing import make_detector, grab_and_wait

from pymodaq_plugins_daqmx.daq_viewer_plugins.plugins_1D.daq_1Dviewer_NIDAQmx_DI import DAQ_1DViewer_NIDAQmx_DI

from nidaqmx_double import driver, system_driver # noqa: F401 (pytest fixtures)


def test_the_tree_offers_the_digital_lines_of_the_computer(qapp, driver, system_driver):
plugin = make_detector(DAQ_1DViewer_NIDAQmx_DI, Nsamples=10)
group = plugin.settings.child('channels')
assert 'Dev1/port0/line0' in group.opts['addList'] and not [n for n in group.opts['addList'] if '/ai' in n]
plugin.close()


def test_the_lines_added_to_the_tree_give_a_trace_each(qapp, driver, system_driver):
plugin = make_detector(DAQ_1DViewer_NIDAQmx_DI, Nsamples=10)
group = plugin.settings.child('channels')
group.addNew('Dev2/port0/line1')
group.addNew('Dev2/port0/line0')
dte = grab_and_wait(plugin)
assert dte[0].dim == 'Data1D' and dte[0].name == 'NI DI Dev2'
assert dte[0].labels == ['Dev2/port0/line1', 'Dev2/port0/line0']
assert [d.shape for d in dte[0].data] == [(10,), (10,)]
# in the double, the line of row c is high at the samples s with c + s even
assert [d.tolist() for d in dte[0].data] == [[1., 0.] * 5, [0., 1.] * 5]
assert [kind for kind, *_ in driver[-1].channels] == ['di', 'di']
plugin.close()


def test_each_module_has_its_own_clocked_task_and_digital_trigger_only(qapp, driver, system_driver):
from nidaqmx.constants import Edge
plugin = make_detector(DAQ_1DViewer_NIDAQmx_DI, Nsamples=10)
group = plugin.settings.child('channels')
group.addNew('Dev1/port0/line0')
group.addNew('Dev2/port0/line0')
plugin.commit_settings(group)
modules = plugin.settings.child('modules')
assert modules.child('Dev1', 'trigger', 'type').opts['limits'] == ['none', 'digital edge']
modules['Dev1', 'frequency'] = 500
trigger = modules.child('Dev1', 'trigger')
trigger.child('type').setValue('digital edge')
plugin.commit_settings(trigger.child('type'))
trigger.child('terminal').setValue('/Dev1/PFI1')
dte = grab_and_wait(plugin)
assert [d.name for d in dte] == ['NI DI Dev1', 'NI DI Dev2']
assert driver[0].timing_calls[0][1] == 500 and driver[1].timing_calls[0][1] == 1000
assert driver[0].trigger_calls == [('dig_edge', '/Dev1/PFI1', Edge.RISING)] and driver[1].trigger_calls == []
assert dte[0].axes[0].units == 's'
plugin.close()


def test_the_digital_viewer_has_no_live_mode_nor_configuration_menu(qapp, driver, system_driver):
plugin = make_detector(DAQ_1DViewer_NIDAQmx_DI)
assert not plugin.live_mode_available
assert 'config' not in plugin.settings.names
plugin.close()
Loading