diff --git a/AGENTS.md b/AGENTS.md index 8438975..8d6ed9b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -253,6 +253,23 @@ 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()`); 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; +- 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. diff --git a/src/pymodaq_plugins_waveform/waveform_factory.py b/src/pymodaq_plugins_waveform/waveform_factory.py new file mode 100644 index 0000000..c7f29a3 --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveform_factory.py @@ -0,0 +1,232 @@ +"""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.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. + +: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() + @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 _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 + +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 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 +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 = '', 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 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 + """ + 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) +class SampledWaveform: + """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 + + +class Waveform(ABC): + """Base class of the waveforms. Subclass it with a dataclass, set ``name`` and register it""" + name: ClassVar[str] = '' + 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 + unit, type_ = meta['unit'], meta['type'] + if type_ == 'float': + value = float(value.m_as(unit)) if isinstance(value, Q_) else float(value) + 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 or ""} 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']} + 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(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 _to_samples(self, sample_rate: float) -> tuple[np.ndarray, Optional[float]]: + """The samples and, for a periodic waveform, the frequency really generated""" + + 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._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) + + +class WaveformFactory: + """Registry of the waveforms by name, and their creation + + ``@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): + """Class decorator registering a waveform under its ``name``""" + def inner_wrapper(wrapped_class: Type[Waveform]) -> Type[Waveform]: + 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 + + @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) diff --git a/src/pymodaq_plugins_waveform/waveforms/__init__.py b/src/pymodaq_plugins_waveform/waveforms/__init__.py new file mode 100644 index 0000000..b7a48ab --- /dev/null +++ b/src/pymodaq_plugins_waveform/waveforms/__init__.py @@ -0,0 +1,20 @@ +"""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:`~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 + +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..0f56bc8 --- /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.waveform_factory import Waveform, WaveformFactory, waveform_field + + +@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""" + 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 + + def _to_samples(self, sample_rate): + values = self.values + if values is None: + if not self.path: + raise ValueError('No file and no values for the array waveform') + 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..721bfc9 --- /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.waveform_factory import (Waveform, WaveformFactory, waveform_field) + + +@WaveformFactory.register() +@dataclasses.dataclass +class DC(Waveform): + name: ClassVar[str] = 'dc' + level: float = waveform_field(0., 'V', 'Level') + duration: float = waveform_field(1e-3, 's', 'Duration', min=0.) + + 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/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 new file mode 100644 index 0000000..8298726 --- /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.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() +@dataclasses.dataclass +class Piecewise(Waveform): + """Straight segments between points given as ``time:value`` pairs (seconds and volts)""" + 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 ' + 'last time') + + def __post_init__(self): + super().__post_init__() + parse_breakpoints(self.points) # fail at creation + + 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 new file mode 100644 index 0000000..91b0204 --- /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.waveform_factory import (Waveform, WaveformFactory, waveform_field) + + +@WaveformFactory.register() +@dataclasses.dataclass +class Pulse(Waveform): + 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') + 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 _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 new file mode 100644 index 0000000..50b436a --- /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.waveform_factory import (Waveform, WaveformFactory, waveform_field) + + +@WaveformFactory.register() +@dataclasses.dataclass +class Ramp(Waveform): + 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.) + + 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 new file mode 100644 index 0000000..6299c14 --- /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.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveforms.periodic import period, phase + + +@WaveformFactory.register() +@dataclasses.dataclass +class Sawtooth(Waveform): + 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.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + + 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 new file mode 100644 index 0000000..f505dee --- /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.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveforms.periodic import period, phase + + +@WaveformFactory.register() +@dataclasses.dataclass +class Sine(Waveform): + 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.) + offset: float = waveform_field(0., 'V', 'Offset') + phase: float = waveform_field(0., 'deg', 'Phase') + + 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 new file mode 100644 index 0000000..1507b39 --- /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.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveforms.periodic import period, phase + + +@WaveformFactory.register() +@dataclasses.dataclass +class Square(Waveform): + 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.) + 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 _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 new file mode 100644 index 0000000..9f9b58d --- /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.waveform_factory import Waveform, WaveformFactory, waveform_field +from pymodaq_plugins_waveform.waveforms.periodic import period, phase + + +@WaveformFactory.register() +@dataclasses.dataclass +class Triangle(Waveform): + 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.) + 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 _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 + 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 new file mode 100644 index 0000000..b592445 --- /dev/null +++ b/tests/test_waveforms.py @@ -0,0 +1,211 @@ +"""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 + +from pymodaq_data import Q_ +from pymodaq_plugins_waveform import waveforms as wf +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): + 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_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() + @dataclasses.dataclass + class Constant2(Waveform): + name: ClassVar[str] = 'test_constant2' + value: float = waveform_field(2., 'V', 'Value') + + 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')).to_samples(1e3).samples.tolist() == [3.] * 4 + finally: + WaveformFactory.unregister('test_constant2') + + +def test_dc(): + 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 + 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(): + 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(): + 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.).to_samples(1000.) + + +def test_square(): + 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(): + 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 + 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(): + 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).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.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.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'), + ('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).to_samples(100.).samples.tolist() == values.tolist() + np.save(tmp_path / 'wave.npy', values) + assert create_waveform('array', path=str(tmp_path / 'wave.npy')).to_samples(100.).samples.tolist() == values.tolist() + (tmp_path / 'wave.csv').write_text('0\n1\n0.5\n') + assert create_waveform('array', path=str(tmp_path / 'wave.csv')).to_samples(100.).samples.tolist() == values.tolist() + with pytest.raises(ValueError, match='No file'): + 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.).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').to_samples(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 = 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'] == '' + + +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')