From 465f9698767e8c5df1b05714ca29496de83b5bba Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:18:59 +0000 Subject: [PATCH 01/10] Add the waveform factory and the waveform output contract waveforms: waveforms as dataclasses of their parameters in a registry (dc, sine, square, triangle, sawtooth, ramp, pulse, piecewise linear, array), samples for a sample rate with a whole number of samples per period, settings generated from the fields, pint quantities accepted. waveform_output: versioned settings groups of the plugins generating waveforms (capabilities and user choices), read back from the control module like the shaper, with a check of what is sent. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- README.rst | 8 + .../hardware/waveform_output.py | 171 ++++++++ .../hardware/waveforms.py | 377 ++++++++++++++++++ tests/test_waveform_output.py | 89 +++++ tests/test_waveforms.py | 159 ++++++++ 5 files changed, 804 insertions(+) create mode 100644 src/pymodaq_plugins_utils/hardware/waveform_output.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms.py create mode 100644 tests/test_waveform_output.py create mode 100644 tests/test_waveforms.py diff --git a/README.rst b/README.rst index 79f835d..6bf6ddb 100644 --- a/README.rst +++ b/README.rst @@ -51,3 +51,11 @@ Utilities * shaper: common interface of the plugins driving a shaper (SLM, DMD...): settings groups with the number of pixels, their size and the properties of the modulator, filled by the plugin and read back by the applications (BeamShaping extension) from the control module, see ``pymodaq_plugins_utils.hardware.shaper`` +* waveforms: waveform factory. A waveform (dc, sine, square, triangle, sawtooth, ramp, pulse, piecewise linear points, + array from a file) is a dataclass of its parameters, given by name from a registry that plugin packages can extend. + ``realize(sample_rate)`` gives the samples, one period with a whole number of samples for a periodic waveform (the + frequency really generated is returned), and ``params()`` the settings, see ``pymodaq_plugins_utils.hardware.waveforms`` +* waveform_output: common interface of the plugins generating waveforms (analog outputs, arbitrary generators): the + capabilities of the instrument and the choices of the user (sample rate, mode, repetitions) as settings groups, + read back by the applications from the control module, which check what they send, see + ``pymodaq_plugins_utils.hardware.waveform_output`` diff --git a/src/pymodaq_plugins_utils/hardware/waveform_output.py b/src/pymodaq_plugins_utils/hardware/waveform_output.py new file mode 100644 index 0000000..0176888 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveform_output.py @@ -0,0 +1,171 @@ +"""Common interface of the instrument plugins generating waveforms (analog outputs, arbitrary generators) + +A waveform output plugin is a DAQ_Move actuator whose position is a :class:`~pymodaq.utils.data.DataActuator` holding +one array of samples (volts) per channel, all of the same length. It adds the settings groups returned by +:func:`waveform_output_params` to its parameters and fills the capabilities once the instrument is initialized +(:func:`fill_waveform_output_settings`). The applications (as the waveform extension) do not call the plugin, which +lives in another thread: they read these groups from the settings of its control module +(:meth:`WaveformOutput.from_module`), then check what they are going to send (:meth:`WaveformOutput.check`) and send +the samples as the position of the actuator. + +Two groups: ``waveform_capabilities`` (read only, what the instrument can do) and ``waveform_output`` (what the user +chooses: sample rate, mode, repetitions; the plugin applies them when it receives samples). The names of the groups and +of their children, and :data:`WAVEFORM_OUTPUT_VERSION`, are the contract. Evolution rule: only add optional children, +never rename or remove one; a breaking change increments :data:`WAVEFORM_OUTPUT_VERSION`. +""" +import dataclasses +from typing import Optional, Sequence + +import numpy as np + +from pymodaq_utils.enums import StrEnum +from pymodaq_utils.logger import set_logger, get_module_name + +logger = set_logger(get_module_name(__file__)) + +WAVEFORM_OUTPUT_VERSION = 1 +CAPABILITIES_NAME = 'waveform_capabilities' +OUTPUT_NAME = 'waveform_output' + + +class OutputMode(StrEnum): + FINITE = 'finite' # the samples are generated once + REPEAT = 'repeat' # the samples are generated ``repetitions`` times + CONTINUOUS = 'continuous' # the samples are generated again and again until the actuator is stopped + + +def waveform_capabilities_params() -> dict: + """Group describing the instrument, read only. The lists (modes, triggers) are comma separated texts""" + return {'title': 'Waveform capabilities:', 'name': CAPABILITIES_NAME, 'type': 'group', 'children': [ + {'title': 'Version:', 'name': 'version', 'type': 'int', 'value': WAVEFORM_OUTPUT_VERSION, 'readonly': True, + 'visible': False}, + {'title': 'Channels:', 'name': 'n_channels', 'type': 'int', 'value': 0, 'readonly': True}, + {'title': 'Min sample rate:', 'name': 'min_rate', 'type': 'float', 'value': 0., 'suffix': 'Hz', + 'siPrefix': True, 'readonly': True}, + {'title': 'Max sample rate:', 'name': 'max_rate', 'type': 'float', 'value': 0., 'suffix': 'Hz', + 'siPrefix': True, 'readonly': True}, + {'title': 'Max samples:', 'name': 'max_samples', 'type': 'int', 'value': 0, 'readonly': True, + 'tip': 'Per channel, 0 for no limit'}, + {'title': 'Min voltage:', 'name': 'min_voltage', 'type': 'float', 'value': -10., 'suffix': 'V', + 'readonly': True}, + {'title': 'Max voltage:', 'name': 'max_voltage', 'type': 'float', 'value': 10., 'suffix': 'V', + 'readonly': True}, + {'title': 'Modes:', 'name': 'modes', 'type': 'str', 'value': OutputMode.FINITE.value, 'readonly': True}, + {'title': 'Triggers:', 'name': 'triggers', 'type': 'str', 'value': '', 'readonly': True, + 'tip': 'Names of the trigger sources the instrument accepts, set in the settings of the plugin'}, + {'title': 'Live update:', 'name': 'live_update', 'type': 'bool', 'value': False, 'readonly': True, + 'tip': 'True if new samples replace the ones being generated without a break of the signal'}, + ]} + + +def waveform_output_settings_params() -> dict: + """Group with the choices of the user""" + return {'title': 'Waveform output:', 'name': OUTPUT_NAME, 'type': 'group', 'children': [ + {'title': 'Version:', 'name': 'version', 'type': 'int', 'value': WAVEFORM_OUTPUT_VERSION, 'readonly': True, + 'visible': False}, + {'title': 'Sample rate:', 'name': 'sample_rate', 'type': 'float', 'value': 1e4, 'min': 0., 'suffix': 'Hz', + 'siPrefix': True}, + {'title': 'Mode:', 'name': 'mode', 'type': 'list', 'limits': [m.value for m in OutputMode], + 'value': OutputMode.FINITE.value}, + {'title': 'Repetitions:', 'name': 'repetitions', 'type': 'int', 'value': 1, 'min': 1, + 'tip': 'Used in the repeat mode'}, + ]} + + +def waveform_output_params() -> list[dict]: + """The groups to add to the parameters of a waveform output plugin""" + return [waveform_capabilities_params(), waveform_output_settings_params()] + + +def fill_waveform_output_settings(settings, n_channels: int, min_rate: float, max_rate: float, max_samples: int = 0, + min_voltage: float = -10., max_voltage: float = 10., + modes: Sequence[OutputMode] = (OutputMode.FINITE,), triggers: Sequence[str] = (), + live_update: bool = False) -> None: + """Fill the capabilities of a plugin in its ``settings`` (to be called in ``ini_stage``) + + The modes of the user choice are limited to the ones the instrument has. + """ + modes = [OutputMode(mode) for mode in modes] + capabilities = settings.child(CAPABILITIES_NAME) + for key, value in (('n_channels', n_channels), ('min_rate', min_rate), ('max_rate', max_rate), + ('max_samples', max_samples), ('min_voltage', min_voltage), ('max_voltage', max_voltage), + ('modes', ','.join(mode.value for mode in modes)), ('triggers', ','.join(triggers)), + ('live_update', live_update)): + capabilities.child(key).setValue(value) + settings.child(OUTPUT_NAME, 'mode').setLimits([mode.value for mode in modes]) + + +@dataclasses.dataclass +class WaveformOutput: + """What an application knows of a waveform output plugin: its capabilities and the choices of the user""" + n_channels: int + min_rate: float + max_rate: float + max_samples: int + min_voltage: float + max_voltage: float + modes: list[OutputMode] + triggers: list[str] + live_update: bool + sample_rate: float + mode: OutputMode + repetitions: int + + @classmethod + def from_settings(cls, capabilities, output) -> 'WaveformOutput': + """Build it from the two groups (Parameter objects) of a waveform output plugin""" + return cls(n_channels=int(capabilities['n_channels']), min_rate=float(capabilities['min_rate']), + max_rate=float(capabilities['max_rate']), max_samples=int(capabilities['max_samples']), + min_voltage=float(capabilities['min_voltage']), max_voltage=float(capabilities['max_voltage']), + modes=[OutputMode(mode) for mode in capabilities['modes'].split(',') if mode], + triggers=[trigger for trigger in capabilities['triggers'].split(',') if trigger], + live_update=bool(capabilities['live_update']), sample_rate=float(output['sample_rate']), + mode=OutputMode(output['mode']), repetitions=int(output['repetitions'])) + + @classmethod + def from_module(cls, module) -> Optional['WaveformOutput']: + """Read it from a DAQ_Move control module + + None if its plugin has no such groups, is not initialized yet (no channel) or follows another version of the + contract (an error is logged in that case). + """ + try: + settings = module.settings.child(module._hw_settings_name) + capabilities, output = settings.child(CAPABILITIES_NAME), settings.child(OUTPUT_NAME) + except (KeyError, AttributeError): + return None + versions = [group['version'] if 'version' in [c.name() for c in group.children()] else None + for group in (capabilities, output)] + if versions != [WAVEFORM_OUTPUT_VERSION] * 2: + logger.error(f'The waveform output groups of {module} have versions {versions}, version ' + f'{WAVEFORM_OUTPUT_VERSION} is expected: update the plugin or pymodaq_plugins_utils') + return None + waveform_output = cls.from_settings(capabilities, output) + return waveform_output if waveform_output.n_channels > 0 else None + + def check(self, samples: Sequence[np.ndarray], sample_rate: Optional[float] = None, + mode: Optional[OutputMode] = None) -> None: + """Raise a ValueError saying what the instrument cannot do with these samples (one array per channel) + + ``sample_rate`` and ``mode`` are the ones of the user choices if not given. + """ + sample_rate = self.sample_rate if sample_rate is None else sample_rate + mode = self.mode if mode is None else OutputMode(mode) + if len(samples) != self.n_channels: + raise ValueError(f'{len(samples)} waveforms for {self.n_channels} channels') + if len({len(channel) for channel in samples}) != 1: + raise ValueError('The waveforms of the channels should have the same number of samples') + n_samples = len(samples[0]) + if self.max_samples and n_samples > self.max_samples: + raise ValueError(f'{n_samples} samples, the instrument holds at most {self.max_samples} per channel') + if not self.min_rate <= sample_rate <= self.max_rate: + raise ValueError(f'Sample rate {sample_rate} Hz out of the range of the instrument: ' + f'{self.min_rate:g} to {self.max_rate:g} Hz') + if mode not in self.modes: + raise ValueError(f'The mode {mode.value} is not available, the instrument has: ' + f'{", ".join(mode.value for mode in self.modes)}') + low, high = min(float(np.min(channel)) for channel in samples), max(float(np.max(channel)) + for channel in samples) + if low < self.min_voltage or high > self.max_voltage: + raise ValueError(f'The waveform goes from {low:.3g} V to {high:.3g} V, the instrument gives ' + f'{self.min_voltage:g} V to {self.max_voltage:g} V') diff --git a/src/pymodaq_plugins_utils/hardware/waveforms.py b/src/pymodaq_plugins_utils/hardware/waveforms.py new file mode 100644 index 0000000..06b8d75 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms.py @@ -0,0 +1,377 @@ +"""Waveform factory: describe a signal by its parameters, get the samples for a given sample rate + +A waveform is a dataclass whose fields are its parameters. The same description serves a device that computes the +signal itself from parameters and one that needs the samples (:meth:`Waveform.realize`). Fields with a ``unit`` are +numbers expressed in that unit (SI: V, s, Hz, degrees for a phase); a pint quantity is accepted when creating the +waveform and converted. + +The registry (:func:`register_waveform`, :func:`create_waveform`, :func:`waveform_names`) gives the forms by name, so an +application can offer them in a list and a plugin package can add its own:: + + @register_waveform + @dataclasses.dataclass + class Gaussian(Waveform): + name: ClassVar[str] = 'gaussian' + center: float = waveform_field(1e-3, 's', 'Center') + width: float = waveform_field(1e-4, 's', 'Width') + duration: float = waveform_field(2e-3, 's', 'Duration') + + def _realize(self, sample_rate): + t = np.arange(self.n_samples(sample_rate)) / sample_rate + return np.exp(-((t - self.center) / self.width) ** 2 / 2), None + +The contract with the applications and the plugins is :data:`WAVEFORM_VERSION`; evolution rule: only add forms and +optional fields, never rename or remove one; a breaking change increments :data:`WAVEFORM_VERSION`. +""" +import dataclasses +import re +from abc import ABC, abstractmethod +from pathlib import Path +from typing import Any, ClassVar, Optional, Type, Union + +import numpy as np + +from pymodaq_data import Q_ + +WAVEFORM_VERSION = 1 + + +def waveform_field(default: Any, unit: Optional[str] = None, title: str = '', min: Optional[float] = None, + max: Optional[float] = None, tip: str = '') -> Any: + """A dataclass field that is a parameter of the waveform + + Parameters + ---------- + default: the default value + unit: the unit of the number (pint syntax), None for a text + title: the label of the parameter in the settings + min, max: bounds of the parameter in the settings (and checked when the samples are computed) + tip: help shown on the parameter + """ + return dataclasses.field(default=default, metadata=dict(unit=unit, title=title, min=min, max=max, tip=tip)) + + +@dataclasses.dataclass(frozen=True) +class RealizedWaveform: + """The samples of a waveform for one sample rate + + Attributes + ---------- + samples: the signal, in volts for a voltage output. One period for a periodic waveform (to be repeated), the whole + signal otherwise + sample_rate: Hz + periodic: True if ``samples`` is one period to repeat + frequency: Hz, the frequency that is really generated by repeating ``samples`` (periodic waveform only). It is the + requested one rounded so that a period has a whole number of samples + frequency_error: Hz, ``frequency`` minus the requested frequency + """ + samples: np.ndarray + sample_rate: float + periodic: bool = False + frequency: Optional[float] = None + frequency_error: float = 0. + + @property + def duration(self) -> float: + """Seconds""" + return len(self.samples) / self.sample_rate + + +@dataclasses.dataclass +class Waveform(ABC): + """Base class of the waveforms. Subclass it with a dataclass, set ``name`` and register it""" + name: ClassVar[str] = '' + title: ClassVar[str] = '' # label in a list of waveforms, ``name`` if empty + periodic: ClassVar[bool] = False # True: :meth:`realize` gives one period to repeat + + def __post_init__(self): + for field in self._parameters(): + value = getattr(self, field.name) + unit = field.metadata['unit'] + if unit is not None: + value = float(value.m_as(unit)) if isinstance(value, Q_) else float(value) + lower, upper = field.metadata['min'], field.metadata['max'] + if (lower is not None and value < lower) or (upper is not None and value > upper): + raise ValueError(f'{self.name}: {field.name} = {value} {unit} is out of its limits ' + f'({lower}, {upper})') + setattr(self, field.name, value) + + # ---- the description as settings + @classmethod + def _parameters(cls) -> list[dataclasses.Field]: + return [field for field in dataclasses.fields(cls) if 'unit' in field.metadata] + + @classmethod + def params(cls) -> list[dict]: + """The parameters of this waveform as a list of settings dictionaries (pyqtgraph Parameter syntax)""" + params = [] + for field in cls._parameters(): + meta = field.metadata + param = {'title': meta['title'] or field.name, 'name': field.name, 'value': field.default, + 'tip': meta['tip']} + if meta['unit'] is None: + param['type'] = 'str' + else: + dimensionless = meta['unit'] in ('dimensionless', 'deg') # no SI prefix (k, m) in front of these + param.update(type='float', suffix='' if meta['unit'] == 'dimensionless' else meta['unit'], + siPrefix=not dimensionless) + for key in ('min', 'max'): + if meta[key] is not None: + param[key] = meta[key] + params.append(param) + return params + + @classmethod + def from_settings(cls, group) -> 'Waveform': + """Build the waveform from a settings group (a Parameter) holding the children of :meth:`params`""" + return cls(**{field.name: group[field.name] for field in cls._parameters()}) + + # ---- the samples + def n_samples(self, sample_rate: float) -> int: + """Number of samples of a waveform defined by its ``duration`` (at least 2)""" + return max(2, int(round(getattr(self, 'duration') * sample_rate))) + + @abstractmethod + def _realize(self, sample_rate: float) -> tuple[np.ndarray, Optional[float]]: + """The samples and, for a periodic waveform, the frequency really generated""" + + def realize(self, sample_rate: Union[float, Q_]) -> RealizedWaveform: + """The samples of the waveform for ``sample_rate`` (Hz, or a pint quantity)""" + sample_rate = float(sample_rate.m_as('Hz')) if isinstance(sample_rate, Q_) else float(sample_rate) + if sample_rate <= 0: + raise ValueError('The sample rate should be positive') + samples, frequency = self._realize(sample_rate) + requested = getattr(self, 'frequency', None) + return RealizedWaveform(np.asarray(samples, dtype=float), sample_rate, self.periodic, frequency, + 0. if frequency is None else frequency - requested) + + +_REGISTRY: dict[str, Type[Waveform]] = {} + + +def register_waveform(cls: Type[Waveform]) -> Type[Waveform]: + """Class decorator adding a waveform to the registry under its ``name``""" + if not cls.name: + raise ValueError(f'{cls.__name__} has no name') + if cls.name in _REGISTRY and _REGISTRY[cls.name] is not cls: + raise ValueError(f'A waveform called {cls.name} is already registered') + _REGISTRY[cls.name] = cls + return cls + + +def waveform_names() -> list[str]: + """Names of the registered waveforms, in the order of their registration""" + return list(_REGISTRY) + + +def get_waveform_class(name: str) -> Type[Waveform]: + try: + return _REGISTRY[name] + except KeyError: + raise KeyError(f'Unknown waveform {name}, available: {waveform_names()}') from None + + +def create_waveform(name: str, **parameters) -> Waveform: + """Create the waveform registered as ``name`` from its parameters (numbers or pint quantities)""" + return get_waveform_class(name)(**parameters) + + +# ---- helpers of the periodic waveforms +def _period(frequency: float, sample_rate: float) -> tuple[int, float]: + """Number of samples of a period and the frequency that is really generated with it + + A looped buffer holds a whole number of periods, so the frequency is the one of the closest whole number of + samples per period. + """ + if frequency <= 0: + raise ValueError('The frequency should be positive') + if frequency > sample_rate / 2: + raise ValueError(f'The frequency {frequency} Hz is above half the sample rate {sample_rate} Hz') + n = int(round(sample_rate / frequency)) + return n, sample_rate / n + + +def _phase(n: int, phase_deg: float) -> np.ndarray: + """The position in the period (0 to 1, going around) of each of the n samples""" + return (np.arange(n) / n + phase_deg / 360.) % 1. + + +@register_waveform +@dataclasses.dataclass +class DC(Waveform): + name: ClassVar[str] = 'dc' + title: ClassVar[str] = 'DC' + level: float = waveform_field(0., 'V', 'Level') + duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) + + def _realize(self, sample_rate): + return np.full(self.n_samples(sample_rate), self.level), None + + +@register_waveform +@dataclasses.dataclass +class Sine(Waveform): + name: ClassVar[str] = 'sine' + title: ClassVar[str] = 'Sine' + periodic: ClassVar[bool] = True + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') + frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + + def _realize(self, sample_rate): + n, frequency = _period(self.frequency, sample_rate) + return self.offset + self.amplitude * np.sin(2 * np.pi * _phase(n, self.phase)), frequency + + +@register_waveform +@dataclasses.dataclass +class Square(Waveform): + name: ClassVar[str] = 'square' + title: ClassVar[str] = 'Square' + periodic: ClassVar[bool] = True + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') + frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + duty_cycle: float = waveform_field(0.5, 'dimensionless', 'Duty cycle', min=0., max=1., + tip='Fraction of the period spent high') + + def _realize(self, sample_rate): + n, frequency = _period(self.frequency, sample_rate) + high = _phase(n, self.phase) < self.duty_cycle + return self.offset + np.where(high, self.amplitude, -self.amplitude), frequency + + +@register_waveform +@dataclasses.dataclass +class Triangle(Waveform): + name: ClassVar[str] = 'triangle' + title: ClassVar[str] = 'Triangle' + periodic: ClassVar[bool] = True + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') + frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + symmetry: float = waveform_field(0.5, 'dimensionless', 'Symmetry', min=0.01, max=0.99, + tip='Fraction of the period spent rising') + + def _realize(self, sample_rate): + n, frequency = _period(self.frequency, sample_rate) + s = self.symmetry + x = (_phase(n, self.phase) + s / 2) % 1. # a symmetric triangle crosses zero rising at phase 0 + y = np.where(x < s, -1 + 2 * x / s, 1 - 2 * (x - s) / (1 - s)) + return self.offset + self.amplitude * y, frequency + + +@register_waveform +@dataclasses.dataclass +class Sawtooth(Waveform): + name: ClassVar[str] = 'sawtooth' + title: ClassVar[str] = 'Sawtooth' + periodic: ClassVar[bool] = True + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') + frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + + def _realize(self, sample_rate): + n, frequency = _period(self.frequency, sample_rate) + return self.offset + self.amplitude * (2 * ((_phase(n, self.phase) + 0.5) % 1.) - 1), frequency + + +@register_waveform +@dataclasses.dataclass +class Ramp(Waveform): + name: ClassVar[str] = 'ramp' + title: ClassVar[str] = 'Ramp' + start: float = waveform_field(0., 'V', 'Start') + stop: float = waveform_field(1., 'V', 'Stop') + duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) + + def _realize(self, sample_rate): + return np.linspace(self.start, self.stop, self.n_samples(sample_rate)), None + + +@register_waveform +@dataclasses.dataclass +class Pulse(Waveform): + name: ClassVar[str] = 'pulse' + title: ClassVar[str] = 'Pulse' + baseline: float = waveform_field(0., 'V', 'Baseline') + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Height of the pulse above the baseline') + delay: float = waveform_field(1e-4, 's', 'Delay', min=0., tip='From the start to the rising edge') + width: float = waveform_field(1e-4, 's', 'Width', min=0.) + duration: float = waveform_field(1e-3, 's', 'Duration', min=0., tip='Total, the signal returns to the baseline') + + def _realize(self, sample_rate): + t = np.arange(self.n_samples(sample_rate)) / sample_rate + high = (t >= self.delay) & (t < self.delay + self.width) + return self.baseline + self.amplitude * high, None + + +_NUMBER = r'[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?' + + +def parse_breakpoints(text: str) -> tuple[np.ndarray, np.ndarray]: + """Times (s) and values (V) of ``'0:0, 1e-3:5, 3e-3:5, 4e-3:0'``, entries separated by a comma or a new line + + Raises ValueError if an entry is not ``time:value`` or the times do not increase. + """ + entries = [entry for entry in re.split(r'[,\n;]+', text) if entry.strip()] + times, values = [], [] + for entry in entries: + match = re.fullmatch(rf'\s*({_NUMBER})\s*:\s*({_NUMBER})\s*', entry) + if match is None: + raise ValueError(f'"{entry.strip()}" is not a time:value pair') + times.append(float(match.group(1))) + values.append(float(match.group(2))) + if len(times) < 2: + raise ValueError('At least two time:value pairs are needed') + if np.any(np.diff(times) <= 0): + raise ValueError('The times should increase') + return np.array(times), np.array(values) + + +@register_waveform +@dataclasses.dataclass +class Piecewise(Waveform): + """Straight segments between points given as ``time:value`` pairs (seconds and volts)""" + name: ClassVar[str] = 'piecewise' + title: ClassVar[str] = 'Piecewise linear' + points: str = waveform_field('0:0, 1e-3:1, 2e-3:0', None, 'Points', + tip='time:value pairs in s and V, separated by commas or new lines. The signal ' + 'goes in a straight line from one point to the next, from the first to the ' + 'last time') + + def __post_init__(self): + super().__post_init__() + parse_breakpoints(self.points) # fail at creation + + def _realize(self, sample_rate): + times, values = parse_breakpoints(self.points) + t = np.arange(int(round((times[-1] - times[0]) * sample_rate)) + 1) / sample_rate + times[0] + return np.interp(t, times, values), None + + +@register_waveform +@dataclasses.dataclass +class Array(Waveform): + """Samples taken as they are, from a file (``.npy`` or text) or given as ``values``; they are played at the sample + rate of the output""" + name: ClassVar[str] = 'array' + title: ClassVar[str] = 'Array' + path: str = waveform_field('', None, 'File', tip='.npy file or text file (csv) with one column of samples in V') + values: Optional[np.ndarray] = None # not a parameter: the samples when no file is given + + def _realize(self, sample_rate): + values = self.values + if values is None: + if not self.path: + raise ValueError('No file and no values for the array waveform') + path = Path(self.path) + values = np.load(path) if path.suffix == '.npy' else np.loadtxt(path, delimiter=',') + values = np.asarray(values, dtype=float) + if values.ndim != 1 or len(values) < 2: + raise ValueError('The samples should be a 1D array of at least two values') + return values, None diff --git a/tests/test_waveform_output.py b/tests/test_waveform_output.py new file mode 100644 index 0000000..bcc8e41 --- /dev/null +++ b/tests/test_waveform_output.py @@ -0,0 +1,89 @@ +"""The waveform output contract: settings groups of the plugins, read back from the settings of their control module""" +import numpy as np +import pytest +from pymodaq_gui.parameter import Parameter + +from pymodaq_plugins_utils.hardware.waveform_output import (WaveformOutput, OutputMode, waveform_output_params, + fill_waveform_output_settings, WAVEFORM_OUTPUT_VERSION) + + +class FakeModule: + """What an application has: the DAQ_Move control module, with the settings tree of its plugin""" + _hw_settings_name = 'actuator_settings' + + def __init__(self, children=None): + children = waveform_output_params() if children is None else children + self.settings = Parameter.create(name='settings', type='group', children=[ + {'name': self._hw_settings_name, 'type': 'group', 'children': children}]) + + @property + def plugin_settings(self): + return self.settings.child(self._hw_settings_name) + + +def fill(module, **kwargs): + values = dict(n_channels=2, min_rate=1., max_rate=1e6, max_samples=1000, min_voltage=-5., max_voltage=5., + modes=[OutputMode.FINITE, OutputMode.CONTINUOUS], triggers=['PFI0', 'PFI1'], live_update=True) + values.update(kwargs) + fill_waveform_output_settings(module.plugin_settings, **values) + + +def test_not_initialized_yet(): + assert WaveformOutput.from_module(FakeModule()) is None + + +def test_no_such_groups(): + assert WaveformOutput.from_module(FakeModule(children=[])) is None + + +def test_roundtrip(): + module = FakeModule() + fill(module) + module.plugin_settings.child('waveform_output', 'sample_rate').setValue(5e4) + module.plugin_settings.child('waveform_output', 'mode').setValue('continuous') + assert WaveformOutput.from_module(module) == WaveformOutput( + n_channels=2, min_rate=1., max_rate=1e6, max_samples=1000, min_voltage=-5., max_voltage=5., + modes=[OutputMode.FINITE, OutputMode.CONTINUOUS], triggers=['PFI0', 'PFI1'], live_update=True, + sample_rate=5e4, mode=OutputMode.CONTINUOUS, repetitions=1) + + +def test_the_modes_the_user_can_choose_are_the_ones_of_the_instrument(): + module = FakeModule() + fill(module, modes=[OutputMode.FINITE]) + assert module.plugin_settings.child('waveform_output', 'mode').opts['limits'] == ['finite'] + + +def test_other_version_is_refused(caplog): + module = FakeModule() + fill(module) + module.plugin_settings.child('waveform_capabilities', 'version').setValue(WAVEFORM_OUTPUT_VERSION + 1) + assert WaveformOutput.from_module(module) is None + + +def make_output(**kwargs): + module = FakeModule() + fill(module, **kwargs) + module.plugin_settings.child('waveform_output', 'sample_rate').setValue(1e3) + return WaveformOutput.from_module(module) + + +def test_check_accepts_what_the_instrument_can_do(): + make_output().check([np.zeros(100), np.ones(100)]) + + +@pytest.mark.parametrize('samples, kwargs, message', [ + ([np.zeros(100)], {}, '1 waveforms for 2 channels'), + ([np.zeros(100), np.zeros(50)], {}, 'same number of samples'), + ([np.zeros(2000), np.zeros(2000)], {}, 'at most 1000'), + ([np.zeros(10), np.zeros(10)], dict(sample_rate=2e6), 'Sample rate'), + ([np.zeros(10), np.zeros(10)], dict(mode='repeat'), 'mode repeat is not available'), + ([np.zeros(10), np.full(10, 6.)], {}, 'goes from 0 V to 6 V.*-5 V to 5 V'), + ([np.zeros(10), np.full(10, -6.)], {}, 'goes from -6 V to 0 V'), +]) +def test_check_says_what_is_wrong(samples, kwargs, message): + with pytest.raises(ValueError, match=message): + make_output().check(samples, **kwargs) + + +def test_no_limit_of_samples_when_zero(): + make_output(max_samples=0).check([np.zeros(10 ** 6), np.zeros(10 ** 6)]) diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py new file mode 100644 index 0000000..9590572 --- /dev/null +++ b/tests/test_waveforms.py @@ -0,0 +1,159 @@ +"""The waveform factory: samples compared with values worked out by hand, the registry and the settings""" +import numpy as np +import pytest +from pymodaq_gui.parameter import Parameter + +from pymodaq_data import Q_ +from pymodaq_plugins_utils.hardware import waveforms as wf +from pymodaq_plugins_utils.hardware.waveforms import (create_waveform, waveform_names, register_waveform, Waveform, + waveform_field, parse_breakpoints) + + +def test_registry_has_the_standard_forms(): + assert waveform_names()[:8] == ['dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise'] + assert 'array' in waveform_names() + with pytest.raises(KeyError, match='Unknown waveform'): + create_waveform('nope') + + +def test_a_plugin_can_register_its_own_waveform(): + import dataclasses + from typing import ClassVar + + @register_waveform + @dataclasses.dataclass + class Constant2(Waveform): + name: ClassVar[str] = 'test_constant2' + value: float = waveform_field(2., 'V', 'Value') + + def _realize(self, sample_rate): + return np.full(4, self.value), None + + try: + assert create_waveform('test_constant2', value=Q_(3000, 'mV')).realize(1e3).samples.tolist() == [3.] * 4 + with pytest.raises(ValueError, match='already registered'): + register_waveform(type('Other', (Constant2,), {'name': 'test_constant2'})) + finally: + wf._REGISTRY.pop('test_constant2') + + +def test_dc(): + realized = create_waveform('dc', level=1.5, duration=5e-3).realize(1000.) + assert realized.samples.tolist() == [1.5] * 5 + assert not realized.periodic and realized.frequency is None + + +def test_sine_one_period(): + # 800 Hz sampling, 100 Hz: 8 samples per period, the quarter of the period is the 3rd sample + realized = create_waveform('sine', amplitude=2., frequency=100., offset=1.).realize(800.) + assert realized.periodic and len(realized.samples) == 8 + assert realized.samples[0] == pytest.approx(1.) + assert realized.samples[2] == pytest.approx(3.) + assert realized.samples[4] == pytest.approx(1.) + assert realized.samples[6] == pytest.approx(-1.) + assert realized.frequency == pytest.approx(100.) and realized.frequency_error == pytest.approx(0.) + + +def test_sine_phase(): + realized = create_waveform('sine', amplitude=1., frequency=100., phase=90.).realize(800.) + assert realized.samples[0] == pytest.approx(1.) # starts at the top + + +def test_frequency_is_rounded_to_a_whole_number_of_samples(): + realized = create_waveform('sine', frequency=30.).realize(1000.) # 33.3 samples per period + assert len(realized.samples) == 33 + assert realized.frequency == pytest.approx(1000. / 33) + assert realized.frequency_error == pytest.approx(1000. / 33 - 30.) + assert realized.duration == pytest.approx(0.033) + + +def test_frequency_above_nyquist_is_refused(): + with pytest.raises(ValueError, match='half the sample rate'): + create_waveform('sine', frequency=600.).realize(1000.) + + +def test_square(): + realized = create_waveform('square', amplitude=2., frequency=100., offset=1., duty_cycle=0.25).realize(800.) + assert realized.samples.tolist() == [3., 3., -1., -1., -1., -1., -1., -1.] + + +def test_triangle(): + realized = create_waveform('triangle', amplitude=2., frequency=100.).realize(800.) + assert realized.samples == pytest.approx([0., 1., 2., 1., 0., -1., -2., -1.]) + + +def test_triangle_symmetry(): + # rises during a quarter of the period: starts at 0 on the rising edge, reaches the top after 1/8 of the period + realized = create_waveform('triangle', frequency=100., symmetry=0.25).realize(800.) + assert realized.samples.max() == pytest.approx(1.) and realized.samples.min() == pytest.approx(-1.) + assert realized.samples[0] == pytest.approx(0.) + assert int(np.argmax(realized.samples)) == 1 + + +def test_sawtooth(): + realized = create_waveform('sawtooth', amplitude=4., frequency=100.).realize(800.) + assert realized.samples == pytest.approx([0., 1., 2., 3., -4., -3., -2., -1.]) + + +def test_ramp_and_pulse(): + assert create_waveform('ramp', start=0., stop=1., duration=5e-3).realize(1000.).samples == \ + pytest.approx([0., 0.25, 0.5, 0.75, 1.]) + pulse = create_waveform('pulse', baseline=-1., amplitude=3., delay=2e-3, width=3e-3, duration=8e-3) + assert pulse.realize(1000.).samples.tolist() == [-1., -1., 2., 2., 2., -1., -1., -1.] + + +def test_piecewise(): + wave = create_waveform('piecewise', points='0:0, 2e-3:4\n4e-3:4, 5e-3:0') + assert wave.realize(1000.).samples == pytest.approx([0., 2., 4., 4., 4., 0.]) + + +@pytest.mark.parametrize('text, message', [('0:0', 'two'), ('0:0, 1e-3', 'time:value'), + ('0:0, 0:1', 'increase'), ('a:b, c:d', 'time:value')]) +def test_breakpoints_errors(text, message): + with pytest.raises(ValueError, match=message): + parse_breakpoints(text) + with pytest.raises(ValueError, match=message): + create_waveform('piecewise', points=text) + + +def test_array_from_values_and_from_files(tmp_path): + values = np.array([0., 1., 0.5]) + assert create_waveform('array', values=values).realize(100.).samples.tolist() == values.tolist() + np.save(tmp_path / 'wave.npy', values) + assert create_waveform('array', path=str(tmp_path / 'wave.npy')).realize(100.).samples.tolist() == values.tolist() + (tmp_path / 'wave.csv').write_text('0\n1\n0.5\n') + assert create_waveform('array', path=str(tmp_path / 'wave.csv')).realize(100.).samples.tolist() == values.tolist() + with pytest.raises(ValueError, match='No file'): + create_waveform('array').realize(100.) + + +def test_pint_quantities_are_converted(): + wave = create_waveform('sine', amplitude=Q_(500, 'mV'), frequency=Q_(2, 'kHz'), phase=Q_(0.5, 'turn')) + assert (wave.amplitude, wave.frequency, wave.phase) == pytest.approx((0.5, 2000., 180.)) + assert create_waveform('sine', frequency=100.).realize(Q_(0.8, 'kHz')).sample_rate == 800. + + +def test_limits(): + with pytest.raises(ValueError, match='out of its limits'): + create_waveform('square', duty_cycle=1.5) + with pytest.raises(ValueError, match='positive'): + create_waveform('dc').realize(0.) + + +@pytest.mark.parametrize('name', ['dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise', + 'array']) +def test_settings_roundtrip(name): + """The params make a settings group and the waveform is read back from it""" + cls = wf.get_waveform_class(name) + group = Parameter.create(name='waveform', type='group', children=cls.params()) + wave = cls.from_settings(group) + defaults = {f.name: f.default for f in cls._parameters()} + assert {f.name: getattr(wave, f.name) for f in cls._parameters()} == defaults + + +def test_settings_carry_units_and_limits(): + params = {param['name']: param for param in wf.Square.params()} + assert params['frequency']['suffix'] == 'Hz' and params['frequency']['siPrefix'] is True + assert params['phase']['suffix'] == 'deg' and params['phase']['siPrefix'] is False + assert (params['duty_cycle']['min'], params['duty_cycle']['max']) == (0., 1.) + assert params['duty_cycle']['suffix'] == '' From aa94faca32229d3c4787c6b8555bcc6ec6f5fd99 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:39:43 +0000 Subject: [PATCH 02/10] Name the package of the extension in the docstring of waveform_output Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- src/pymodaq_plugins_utils/hardware/waveform_output.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/pymodaq_plugins_utils/hardware/waveform_output.py b/src/pymodaq_plugins_utils/hardware/waveform_output.py index 0176888..5655a5e 100644 --- a/src/pymodaq_plugins_utils/hardware/waveform_output.py +++ b/src/pymodaq_plugins_utils/hardware/waveform_output.py @@ -3,10 +3,10 @@ A waveform output plugin is a DAQ_Move actuator whose position is a :class:`~pymodaq.utils.data.DataActuator` holding one array of samples (volts) per channel, all of the same length. It adds the settings groups returned by :func:`waveform_output_params` to its parameters and fills the capabilities once the instrument is initialized -(:func:`fill_waveform_output_settings`). The applications (as the waveform extension) do not call the plugin, which -lives in another thread: they read these groups from the settings of its control module -(:meth:`WaveformOutput.from_module`), then check what they are going to send (:meth:`WaveformOutput.check`) and send -the samples as the position of the actuator. +(:func:`fill_waveform_output_settings`). The applications (for instance the extension of the package +pymodaq_plugins_waveform) do not call the plugin, which lives in another thread: they read these groups from the +settings of its control module (:meth:`WaveformOutput.from_module`), then check what they are going to send (:meth:`WaveformOutput.check`) and +send the samples as the position of the actuator. Two groups: ``waveform_capabilities`` (read only, what the instrument can do) and ``waveform_output`` (what the user chooses: sample rate, mode, repetitions; the plugin applies them when it receives samples). The names of the groups and From 381951592c363e9ef9e61cbb3d65a2d303ae072a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:44:54 +0000 Subject: [PATCH 03/10] Use the usual ObjectFactory pattern for the waveform factory Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../hardware/waveforms.py | 82 +++++++++---------- tests/test_waveforms.py | 26 +++--- 2 files changed, 52 insertions(+), 56 deletions(-) diff --git a/src/pymodaq_plugins_utils/hardware/waveforms.py b/src/pymodaq_plugins_utils/hardware/waveforms.py index 06b8d75..3ba2cbb 100644 --- a/src/pymodaq_plugins_utils/hardware/waveforms.py +++ b/src/pymodaq_plugins_utils/hardware/waveforms.py @@ -5,13 +5,13 @@ numbers expressed in that unit (SI: V, s, Hz, degrees for a phase); a pint quantity is accepted when creating the waveform and converted. -The registry (:func:`register_waveform`, :func:`create_waveform`, :func:`waveform_names`) gives the forms by name, so an -application can offer them in a list and a plugin package can add its own:: +:class:`WaveformFactory` is a PyMoDAQ :class:`~pymodaq_utils.factory.ObjectFactory`: it gives the forms by name, so an +application can offer them in a list (``WaveformFactory.names()``) and create one (``WaveformFactory().get('sine', +frequency=1e3)``), and a plugin package can add its own:: - @register_waveform + @WaveformFactory.register('gaussian') @dataclasses.dataclass class Gaussian(Waveform): - name: ClassVar[str] = 'gaussian' center: float = waveform_field(1e-3, 's', 'Center') width: float = waveform_field(1e-4, 's', 'Width') duration: float = waveform_field(2e-3, 's', 'Duration') @@ -32,6 +32,7 @@ def _realize(self, sample_rate): import numpy as np from pymodaq_data import Q_ +from pymodaq_utils.factory import ObjectFactory WAVEFORM_VERSION = 1 @@ -146,34 +147,34 @@ def realize(self, sample_rate: Union[float, Q_]) -> RealizedWaveform: 0. if frequency is None else frequency - requested) -_REGISTRY: dict[str, Type[Waveform]] = {} +class WaveformFactory(ObjectFactory): + """Factory class registering and creating the waveforms by name + ``@WaveformFactory.register('sine')`` on a :class:`Waveform` dataclass registers it and gives it its ``name``. + """ -def register_waveform(cls: Type[Waveform]) -> Type[Waveform]: - """Class decorator adding a waveform to the registry under its ``name``""" - if not cls.name: - raise ValueError(f'{cls.__name__} has no name') - if cls.name in _REGISTRY and _REGISTRY[cls.name] is not cls: - raise ValueError(f'A waveform called {cls.name} is already registered') - _REGISTRY[cls.name] = cls - return cls - - -def waveform_names() -> list[str]: - """Names of the registered waveforms, in the order of their registration""" - return list(_REGISTRY) - + @classmethod + def register(cls, key: str): + def inner_wrapper(wrapped_class: Type[Waveform]) -> Type[Waveform]: + wrapped_class.name = key + return super(WaveformFactory, cls).register(key)(wrapped_class) + return inner_wrapper -def get_waveform_class(name: str) -> Type[Waveform]: - try: - return _REGISTRY[name] - except KeyError: - raise KeyError(f'Unknown waveform {name}, available: {waveform_names()}') from None + @classmethod + def names(cls) -> list[str]: + """Names of the registered waveforms, in the order of their registration""" + return list(cls._builders.get(cls.__name__, {})) + @classmethod + def get_class(cls, key: str) -> Type[Waveform]: + waveform_class = super().get_class(key) + if waveform_class is None: + raise KeyError(f'Unknown waveform {key}, available: {cls.names()}') + return waveform_class -def create_waveform(name: str, **parameters) -> Waveform: - """Create the waveform registered as ``name`` from its parameters (numbers or pint quantities)""" - return get_waveform_class(name)(**parameters) + def get(self, name: str, **parameters) -> Waveform: + """Create the waveform registered as ``name`` from its parameters (numbers or pint quantities)""" + return self.get_class(name)(**parameters) # ---- helpers of the periodic waveforms @@ -196,10 +197,9 @@ def _phase(n: int, phase_deg: float) -> np.ndarray: return (np.arange(n) / n + phase_deg / 360.) % 1. -@register_waveform +@WaveformFactory.register('dc') @dataclasses.dataclass class DC(Waveform): - name: ClassVar[str] = 'dc' title: ClassVar[str] = 'DC' level: float = waveform_field(0., 'V', 'Level') duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) @@ -208,10 +208,9 @@ def _realize(self, sample_rate): return np.full(self.n_samples(sample_rate), self.level), None -@register_waveform +@WaveformFactory.register('sine') @dataclasses.dataclass class Sine(Waveform): - name: ClassVar[str] = 'sine' title: ClassVar[str] = 'Sine' periodic: ClassVar[bool] = True amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') @@ -224,10 +223,9 @@ def _realize(self, sample_rate): return self.offset + self.amplitude * np.sin(2 * np.pi * _phase(n, self.phase)), frequency -@register_waveform +@WaveformFactory.register('square') @dataclasses.dataclass class Square(Waveform): - name: ClassVar[str] = 'square' title: ClassVar[str] = 'Square' periodic: ClassVar[bool] = True amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') @@ -243,10 +241,9 @@ def _realize(self, sample_rate): return self.offset + np.where(high, self.amplitude, -self.amplitude), frequency -@register_waveform +@WaveformFactory.register('triangle') @dataclasses.dataclass class Triangle(Waveform): - name: ClassVar[str] = 'triangle' title: ClassVar[str] = 'Triangle' periodic: ClassVar[bool] = True amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') @@ -264,10 +261,9 @@ def _realize(self, sample_rate): return self.offset + self.amplitude * y, frequency -@register_waveform +@WaveformFactory.register('sawtooth') @dataclasses.dataclass class Sawtooth(Waveform): - name: ClassVar[str] = 'sawtooth' title: ClassVar[str] = 'Sawtooth' periodic: ClassVar[bool] = True amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') @@ -280,10 +276,9 @@ def _realize(self, sample_rate): return self.offset + self.amplitude * (2 * ((_phase(n, self.phase) + 0.5) % 1.) - 1), frequency -@register_waveform +@WaveformFactory.register('ramp') @dataclasses.dataclass class Ramp(Waveform): - name: ClassVar[str] = 'ramp' title: ClassVar[str] = 'Ramp' start: float = waveform_field(0., 'V', 'Start') stop: float = waveform_field(1., 'V', 'Stop') @@ -293,10 +288,9 @@ def _realize(self, sample_rate): return np.linspace(self.start, self.stop, self.n_samples(sample_rate)), None -@register_waveform +@WaveformFactory.register('pulse') @dataclasses.dataclass class Pulse(Waveform): - name: ClassVar[str] = 'pulse' title: ClassVar[str] = 'Pulse' baseline: float = waveform_field(0., 'V', 'Baseline') amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Height of the pulse above the baseline') @@ -333,11 +327,10 @@ def parse_breakpoints(text: str) -> tuple[np.ndarray, np.ndarray]: return np.array(times), np.array(values) -@register_waveform +@WaveformFactory.register('piecewise') @dataclasses.dataclass class Piecewise(Waveform): """Straight segments between points given as ``time:value`` pairs (seconds and volts)""" - name: ClassVar[str] = 'piecewise' title: ClassVar[str] = 'Piecewise linear' points: str = waveform_field('0:0, 1e-3:1, 2e-3:0', None, 'Points', tip='time:value pairs in s and V, separated by commas or new lines. The signal ' @@ -354,12 +347,11 @@ def _realize(self, sample_rate): return np.interp(t, times, values), None -@register_waveform +@WaveformFactory.register('array') @dataclasses.dataclass class Array(Waveform): """Samples taken as they are, from a file (``.npy`` or text) or given as ``values``; they are played at the sample rate of the output""" - name: ClassVar[str] = 'array' title: ClassVar[str] = 'Array' path: str = waveform_field('', None, 'File', tip='.npy file or text file (csv) with one column of samples in V') values: Optional[np.ndarray] = None # not a parameter: the samples when no file is given diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py index 9590572..e5927df 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -5,36 +5,40 @@ from pymodaq_data import Q_ from pymodaq_plugins_utils.hardware import waveforms as wf -from pymodaq_plugins_utils.hardware.waveforms import (create_waveform, waveform_names, register_waveform, Waveform, - waveform_field, parse_breakpoints) +from pymodaq_plugins_utils.hardware.waveforms import WaveformFactory, Waveform, waveform_field, parse_breakpoints + + +def create_waveform(name, **parameters): + return WaveformFactory().get(name, **parameters) def test_registry_has_the_standard_forms(): - assert waveform_names()[:8] == ['dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise'] - assert 'array' in waveform_names() + assert WaveformFactory.names()[:8] == ['dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', + 'piecewise'] + assert 'array' in WaveformFactory.names() + assert 'sine' in WaveformFactory().keys # the usual interface of the PyMoDAQ factories + assert WaveformFactory.get_class('sine') is wf.Sine and wf.Sine.name == 'sine' with pytest.raises(KeyError, match='Unknown waveform'): create_waveform('nope') def test_a_plugin_can_register_its_own_waveform(): import dataclasses - from typing import ClassVar - @register_waveform + @WaveformFactory.register('test_constant2') @dataclasses.dataclass class Constant2(Waveform): - name: ClassVar[str] = 'test_constant2' value: float = waveform_field(2., 'V', 'Value') def _realize(self, sample_rate): return np.full(4, self.value), None try: + assert Constant2.name == 'test_constant2' + assert 'test_constant2' in WaveformFactory.names() assert create_waveform('test_constant2', value=Q_(3000, 'mV')).realize(1e3).samples.tolist() == [3.] * 4 - with pytest.raises(ValueError, match='already registered'): - register_waveform(type('Other', (Constant2,), {'name': 'test_constant2'})) finally: - wf._REGISTRY.pop('test_constant2') + wf.WaveformFactory._builders['WaveformFactory'].pop('test_constant2') def test_dc(): @@ -144,7 +148,7 @@ def test_limits(): 'array']) def test_settings_roundtrip(name): """The params make a settings group and the waveform is read back from it""" - cls = wf.get_waveform_class(name) + cls = wf.WaveformFactory.get_class(name) group = Parameter.create(name='waveform', type='group', children=cls.params()) wave = cls.from_settings(group) defaults = {f.name: f.default for f in cls._parameters()} From 912be9e53dc6a48ee9e7b8105714c68039d7ef98 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:47:04 +0000 Subject: [PATCH 04/10] Move the waveforms in a package: waveform_factory plus one module per form Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- README.rst | 5 +- .../hardware/waveforms/__init__.py | 23 +++ .../hardware/waveforms/array.py | 30 +++ .../hardware/waveforms/dc.py | 18 ++ .../hardware/waveforms/piecewise.py | 51 +++++ .../hardware/waveforms/pulse.py | 23 +++ .../hardware/waveforms/ramp.py | 19 ++ .../hardware/waveforms/sawtooth.py | 23 +++ .../hardware/waveforms/sine.py | 23 +++ .../hardware/waveforms/square.py | 26 +++ .../hardware/waveforms/triangle.py | 28 +++ .../waveform_factory.py} | 179 +----------------- tests/test_waveforms.py | 5 +- 13 files changed, 273 insertions(+), 180 deletions(-) create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/__init__.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/array.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/dc.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/piecewise.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/pulse.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/ramp.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/sawtooth.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/sine.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/square.py create mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/triangle.py rename src/pymodaq_plugins_utils/hardware/{waveforms.py => waveforms/waveform_factory.py} (53%) diff --git a/README.rst b/README.rst index 6bf6ddb..50c7b77 100644 --- a/README.rst +++ b/README.rst @@ -52,9 +52,10 @@ Utilities their size and the properties of the modulator, filled by the plugin and read back by the applications (BeamShaping extension) from the control module, see ``pymodaq_plugins_utils.hardware.shaper`` * waveforms: waveform factory. A waveform (dc, sine, square, triangle, sawtooth, ramp, pulse, piecewise linear points, - array from a file) is a dataclass of its parameters, given by name from a registry that plugin packages can extend. + array from a file) is a dataclass of its parameters, given by name from a ``WaveformFactory`` that plugin packages can extend. The forms are one module each in the + ``waveforms`` folder, imported all together by its ``__init__``. ``realize(sample_rate)`` gives the samples, one period with a whole number of samples for a periodic waveform (the - frequency really generated is returned), and ``params()`` the settings, see ``pymodaq_plugins_utils.hardware.waveforms`` + frequency really generated is returned), and ``params()`` the settings, see ``pymodaq_plugins_utils.hardware.waveforms.waveform_factory`` * waveform_output: common interface of the plugins generating waveforms (analog outputs, arbitrary generators): the capabilities of the instrument and the choices of the user (sample rate, mode, repetitions) as settings groups, read back by the applications from the control module, which check what they send, see diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/__init__.py b/src/pymodaq_plugins_utils/hardware/waveforms/__init__.py new file mode 100644 index 0000000..58ec6ec --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/__init__.py @@ -0,0 +1,23 @@ +"""Waveforms: the factory (:mod:`.waveform_factory`) and one module per form + +Importing this package imports all its submodules, so every form is registered in the +:class:`~.waveform_factory.WaveformFactory`. To add a form to the package, add a module here: nothing else to update. +""" +import importlib +import pkgutil + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( # noqa: F401 + WAVEFORM_VERSION, RealizedWaveform, Waveform, WaveformFactory, waveform_field) + +for _module in pkgutil.iter_modules(__path__): + importlib.import_module(f'{__name__}.{_module.name}') + +from pymodaq_plugins_utils.hardware.waveforms.array import Array # noqa: E402,F401 +from pymodaq_plugins_utils.hardware.waveforms.dc import DC # noqa: E402,F401 +from pymodaq_plugins_utils.hardware.waveforms.piecewise import Piecewise, parse_breakpoints # noqa: E402,F401 +from pymodaq_plugins_utils.hardware.waveforms.pulse import Pulse # noqa: E402,F401 +from pymodaq_plugins_utils.hardware.waveforms.ramp import Ramp # noqa: E402,F401 +from pymodaq_plugins_utils.hardware.waveforms.sawtooth import Sawtooth # noqa: E402,F401 +from pymodaq_plugins_utils.hardware.waveforms.sine import Sine # noqa: E402,F401 +from pymodaq_plugins_utils.hardware.waveforms.square import Square # noqa: E402,F401 +from pymodaq_plugins_utils.hardware.waveforms.triangle import Triangle # noqa: E402,F401 diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/array.py b/src/pymodaq_plugins_utils/hardware/waveforms/array.py new file mode 100644 index 0000000..7c8118c --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/array.py @@ -0,0 +1,30 @@ +"""Samples from a file or an array""" +import dataclasses +from pathlib import Path +from typing import ClassVar, Optional + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import Waveform, WaveformFactory, waveform_field + + +@WaveformFactory.register('array') +@dataclasses.dataclass +class Array(Waveform): + """Samples taken as they are, from a file (``.npy`` or text) or given as ``values``; they are played at the sample + rate of the output""" + title: ClassVar[str] = 'Array' + path: str = waveform_field('', None, 'File', tip='.npy file or text file (csv) with one column of samples in V') + values: Optional[np.ndarray] = None # not a parameter: the samples when no file is given + + def _realize(self, sample_rate): + values = self.values + if values is None: + if not self.path: + raise ValueError('No file and no values for the array waveform') + path = Path(self.path) + values = np.load(path) if path.suffix == '.npy' else np.loadtxt(path, delimiter=',') + values = np.asarray(values, dtype=float) + if values.ndim != 1 or len(values) < 2: + raise ValueError('The samples should be a 1D array of at least two values') + return values, None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/dc.py b/src/pymodaq_plugins_utils/hardware/waveforms/dc.py new file mode 100644 index 0000000..871f4c8 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/dc.py @@ -0,0 +1,18 @@ +"""Constant level""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) + + +@WaveformFactory.register('dc') +@dataclasses.dataclass +class DC(Waveform): + title: ClassVar[str] = 'DC' + level: float = waveform_field(0., 'V', 'Level') + duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) + + def _realize(self, sample_rate): + return np.full(self.n_samples(sample_rate), self.level), None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/piecewise.py b/src/pymodaq_plugins_utils/hardware/waveforms/piecewise.py new file mode 100644 index 0000000..507eb69 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/piecewise.py @@ -0,0 +1,51 @@ +"""Straight segments between time:value points""" +import dataclasses +import re +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import Waveform, WaveformFactory, waveform_field + + +_NUMBER = r'[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?' + + +def parse_breakpoints(text: str) -> tuple[np.ndarray, np.ndarray]: + """Times (s) and values (V) of ``'0:0, 1e-3:5, 3e-3:5, 4e-3:0'``, entries separated by a comma or a new line + + Raises ValueError if an entry is not ``time:value`` or the times do not increase. + """ + entries = [entry for entry in re.split(r'[,\n;]+', text) if entry.strip()] + times, values = [], [] + for entry in entries: + match = re.fullmatch(rf'\s*({_NUMBER})\s*:\s*({_NUMBER})\s*', entry) + if match is None: + raise ValueError(f'"{entry.strip()}" is not a time:value pair') + times.append(float(match.group(1))) + values.append(float(match.group(2))) + if len(times) < 2: + raise ValueError('At least two time:value pairs are needed') + if np.any(np.diff(times) <= 0): + raise ValueError('The times should increase') + return np.array(times), np.array(values) + + +@WaveformFactory.register('piecewise') +@dataclasses.dataclass +class Piecewise(Waveform): + """Straight segments between points given as ``time:value`` pairs (seconds and volts)""" + title: ClassVar[str] = 'Piecewise linear' + points: str = waveform_field('0:0, 1e-3:1, 2e-3:0', None, 'Points', + tip='time:value pairs in s and V, separated by commas or new lines. The signal ' + 'goes in a straight line from one point to the next, from the first to the ' + 'last time') + + def __post_init__(self): + super().__post_init__() + parse_breakpoints(self.points) # fail at creation + + def _realize(self, sample_rate): + times, values = parse_breakpoints(self.points) + t = np.arange(int(round((times[-1] - times[0]) * sample_rate)) + 1) / sample_rate + times[0] + return np.interp(t, times, values), None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/pulse.py b/src/pymodaq_plugins_utils/hardware/waveforms/pulse.py new file mode 100644 index 0000000..19ea3f0 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/pulse.py @@ -0,0 +1,23 @@ +"""Single pulse""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) + + +@WaveformFactory.register('pulse') +@dataclasses.dataclass +class Pulse(Waveform): + title: ClassVar[str] = 'Pulse' + baseline: float = waveform_field(0., 'V', 'Baseline') + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Height of the pulse above the baseline') + delay: float = waveform_field(1e-4, 's', 'Delay', min=0., tip='From the start to the rising edge') + width: float = waveform_field(1e-4, 's', 'Width', min=0.) + duration: float = waveform_field(1e-3, 's', 'Duration', min=0., tip='Total, the signal returns to the baseline') + + def _realize(self, sample_rate): + t = np.arange(self.n_samples(sample_rate)) / sample_rate + high = (t >= self.delay) & (t < self.delay + self.width) + return self.baseline + self.amplitude * high, None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/ramp.py b/src/pymodaq_plugins_utils/hardware/waveforms/ramp.py new file mode 100644 index 0000000..d408241 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/ramp.py @@ -0,0 +1,19 @@ +"""Linear ramp""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) + + +@WaveformFactory.register('ramp') +@dataclasses.dataclass +class Ramp(Waveform): + title: ClassVar[str] = 'Ramp' + start: float = waveform_field(0., 'V', 'Start') + stop: float = waveform_field(1., 'V', 'Stop') + duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) + + def _realize(self, sample_rate): + return np.linspace(self.start, self.stop, self.n_samples(sample_rate)), None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/sawtooth.py b/src/pymodaq_plugins_utils/hardware/waveforms/sawtooth.py new file mode 100644 index 0000000..4615c49 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/sawtooth.py @@ -0,0 +1,23 @@ +"""Sawtooth""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( + Waveform, WaveformFactory, waveform_field, _period, _phase) + + +@WaveformFactory.register('sawtooth') +@dataclasses.dataclass +class Sawtooth(Waveform): + title: ClassVar[str] = 'Sawtooth' + periodic: ClassVar[bool] = True + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') + frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + + def _realize(self, sample_rate): + n, frequency = _period(self.frequency, sample_rate) + return self.offset + self.amplitude * (2 * ((_phase(n, self.phase) + 0.5) % 1.) - 1), frequency diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/sine.py b/src/pymodaq_plugins_utils/hardware/waveforms/sine.py new file mode 100644 index 0000000..cb48bef --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/sine.py @@ -0,0 +1,23 @@ +"""Sine""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( + Waveform, WaveformFactory, waveform_field, _period, _phase) + + +@WaveformFactory.register('sine') +@dataclasses.dataclass +class Sine(Waveform): + title: ClassVar[str] = 'Sine' + periodic: ClassVar[bool] = True + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') + frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + + def _realize(self, sample_rate): + n, frequency = _period(self.frequency, sample_rate) + return self.offset + self.amplitude * np.sin(2 * np.pi * _phase(n, self.phase)), frequency diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/square.py b/src/pymodaq_plugins_utils/hardware/waveforms/square.py new file mode 100644 index 0000000..de4d5f1 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/square.py @@ -0,0 +1,26 @@ +"""Square with an adjustable duty cycle""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( + Waveform, WaveformFactory, waveform_field, _period, _phase) + + +@WaveformFactory.register('square') +@dataclasses.dataclass +class Square(Waveform): + title: ClassVar[str] = 'Square' + periodic: ClassVar[bool] = True + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') + frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + duty_cycle: float = waveform_field(0.5, 'dimensionless', 'Duty cycle', min=0., max=1., + tip='Fraction of the period spent high') + + def _realize(self, sample_rate): + n, frequency = _period(self.frequency, sample_rate) + high = _phase(n, self.phase) < self.duty_cycle + return self.offset + np.where(high, self.amplitude, -self.amplitude), frequency diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/triangle.py b/src/pymodaq_plugins_utils/hardware/waveforms/triangle.py new file mode 100644 index 0000000..4182c90 --- /dev/null +++ b/src/pymodaq_plugins_utils/hardware/waveforms/triangle.py @@ -0,0 +1,28 @@ +"""Triangle with an adjustable symmetry""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( + Waveform, WaveformFactory, waveform_field, _period, _phase) + + +@WaveformFactory.register('triangle') +@dataclasses.dataclass +class Triangle(Waveform): + title: ClassVar[str] = 'Triangle' + periodic: ClassVar[bool] = True + amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') + frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + symmetry: float = waveform_field(0.5, 'dimensionless', 'Symmetry', min=0.01, max=0.99, + tip='Fraction of the period spent rising') + + def _realize(self, sample_rate): + n, frequency = _period(self.frequency, sample_rate) + s = self.symmetry + x = (_phase(n, self.phase) + s / 2) % 1. # a symmetric triangle crosses zero rising at phase 0 + y = np.where(x < s, -1 + 2 * x / s, 1 - 2 * (x - s) / (1 - s)) + return self.offset + self.amplitude * y, frequency diff --git a/src/pymodaq_plugins_utils/hardware/waveforms.py b/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py similarity index 53% rename from src/pymodaq_plugins_utils/hardware/waveforms.py rename to src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py index 3ba2cbb..5401ab0 100644 --- a/src/pymodaq_plugins_utils/hardware/waveforms.py +++ b/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py @@ -22,11 +22,12 @@ def _realize(self, sample_rate): The contract with the applications and the plugins is :data:`WAVEFORM_VERSION`; evolution rule: only add forms and optional fields, never rename or remove one; a breaking change increments :data:`WAVEFORM_VERSION`. + +The forms live in the other modules of this package, which register themselves in the factory when imported (the +``__init__`` imports them all). """ import dataclasses -import re from abc import ABC, abstractmethod -from pathlib import Path from typing import Any, ClassVar, Optional, Type, Union import numpy as np @@ -162,7 +163,7 @@ def inner_wrapper(wrapped_class: Type[Waveform]) -> Type[Waveform]: @classmethod def names(cls) -> list[str]: - """Names of the registered waveforms, in the order of their registration""" + """Names of the registered waveforms, sorted as the form modules are imported""" return list(cls._builders.get(cls.__name__, {})) @classmethod @@ -195,175 +196,3 @@ def _period(frequency: float, sample_rate: float) -> tuple[int, float]: def _phase(n: int, phase_deg: float) -> np.ndarray: """The position in the period (0 to 1, going around) of each of the n samples""" return (np.arange(n) / n + phase_deg / 360.) % 1. - - -@WaveformFactory.register('dc') -@dataclasses.dataclass -class DC(Waveform): - title: ClassVar[str] = 'DC' - level: float = waveform_field(0., 'V', 'Level') - duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) - - def _realize(self, sample_rate): - return np.full(self.n_samples(sample_rate), self.level), None - - -@WaveformFactory.register('sine') -@dataclasses.dataclass -class Sine(Waveform): - title: ClassVar[str] = 'Sine' - periodic: ClassVar[bool] = True - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') - frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) - offset: float = waveform_field(0., 'V', 'Offset') - phase: float = waveform_field(0., 'deg', 'Phase') - - def _realize(self, sample_rate): - n, frequency = _period(self.frequency, sample_rate) - return self.offset + self.amplitude * np.sin(2 * np.pi * _phase(n, self.phase)), frequency - - -@WaveformFactory.register('square') -@dataclasses.dataclass -class Square(Waveform): - title: ClassVar[str] = 'Square' - periodic: ClassVar[bool] = True - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') - frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) - offset: float = waveform_field(0., 'V', 'Offset') - phase: float = waveform_field(0., 'deg', 'Phase') - duty_cycle: float = waveform_field(0.5, 'dimensionless', 'Duty cycle', min=0., max=1., - tip='Fraction of the period spent high') - - def _realize(self, sample_rate): - n, frequency = _period(self.frequency, sample_rate) - high = _phase(n, self.phase) < self.duty_cycle - return self.offset + np.where(high, self.amplitude, -self.amplitude), frequency - - -@WaveformFactory.register('triangle') -@dataclasses.dataclass -class Triangle(Waveform): - title: ClassVar[str] = 'Triangle' - periodic: ClassVar[bool] = True - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') - frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) - offset: float = waveform_field(0., 'V', 'Offset') - phase: float = waveform_field(0., 'deg', 'Phase') - symmetry: float = waveform_field(0.5, 'dimensionless', 'Symmetry', min=0.01, max=0.99, - tip='Fraction of the period spent rising') - - def _realize(self, sample_rate): - n, frequency = _period(self.frequency, sample_rate) - s = self.symmetry - x = (_phase(n, self.phase) + s / 2) % 1. # a symmetric triangle crosses zero rising at phase 0 - y = np.where(x < s, -1 + 2 * x / s, 1 - 2 * (x - s) / (1 - s)) - return self.offset + self.amplitude * y, frequency - - -@WaveformFactory.register('sawtooth') -@dataclasses.dataclass -class Sawtooth(Waveform): - title: ClassVar[str] = 'Sawtooth' - periodic: ClassVar[bool] = True - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') - frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) - offset: float = waveform_field(0., 'V', 'Offset') - phase: float = waveform_field(0., 'deg', 'Phase') - - def _realize(self, sample_rate): - n, frequency = _period(self.frequency, sample_rate) - return self.offset + self.amplitude * (2 * ((_phase(n, self.phase) + 0.5) % 1.) - 1), frequency - - -@WaveformFactory.register('ramp') -@dataclasses.dataclass -class Ramp(Waveform): - title: ClassVar[str] = 'Ramp' - start: float = waveform_field(0., 'V', 'Start') - stop: float = waveform_field(1., 'V', 'Stop') - duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) - - def _realize(self, sample_rate): - return np.linspace(self.start, self.stop, self.n_samples(sample_rate)), None - - -@WaveformFactory.register('pulse') -@dataclasses.dataclass -class Pulse(Waveform): - title: ClassVar[str] = 'Pulse' - baseline: float = waveform_field(0., 'V', 'Baseline') - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Height of the pulse above the baseline') - delay: float = waveform_field(1e-4, 's', 'Delay', min=0., tip='From the start to the rising edge') - width: float = waveform_field(1e-4, 's', 'Width', min=0.) - duration: float = waveform_field(1e-3, 's', 'Duration', min=0., tip='Total, the signal returns to the baseline') - - def _realize(self, sample_rate): - t = np.arange(self.n_samples(sample_rate)) / sample_rate - high = (t >= self.delay) & (t < self.delay + self.width) - return self.baseline + self.amplitude * high, None - - -_NUMBER = r'[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?' - - -def parse_breakpoints(text: str) -> tuple[np.ndarray, np.ndarray]: - """Times (s) and values (V) of ``'0:0, 1e-3:5, 3e-3:5, 4e-3:0'``, entries separated by a comma or a new line - - Raises ValueError if an entry is not ``time:value`` or the times do not increase. - """ - entries = [entry for entry in re.split(r'[,\n;]+', text) if entry.strip()] - times, values = [], [] - for entry in entries: - match = re.fullmatch(rf'\s*({_NUMBER})\s*:\s*({_NUMBER})\s*', entry) - if match is None: - raise ValueError(f'"{entry.strip()}" is not a time:value pair') - times.append(float(match.group(1))) - values.append(float(match.group(2))) - if len(times) < 2: - raise ValueError('At least two time:value pairs are needed') - if np.any(np.diff(times) <= 0): - raise ValueError('The times should increase') - return np.array(times), np.array(values) - - -@WaveformFactory.register('piecewise') -@dataclasses.dataclass -class Piecewise(Waveform): - """Straight segments between points given as ``time:value`` pairs (seconds and volts)""" - title: ClassVar[str] = 'Piecewise linear' - points: str = waveform_field('0:0, 1e-3:1, 2e-3:0', None, 'Points', - tip='time:value pairs in s and V, separated by commas or new lines. The signal ' - 'goes in a straight line from one point to the next, from the first to the ' - 'last time') - - def __post_init__(self): - super().__post_init__() - parse_breakpoints(self.points) # fail at creation - - def _realize(self, sample_rate): - times, values = parse_breakpoints(self.points) - t = np.arange(int(round((times[-1] - times[0]) * sample_rate)) + 1) / sample_rate + times[0] - return np.interp(t, times, values), None - - -@WaveformFactory.register('array') -@dataclasses.dataclass -class Array(Waveform): - """Samples taken as they are, from a file (``.npy`` or text) or given as ``values``; they are played at the sample - rate of the output""" - title: ClassVar[str] = 'Array' - path: str = waveform_field('', None, 'File', tip='.npy file or text file (csv) with one column of samples in V') - values: Optional[np.ndarray] = None # not a parameter: the samples when no file is given - - def _realize(self, sample_rate): - values = self.values - if values is None: - if not self.path: - raise ValueError('No file and no values for the array waveform') - path = Path(self.path) - values = np.load(path) if path.suffix == '.npy' else np.loadtxt(path, delimiter=',') - values = np.asarray(values, dtype=float) - if values.ndim != 1 or len(values) < 2: - raise ValueError('The samples should be a 1D array of at least two values') - return values, None diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py index e5927df..f1a6f07 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -13,9 +13,8 @@ def create_waveform(name, **parameters): def test_registry_has_the_standard_forms(): - assert WaveformFactory.names()[:8] == ['dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', - 'piecewise'] - assert 'array' in WaveformFactory.names() + assert {'dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise', + 'array'} <= set(WaveformFactory.names()) assert 'sine' in WaveformFactory().keys # the usual interface of the PyMoDAQ factories assert WaveformFactory.get_class('sine') is wf.Sine and wf.Sine.name == 'sine' with pytest.raises(KeyError, match='Unknown waveform'): From 740cf5c5eaf11b5bd993e359a753d4668839272a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:47:30 +0000 Subject: [PATCH 05/10] WaveformFactory: self contained registry, no ObjectFactory inheritance Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../hardware/waveforms/waveform_factory.py | 40 ++++++++++++------- tests/test_waveforms.py | 2 +- 2 files changed, 27 insertions(+), 15 deletions(-) diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py b/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py index 5401ab0..c75714b 100644 --- a/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py +++ b/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py @@ -5,8 +5,8 @@ numbers expressed in that unit (SI: V, s, Hz, degrees for a phase); a pint quantity is accepted when creating the waveform and converted. -:class:`WaveformFactory` is a PyMoDAQ :class:`~pymodaq_utils.factory.ObjectFactory`: it gives the forms by name, so an -application can offer them in a list (``WaveformFactory.names()``) and create one (``WaveformFactory().get('sine', +:class:`WaveformFactory` gives the forms by name (a registry in the spirit of the PyMoDAQ factories, but self contained), +so an application can offer them in a list (``WaveformFactory.names()``) and create one (``WaveformFactory().get('sine', frequency=1e3)``), and a plugin package can add its own:: @WaveformFactory.register('gaussian') @@ -33,7 +33,6 @@ def _realize(self, sample_rate): import numpy as np from pymodaq_data import Q_ -from pymodaq_utils.factory import ObjectFactory WAVEFORM_VERSION = 1 @@ -148,34 +147,47 @@ def realize(self, sample_rate: Union[float, Q_]) -> RealizedWaveform: 0. if frequency is None else frequency - requested) -class WaveformFactory(ObjectFactory): - """Factory class registering and creating the waveforms by name +class WaveformFactory: + """Registry of the waveforms by name, and their creation - ``@WaveformFactory.register('sine')`` on a :class:`Waveform` dataclass registers it and gives it its ``name``. + ``@WaveformFactory.register('sine')`` on a :class:`Waveform` dataclass registers it and gives it its ``name``. The + registry belongs to the class, so there is a single one whatever the number of instances. """ + _waveforms: dict[str, Type[Waveform]] = {} @classmethod def register(cls, key: str): + """Class decorator registering a waveform as ``key``""" def inner_wrapper(wrapped_class: Type[Waveform]) -> Type[Waveform]: wrapped_class.name = key - return super(WaveformFactory, cls).register(key)(wrapped_class) + cls._waveforms[key] = wrapped_class + return wrapped_class return inner_wrapper + @classmethod + def unregister(cls, key: str) -> None: + cls._waveforms.pop(key, None) + @classmethod def names(cls) -> list[str]: """Names of the registered waveforms, sorted as the form modules are imported""" - return list(cls._builders.get(cls.__name__, {})) + return list(cls._waveforms) @classmethod def get_class(cls, key: str) -> Type[Waveform]: - waveform_class = super().get_class(key) - if waveform_class is None: - raise KeyError(f'Unknown waveform {key}, available: {cls.names()}') - return waveform_class + try: + return cls._waveforms[key] + except KeyError: + raise KeyError(f'Unknown waveform {key}, available: {cls.names()}') from None - def get(self, name: str, **parameters) -> Waveform: + @classmethod + def create(cls, name: str, **parameters) -> Waveform: """Create the waveform registered as ``name`` from its parameters (numbers or pint quantities)""" - return self.get_class(name)(**parameters) + return cls.get_class(name)(**parameters) + + def get(self, name: str, **parameters) -> Waveform: + """Same as :meth:`create`""" + return self.create(name, **parameters) # ---- helpers of the periodic waveforms diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py index f1a6f07..a48e9d3 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -37,7 +37,7 @@ def _realize(self, sample_rate): assert 'test_constant2' in WaveformFactory.names() assert create_waveform('test_constant2', value=Q_(3000, 'mV')).realize(1e3).samples.tolist() == [3.] * 4 finally: - wf.WaveformFactory._builders['WaveformFactory'].pop('test_constant2') + wf.WaveformFactory.unregister('test_constant2') def test_dc(): From ceb96e19c5f0eb954773ab8c49d80dca4ca7a569 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:47:43 +0000 Subject: [PATCH 06/10] Fix the registry test after the factory change Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- tests/test_waveforms.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py index a48e9d3..19854c4 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -15,7 +15,6 @@ def create_waveform(name, **parameters): def test_registry_has_the_standard_forms(): assert {'dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise', 'array'} <= set(WaveformFactory.names()) - assert 'sine' in WaveformFactory().keys # the usual interface of the PyMoDAQ factories assert WaveformFactory.get_class('sine') is wf.Sine and wf.Sine.name == 'sine' with pytest.raises(KeyError, match='Unknown waveform'): create_waveform('nope') From b5fe3c8384824ba0ed917820b14b6a2607adb96d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:48:34 +0000 Subject: [PATCH 07/10] Move the waveform factory to pymodaq_plugins_waveform, keep the output contract here Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- README.rst | 5 - .../hardware/waveforms/__init__.py | 23 -- .../hardware/waveforms/array.py | 30 --- .../hardware/waveforms/dc.py | 18 -- .../hardware/waveforms/piecewise.py | 51 ----- .../hardware/waveforms/pulse.py | 23 -- .../hardware/waveforms/ramp.py | 19 -- .../hardware/waveforms/sawtooth.py | 23 -- .../hardware/waveforms/sine.py | 23 -- .../hardware/waveforms/square.py | 26 --- .../hardware/waveforms/triangle.py | 28 --- .../hardware/waveforms/waveform_factory.py | 210 ------------------ tests/test_waveforms.py | 161 -------------- 13 files changed, 640 deletions(-) delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/__init__.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/array.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/dc.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/piecewise.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/pulse.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/ramp.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/sawtooth.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/sine.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/square.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/triangle.py delete mode 100644 src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py delete mode 100644 tests/test_waveforms.py diff --git a/README.rst b/README.rst index 50c7b77..2251f0b 100644 --- a/README.rst +++ b/README.rst @@ -51,11 +51,6 @@ Utilities * shaper: common interface of the plugins driving a shaper (SLM, DMD...): settings groups with the number of pixels, their size and the properties of the modulator, filled by the plugin and read back by the applications (BeamShaping extension) from the control module, see ``pymodaq_plugins_utils.hardware.shaper`` -* waveforms: waveform factory. A waveform (dc, sine, square, triangle, sawtooth, ramp, pulse, piecewise linear points, - array from a file) is a dataclass of its parameters, given by name from a ``WaveformFactory`` that plugin packages can extend. The forms are one module each in the - ``waveforms`` folder, imported all together by its ``__init__``. - ``realize(sample_rate)`` gives the samples, one period with a whole number of samples for a periodic waveform (the - frequency really generated is returned), and ``params()`` the settings, see ``pymodaq_plugins_utils.hardware.waveforms.waveform_factory`` * waveform_output: common interface of the plugins generating waveforms (analog outputs, arbitrary generators): the capabilities of the instrument and the choices of the user (sample rate, mode, repetitions) as settings groups, read back by the applications from the control module, which check what they send, see diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/__init__.py b/src/pymodaq_plugins_utils/hardware/waveforms/__init__.py deleted file mode 100644 index 58ec6ec..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Waveforms: the factory (:mod:`.waveform_factory`) and one module per form - -Importing this package imports all its submodules, so every form is registered in the -:class:`~.waveform_factory.WaveformFactory`. To add a form to the package, add a module here: nothing else to update. -""" -import importlib -import pkgutil - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( # noqa: F401 - WAVEFORM_VERSION, RealizedWaveform, Waveform, WaveformFactory, waveform_field) - -for _module in pkgutil.iter_modules(__path__): - importlib.import_module(f'{__name__}.{_module.name}') - -from pymodaq_plugins_utils.hardware.waveforms.array import Array # noqa: E402,F401 -from pymodaq_plugins_utils.hardware.waveforms.dc import DC # noqa: E402,F401 -from pymodaq_plugins_utils.hardware.waveforms.piecewise import Piecewise, parse_breakpoints # noqa: E402,F401 -from pymodaq_plugins_utils.hardware.waveforms.pulse import Pulse # noqa: E402,F401 -from pymodaq_plugins_utils.hardware.waveforms.ramp import Ramp # noqa: E402,F401 -from pymodaq_plugins_utils.hardware.waveforms.sawtooth import Sawtooth # noqa: E402,F401 -from pymodaq_plugins_utils.hardware.waveforms.sine import Sine # noqa: E402,F401 -from pymodaq_plugins_utils.hardware.waveforms.square import Square # noqa: E402,F401 -from pymodaq_plugins_utils.hardware.waveforms.triangle import Triangle # noqa: E402,F401 diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/array.py b/src/pymodaq_plugins_utils/hardware/waveforms/array.py deleted file mode 100644 index 7c8118c..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/array.py +++ /dev/null @@ -1,30 +0,0 @@ -"""Samples from a file or an array""" -import dataclasses -from pathlib import Path -from typing import ClassVar, Optional - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import Waveform, WaveformFactory, waveform_field - - -@WaveformFactory.register('array') -@dataclasses.dataclass -class Array(Waveform): - """Samples taken as they are, from a file (``.npy`` or text) or given as ``values``; they are played at the sample - rate of the output""" - title: ClassVar[str] = 'Array' - path: str = waveform_field('', None, 'File', tip='.npy file or text file (csv) with one column of samples in V') - values: Optional[np.ndarray] = None # not a parameter: the samples when no file is given - - def _realize(self, sample_rate): - values = self.values - if values is None: - if not self.path: - raise ValueError('No file and no values for the array waveform') - path = Path(self.path) - values = np.load(path) if path.suffix == '.npy' else np.loadtxt(path, delimiter=',') - values = np.asarray(values, dtype=float) - if values.ndim != 1 or len(values) < 2: - raise ValueError('The samples should be a 1D array of at least two values') - return values, None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/dc.py b/src/pymodaq_plugins_utils/hardware/waveforms/dc.py deleted file mode 100644 index 871f4c8..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/dc.py +++ /dev/null @@ -1,18 +0,0 @@ -"""Constant level""" -import dataclasses -from typing import ClassVar - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) - - -@WaveformFactory.register('dc') -@dataclasses.dataclass -class DC(Waveform): - title: ClassVar[str] = 'DC' - level: float = waveform_field(0., 'V', 'Level') - duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) - - def _realize(self, sample_rate): - return np.full(self.n_samples(sample_rate), self.level), None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/piecewise.py b/src/pymodaq_plugins_utils/hardware/waveforms/piecewise.py deleted file mode 100644 index 507eb69..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/piecewise.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Straight segments between time:value points""" -import dataclasses -import re -from typing import ClassVar - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import Waveform, WaveformFactory, waveform_field - - -_NUMBER = r'[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?' - - -def parse_breakpoints(text: str) -> tuple[np.ndarray, np.ndarray]: - """Times (s) and values (V) of ``'0:0, 1e-3:5, 3e-3:5, 4e-3:0'``, entries separated by a comma or a new line - - Raises ValueError if an entry is not ``time:value`` or the times do not increase. - """ - entries = [entry for entry in re.split(r'[,\n;]+', text) if entry.strip()] - times, values = [], [] - for entry in entries: - match = re.fullmatch(rf'\s*({_NUMBER})\s*:\s*({_NUMBER})\s*', entry) - if match is None: - raise ValueError(f'"{entry.strip()}" is not a time:value pair') - times.append(float(match.group(1))) - values.append(float(match.group(2))) - if len(times) < 2: - raise ValueError('At least two time:value pairs are needed') - if np.any(np.diff(times) <= 0): - raise ValueError('The times should increase') - return np.array(times), np.array(values) - - -@WaveformFactory.register('piecewise') -@dataclasses.dataclass -class Piecewise(Waveform): - """Straight segments between points given as ``time:value`` pairs (seconds and volts)""" - title: ClassVar[str] = 'Piecewise linear' - points: str = waveform_field('0:0, 1e-3:1, 2e-3:0', None, 'Points', - tip='time:value pairs in s and V, separated by commas or new lines. The signal ' - 'goes in a straight line from one point to the next, from the first to the ' - 'last time') - - def __post_init__(self): - super().__post_init__() - parse_breakpoints(self.points) # fail at creation - - def _realize(self, sample_rate): - times, values = parse_breakpoints(self.points) - t = np.arange(int(round((times[-1] - times[0]) * sample_rate)) + 1) / sample_rate + times[0] - return np.interp(t, times, values), None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/pulse.py b/src/pymodaq_plugins_utils/hardware/waveforms/pulse.py deleted file mode 100644 index 19ea3f0..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/pulse.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Single pulse""" -import dataclasses -from typing import ClassVar - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) - - -@WaveformFactory.register('pulse') -@dataclasses.dataclass -class Pulse(Waveform): - title: ClassVar[str] = 'Pulse' - baseline: float = waveform_field(0., 'V', 'Baseline') - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Height of the pulse above the baseline') - delay: float = waveform_field(1e-4, 's', 'Delay', min=0., tip='From the start to the rising edge') - width: float = waveform_field(1e-4, 's', 'Width', min=0.) - duration: float = waveform_field(1e-3, 's', 'Duration', min=0., tip='Total, the signal returns to the baseline') - - def _realize(self, sample_rate): - t = np.arange(self.n_samples(sample_rate)) / sample_rate - high = (t >= self.delay) & (t < self.delay + self.width) - return self.baseline + self.amplitude * high, None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/ramp.py b/src/pymodaq_plugins_utils/hardware/waveforms/ramp.py deleted file mode 100644 index d408241..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/ramp.py +++ /dev/null @@ -1,19 +0,0 @@ -"""Linear ramp""" -import dataclasses -from typing import ClassVar - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) - - -@WaveformFactory.register('ramp') -@dataclasses.dataclass -class Ramp(Waveform): - title: ClassVar[str] = 'Ramp' - start: float = waveform_field(0., 'V', 'Start') - stop: float = waveform_field(1., 'V', 'Stop') - duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) - - def _realize(self, sample_rate): - return np.linspace(self.start, self.stop, self.n_samples(sample_rate)), None diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/sawtooth.py b/src/pymodaq_plugins_utils/hardware/waveforms/sawtooth.py deleted file mode 100644 index 4615c49..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/sawtooth.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Sawtooth""" -import dataclasses -from typing import ClassVar - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( - Waveform, WaveformFactory, waveform_field, _period, _phase) - - -@WaveformFactory.register('sawtooth') -@dataclasses.dataclass -class Sawtooth(Waveform): - title: ClassVar[str] = 'Sawtooth' - periodic: ClassVar[bool] = True - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') - frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) - offset: float = waveform_field(0., 'V', 'Offset') - phase: float = waveform_field(0., 'deg', 'Phase') - - def _realize(self, sample_rate): - n, frequency = _period(self.frequency, sample_rate) - return self.offset + self.amplitude * (2 * ((_phase(n, self.phase) + 0.5) % 1.) - 1), frequency diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/sine.py b/src/pymodaq_plugins_utils/hardware/waveforms/sine.py deleted file mode 100644 index cb48bef..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/sine.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Sine""" -import dataclasses -from typing import ClassVar - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( - Waveform, WaveformFactory, waveform_field, _period, _phase) - - -@WaveformFactory.register('sine') -@dataclasses.dataclass -class Sine(Waveform): - title: ClassVar[str] = 'Sine' - periodic: ClassVar[bool] = True - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') - frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) - offset: float = waveform_field(0., 'V', 'Offset') - phase: float = waveform_field(0., 'deg', 'Phase') - - def _realize(self, sample_rate): - n, frequency = _period(self.frequency, sample_rate) - return self.offset + self.amplitude * np.sin(2 * np.pi * _phase(n, self.phase)), frequency diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/square.py b/src/pymodaq_plugins_utils/hardware/waveforms/square.py deleted file mode 100644 index de4d5f1..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/square.py +++ /dev/null @@ -1,26 +0,0 @@ -"""Square with an adjustable duty cycle""" -import dataclasses -from typing import ClassVar - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( - Waveform, WaveformFactory, waveform_field, _period, _phase) - - -@WaveformFactory.register('square') -@dataclasses.dataclass -class Square(Waveform): - title: ClassVar[str] = 'Square' - periodic: ClassVar[bool] = True - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') - frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) - offset: float = waveform_field(0., 'V', 'Offset') - phase: float = waveform_field(0., 'deg', 'Phase') - duty_cycle: float = waveform_field(0.5, 'dimensionless', 'Duty cycle', min=0., max=1., - tip='Fraction of the period spent high') - - def _realize(self, sample_rate): - n, frequency = _period(self.frequency, sample_rate) - high = _phase(n, self.phase) < self.duty_cycle - return self.offset + np.where(high, self.amplitude, -self.amplitude), frequency diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/triangle.py b/src/pymodaq_plugins_utils/hardware/waveforms/triangle.py deleted file mode 100644 index 4182c90..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/triangle.py +++ /dev/null @@ -1,28 +0,0 @@ -"""Triangle with an adjustable symmetry""" -import dataclasses -from typing import ClassVar - -import numpy as np - -from pymodaq_plugins_utils.hardware.waveforms.waveform_factory import ( - Waveform, WaveformFactory, waveform_field, _period, _phase) - - -@WaveformFactory.register('triangle') -@dataclasses.dataclass -class Triangle(Waveform): - title: ClassVar[str] = 'Triangle' - periodic: ClassVar[bool] = True - amplitude: float = waveform_field(1., 'V', 'Amplitude', tip='Peak value, half of the peak to peak') - frequency: float = waveform_field(1e3, 'Hz', 'Frequency', min=0.) - offset: float = waveform_field(0., 'V', 'Offset') - phase: float = waveform_field(0., 'deg', 'Phase') - symmetry: float = waveform_field(0.5, 'dimensionless', 'Symmetry', min=0.01, max=0.99, - tip='Fraction of the period spent rising') - - def _realize(self, sample_rate): - n, frequency = _period(self.frequency, sample_rate) - s = self.symmetry - x = (_phase(n, self.phase) + s / 2) % 1. # a symmetric triangle crosses zero rising at phase 0 - y = np.where(x < s, -1 + 2 * x / s, 1 - 2 * (x - s) / (1 - s)) - return self.offset + self.amplitude * y, frequency diff --git a/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py b/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py deleted file mode 100644 index c75714b..0000000 --- a/src/pymodaq_plugins_utils/hardware/waveforms/waveform_factory.py +++ /dev/null @@ -1,210 +0,0 @@ -"""Waveform factory: describe a signal by its parameters, get the samples for a given sample rate - -A waveform is a dataclass whose fields are its parameters. The same description serves a device that computes the -signal itself from parameters and one that needs the samples (:meth:`Waveform.realize`). Fields with a ``unit`` are -numbers expressed in that unit (SI: V, s, Hz, degrees for a phase); a pint quantity is accepted when creating the -waveform and converted. - -:class:`WaveformFactory` gives the forms by name (a registry in the spirit of the PyMoDAQ factories, but self contained), -so an application can offer them in a list (``WaveformFactory.names()``) and create one (``WaveformFactory().get('sine', -frequency=1e3)``), and a plugin package can add its own:: - - @WaveformFactory.register('gaussian') - @dataclasses.dataclass - class Gaussian(Waveform): - center: float = waveform_field(1e-3, 's', 'Center') - width: float = waveform_field(1e-4, 's', 'Width') - duration: float = waveform_field(2e-3, 's', 'Duration') - - def _realize(self, sample_rate): - t = np.arange(self.n_samples(sample_rate)) / sample_rate - return np.exp(-((t - self.center) / self.width) ** 2 / 2), None - -The contract with the applications and the plugins is :data:`WAVEFORM_VERSION`; evolution rule: only add forms and -optional fields, never rename or remove one; a breaking change increments :data:`WAVEFORM_VERSION`. - -The forms live in the other modules of this package, which register themselves in the factory when imported (the -``__init__`` imports them all). -""" -import dataclasses -from abc import ABC, abstractmethod -from typing import Any, ClassVar, Optional, Type, Union - -import numpy as np - -from pymodaq_data import Q_ - -WAVEFORM_VERSION = 1 - - -def waveform_field(default: Any, unit: Optional[str] = None, title: str = '', min: Optional[float] = None, - max: Optional[float] = None, tip: str = '') -> Any: - """A dataclass field that is a parameter of the waveform - - Parameters - ---------- - default: the default value - unit: the unit of the number (pint syntax), None for a text - title: the label of the parameter in the settings - min, max: bounds of the parameter in the settings (and checked when the samples are computed) - tip: help shown on the parameter - """ - return dataclasses.field(default=default, metadata=dict(unit=unit, title=title, min=min, max=max, tip=tip)) - - -@dataclasses.dataclass(frozen=True) -class RealizedWaveform: - """The samples of a waveform for one sample rate - - Attributes - ---------- - samples: the signal, in volts for a voltage output. One period for a periodic waveform (to be repeated), the whole - signal otherwise - sample_rate: Hz - periodic: True if ``samples`` is one period to repeat - frequency: Hz, the frequency that is really generated by repeating ``samples`` (periodic waveform only). It is the - requested one rounded so that a period has a whole number of samples - frequency_error: Hz, ``frequency`` minus the requested frequency - """ - samples: np.ndarray - sample_rate: float - periodic: bool = False - frequency: Optional[float] = None - frequency_error: float = 0. - - @property - def duration(self) -> float: - """Seconds""" - return len(self.samples) / self.sample_rate - - -@dataclasses.dataclass -class Waveform(ABC): - """Base class of the waveforms. Subclass it with a dataclass, set ``name`` and register it""" - name: ClassVar[str] = '' - title: ClassVar[str] = '' # label in a list of waveforms, ``name`` if empty - periodic: ClassVar[bool] = False # True: :meth:`realize` gives one period to repeat - - def __post_init__(self): - for field in self._parameters(): - value = getattr(self, field.name) - unit = field.metadata['unit'] - if unit is not None: - value = float(value.m_as(unit)) if isinstance(value, Q_) else float(value) - lower, upper = field.metadata['min'], field.metadata['max'] - if (lower is not None and value < lower) or (upper is not None and value > upper): - raise ValueError(f'{self.name}: {field.name} = {value} {unit} is out of its limits ' - f'({lower}, {upper})') - setattr(self, field.name, value) - - # ---- the description as settings - @classmethod - def _parameters(cls) -> list[dataclasses.Field]: - return [field for field in dataclasses.fields(cls) if 'unit' in field.metadata] - - @classmethod - def params(cls) -> list[dict]: - """The parameters of this waveform as a list of settings dictionaries (pyqtgraph Parameter syntax)""" - params = [] - for field in cls._parameters(): - meta = field.metadata - param = {'title': meta['title'] or field.name, 'name': field.name, 'value': field.default, - 'tip': meta['tip']} - if meta['unit'] is None: - param['type'] = 'str' - else: - dimensionless = meta['unit'] in ('dimensionless', 'deg') # no SI prefix (k, m) in front of these - param.update(type='float', suffix='' if meta['unit'] == 'dimensionless' else meta['unit'], - siPrefix=not dimensionless) - for key in ('min', 'max'): - if meta[key] is not None: - param[key] = meta[key] - params.append(param) - return params - - @classmethod - def from_settings(cls, group) -> 'Waveform': - """Build the waveform from a settings group (a Parameter) holding the children of :meth:`params`""" - return cls(**{field.name: group[field.name] for field in cls._parameters()}) - - # ---- the samples - def n_samples(self, sample_rate: float) -> int: - """Number of samples of a waveform defined by its ``duration`` (at least 2)""" - return max(2, int(round(getattr(self, 'duration') * sample_rate))) - - @abstractmethod - def _realize(self, sample_rate: float) -> tuple[np.ndarray, Optional[float]]: - """The samples and, for a periodic waveform, the frequency really generated""" - - def realize(self, sample_rate: Union[float, Q_]) -> RealizedWaveform: - """The samples of the waveform for ``sample_rate`` (Hz, or a pint quantity)""" - sample_rate = float(sample_rate.m_as('Hz')) if isinstance(sample_rate, Q_) else float(sample_rate) - if sample_rate <= 0: - raise ValueError('The sample rate should be positive') - samples, frequency = self._realize(sample_rate) - requested = getattr(self, 'frequency', None) - return RealizedWaveform(np.asarray(samples, dtype=float), sample_rate, self.periodic, frequency, - 0. if frequency is None else frequency - requested) - - -class WaveformFactory: - """Registry of the waveforms by name, and their creation - - ``@WaveformFactory.register('sine')`` on a :class:`Waveform` dataclass registers it and gives it its ``name``. The - registry belongs to the class, so there is a single one whatever the number of instances. - """ - _waveforms: dict[str, Type[Waveform]] = {} - - @classmethod - def register(cls, key: str): - """Class decorator registering a waveform as ``key``""" - def inner_wrapper(wrapped_class: Type[Waveform]) -> Type[Waveform]: - wrapped_class.name = key - cls._waveforms[key] = wrapped_class - return wrapped_class - return inner_wrapper - - @classmethod - def unregister(cls, key: str) -> None: - cls._waveforms.pop(key, None) - - @classmethod - def names(cls) -> list[str]: - """Names of the registered waveforms, sorted as the form modules are imported""" - return list(cls._waveforms) - - @classmethod - def get_class(cls, key: str) -> Type[Waveform]: - try: - return cls._waveforms[key] - except KeyError: - raise KeyError(f'Unknown waveform {key}, available: {cls.names()}') from None - - @classmethod - def create(cls, name: str, **parameters) -> Waveform: - """Create the waveform registered as ``name`` from its parameters (numbers or pint quantities)""" - return cls.get_class(name)(**parameters) - - def get(self, name: str, **parameters) -> Waveform: - """Same as :meth:`create`""" - return self.create(name, **parameters) - - -# ---- helpers of the periodic waveforms -def _period(frequency: float, sample_rate: float) -> tuple[int, float]: - """Number of samples of a period and the frequency that is really generated with it - - A looped buffer holds a whole number of periods, so the frequency is the one of the closest whole number of - samples per period. - """ - if frequency <= 0: - raise ValueError('The frequency should be positive') - if frequency > sample_rate / 2: - raise ValueError(f'The frequency {frequency} Hz is above half the sample rate {sample_rate} Hz') - n = int(round(sample_rate / frequency)) - return n, sample_rate / n - - -def _phase(n: int, phase_deg: float) -> np.ndarray: - """The position in the period (0 to 1, going around) of each of the n samples""" - return (np.arange(n) / n + phase_deg / 360.) % 1. diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py deleted file mode 100644 index 19854c4..0000000 --- a/tests/test_waveforms.py +++ /dev/null @@ -1,161 +0,0 @@ -"""The waveform factory: samples compared with values worked out by hand, the registry and the settings""" -import numpy as np -import pytest -from pymodaq_gui.parameter import Parameter - -from pymodaq_data import Q_ -from pymodaq_plugins_utils.hardware import waveforms as wf -from pymodaq_plugins_utils.hardware.waveforms import WaveformFactory, Waveform, waveform_field, parse_breakpoints - - -def create_waveform(name, **parameters): - return WaveformFactory().get(name, **parameters) - - -def test_registry_has_the_standard_forms(): - assert {'dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise', - 'array'} <= set(WaveformFactory.names()) - assert WaveformFactory.get_class('sine') is wf.Sine and wf.Sine.name == 'sine' - with pytest.raises(KeyError, match='Unknown waveform'): - create_waveform('nope') - - -def test_a_plugin_can_register_its_own_waveform(): - import dataclasses - - @WaveformFactory.register('test_constant2') - @dataclasses.dataclass - class Constant2(Waveform): - value: float = waveform_field(2., 'V', 'Value') - - def _realize(self, sample_rate): - return np.full(4, self.value), None - - try: - assert Constant2.name == 'test_constant2' - assert 'test_constant2' in WaveformFactory.names() - assert create_waveform('test_constant2', value=Q_(3000, 'mV')).realize(1e3).samples.tolist() == [3.] * 4 - finally: - wf.WaveformFactory.unregister('test_constant2') - - -def test_dc(): - realized = create_waveform('dc', level=1.5, duration=5e-3).realize(1000.) - assert realized.samples.tolist() == [1.5] * 5 - assert not realized.periodic and realized.frequency is None - - -def test_sine_one_period(): - # 800 Hz sampling, 100 Hz: 8 samples per period, the quarter of the period is the 3rd sample - realized = create_waveform('sine', amplitude=2., frequency=100., offset=1.).realize(800.) - assert realized.periodic and len(realized.samples) == 8 - assert realized.samples[0] == pytest.approx(1.) - assert realized.samples[2] == pytest.approx(3.) - assert realized.samples[4] == pytest.approx(1.) - assert realized.samples[6] == pytest.approx(-1.) - assert realized.frequency == pytest.approx(100.) and realized.frequency_error == pytest.approx(0.) - - -def test_sine_phase(): - realized = create_waveform('sine', amplitude=1., frequency=100., phase=90.).realize(800.) - assert realized.samples[0] == pytest.approx(1.) # starts at the top - - -def test_frequency_is_rounded_to_a_whole_number_of_samples(): - realized = create_waveform('sine', frequency=30.).realize(1000.) # 33.3 samples per period - assert len(realized.samples) == 33 - assert realized.frequency == pytest.approx(1000. / 33) - assert realized.frequency_error == pytest.approx(1000. / 33 - 30.) - assert realized.duration == pytest.approx(0.033) - - -def test_frequency_above_nyquist_is_refused(): - with pytest.raises(ValueError, match='half the sample rate'): - create_waveform('sine', frequency=600.).realize(1000.) - - -def test_square(): - realized = create_waveform('square', amplitude=2., frequency=100., offset=1., duty_cycle=0.25).realize(800.) - assert realized.samples.tolist() == [3., 3., -1., -1., -1., -1., -1., -1.] - - -def test_triangle(): - realized = create_waveform('triangle', amplitude=2., frequency=100.).realize(800.) - assert realized.samples == pytest.approx([0., 1., 2., 1., 0., -1., -2., -1.]) - - -def test_triangle_symmetry(): - # rises during a quarter of the period: starts at 0 on the rising edge, reaches the top after 1/8 of the period - realized = create_waveform('triangle', frequency=100., symmetry=0.25).realize(800.) - assert realized.samples.max() == pytest.approx(1.) and realized.samples.min() == pytest.approx(-1.) - assert realized.samples[0] == pytest.approx(0.) - assert int(np.argmax(realized.samples)) == 1 - - -def test_sawtooth(): - realized = create_waveform('sawtooth', amplitude=4., frequency=100.).realize(800.) - assert realized.samples == pytest.approx([0., 1., 2., 3., -4., -3., -2., -1.]) - - -def test_ramp_and_pulse(): - assert create_waveform('ramp', start=0., stop=1., duration=5e-3).realize(1000.).samples == \ - pytest.approx([0., 0.25, 0.5, 0.75, 1.]) - pulse = create_waveform('pulse', baseline=-1., amplitude=3., delay=2e-3, width=3e-3, duration=8e-3) - assert pulse.realize(1000.).samples.tolist() == [-1., -1., 2., 2., 2., -1., -1., -1.] - - -def test_piecewise(): - wave = create_waveform('piecewise', points='0:0, 2e-3:4\n4e-3:4, 5e-3:0') - assert wave.realize(1000.).samples == pytest.approx([0., 2., 4., 4., 4., 0.]) - - -@pytest.mark.parametrize('text, message', [('0:0', 'two'), ('0:0, 1e-3', 'time:value'), - ('0:0, 0:1', 'increase'), ('a:b, c:d', 'time:value')]) -def test_breakpoints_errors(text, message): - with pytest.raises(ValueError, match=message): - parse_breakpoints(text) - with pytest.raises(ValueError, match=message): - create_waveform('piecewise', points=text) - - -def test_array_from_values_and_from_files(tmp_path): - values = np.array([0., 1., 0.5]) - assert create_waveform('array', values=values).realize(100.).samples.tolist() == values.tolist() - np.save(tmp_path / 'wave.npy', values) - assert create_waveform('array', path=str(tmp_path / 'wave.npy')).realize(100.).samples.tolist() == values.tolist() - (tmp_path / 'wave.csv').write_text('0\n1\n0.5\n') - assert create_waveform('array', path=str(tmp_path / 'wave.csv')).realize(100.).samples.tolist() == values.tolist() - with pytest.raises(ValueError, match='No file'): - create_waveform('array').realize(100.) - - -def test_pint_quantities_are_converted(): - wave = create_waveform('sine', amplitude=Q_(500, 'mV'), frequency=Q_(2, 'kHz'), phase=Q_(0.5, 'turn')) - assert (wave.amplitude, wave.frequency, wave.phase) == pytest.approx((0.5, 2000., 180.)) - assert create_waveform('sine', frequency=100.).realize(Q_(0.8, 'kHz')).sample_rate == 800. - - -def test_limits(): - with pytest.raises(ValueError, match='out of its limits'): - create_waveform('square', duty_cycle=1.5) - with pytest.raises(ValueError, match='positive'): - create_waveform('dc').realize(0.) - - -@pytest.mark.parametrize('name', ['dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise', - 'array']) -def test_settings_roundtrip(name): - """The params make a settings group and the waveform is read back from it""" - cls = wf.WaveformFactory.get_class(name) - group = Parameter.create(name='waveform', type='group', children=cls.params()) - wave = cls.from_settings(group) - defaults = {f.name: f.default for f in cls._parameters()} - assert {f.name: getattr(wave, f.name) for f in cls._parameters()} == defaults - - -def test_settings_carry_units_and_limits(): - params = {param['name']: param for param in wf.Square.params()} - assert params['frequency']['suffix'] == 'Hz' and params['frequency']['siPrefix'] is True - assert params['phase']['suffix'] == 'deg' and params['phase']['siPrefix'] is False - assert (params['duty_cycle']['min'], params['duty_cycle']['max']) == (0., 1.) - assert params['duty_cycle']['suffix'] == '' From ad57209afac512c8b47f98f32b54ed4882afea3d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:52:20 +0000 Subject: [PATCH 08/10] AGENTS.md: structure of the families of classes (factory module next to a folder of classes) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- AGENTS.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index e36f049..9640312 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -193,6 +193,21 @@ extensions already does the job and only the conversion of the measurements or o - Do not use the old `pid_models` flag nor the word "preset" in new code: a model script that opens the Dashboard loads an experiment file. +## 6b. Families of interchangeable classes (factories) + +Before designing the structure of a new piece of code, look at how PyMoDAQ already does the same thing and copy it +(do not reinvent it): for instance the sequencer elements (`pymodaq/extensions/sequencer/utilities/`), the scanners +(`ScannerFactory`) or the data processors. For a family of classes chosen by name (waveforms, scan types, exporters...): + +- the base class and the factory live in one module, `_factory.py`, **not** in the folder of the classes; +- the classes live in a sibling folder (`s/`), **one module per class**, each registering itself with a + decorator of the factory (`@WaveformFactory.register('sine')`); +- the `__init__.py` of that folder imports all its submodules (`pkgutil`), so adding a class is adding a file and + nothing else, and a plugin package can register its own classes the same way; +- the factory is a plain class that encapsulates its own registry (a class level dictionary, with `register`, + `names`, `get_class`, `create`). Do not inherit from `pymodaq_utils.factory.ObjectFactory`: it complicates the + management of the registry. + ## 7. Done checklist - [ ] Names (package, files, classes) match and the `template` placeholders are gone. From 7fb1d3a86f1702d19a6d2138701274b85b084d09 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:54:42 +0000 Subject: [PATCH 09/10] AGENTS.md: say how the sequencer imports its element modules Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- AGENTS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9640312..03e70f9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -202,8 +202,9 @@ Before designing the structure of a new piece of code, look at how PyMoDAQ alrea - the base class and the factory live in one module, `_factory.py`, **not** in the folder of the classes; - the classes live in a sibling folder (`s/`), **one module per class**, each registering itself with a decorator of the factory (`@WaveformFactory.register('sine')`); -- the `__init__.py` of that folder imports all its submodules (`pkgutil`), so adding a class is adding a file and - nothing else, and a plugin package can register its own classes the same way; +- all the submodules of that folder are imported, by its `__init__.py` (`pkgutil`) or by a function of the factory + module as `register_elements` of the sequencer does, so adding a class is adding a file and nothing else, and a + plugin package can register its own classes the same way; - the factory is a plain class that encapsulates its own registry (a class level dictionary, with `register`, `names`, `get_class`, `create`). Do not inherit from `pymodaq_utils.factory.ObjectFactory`: it complicates the management of the registry. From 5814286ef896dc88f3b9142b313a0d55ecfd6ec8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:00:34 +0000 Subject: [PATCH 10/10] AGENTS.md: the name of a registered class is written once (class attribute) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- AGENTS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/AGENTS.md b/AGENTS.md index 03e70f9..7271d09 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -201,7 +201,8 @@ Before designing the structure of a new piece of code, look at how PyMoDAQ alrea - the base class and the factory live in one module, `_factory.py`, **not** in the folder of the classes; - the classes live in a sibling folder (`s/`), **one module per class**, each registering itself with a - decorator of the factory (`@WaveformFactory.register('sine')`); + decorator of the factory (`@WaveformFactory.register()`); the name is written once, as a class attribute + (like `elt_name` of the sequencer elements), not repeated in the decorator, in a title and in the class name; - all the submodules of that folder are imported, by its `__init__.py` (`pkgutil`) or by a function of the factory module as `register_elements` of the sequencer does, so adding a class is adding a file and nothing else, and a plugin package can register its own classes the same way;