From 5a478a0abc3e69ae80a5f82f55b7eefd483846d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:48:27 +0000 Subject: [PATCH 01/10] Add the waveform factory and the waveforms (one module per form) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../waveforms/__init__.py | 23 ++ .../waveforms/array.py | 30 +++ src/pymodaq_plugins_waveform/waveforms/dc.py | 18 ++ .../waveforms/piecewise.py | 51 +++++ .../waveforms/pulse.py | 23 ++ .../waveforms/ramp.py | 19 ++ .../waveforms/sawtooth.py | 23 ++ .../waveforms/sine.py | 23 ++ .../waveforms/square.py | 26 +++ .../waveforms/triangle.py | 28 +++ .../waveforms/waveform_factory.py | 210 ++++++++++++++++++ tests/test_waveforms.py | 161 ++++++++++++++ 12 files changed, 635 insertions(+) create mode 100644 src/pymodaq_plugins_waveform/waveforms/__init__.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/array.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/dc.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/piecewise.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/pulse.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/ramp.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/sawtooth.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/sine.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/square.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/triangle.py create mode 100644 src/pymodaq_plugins_waveform/waveforms/waveform_factory.py create mode 100644 tests/test_waveforms.py diff --git a/src/pymodaq_plugins_waveform/waveforms/__init__.py b/src/pymodaq_plugins_waveform/waveforms/__init__.py new file mode 100644 index 0000000..9937051 --- /dev/null +++ b/src/pymodaq_plugins_waveform/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_waveform.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_waveform.waveforms.array import Array # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.dc import DC # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.piecewise import Piecewise, parse_breakpoints # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.pulse import Pulse # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.ramp import Ramp # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.sawtooth import Sawtooth # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.sine import Sine # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.square import Square # noqa: E402,F401 +from pymodaq_plugins_waveform.waveforms.triangle import Triangle # noqa: E402,F401 diff --git a/src/pymodaq_plugins_waveform/waveforms/array.py b/src/pymodaq_plugins_waveform/waveforms/array.py new file mode 100644 index 0000000..4254deb --- /dev/null +++ b/src/pymodaq_plugins_waveform/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_waveform.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_waveform/waveforms/dc.py b/src/pymodaq_plugins_waveform/waveforms/dc.py new file mode 100644 index 0000000..c167987 --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveforms/dc.py @@ -0,0 +1,18 @@ +"""Constant level""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_waveform.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_waveform/waveforms/piecewise.py b/src/pymodaq_plugins_waveform/waveforms/piecewise.py new file mode 100644 index 0000000..e7e85ed --- /dev/null +++ b/src/pymodaq_plugins_waveform/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_waveform.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_waveform/waveforms/pulse.py b/src/pymodaq_plugins_waveform/waveforms/pulse.py new file mode 100644 index 0000000..75e5a79 --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveforms/pulse.py @@ -0,0 +1,23 @@ +"""Single pulse""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_waveform.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_waveform/waveforms/ramp.py b/src/pymodaq_plugins_waveform/waveforms/ramp.py new file mode 100644 index 0000000..8a42a4f --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveforms/ramp.py @@ -0,0 +1,19 @@ +"""Linear ramp""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_waveform.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_waveform/waveforms/sawtooth.py b/src/pymodaq_plugins_waveform/waveforms/sawtooth.py new file mode 100644 index 0000000..99608ca --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveforms/sawtooth.py @@ -0,0 +1,23 @@ +"""Sawtooth""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_waveform.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_waveform/waveforms/sine.py b/src/pymodaq_plugins_waveform/waveforms/sine.py new file mode 100644 index 0000000..f13b31c --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveforms/sine.py @@ -0,0 +1,23 @@ +"""Sine""" +import dataclasses +from typing import ClassVar + +import numpy as np + +from pymodaq_plugins_waveform.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_waveform/waveforms/square.py b/src/pymodaq_plugins_waveform/waveforms/square.py new file mode 100644 index 0000000..da452af --- /dev/null +++ b/src/pymodaq_plugins_waveform/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_waveform.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_waveform/waveforms/triangle.py b/src/pymodaq_plugins_waveform/waveforms/triangle.py new file mode 100644 index 0000000..ca7d3c2 --- /dev/null +++ b/src/pymodaq_plugins_waveform/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_waveform.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_waveform/waveforms/waveform_factory.py b/src/pymodaq_plugins_waveform/waveforms/waveform_factory.py new file mode 100644 index 0000000..c75714b --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveforms/waveform_factory.py @@ -0,0 +1,210 @@ +"""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 new file mode 100644 index 0000000..79a8611 --- /dev/null +++ b/tests/test_waveforms.py @@ -0,0 +1,161 @@ +"""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_waveform import waveforms as wf +from pymodaq_plugins_waveform.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 68c8aa585c35d6db6700d21a9c89e1e339e175ed Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:51:41 +0000 Subject: [PATCH 02/10] Put the factory next to the waveforms folder, as the sequencer elements do Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../{waveforms => }/waveform_factory.py | 24 ++----------------- .../waveforms/__init__.py | 7 ++---- .../waveforms/array.py | 2 +- src/pymodaq_plugins_waveform/waveforms/dc.py | 2 +- .../waveforms/periodic.py | 21 ++++++++++++++++ .../waveforms/piecewise.py | 2 +- .../waveforms/pulse.py | 2 +- .../waveforms/ramp.py | 2 +- .../waveforms/sawtooth.py | 8 +++---- .../waveforms/sine.py | 8 +++---- .../waveforms/square.py | 8 +++---- .../waveforms/triangle.py | 8 +++---- tests/test_waveforms.py | 7 +++--- 13 files changed, 50 insertions(+), 51 deletions(-) rename src/pymodaq_plugins_waveform/{waveforms => }/waveform_factory.py (89%) create mode 100644 src/pymodaq_plugins_waveform/waveforms/periodic.py diff --git a/src/pymodaq_plugins_waveform/waveforms/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py similarity index 89% rename from src/pymodaq_plugins_waveform/waveforms/waveform_factory.py rename to src/pymodaq_plugins_waveform/waveform_factory.py index c75714b..fcd007e 100644 --- a/src/pymodaq_plugins_waveform/waveforms/waveform_factory.py +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -23,8 +23,8 @@ 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). +The forms are in the ``waveforms`` folder, one module each, which register themselves in the factory when imported +(the ``__init__`` of the folder imports them all). """ import dataclasses from abc import ABC, abstractmethod @@ -188,23 +188,3 @@ def create(cls, name: str, **parameters) -> Waveform: 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/src/pymodaq_plugins_waveform/waveforms/__init__.py b/src/pymodaq_plugins_waveform/waveforms/__init__.py index 9937051..b7a48ab 100644 --- a/src/pymodaq_plugins_waveform/waveforms/__init__.py +++ b/src/pymodaq_plugins_waveform/waveforms/__init__.py @@ -1,14 +1,11 @@ -"""Waveforms: the factory (:mod:`.waveform_factory`) and one module per form +"""The standard waveforms, one module per form (the factory is :mod:`pymodaq_plugins_waveform.waveform_factory`) 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. +:class:`~pymodaq_plugins_waveform.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_waveform.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}') diff --git a/src/pymodaq_plugins_waveform/waveforms/array.py b/src/pymodaq_plugins_waveform/waveforms/array.py index 4254deb..afad66d 100644 --- a/src/pymodaq_plugins_waveform/waveforms/array.py +++ b/src/pymodaq_plugins_waveform/waveforms/array.py @@ -5,7 +5,7 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveform_factory import Waveform, WaveformFactory, waveform_field @WaveformFactory.register('array') diff --git a/src/pymodaq_plugins_waveform/waveforms/dc.py b/src/pymodaq_plugins_waveform/waveforms/dc.py index c167987..6884026 100644 --- a/src/pymodaq_plugins_waveform/waveforms/dc.py +++ b/src/pymodaq_plugins_waveform/waveforms/dc.py @@ -4,7 +4,7 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) +from pymodaq_plugins_waveform.waveform_factory import (Waveform, WaveformFactory, waveform_field) @WaveformFactory.register('dc') diff --git a/src/pymodaq_plugins_waveform/waveforms/periodic.py b/src/pymodaq_plugins_waveform/waveforms/periodic.py new file mode 100644 index 0000000..7660e1d --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveforms/periodic.py @@ -0,0 +1,21 @@ +"""Helpers of the periodic waveforms""" +import numpy as np + + +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/src/pymodaq_plugins_waveform/waveforms/piecewise.py b/src/pymodaq_plugins_waveform/waveforms/piecewise.py index e7e85ed..0ed809b 100644 --- a/src/pymodaq_plugins_waveform/waveforms/piecewise.py +++ b/src/pymodaq_plugins_waveform/waveforms/piecewise.py @@ -5,7 +5,7 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveform_factory import Waveform, WaveformFactory, waveform_field _NUMBER = r'[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?' diff --git a/src/pymodaq_plugins_waveform/waveforms/pulse.py b/src/pymodaq_plugins_waveform/waveforms/pulse.py index 75e5a79..1f8be01 100644 --- a/src/pymodaq_plugins_waveform/waveforms/pulse.py +++ b/src/pymodaq_plugins_waveform/waveforms/pulse.py @@ -4,7 +4,7 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) +from pymodaq_plugins_waveform.waveform_factory import (Waveform, WaveformFactory, waveform_field) @WaveformFactory.register('pulse') diff --git a/src/pymodaq_plugins_waveform/waveforms/ramp.py b/src/pymodaq_plugins_waveform/waveforms/ramp.py index 8a42a4f..9afdd45 100644 --- a/src/pymodaq_plugins_waveform/waveforms/ramp.py +++ b/src/pymodaq_plugins_waveform/waveforms/ramp.py @@ -4,7 +4,7 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import (Waveform, WaveformFactory, waveform_field) +from pymodaq_plugins_waveform.waveform_factory import (Waveform, WaveformFactory, waveform_field) @WaveformFactory.register('ramp') diff --git a/src/pymodaq_plugins_waveform/waveforms/sawtooth.py b/src/pymodaq_plugins_waveform/waveforms/sawtooth.py index 99608ca..9a9cd1d 100644 --- a/src/pymodaq_plugins_waveform/waveforms/sawtooth.py +++ b/src/pymodaq_plugins_waveform/waveforms/sawtooth.py @@ -4,8 +4,8 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import ( - Waveform, WaveformFactory, waveform_field, _period, _phase) +from pymodaq_plugins_waveform.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveforms.periodic import period, phase @WaveformFactory.register('sawtooth') @@ -19,5 +19,5 @@ class Sawtooth(Waveform): 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 + 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_waveform/waveforms/sine.py b/src/pymodaq_plugins_waveform/waveforms/sine.py index f13b31c..51c591b 100644 --- a/src/pymodaq_plugins_waveform/waveforms/sine.py +++ b/src/pymodaq_plugins_waveform/waveforms/sine.py @@ -4,8 +4,8 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import ( - Waveform, WaveformFactory, waveform_field, _period, _phase) +from pymodaq_plugins_waveform.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveforms.periodic import period, phase @WaveformFactory.register('sine') @@ -19,5 +19,5 @@ class Sine(Waveform): 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 + 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_waveform/waveforms/square.py b/src/pymodaq_plugins_waveform/waveforms/square.py index da452af..97855fc 100644 --- a/src/pymodaq_plugins_waveform/waveforms/square.py +++ b/src/pymodaq_plugins_waveform/waveforms/square.py @@ -4,8 +4,8 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import ( - Waveform, WaveformFactory, waveform_field, _period, _phase) +from pymodaq_plugins_waveform.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveforms.periodic import period, phase @WaveformFactory.register('square') @@ -21,6 +21,6 @@ class Square(Waveform): 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 + 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_waveform/waveforms/triangle.py b/src/pymodaq_plugins_waveform/waveforms/triangle.py index ca7d3c2..b4bd517 100644 --- a/src/pymodaq_plugins_waveform/waveforms/triangle.py +++ b/src/pymodaq_plugins_waveform/waveforms/triangle.py @@ -4,8 +4,8 @@ import numpy as np -from pymodaq_plugins_waveform.waveforms.waveform_factory import ( - Waveform, WaveformFactory, waveform_field, _period, _phase) +from pymodaq_plugins_waveform.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveforms.periodic import period, phase @WaveformFactory.register('triangle') @@ -21,8 +21,8 @@ class Triangle(Waveform): tip='Fraction of the period spent rising') def _realize(self, sample_rate): - n, frequency = _period(self.frequency, 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 + 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/tests/test_waveforms.py b/tests/test_waveforms.py index 79a8611..425b60d 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -5,7 +5,8 @@ from pymodaq_data import Q_ from pymodaq_plugins_waveform import waveforms as wf -from pymodaq_plugins_waveform.waveforms import WaveformFactory, Waveform, waveform_field, parse_breakpoints +from pymodaq_plugins_waveform.waveform_factory import WaveformFactory, Waveform, waveform_field +from pymodaq_plugins_waveform.waveforms.piecewise import parse_breakpoints def create_waveform(name, **parameters): @@ -36,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.unregister('test_constant2') + WaveformFactory.unregister('test_constant2') def test_dc(): @@ -146,7 +147,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.WaveformFactory.get_class(name) + cls = 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 86914548e631b0f1c81ecb24f3159bec95cecf76 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:52:18 +0000 Subject: [PATCH 03/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 8438975..bfd6efa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -253,6 +253,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 7cff8565fab48595421c61ab79601019e67dc685 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:54:44 +0000 Subject: [PATCH 04/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 bfd6efa..5d44eaf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -262,8 +262,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 15925d385b31fca28ca58788954c631300b66148 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:57:09 +0000 Subject: [PATCH 05/10] Rename RealizedWaveform to SampledWaveform Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- src/pymodaq_plugins_waveform/waveform_factory.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/pymodaq_plugins_waveform/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py index fcd007e..8f79855 100644 --- a/src/pymodaq_plugins_waveform/waveform_factory.py +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -53,7 +53,7 @@ def waveform_field(default: Any, unit: Optional[str] = None, title: str = '', mi @dataclasses.dataclass(frozen=True) -class RealizedWaveform: +class SampledWaveform: """The samples of a waveform for one sample rate Attributes @@ -136,14 +136,14 @@ def n_samples(self, sample_rate: float) -> int: 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: + def realize(self, sample_rate: Union[float, Q_]) -> SampledWaveform: """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, + return SampledWaveform(np.asarray(samples, dtype=float), sample_rate, self.periodic, frequency, 0. if frequency is None else frequency - requested) From 53407aa42ec3abfe59c157d086f05c5b4add54b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 16:57:40 +0000 Subject: [PATCH 06/10] Rename realize to to_samples Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../waveform_factory.py | 12 +-- .../waveforms/array.py | 2 +- src/pymodaq_plugins_waveform/waveforms/dc.py | 2 +- .../waveforms/piecewise.py | 2 +- .../waveforms/pulse.py | 2 +- .../waveforms/ramp.py | 2 +- .../waveforms/sawtooth.py | 2 +- .../waveforms/sine.py | 2 +- .../waveforms/square.py | 2 +- .../waveforms/triangle.py | 2 +- tests/test_waveforms.py | 78 +++++++++---------- 11 files changed, 54 insertions(+), 54 deletions(-) diff --git a/src/pymodaq_plugins_waveform/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py index 8f79855..bc152e0 100644 --- a/src/pymodaq_plugins_waveform/waveform_factory.py +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -1,7 +1,7 @@ """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 +signal itself from parameters and one that needs the samples (:meth:`Waveform.to_samples`). 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. @@ -16,7 +16,7 @@ class Gaussian(Waveform): width: float = waveform_field(1e-4, 's', 'Width') duration: float = waveform_field(2e-3, 's', 'Duration') - def _realize(self, sample_rate): + def _to_samples(self, sample_rate): t = np.arange(self.n_samples(sample_rate)) / sample_rate return np.exp(-((t - self.center) / self.width) ** 2 / 2), None @@ -83,7 +83,7 @@ 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 + periodic: ClassVar[bool] = False # True: :meth:`to_samples` gives one period to repeat def __post_init__(self): for field in self._parameters(): @@ -133,15 +133,15 @@ def n_samples(self, sample_rate: float) -> int: return max(2, int(round(getattr(self, 'duration') * sample_rate))) @abstractmethod - def _realize(self, sample_rate: float) -> tuple[np.ndarray, Optional[float]]: + def _to_samples(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_]) -> SampledWaveform: + def to_samples(self, sample_rate: Union[float, Q_]) -> SampledWaveform: """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) + samples, frequency = self._to_samples(sample_rate) requested = getattr(self, 'frequency', None) return SampledWaveform(np.asarray(samples, dtype=float), sample_rate, self.periodic, frequency, 0. if frequency is None else frequency - requested) diff --git a/src/pymodaq_plugins_waveform/waveforms/array.py b/src/pymodaq_plugins_waveform/waveforms/array.py index afad66d..da3ebdc 100644 --- a/src/pymodaq_plugins_waveform/waveforms/array.py +++ b/src/pymodaq_plugins_waveform/waveforms/array.py @@ -17,7 +17,7 @@ class Array(Waveform): 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): + def _to_samples(self, sample_rate): values = self.values if values is None: if not self.path: diff --git a/src/pymodaq_plugins_waveform/waveforms/dc.py b/src/pymodaq_plugins_waveform/waveforms/dc.py index 6884026..4f2cc44 100644 --- a/src/pymodaq_plugins_waveform/waveforms/dc.py +++ b/src/pymodaq_plugins_waveform/waveforms/dc.py @@ -14,5 +14,5 @@ class DC(Waveform): level: float = waveform_field(0., 'V', 'Level') duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) - def _realize(self, sample_rate): + def _to_samples(self, sample_rate): return np.full(self.n_samples(sample_rate), self.level), None diff --git a/src/pymodaq_plugins_waveform/waveforms/piecewise.py b/src/pymodaq_plugins_waveform/waveforms/piecewise.py index 0ed809b..607ec47 100644 --- a/src/pymodaq_plugins_waveform/waveforms/piecewise.py +++ b/src/pymodaq_plugins_waveform/waveforms/piecewise.py @@ -45,7 +45,7 @@ def __post_init__(self): super().__post_init__() parse_breakpoints(self.points) # fail at creation - def _realize(self, sample_rate): + def _to_samples(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_waveform/waveforms/pulse.py b/src/pymodaq_plugins_waveform/waveforms/pulse.py index 1f8be01..adea8e8 100644 --- a/src/pymodaq_plugins_waveform/waveforms/pulse.py +++ b/src/pymodaq_plugins_waveform/waveforms/pulse.py @@ -17,7 +17,7 @@ class Pulse(Waveform): 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): + def _to_samples(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_waveform/waveforms/ramp.py b/src/pymodaq_plugins_waveform/waveforms/ramp.py index 9afdd45..b2ef6dc 100644 --- a/src/pymodaq_plugins_waveform/waveforms/ramp.py +++ b/src/pymodaq_plugins_waveform/waveforms/ramp.py @@ -15,5 +15,5 @@ class Ramp(Waveform): stop: float = waveform_field(1., 'V', 'Stop') duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) - def _realize(self, sample_rate): + def _to_samples(self, sample_rate): return np.linspace(self.start, self.stop, self.n_samples(sample_rate)), None diff --git a/src/pymodaq_plugins_waveform/waveforms/sawtooth.py b/src/pymodaq_plugins_waveform/waveforms/sawtooth.py index 9a9cd1d..df354a7 100644 --- a/src/pymodaq_plugins_waveform/waveforms/sawtooth.py +++ b/src/pymodaq_plugins_waveform/waveforms/sawtooth.py @@ -18,6 +18,6 @@ class Sawtooth(Waveform): offset: float = waveform_field(0., 'V', 'Offset') phase: float = waveform_field(0., 'deg', 'Phase') - def _realize(self, sample_rate): + def _to_samples(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_waveform/waveforms/sine.py b/src/pymodaq_plugins_waveform/waveforms/sine.py index 51c591b..b1767d7 100644 --- a/src/pymodaq_plugins_waveform/waveforms/sine.py +++ b/src/pymodaq_plugins_waveform/waveforms/sine.py @@ -18,6 +18,6 @@ class Sine(Waveform): offset: float = waveform_field(0., 'V', 'Offset') phase: float = waveform_field(0., 'deg', 'Phase') - def _realize(self, sample_rate): + def _to_samples(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_waveform/waveforms/square.py b/src/pymodaq_plugins_waveform/waveforms/square.py index 97855fc..cc602ad 100644 --- a/src/pymodaq_plugins_waveform/waveforms/square.py +++ b/src/pymodaq_plugins_waveform/waveforms/square.py @@ -20,7 +20,7 @@ class Square(Waveform): 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): + def _to_samples(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_waveform/waveforms/triangle.py b/src/pymodaq_plugins_waveform/waveforms/triangle.py index b4bd517..e45995c 100644 --- a/src/pymodaq_plugins_waveform/waveforms/triangle.py +++ b/src/pymodaq_plugins_waveform/waveforms/triangle.py @@ -20,7 +20,7 @@ class Triangle(Waveform): 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): + def _to_samples(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 diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py index 425b60d..1302b74 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -29,85 +29,85 @@ def test_a_plugin_can_register_its_own_waveform(): class Constant2(Waveform): value: float = waveform_field(2., 'V', 'Value') - def _realize(self, sample_rate): + def _to_samples(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 + assert create_waveform('test_constant2', value=Q_(3000, 'mV')).to_samples(1e3).samples.tolist() == [3.] * 4 finally: 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 + sampled = create_waveform('dc', level=1.5, duration=5e-3).to_samples(1000.) + assert sampled.samples.tolist() == [1.5] * 5 + assert not sampled.periodic and sampled.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.) + sampled = create_waveform('sine', amplitude=2., frequency=100., offset=1.).to_samples(800.) + assert sampled.periodic and len(sampled.samples) == 8 + assert sampled.samples[0] == pytest.approx(1.) + assert sampled.samples[2] == pytest.approx(3.) + assert sampled.samples[4] == pytest.approx(1.) + assert sampled.samples[6] == pytest.approx(-1.) + assert sampled.frequency == pytest.approx(100.) and sampled.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 + sampled = create_waveform('sine', amplitude=1., frequency=100., phase=90.).to_samples(800.) + assert sampled.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) + sampled = create_waveform('sine', frequency=30.).to_samples(1000.) # 33.3 samples per period + assert len(sampled.samples) == 33 + assert sampled.frequency == pytest.approx(1000. / 33) + assert sampled.frequency_error == pytest.approx(1000. / 33 - 30.) + assert sampled.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.) + create_waveform('sine', frequency=600.).to_samples(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.] + sampled = create_waveform('square', amplitude=2., frequency=100., offset=1., duty_cycle=0.25).to_samples(800.) + assert sampled.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.]) + sampled = create_waveform('triangle', amplitude=2., frequency=100.).to_samples(800.) + assert sampled.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 + sampled = create_waveform('triangle', frequency=100., symmetry=0.25).to_samples(800.) + assert sampled.samples.max() == pytest.approx(1.) and sampled.samples.min() == pytest.approx(-1.) + assert sampled.samples[0] == pytest.approx(0.) + assert int(np.argmax(sampled.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.]) + sampled = create_waveform('sawtooth', amplitude=4., frequency=100.).to_samples(800.) + assert sampled.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 == \ + assert create_waveform('ramp', start=0., stop=1., duration=5e-3).to_samples(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.] + assert pulse.to_samples(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.]) + assert wave.to_samples(1000.).samples == pytest.approx([0., 2., 4., 4., 4., 0.]) @pytest.mark.parametrize('text, message', [('0:0', 'two'), ('0:0, 1e-3', 'time:value'), @@ -121,26 +121,26 @@ def test_breakpoints_errors(text, message): def test_array_from_values_and_from_files(tmp_path): values = np.array([0., 1., 0.5]) - assert create_waveform('array', values=values).realize(100.).samples.tolist() == values.tolist() + assert create_waveform('array', values=values).to_samples(100.).samples.tolist() == values.tolist() np.save(tmp_path / 'wave.npy', values) - assert create_waveform('array', path=str(tmp_path / 'wave.npy')).realize(100.).samples.tolist() == values.tolist() + assert create_waveform('array', path=str(tmp_path / 'wave.npy')).to_samples(100.).samples.tolist() == values.tolist() (tmp_path / 'wave.csv').write_text('0\n1\n0.5\n') - assert create_waveform('array', path=str(tmp_path / 'wave.csv')).realize(100.).samples.tolist() == values.tolist() + assert create_waveform('array', path=str(tmp_path / 'wave.csv')).to_samples(100.).samples.tolist() == values.tolist() with pytest.raises(ValueError, match='No file'): - create_waveform('array').realize(100.) + create_waveform('array').to_samples(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. + assert create_waveform('sine', frequency=100.).to_samples(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.) + create_waveform('dc').to_samples(0.) @pytest.mark.parametrize('name', ['dc', 'sine', 'square', 'triangle', 'sawtooth', 'ramp', 'pulse', 'piecewise', From 20d8a1a48892f2e5166fee2d89c5f1614f09f5bd Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:00:37 +0000 Subject: [PATCH 07/10] One place for the name of a waveform: the class attribute name, no title, register() without argument Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- AGENTS.md | 3 ++- src/pymodaq_plugins_waveform/waveform_factory.py | 16 +++++++++------- src/pymodaq_plugins_waveform/waveforms/array.py | 4 ++-- src/pymodaq_plugins_waveform/waveforms/dc.py | 4 ++-- .../waveforms/piecewise.py | 4 ++-- src/pymodaq_plugins_waveform/waveforms/pulse.py | 4 ++-- src/pymodaq_plugins_waveform/waveforms/ramp.py | 4 ++-- .../waveforms/sawtooth.py | 4 ++-- src/pymodaq_plugins_waveform/waveforms/sine.py | 4 ++-- src/pymodaq_plugins_waveform/waveforms/square.py | 4 ++-- .../waveforms/triangle.py | 4 ++-- tests/test_waveforms.py | 16 +++++++++++++++- 12 files changed, 44 insertions(+), 27 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5d44eaf..8d6ed9b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -261,7 +261,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; diff --git a/src/pymodaq_plugins_waveform/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py index bc152e0..1b11009 100644 --- a/src/pymodaq_plugins_waveform/waveform_factory.py +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -9,9 +9,10 @@ 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') + @WaveformFactory.register() @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') @@ -82,7 +83,6 @@ def duration(self) -> float: 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:`to_samples` gives one period to repeat def __post_init__(self): @@ -150,17 +150,19 @@ def to_samples(self, sample_rate: Union[float, Q_]) -> SampledWaveform: 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 + ``@WaveformFactory.register()`` on a :class:`Waveform` dataclass registers it under its ``name`` (a class attribute, + the only place where the name is written, as ``elt_name`` of the sequencer elements). 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 register(cls): + """Class decorator registering a waveform under its ``name``""" def inner_wrapper(wrapped_class: Type[Waveform]) -> Type[Waveform]: - wrapped_class.name = key - cls._waveforms[key] = wrapped_class + if not wrapped_class.name: + raise ValueError(f'{wrapped_class.__name__} has no name: set the class attribute ``name``') + cls._waveforms[wrapped_class.name] = wrapped_class return wrapped_class return inner_wrapper diff --git a/src/pymodaq_plugins_waveform/waveforms/array.py b/src/pymodaq_plugins_waveform/waveforms/array.py index da3ebdc..0f56bc8 100644 --- a/src/pymodaq_plugins_waveform/waveforms/array.py +++ b/src/pymodaq_plugins_waveform/waveforms/array.py @@ -8,12 +8,12 @@ from pymodaq_plugins_waveform.waveform_factory import Waveform, WaveformFactory, waveform_field -@WaveformFactory.register('array') +@WaveformFactory.register() @dataclasses.dataclass class Array(Waveform): """Samples taken as they are, from a file (``.npy`` or text) or given as ``values``; they are played at the sample rate of the output""" - title: ClassVar[str] = 'Array' + name: 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/src/pymodaq_plugins_waveform/waveforms/dc.py b/src/pymodaq_plugins_waveform/waveforms/dc.py index 4f2cc44..721bfc9 100644 --- a/src/pymodaq_plugins_waveform/waveforms/dc.py +++ b/src/pymodaq_plugins_waveform/waveforms/dc.py @@ -7,10 +7,10 @@ from pymodaq_plugins_waveform.waveform_factory import (Waveform, WaveformFactory, waveform_field) -@WaveformFactory.register('dc') +@WaveformFactory.register() @dataclasses.dataclass class DC(Waveform): - title: ClassVar[str] = 'DC' + name: ClassVar[str] = 'dc' level: float = waveform_field(0., 'V', 'Level') duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) diff --git a/src/pymodaq_plugins_waveform/waveforms/piecewise.py b/src/pymodaq_plugins_waveform/waveforms/piecewise.py index 607ec47..8298726 100644 --- a/src/pymodaq_plugins_waveform/waveforms/piecewise.py +++ b/src/pymodaq_plugins_waveform/waveforms/piecewise.py @@ -31,11 +31,11 @@ def parse_breakpoints(text: str) -> tuple[np.ndarray, np.ndarray]: return np.array(times), np.array(values) -@WaveformFactory.register('piecewise') +@WaveformFactory.register() @dataclasses.dataclass class Piecewise(Waveform): """Straight segments between points given as ``time:value`` pairs (seconds and volts)""" - title: ClassVar[str] = 'Piecewise linear' + name: ClassVar[str] = 'piecewise' 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 ' diff --git a/src/pymodaq_plugins_waveform/waveforms/pulse.py b/src/pymodaq_plugins_waveform/waveforms/pulse.py index adea8e8..91b0204 100644 --- a/src/pymodaq_plugins_waveform/waveforms/pulse.py +++ b/src/pymodaq_plugins_waveform/waveforms/pulse.py @@ -7,10 +7,10 @@ from pymodaq_plugins_waveform.waveform_factory import (Waveform, WaveformFactory, waveform_field) -@WaveformFactory.register('pulse') +@WaveformFactory.register() @dataclasses.dataclass class Pulse(Waveform): - title: ClassVar[str] = 'Pulse' + name: 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') diff --git a/src/pymodaq_plugins_waveform/waveforms/ramp.py b/src/pymodaq_plugins_waveform/waveforms/ramp.py index b2ef6dc..50b436a 100644 --- a/src/pymodaq_plugins_waveform/waveforms/ramp.py +++ b/src/pymodaq_plugins_waveform/waveforms/ramp.py @@ -7,10 +7,10 @@ from pymodaq_plugins_waveform.waveform_factory import (Waveform, WaveformFactory, waveform_field) -@WaveformFactory.register('ramp') +@WaveformFactory.register() @dataclasses.dataclass class Ramp(Waveform): - title: ClassVar[str] = 'Ramp' + name: 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.) diff --git a/src/pymodaq_plugins_waveform/waveforms/sawtooth.py b/src/pymodaq_plugins_waveform/waveforms/sawtooth.py index df354a7..6299c14 100644 --- a/src/pymodaq_plugins_waveform/waveforms/sawtooth.py +++ b/src/pymodaq_plugins_waveform/waveforms/sawtooth.py @@ -8,10 +8,10 @@ from pymodaq_plugins_waveform.waveforms.periodic import period, phase -@WaveformFactory.register('sawtooth') +@WaveformFactory.register() @dataclasses.dataclass class Sawtooth(Waveform): - title: ClassVar[str] = 'Sawtooth' + name: 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.) diff --git a/src/pymodaq_plugins_waveform/waveforms/sine.py b/src/pymodaq_plugins_waveform/waveforms/sine.py index b1767d7..f505dee 100644 --- a/src/pymodaq_plugins_waveform/waveforms/sine.py +++ b/src/pymodaq_plugins_waveform/waveforms/sine.py @@ -8,10 +8,10 @@ from pymodaq_plugins_waveform.waveforms.periodic import period, phase -@WaveformFactory.register('sine') +@WaveformFactory.register() @dataclasses.dataclass class Sine(Waveform): - title: ClassVar[str] = 'Sine' + name: 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.) diff --git a/src/pymodaq_plugins_waveform/waveforms/square.py b/src/pymodaq_plugins_waveform/waveforms/square.py index cc602ad..1507b39 100644 --- a/src/pymodaq_plugins_waveform/waveforms/square.py +++ b/src/pymodaq_plugins_waveform/waveforms/square.py @@ -8,10 +8,10 @@ from pymodaq_plugins_waveform.waveforms.periodic import period, phase -@WaveformFactory.register('square') +@WaveformFactory.register() @dataclasses.dataclass class Square(Waveform): - title: ClassVar[str] = 'Square' + name: 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.) diff --git a/src/pymodaq_plugins_waveform/waveforms/triangle.py b/src/pymodaq_plugins_waveform/waveforms/triangle.py index e45995c..9f9b58d 100644 --- a/src/pymodaq_plugins_waveform/waveforms/triangle.py +++ b/src/pymodaq_plugins_waveform/waveforms/triangle.py @@ -8,10 +8,10 @@ from pymodaq_plugins_waveform.waveforms.periodic import period, phase -@WaveformFactory.register('triangle') +@WaveformFactory.register() @dataclasses.dataclass class Triangle(Waveform): - title: ClassVar[str] = 'Triangle' + name: 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.) diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py index 1302b74..fa3f468 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -1,4 +1,6 @@ """The waveform factory: samples compared with values worked out by hand, the registry and the settings""" +from typing import ClassVar + import numpy as np import pytest from pymodaq_gui.parameter import Parameter @@ -21,12 +23,24 @@ def test_registry_has_the_standard_forms(): create_waveform('nope') +def test_a_waveform_without_name_is_refused(): + import dataclasses + + with pytest.raises(ValueError, match='no name'): + @WaveformFactory.register() + @dataclasses.dataclass + class Nameless(Waveform): + def _to_samples(self, sample_rate): + return np.zeros(2), None + + def test_a_plugin_can_register_its_own_waveform(): import dataclasses - @WaveformFactory.register('test_constant2') + @WaveformFactory.register() @dataclasses.dataclass class Constant2(Waveform): + name: ClassVar[str] = 'test_constant2' value: float = waveform_field(2., 'V', 'Value') def _to_samples(self, sample_rate): From 1999cb5ad2d2f2b7c558bd0ed7c542c39fa69e0d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:05:43 +0000 Subject: [PATCH 08/10] waveform_field: optional type (int, bool, list with limits) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- .../waveform_factory.py | 49 ++++++++++++++----- tests/test_waveforms.py | 35 +++++++++++++ 2 files changed, 72 insertions(+), 12 deletions(-) diff --git a/src/pymodaq_plugins_waveform/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py index 1b11009..c866bf8 100644 --- a/src/pymodaq_plugins_waveform/waveform_factory.py +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -39,18 +39,30 @@ def _to_samples(self, sample_rate): def waveform_field(default: Any, unit: Optional[str] = None, title: str = '', min: Optional[float] = None, - max: Optional[float] = None, tip: str = '') -> Any: + max: Optional[float] = None, tip: str = '', type: Optional[str] = None, + limits: Optional[list] = None) -> 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 + unit: the unit of the number (pint syntax), None for a parameter that is not a physical quantity (see ``type``) 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 + type: the type of the parameter in the settings: ``'float'`` (the default when there is a ``unit``), ``'str'`` (the + default without unit), ``'int'``, ``'bool'`` or ``'list'`` (a choice among ``limits``) + limits: the choices of a ``'list'`` parameter """ - return dataclasses.field(default=default, metadata=dict(unit=unit, title=title, min=min, max=max, tip=tip)) + if unit is not None and type not in (None, 'float'): + raise ValueError(f'A parameter with a unit is a float, not {type}') + type = 'float' if unit is not None else (type or 'str') + if type not in ('float', 'str', 'int', 'bool', 'list'): + raise ValueError(f'Unknown parameter type {type}') + if type == 'list' and not limits: + raise ValueError('A list parameter needs its limits') + return dataclasses.field(default=default, metadata=dict(unit=unit, title=title, min=min, max=max, tip=tip, + type=type, limits=limits)) @dataclasses.dataclass(frozen=True) @@ -88,14 +100,22 @@ class Waveform(ABC): def __post_init__(self): for field in self._parameters(): value = getattr(self, field.name) - unit = field.metadata['unit'] - if unit is not None: + meta = field.metadata + unit, type_ = meta['unit'], meta['type'] + if type_ == 'float': value = float(value.m_as(unit)) if isinstance(value, Q_) else float(value) - lower, upper = field.metadata['min'], field.metadata['max'] + elif type_ == 'int': + value = int(value) + elif type_ == 'bool': + value = bool(value) + elif type_ == 'list' and value not in meta['limits']: + raise ValueError(f'{self.name}: {field.name} = {value} is not one of {meta["limits"]}') + if type_ in ('float', 'int'): + lower, upper = meta['min'], meta['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 ' + raise ValueError(f'{self.name}: {field.name} = {value} {unit or ""} is out of its limits ' f'({lower}, {upper})') - setattr(self, field.name, value) + setattr(self, field.name, value) # ---- the description as settings @classmethod @@ -110,11 +130,16 @@ def params(cls) -> list[dict]: 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: + param['type'] = meta['type'] + if meta['type'] == 'list': + param['limits'] = list(meta['limits']) + elif meta['type'] == 'int': + for key in ('min', 'max'): + if meta[key] is not None: + param[key] = meta[key] + elif meta['type'] == 'float': 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'], + param.update(suffix='' if meta['unit'] == 'dimensionless' else meta['unit'], siPrefix=not dimensionless) for key in ('min', 'max'): if meta[key] is not None: diff --git a/tests/test_waveforms.py b/tests/test_waveforms.py index fa3f468..b592445 100644 --- a/tests/test_waveforms.py +++ b/tests/test_waveforms.py @@ -174,3 +174,38 @@ def test_settings_carry_units_and_limits(): 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'] == '' + + +def test_int_bool_and_list_parameters(): + import dataclasses + + @dataclasses.dataclass + class Stairs(Waveform): + name: ClassVar[str] = 'stairs' + steps: int = waveform_field(4, title='Steps', type='int', min=1, max=100) + reverse: bool = waveform_field(False, title='Reverse', type='bool') + shape: str = waveform_field('linear', title='Shape', type='list', limits=['linear', 'log']) + + def _to_samples(self, sample_rate): + return np.zeros(2), None + + params = {param['name']: param for param in Stairs.params()} + assert [params[n]['type'] for n in ('steps', 'reverse', 'shape')] == ['int', 'bool', 'list'] + assert params['shape']['limits'] == ['linear', 'log'] and (params['steps']['min'], params['steps']['max']) == (1, 100) + group = Parameter.create(name='waveform', type='group', children=Stairs.params()) + group['steps'], group['shape'] = 7.0, 'log' + wave = Stairs.from_settings(group) + assert (wave.steps, wave.reverse, wave.shape) == (7, False, 'log') and isinstance(wave.steps, int) + with pytest.raises(ValueError, match='out of its limits'): + Stairs(steps=0) + with pytest.raises(ValueError, match='not one of'): + Stairs(shape='cubic') + + +def test_waveform_field_refuses_inconsistent_arguments(): + with pytest.raises(ValueError, match='list parameter needs'): + waveform_field('a', type='list') + with pytest.raises(ValueError, match='unit is a float|with a unit'): + waveform_field(1, 'V', type='int') + with pytest.raises(ValueError, match='Unknown parameter type'): + waveform_field(1, type='complex') From 1b86add8239bf819e66f8988eb9281da5f84d491 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:06:32 +0000 Subject: [PATCH 09/10] Waveform base class: no dataclass decorator (it has no field) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- src/pymodaq_plugins_waveform/waveform_factory.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/pymodaq_plugins_waveform/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py index c866bf8..80f0341 100644 --- a/src/pymodaq_plugins_waveform/waveform_factory.py +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -91,7 +91,6 @@ def duration(self) -> float: 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] = '' From f434b44457aaac7ac99429eb8f743d07f8fe76df Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:07:55 +0000 Subject: [PATCH 10/10] Waveform: validation of the parameters in a documented method Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN81tBxMB6iaf8J6KLJL --- src/pymodaq_plugins_waveform/waveform_factory.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/pymodaq_plugins_waveform/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py index 80f0341..c7f29a3 100644 --- a/src/pymodaq_plugins_waveform/waveform_factory.py +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -97,6 +97,22 @@ class Waveform(ABC): periodic: ClassVar[bool] = False # True: :meth:`to_samples` gives one period to repeat def __post_init__(self): + """Called by the ``__init__`` that the dataclass decorator of each form generates, once the fields are set""" + self._validate_parameters() + + def _validate_parameters(self) -> None: + """Check and normalize the value of every parameter (the fields declared with :func:`waveform_field`) + + For each parameter, according to its type: + + - ``float``: a pint quantity is converted to the unit of the field, any number is made a ``float``; + - ``int`` and ``bool``: the value is converted to this type; + - ``list``: the value should be one of the ``limits`` of the field; + - ``float`` and ``int``: the value should be within ``min`` and ``max`` if they are set. + + The converted value replaces the given one. A ``ValueError`` names the waveform and the parameter when a bound + or a choice is not respected. A form with more to check extends :meth:`__post_init__` and calls ``super()``. + """ for field in self._parameters(): value = getattr(self, field.name) meta = field.metadata