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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, `<name>_factory.py`, **not** in the folder of the classes;
- the classes live in a sibling folder (`<name>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.
Expand Down
232 changes: 232 additions & 0 deletions src/pymodaq_plugins_waveform/waveform_factory.py
Original file line number Diff line number Diff line change
@@ -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)
20 changes: 20 additions & 0 deletions src/pymodaq_plugins_waveform/waveforms/__init__.py
Original file line number Diff line number Diff line change
@@ -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
30 changes: 30 additions & 0 deletions src/pymodaq_plugins_waveform/waveforms/array.py
Original file line number Diff line number Diff line change
@@ -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
18 changes: 18 additions & 0 deletions src/pymodaq_plugins_waveform/waveforms/dc.py
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions src/pymodaq_plugins_waveform/waveforms/periodic.py
Original file line number Diff line number Diff line change
@@ -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.
Loading