From 69006780a8d668dfe169d35252689aff74e72791 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 11:03:50 +0000 Subject: [PATCH 1/8] Input compensation as a modular option chosen in the AlgoApp settings A factory of compensations like the initial phases (NoCompensation, DivideByInput), a settings group shown for the algorithms that use it (INPUT_COMPENSATION), used by the binary holograms and the checkerboard. The unreachable region is outlined as soon as the compensation is chosen, before any run. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- AGENTS_BEAM_SHAPING.md | 1 + docs/src/user_guide/algorithm_reference.rst | 39 ++++-- src/pymodaq_plugins_beam_shaping/__init__.py | 6 + .../algorithms/algo_base.py | 37 ++++++ .../algorithms/algorithm_app.py | 32 +++++ .../algorithms/algorithms/binary_holograms.py | 66 +++------- .../algorithms/algorithms/checker_board.py | 5 +- .../algorithms/compensation.py | 117 ++++++++++++++++++ .../algorithms/compensations/__init__.py | 0 .../compensations/divide_by_input.py | 40 ++++++ .../compensations/no_compensation.py | 11 ++ .../extensions/spatial_beam_shaping.py | 11 ++ .../utilities/headless_algorithms.py | 19 +++ tests/test_algo_helpers.py | 66 +++++++++- tests/test_compensation.py | 93 ++++++++++++++ tests/test_custom_apps.py | 23 ++++ tests/test_region_outline.py | 45 +++++++ 17 files changed, 547 insertions(+), 64 deletions(-) create mode 100644 src/pymodaq_plugins_beam_shaping/algorithms/compensation.py create mode 100644 src/pymodaq_plugins_beam_shaping/algorithms/compensations/__init__.py create mode 100644 src/pymodaq_plugins_beam_shaping/algorithms/compensations/divide_by_input.py create mode 100644 src/pymodaq_plugins_beam_shaping/algorithms/compensations/no_compensation.py create mode 100644 tests/test_compensation.py diff --git a/AGENTS_BEAM_SHAPING.md b/AGENTS_BEAM_SHAPING.md index 9c377dd..2319fe0 100644 --- a/AGENTS_BEAM_SHAPING.md +++ b/AGENTS_BEAM_SHAPING.md @@ -30,6 +30,7 @@ close to the template so that it can be updated); this file is what is specific | `algorithms/factory.py` | `AlgorithmFactory`, `register_algorithms()` and the entry point group `pymodaq_plugins_beam_shaping.algorithms` for third party algorithms. | | `algorithms/algorithms/` | The **algorithms**, one module per family (see below). | | `algorithms/ini_phases/`, `stoppings/`, `loss.py` | Initial phases, stopping criteria and loss functions used by iterative algorithms. | +| `algorithms/compensation.py`, `compensations/` | Compensation of the input beam profile (factory like the initial phases, chosen in the AlgoApp settings); an algorithm sets `INPUT_COMPENSATION = True` and calls `compensate_target`. | | `algorithms/algorithm_app.py` | `AlgoApp`: the widget running an algorithm, owning the masks, the shaper and the fields. | | `algorithms/utils.py` | Enums (`AlgoStatus`, `AlgoType`, `ApplyMaskTo`, `LensSetup`). | | `utilities/shaper.py` | `Shaper` and `ModulatorType` (phase, amplitude, both), defined in `pymodaq_plugins_utils`; `get_default_shaper()` reads the config. | diff --git a/docs/src/user_guide/algorithm_reference.rst b/docs/src/user_guide/algorithm_reference.rst index a37d2ac..f675fca 100644 --- a/docs/src/user_guide/algorithm_reference.rst +++ b/docs/src/user_guide/algorithm_reference.rst @@ -49,6 +49,8 @@ by encoding the complex field on a checkerboard (:cite:t:`mendoza-yero_encoding_ *Settings*: * ``Mask block size (pxls)`` (default 5): size of the blocks of the checkerboard. +* The input beam is compensated (see *Input compensation* below): the amplitude of the target is divided by the one of + the beam before the angles of the checkerboard are computed. * ``amplitude divider`` (default 1). .. _sec-algo-amplitude-modulation: @@ -91,14 +93,7 @@ in the review but not available. * ``Binarize`` (default checked): the pattern is binarized, as a DMD can only switch its pixels on or off. Unchecked, the grey levels of the pattern are kept (the grey off-axis hologram, an ideal modulation not feasible on a DMD, to see what the binarization costs). -* ``Compensate input`` (default checked, *Parallel Lee* and *Superpixel*) and ``Min input level`` (default 0.2: the transmission needed is at most 5 times the one at the peak of the beam, a lower level leaves little to the centre): the - mirrors multiply the amplitude of the input beam, so the amplitude to encode is the target divided by the input - amplitude, scaled so that no mirror has to give more than the input (4f setups: the magnification only changes the - axes, the arrays keep their shape). Where the input is below the minimum level (a fraction of its maximum) the - mirrors are off and the target cannot be obtained: this region is outlined in red on the target, modulator and output views of - the extension (the same pixels in 4f, only the axes are scaled), is in the ``unreachable`` data of the algorithm and - its fraction of the target is ``unreachable_fraction``. Unchecked, the output is the target times the beam profile. For *Superpixel* - the input is averaged over each superpixel. +* The compensation of the input beam is not a setting of the algorithm: see *Input compensation* below. * ``Remove carrier`` (default checked), ``Carrier from`` and ``Carrier factor``: see below. * ``Order position``: a read-only text, updated with the periods, giving the position of the order to filter, and the slices of a mask around it that can be copied to the slices of the *Intermediate Masking*. @@ -245,3 +240,31 @@ Minimize and TorchOptim *Minimize* only: ``Method`` of the minimizer (default l-bfgs): bfgs, l-bfgs, cg, newton-cg, newton-exact, dogleg, trust-ncg, trust-exact or trust-krylov. + + +Input compensation +------------------ + +The algorithms that compute the pattern of the modulator from the target (*Parallel Lee*, *Superpixel* and the +checkerboard *OL2014*) give, without compensation, a target multiplied by the amplitude profile of the input beam. The +group ``Input Compensation`` of the settings of the algorithm app (shown for these algorithms only, like the initial +phase for the algorithms that have one) chooses what is done: + +* ``NoCompensation``: the output is the target times the profile of the beam. +* ``DivideByInput`` (default): the amplitude to encode is the target divided by the input amplitude, scaled so that no + pixel has to give more than the input. ``Min input level`` (default 0.2: the transmission needed is at most 5 times + the one at the peak of the beam, a lower level leaves little to the centre) is the fraction of the maximum of the + input amplitude below which the target cannot be obtained: this *unreachable* region is off (null transmission). For + *Superpixel* the input is averaged over each superpixel. 4f setups: the magnification only changes the axes, the + arrays keep their shape. + +The unreachable region is outlined in red, **as soon as the compensation is chosen** and without running the algorithm, +on the input and target loaders and on the target views; after a run also on the modulator and output views of the +extension. It is in the ``unreachable`` data of the algorithm and its fraction of the target is +``unreachable_fraction``. In a script, ``set_compensation(app, 'DivideByInput', {'min_input_level': 0.3})`` of +``headless_algorithms`` chooses the compensation and ``algo.preview_unreachable()`` gives the region. + +A compensation is a class of the package ``algorithms/compensations``, registered with +``CompensationFactory.register_compensation()``, with its own ``params``, like an initial phase: another type (for +instance for a 2f setup) is added by writing one more module. An algorithm that uses it sets ``INPUT_COMPENSATION = True`` +and calls ``self.compensate_target(amplitude)``. diff --git a/src/pymodaq_plugins_beam_shaping/__init__.py b/src/pymodaq_plugins_beam_shaping/__init__.py index 9f2ed28..7bf2353 100644 --- a/src/pymodaq_plugins_beam_shaping/__init__.py +++ b/src/pymodaq_plugins_beam_shaping/__init__.py @@ -11,6 +11,7 @@ from .field import LoaderFactory, register_loaders from .algorithms.factory import AlgorithmFactory, register_algorithms from .algorithms.ini_phase import register_phases +from .algorithms.compensation import register_compensations from .algorithms.stopping import register_stoppings logger = set_logger(get_module_name(__file__)) @@ -26,6 +27,11 @@ register_phases() logger.info('****************************************') +logger.info('****************************************') +logger.info('Registering Optical Shaping compensations of the input beam') +register_compensations() +logger.info('****************************************') + logger.info('****************************************') logger.info('Registering Optical Shaping stopping criteria') diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py index 240b14c..4a9eed9 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py @@ -16,6 +16,7 @@ from pymodaq_plugins_beam_shaping.algorithms.utils import (AlgoType, AlgoStatus, ApplyMaskTo, LensSetup, CrossTalk, PhaseManipulation) from pymodaq_plugins_beam_shaping.field import Field +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationBase from pymodaq_plugins_beam_shaping.utilities import sizing from pymodaq_plugins_beam_shaping.utilities.masking import MaskType @@ -52,6 +53,7 @@ class AlgoBase(AlgoParameterManager, metaclass=ABCMeta): # the modulators the algorithm can compute a mask for (a shaper modulating both accepts any algorithm) MODULATOR_TYPES: tuple[ModulatorType] = (ModulatorType.PHASE, ) INI_PHASE = True # if True, the algorithm will init an initial phase + INPUT_COMPENSATION = False # if True, the algorithm uses the compensation of the input beam chosen in the app ITERATIVE = False MANUAL_LOOP = True RECOMPUTE_ON_CHANGE = False # if True, the algorithm is run again when one of its settings changes @@ -284,6 +286,41 @@ def unreachable_fraction(self) -> float: asked = self._target_field.amplitude > 0 return float(np.sum(self._unreachable_mask & asked) / max(np.sum(asked), 1)) + @property + def compensation(self) -> Optional[CompensationBase]: + """ The compensation of the input beam chosen in the app, None if this algorithm does not use one""" + if not self.INPUT_COMPENSATION: + return None + compensation = getattr(self.parent_app, 'compensation', None) + if compensation is None: # no app: the default compensation + from pymodaq_plugins_beam_shaping.utilities.headless_algorithms import make_compensation + compensation = make_compensation() + return compensation + + @property + def input_block(self) -> int: + """ Size of the blocks of modulator pixels that see the same input amplitude (a superpixel), 1 if none""" + return 1 + + def compensate_target(self, target: np.ndarray) -> np.ndarray: + """ The amplitude to ask to the modulator to get the target, after the compensation of the input beam, and + the unreachable region it gives (:attr:`unreachable_mask`). The target itself if there is no compensation""" + compensation = self.compensation + if compensation is None: + self._unreachable_mask = None + return target + compensated, self._unreachable_mask = compensation.compensate(target, self._input_field.amplitude, + self.input_block) + return compensated + + def preview_unreachable(self) -> Optional[np.ndarray]: + """ The unreachable region the next run will have, knowing the input beam and the compensation only (None: + no region)""" + compensation = self.compensation + if compensation is None or self._input_field is None or self._input_field.amplitude is None: + return None + return compensation.unreachable(self._input_field.amplitude, self.input_block) + def set_phase_in_modulator_plane(self, phase: np.ndarray, induced_amplitude: np.ndarray = None): if phase.shape == self._modulator_field.shape: phase = phase.copy() diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py index a46e2d7..7990402 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py @@ -34,6 +34,7 @@ from pymodaq_plugins_beam_shaping.algorithms.factory import AlgorithmFactory from pymodaq_plugins_beam_shaping.algorithms.algo_base import AlgoBase from pymodaq_plugins_beam_shaping.algorithms.ini_phase import PhaseFactory, PhaseBase +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationFactory, CompensationBase from pymodaq_plugins_beam_shaping.algorithms.stopping import StoppingFactory, StoppingBase from pymodaq_plugins_beam_shaping.algorithms.utils import (AlgoStatus, ApplyMaskTo, LensSetup, CrossTalk, PhaseManipulation) @@ -53,6 +54,7 @@ algo_factory = AlgorithmFactory() phase_factory = PhaseFactory() +compensation_factory = CompensationFactory() stopping_factory = StoppingFactory() algo_config = AlgoConfig() @@ -120,6 +122,16 @@ class AlgoApp(CustomApp): 'limits': phase_factory.phases}, {'title': 'Phase Parameters', 'name': 'phase_params', 'type': 'group', 'children': []}, ]}, + {'title': 'Input Compensation', 'name': 'compensation_group', 'type': 'group', + 'tip': 'Compensation of the profile of the input beam, for the algorithms that compute the pattern of the ' + 'modulator from the target (they use it, the others do not show this group)', + 'children': [ + {'title': 'Compensation:', 'name': 'compensation_factory', 'type': 'list', + 'value': 'DivideByInput' if 'DivideByInput' in compensation_factory.compensations + else compensation_factory.compensations[0], + 'limits': compensation_factory.compensations}, + {'title': 'Compensation Parameters', 'name': 'compensation_params', 'type': 'group', 'children': []}, + ]}, {'title': 'Stopping Criteria:', 'name': 'stopping', 'expanded': True, 'type': 'group', 'children': [ {'title': 'Stopping Type', 'name': 'stopping_type', 'type': 'list', @@ -158,6 +170,7 @@ class AlgoApp(CustomApp): command_runner = QtCore.Signal(ThreadCommand) slm_field_signal = QtCore.Signal(Field) algo_changed = QtCore.Signal(AlgoBase) + compensation_changed = QtCore.Signal() # the compensation of the input beam or one of its parameters changed fields_to_plot = QtCore.Signal(DataToExport) def __init__(self, dockarea, toolbar: QtWidgets.QToolBar=None, shaper: Shaper = None): @@ -192,6 +205,12 @@ def __init__(self, dockarea, toolbar: QtWidgets.QToolBar=None, shaper: Shaper = 'visible': self.settings['ini_phase_group', 'ini_phase_factory'] == phase, 'children': phase_factory.get_phase(phase).params}) + for compensation in compensation_factory.compensations: + self.settings.child('compensation_group', 'compensation_params').addChild( + {'title': compensation, 'name': compensation, 'type': 'group', + 'visible': self.settings['compensation_group', 'compensation_factory'] == compensation, + 'children': compensation_factory.get_compensation(compensation).params}) + for stop in stopping_factory.stops: self.settings.child('stopping').addChild( {'title': stop, 'name': stop, 'type': 'group', @@ -347,6 +366,7 @@ def set_algorithm(self, algo_name: str = None): plugin_config.save() self.settings.child('ini_phase_group').show(self._algorithm.INI_PHASE) + self.settings.child('compensation_group').show(self._algorithm.INPUT_COMPENSATION) self.settings.child(str(ApplyMaskTo.INTERMEDIATE)).show(self._algorithm.SETUP_TYPE == LensSetup.FourF) self.settings.child('stopping').show(self._algorithm.ITERATIVE == True) @@ -385,6 +405,13 @@ def ini_phase_modulator(self) -> PhaseBase: self.settings['ini_phase_group', 'ini_phase_factory']), self.algorithm) + @property + def compensation(self) -> CompensationBase: + """ The compensation of the input beam chosen in the settings""" + name = self.settings['compensation_group', 'compensation_factory'] + return compensation_factory.get_compensation(name)( + self.settings.child('compensation_group', 'compensation_params', name)) + @property def ini_stopping_criteria(self) -> StoppingBase: return stopping_factory.get_stop_class(self.settings['stopping', 'stopping_type'])( @@ -670,6 +697,11 @@ def value_changed(self, param: Parameter): if param.name() == 'ini_phase_factory': for param_child in self.settings.child('ini_phase_group', 'phase_params').children(): param_child.show(param.value() == param_child.name() and param_child.hasChildren()) + elif 'compensation_group' in putils.get_param_path(param): + if param.name() == 'compensation_factory': + for param_child in self.settings.child('compensation_group', 'compensation_params').children(): + param_child.show(param.value() == param_child.name() and param_child.hasChildren()) + self.compensation_changed.emit() elif 'crosstalk' in putils.get_param_path(param): self._algorithm.crosstalk = CrossTalk(self.settings['crosstalk', 'apply'], self.settings['crosstalk', 'value'], ) diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py index 672e1d9..d1ccdfa 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py @@ -48,18 +48,6 @@ STATUS_NOTE_CODE_ONLY = 'Code only: the filtered order is checked against the theory in simulation, not on a bench' -def block_average(array: np.ndarray, n: int) -> np.ndarray: - """ Each element replaced by the mean of its block of n x n elements (the blocks on the edges are cut)""" - ny, nx = array.shape - blocks_y, blocks_x = -(-ny // n), -(-nx // n) - padded = np.zeros((blocks_y * n, blocks_x * n)) - counts = np.zeros(padded.shape) - padded[:ny, :nx], counts[:ny, :nx] = array, 1. - sums = padded.reshape(blocks_y, n, blocks_x, n).sum(axis=(1, 3)) - number = counts.reshape(blocks_y, n, blocks_x, n).sum(axis=(1, 3)) - return np.kron(sums / number, np.ones((n, n)))[:ny, :nx] - - class BinaryHologram(AlgoBase): """ Base of the binary holograms of a 4f line, with a filter in the Fourier plane selecting one diffraction order @@ -76,6 +64,7 @@ class BinaryHologram(AlgoBase): SETUP_TYPE = LensSetup.FourF ITERATIVE = False INI_PHASE = False # an amplitude modulator has no phase to initialize + INPUT_COMPENSATION = True # the target is divided by the input beam, see encoded_amplitude RECOMPUTE_ON_CHANGE = True _params_carrier = [ @@ -92,16 +81,6 @@ class BinaryHologram(AlgoBase): 'tip': 'Position of the order to filter (-1, 0) in the intermediate plane, and the slices of a mask around ' 'it, to copy to the slices of the Intermediate Masking'}, ] - _params_compensation = [ - {'title': 'Compensate input:', 'name': 'compensate_input', 'type': 'bool', 'value': True, - 'tip': 'Divide the target amplitude by the amplitude of the input beam, so that the output is the target and ' - 'not the target times the beam profile. The scale of the target is then set so that no mirror has to ' - 'give more than the input'}, - {'title': 'Min input level:', 'name': 'min_input_level', 'type': 'float', 'value': 0.2, 'min': 0., - 'max': 1., 'step': 0.01, - 'tip': 'Fraction of the maximum of the input amplitude below which the mirrors are off: the target cannot ' - 'be obtained there (the region is shown in the unreachable data)'}, - ] _params_period = [ {'title': 'Period px (pxls):', 'name': 'px', 'type': 'int', 'value': 4, 'min': 2, 'tip': 'Period of the grating along x, in pixels'}, @@ -196,35 +175,15 @@ def get_carrier(self, spectrum: np.ndarray = None) -> tuple[float, float] | None for _slice, size in zip(slices, self.shape)) return tuple(self.settings['carrier_factor'] * value for value in carrier) - def encoded_amplitude(self, block: int = 1) -> np.ndarray: + def encoded_amplitude(self) -> np.ndarray: """ Amplitude to encode in the pattern, from 0 to 1: the target amplitude compensated for the beam profile - The mirrors multiply the amplitude of the input beam by their transmission t (0 or 1, in average between). To - get the target the amplitude to encode is t = target / input. The input is the amplitude seen on the - mirrors: averaged over blocks of ``block`` x ``block`` mirrors (a superpixel). The result is scaled so that - its maximum is 1 (the efficiency is the price of the flat output). Where the input is lower than the *minimum - input level* (relative to its maximum) the mirrors cannot give the amplitude requested: t is 0 there and they - are flagged in :attr:`unreachable_mask` if the target asks for light there. - - Without compensation, or if the input is null, the target normalised to one is returned. + The mirrors multiply the amplitude of the input beam by their transmission (0 or 1, in average between): see + the compensation of the input beam chosen in the app, and :attr:`input_block` for the input seen by the + mirrors of a superpixel. Without compensation (or if the input is null) the target normalised to one is + returned. """ - target = self._target_field.normalise_to_one().amplitude - input_amplitude = self._input_field.amplitude - peak = float(np.max(input_amplitude)) if input_amplitude.size else 0. - if not self.settings['compensate_input'] or peak == 0.: - self._unreachable_mask = None - return target - if input_amplitude.shape != target.shape: # not expected: the field loaders give the same shape to both - logger.warning('The input and the target do not have the same shape: the input is not compensated') - self._unreachable_mask = None - return target - if block > 1: - input_amplitude = block_average(input_amplitude, block) - reachable = input_amplitude >= self.settings['min_input_level'] * peak - transmission = np.where(reachable, target / np.where(reachable, input_amplitude, 1.), 0.) - self._unreachable_mask = ~reachable - maximum = float(np.max(transmission)) - return transmission / maximum if maximum > 0 else transmission + return self.compensate_target(self._target_field.normalise_to_one().amplitude) def compute_phase_and_or_amplitude(self, do_step=True, **kwargs): self.update_order_position() @@ -262,6 +221,7 @@ class BinaryThreshold(BinaryHologram): STATUS = AlgoStatus.TESTED STATUS_NOTE = STATUS_NOTE_CODE_ONLY ALGOTYPE = AlgoType.PHASE + INPUT_COMPENSATION = False # a phase hologram: no amplitude to encode params = ( BinaryHologram._params_period + @@ -303,7 +263,7 @@ class ParallelLee(BinaryHologram): ALGOTYPE = AlgoType.AMPLITUDE_PHASE params = ( - BinaryHologram._params_period + BinaryHologram._params_compensation + + BinaryHologram._params_period + [{'title': 'Binarize:', 'name': 'binarize', 'type': 'bool', 'value': True, 'tip': 'Binarize the pattern to 0 and 1, as a DMD can only do (width modulation of the fringes). ' 'Unchecked: the grey levels of the pattern are kept (ideal modulation)'}] + @@ -385,7 +345,11 @@ class Superpixel(BinaryHologram): {'title': 'Period py (pxls):', 'name': 'py', 'type': 'int', 'value': 16, 'readonly': True, 'tip': 'Imposed to px**2: the smallest period that lifts the degeneracy of the phase in the superpixel ' 'lattice (review of Gutiérrez-Cuevas and Popoff)'}] + - BinaryHologram._params_compensation + BinaryHologram._params_carrier) + BinaryHologram._params_carrier) + + @property + def input_block(self) -> int: + return self.settings['px'] # the input is averaged over a superpixel def fix_period(self) -> bool: if self.settings['py'] != self.settings['px'] ** 2: @@ -398,7 +362,7 @@ def compute_amplitude_pattern(self) -> np.ndarray: tree, codes, values, reach = superpixel_table(n) ny, nx = self.shape xx, yy = self.compute_grid() - target = self.encoded_amplitude(block=n) * reach * np.exp(1j * self._target_field.phase) + target = self.encoded_amplitude() * reach * np.exp(1j * self._target_field.phase) # value of each superpixel: the mean of the target over its pixels (the superpixels on the edges are cut) blocks_y, blocks_x = -(-ny // n), -(-nx // n) diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py index 5787f04..c98a28b 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py @@ -45,6 +45,7 @@ class OL2014(AlgoBase): ALGOTYPE = AlgoType.AMPLITUDE_PHASE SETUP_TYPE = LensSetup.FourF ITERATIVE = False + INPUT_COMPENSATION = True # cos(beta) is the amplitude of the target to divide by the input beam RECOMPUTE_ON_CHANGE = True params = [ @@ -66,7 +67,9 @@ def compute_phase_and_or_amplitude(self, do_step=True, **kwargs): calculated_field: Field = deepcopy(self._target_field) - beta = np.arccos(calculated_field.amplitude / np.max(calculated_field.amplitude) / self.settings['divider']) + # the modulator multiplies the input beam: the amplitude to ask to it is the target divided by the beam (max 1) + amplitude = self.compensate_target(calculated_field.amplitude / np.max(calculated_field.amplitude)) + beta = np.arccos(np.clip(amplitude / np.max(amplitude) / self.settings['divider'], -1., 1.)) theta_field = Field('theta', phase=calculated_field.phase + beta) alpha_field = Field('alpha', phase=calculated_field.phase - beta) diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/compensation.py b/src/pymodaq_plugins_beam_shaping/algorithms/compensation.py new file mode 100644 index 0000000..7d726e5 --- /dev/null +++ b/src/pymodaq_plugins_beam_shaping/algorithms/compensation.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +"""Compensation of the beam profile of the input beam, a piece of code of its own like the initial phase + +The modulator multiplies the input beam by what it is asked to do: for an algorithm that computes the pattern of the +modulator from the target directly (binary holograms, checkerboard), the output is the target times the profile of the +beam, unless the pattern is computed for a target divided by this profile. Such a compensation can not give light +where the input has none: this region is *unreachable*. + +A compensation is a class registered in the :class:`CompensationFactory`, with its own parameters shown in the +settings of the algorithm app, in the modules of the package ``compensations``. It works on arrays only. +""" +from abc import ABC, abstractmethod +from importlib import import_module +from pathlib import Path +from typing import Callable, Optional + +import numpy as np + +from pymodaq_gui.parameter import Parameter +from pymodaq_utils.logger import set_logger, get_module_name + +logger = set_logger(get_module_name(__file__)) + +NO_COMPENSATION = 'NoCompensation' # name of the compensation that does nothing + + +def register_compensations(parent_module_name: str = 'pymodaq_plugins_beam_shaping'): + """ Browse the modules containing compensations and register them in the factory""" + compensations = [] + try: + compensation_module = import_module(f'{parent_module_name}.algorithms.compensations') + compensation_path = Path(compensation_module.__path__[0]) + for file in sorted(compensation_path.iterdir()): + if file.is_file() and file.suffix == '.py' and file.stem != '__init__': + try: + compensations.append(import_module(f'.{file.stem}', compensation_module.__name__)) + except (ModuleNotFoundError, NotImplementedError) as e: + logger.warning(str(e)) + except ModuleNotFoundError as e: + logger.warning(str(e)) + return compensations + + +def block_average(array: np.ndarray, n: int) -> np.ndarray: + """ Each element replaced by the mean of its block of n x n elements (the blocks on the edges are cut)""" + ny, nx = array.shape + blocks_y, blocks_x = -(-ny // n), -(-nx // n) + padded = np.zeros((blocks_y * n, blocks_x * n)) + counts = np.zeros(padded.shape) + padded[:ny, :nx], counts[:ny, :nx] = array, 1. + sums = padded.reshape(blocks_y, n, blocks_x, n).sum(axis=(1, 3)) + number = counts.reshape(blocks_y, n, blocks_x, n).sum(axis=(1, 3)) + return np.kron(sums / number, np.ones((n, n)))[:ny, :nx] + + +class CompensationBase(ABC): + """ Base class of the compensations of the input beam + + Parameters + ---------- + settings: Parameter + the group holding the parameters defined in :attr:`params` + """ + + params: list[dict] = [] # definition of the specific parameters of the compensation + + def __init__(self, settings: Parameter): + self.settings = settings + + @abstractmethod + def compensate(self, target: np.ndarray, input_amplitude: np.ndarray, block: int = 1 + ) -> tuple[np.ndarray, Optional[np.ndarray]]: + """ The amplitude to ask to the modulator to get the target with this input beam + + Parameters + ---------- + target: the amplitude of the target + input_amplitude: the amplitude of the input beam on the modulator, of the same shape + block: the input seen by the modulator is its average over blocks of block x block pixels (a superpixel) + + Returns + ------- + the compensated amplitude, and the boolean array of the unreachable region (None if there is no such region) + """ + + def unreachable(self, input_amplitude: np.ndarray, block: int = 1) -> Optional[np.ndarray]: + """ The region where the target cannot be obtained, knowing only the input beam (None if no such region)""" + return self.compensate(np.ones_like(input_amplitude, dtype=float), input_amplitude, block)[1] + + +class CompensationFactory: + """ The factory class for creating compensations of the input beam""" + + _registry: dict[str, type[CompensationBase]] = {} + + @classmethod + def register_compensation(cls) -> Callable: + """ Class decorator to register a compensation, above the definition of a CompensationBase class""" + + def inner_wrapper(wrapped_class: type[CompensationBase]) -> type[CompensationBase]: + name = wrapped_class.__name__ + if name not in cls._registry: + cls._registry[name] = wrapped_class + return wrapped_class + + return inner_wrapper + + @classmethod + def get_compensation(cls, name: str) -> type[CompensationBase]: + if name not in cls._registry: + raise ValueError(f'{name} is not a supported compensation of the input beam.') + return cls._registry[name] + + @property + def compensations(self) -> list[str]: + """ The names of the compensations, the one that does nothing first""" + return sorted(self._registry, key=lambda name: (name != NO_COMPENSATION, name)) diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/compensations/__init__.py b/src/pymodaq_plugins_beam_shaping/algorithms/compensations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/compensations/divide_by_input.py b/src/pymodaq_plugins_beam_shaping/algorithms/compensations/divide_by_input.py new file mode 100644 index 0000000..10fd449 --- /dev/null +++ b/src/pymodaq_plugins_beam_shaping/algorithms/compensations/divide_by_input.py @@ -0,0 +1,40 @@ +import numpy as np + +from pymodaq_utils.logger import set_logger, get_module_name + +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationBase, CompensationFactory, block_average + +logger = set_logger(get_module_name(__file__)) + + +@CompensationFactory.register_compensation() +class DivideByInput(CompensationBase): + """ The target is divided by the amplitude of the input beam, so that the output is the target and not the target + times the beam profile + + The modulator multiplies the amplitude of the input beam by a transmission t (0 to 1). To get the target, t is + target / input, scaled so that its maximum is 1 (the efficiency is the price of the flat output). Where the input + is lower than the *minimum input level* (relative to its maximum) the target cannot be obtained: t is 0 and the + pixel belongs to the unreachable region. + """ + + params = [ + {'title': 'Min input level:', 'name': 'min_input_level', 'type': 'float', 'value': 0.2, 'min': 0., + 'max': 1., 'step': 0.01, + 'tip': 'Fraction of the maximum of the input amplitude below which the target cannot be obtained (the ' + 'region is the unreachable one, drawn in red)'}, + ] + + def compensate(self, target: np.ndarray, input_amplitude: np.ndarray, block: int = 1): + peak = float(np.max(input_amplitude)) if input_amplitude.size else 0. + if peak == 0.: + return target, None + if input_amplitude.shape != target.shape: # not expected: the field loaders give the same shape to both + logger.warning('The input and the target do not have the same shape: the input is not compensated') + return target, None + if block > 1: + input_amplitude = block_average(input_amplitude, block) + reachable = input_amplitude >= self.settings['min_input_level'] * peak + transmission = np.where(reachable, target / np.where(reachable, input_amplitude, 1.), 0.) + maximum = float(np.max(transmission)) + return (transmission / maximum if maximum > 0 else transmission), ~reachable diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/compensations/no_compensation.py b/src/pymodaq_plugins_beam_shaping/algorithms/compensations/no_compensation.py new file mode 100644 index 0000000..7d1f07a --- /dev/null +++ b/src/pymodaq_plugins_beam_shaping/algorithms/compensations/no_compensation.py @@ -0,0 +1,11 @@ +import numpy as np + +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationBase, CompensationFactory + + +@CompensationFactory.register_compensation() +class NoCompensation(CompensationBase): + """ The output is the target times the profile of the input beam""" + + def compensate(self, target: np.ndarray, input_amplitude: np.ndarray, block: int = 1): + return target, None diff --git a/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py b/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py index 80942b2..8ed6e7c 100644 --- a/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py +++ b/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py @@ -614,6 +614,12 @@ def do_things_after_ui_setup(self): self._input_field_loader.field_signal.connect(self._algorithm.set_input_field) self._target_field_loader.field_signal.connect(self._algorithm.set_target_field) self._target_field_loader.field_signal.connect(lambda field: self.show_set_target_roi_select()) + # the unreachable region is known without a run: from the input beam, the algorithm and its compensation + # (connected after the algorithm got the fields) + self._input_field_loader.field_signal.connect(lambda field: self.update_unreachable_preview()) + self._target_field_loader.field_signal.connect(lambda field: self.update_unreachable_preview()) + self._algorithm.algo_changed.connect(lambda algo: self.update_unreachable_preview()) + self._algorithm.compensation_changed.connect(self.update_unreachable_preview) self.set_menu(self._algorithm.menu) #adds this to the menu dict (automatically added in the sharedUI) @@ -694,6 +700,11 @@ def plot_fields(self, dte: DataToExport): self.metrics_viewer.show_data(metrics.split_as_dte('Metrics')) self.other_viewers.show_data(dte) + def update_unreachable_preview(self): + """ Outline the region the next run will not reach, before any run""" + algo = self._algorithm._algorithm if self._algorithm is not None else None # not created by this call + self.show_region(algo.preview_unreachable() if algo is not None else None) + def show_region(self, unreachable): """ Outline the region the target cannot be obtained in (None: no region) on the views of the planes it has a meaning in: the input and the target loaders, the target, the modulator and the output views (not the diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index ceaa5a5..2493dd3 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -17,6 +17,7 @@ from pymodaq_plugins_beam_shaping.field.factory import LoaderFactory, register_loaders from pymodaq_plugins_beam_shaping.algorithms.factory import AlgorithmFactory, register_algorithms from pymodaq_plugins_beam_shaping.algorithms.ini_phase import PhaseFactory, register_phases +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationFactory, register_compensations from pymodaq_plugins_beam_shaping.algorithms.utils import ApplyMaskTo from pymodaq_plugins_beam_shaping.utilities import regions, sizing from pymodaq_plugins_beam_shaping.utilities.masking import MaskType @@ -35,6 +36,23 @@ def ensure_qapp(): return mkQApp('AlgorithmPlayground') +def make_compensation(name: str = 'DivideByInput', params: Optional[dict] = None): + """ A compensation of the input beam (see :mod:`algorithms.compensations`) with its parameters set""" + from pyqtgraph.parametertree import Parameter + register_compensations() + compensation_class = CompensationFactory.get_compensation(name) + settings = Parameter.create(name=name, type='group', children=compensation_class.params) + for key, value in (params or {}).items(): + settings.child(key).setValue(value) + return compensation_class(settings) + + +def set_compensation(app, name: str = 'DivideByInput', params: Optional[dict] = None): + """ Choose the compensation of the input beam of the app (as the settings of the AlgoApp do): ``'NoCompensation'`` + or ``'DivideByInput'`` with the parameter ``min_input_level``""" + app.compensation = make_compensation(name, params) + + def set_parameters(manager, values: dict): """ Set the values of the parameters of an algorithm or a loader, without using the Parameter objects. @@ -91,6 +109,7 @@ class HeadlessApp: def __init__(self, shaper: Shaper): self.shaper = shaper self.algorithm = None + self.compensation = make_compensation() # the compensation of the input beam, see set_compensation self.masks = {str(ApplyMaskTo.TARGET): None, str(ApplyMaskTo.INTERMEDIATE): None} shape = sizing.get_effective_needed_field_size(shaper) pixel_size = sizing.get_effective_slm_pixel_size(shaper) diff --git a/tests/test_algo_helpers.py b/tests/test_algo_helpers.py index 8f92093..7d55556 100644 --- a/tests/test_algo_helpers.py +++ b/tests/test_algo_helpers.py @@ -88,10 +88,11 @@ def test_the_input_beam_is_compensated_for_the_amplitude_modulators(qapp): pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, # around the filtered order, in um from the center tuple(slice((freq - half) * size, (freq + half) * size) for freq, size in zip(algo.order_frequency(), sizes))) - pg.set_parameters(algo, {'binarize': False, 'compensate_input': False}) + pg.set_parameters(algo, {'binarize': False}) + pg.set_compensation(app, 'NoCompensation') pg.run_algorithm(algo, verbose=False) raw = algo.output_field.amplitude.copy() - pg.set_parameters(algo, {'compensate_input': True}) + pg.set_compensation(app, 'DivideByInput') pg.run_algorithm(algo, verbose=False) compensated = algo.output_field.amplitude target = algo._target_field.amplitude @@ -102,7 +103,7 @@ def correlation(output): assert correlation(compensated) > correlation(raw) assert algo.unreachable_mask is not None # the pixels below the minimum input level are off, those of the mask of unreachable pixels - level = algo.settings['min_input_level'] * algo._input_field.amplitude.max() + level = app.compensation.settings['min_input_level'] * algo._input_field.amplitude.max() assert np.array_equal(algo.unreachable_mask, algo._input_field.amplitude < level) pg.set_parameters(algo, {'binarize': True}) # a mirror cannot be grey: the unreachable ones are off pg.run_algorithm(algo, verbose=False) @@ -111,7 +112,7 @@ def correlation(output): def test_compensation_can_be_switched_off(qapp): app, algo = prepare('Parallel Lee', 'amplitude') - pg.set_parameters(algo, {'compensate_input': False}) + pg.set_compensation(app, 'NoCompensation') pg.run_algorithm(algo, verbose=False) assert algo.unreachable_mask is None assert algo.unreachable_fraction == 0. @@ -166,3 +167,60 @@ def test_a_target_not_on_the_shape_of_the_input_is_not_compensated_and_says_so(q encoded = algo.encoded_amplitude() assert encoded.shape == algo._target_field.amplitude.shape and algo.unreachable_mask is None assert 'compensat' in caplog.text + + +def flat_target_through_a_gaussian_beam(algo): + ny, nx = algo.shape + y, x = np.indices((ny, nx)) + algo._input_field.amplitude = np.exp(-(((y - ny / 2) / (ny / 3)) ** 2 + ((x - nx / 2) / (nx / 3)) ** 2)) + algo._target_field.amplitude = np.ones(algo.shape) + + +def test_the_checkerboard_uses_the_compensation_too(qapp): + """ The phases of the checkerboard give an amplitude cos(beta) multiplied by the beam: the output is the target + only for a target divided by the beam""" + app, algo = prepare('OL2014 - Amplitude/Phase Checkerboard', 'phase') + flat_target_through_a_gaussian_beam(algo) + inside = algo._input_field.amplitude > 0.5 * algo._input_field.amplitude.max() + sizes = pg.regions.pixel_sizes_in_um(algo.intermediate_pixel_sizes) + pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, tuple(slice(-3 * size, 3 * size) for size in sizes)) # around the zero order + + def flatness(): + pg.run_algorithm(algo, verbose=False) + output = algo.output_field.amplitude[inside] + return output.std() / output.mean() + + pg.set_compensation(app, 'NoCompensation') + raw = flatness() + assert algo.unreachable_mask is None + pg.set_compensation(app, 'DivideByInput') + compensated = flatness() + assert algo.unreachable_mask is not None and algo.unreachable_mask.any() + assert compensated < raw / 2 + + +def test_the_unreachable_region_is_known_before_any_run(qapp): + """ What the app shows as soon as the compensation is chosen: the region of the run, without a run""" + app, algo = prepare('Parallel Lee', 'amplitude') + flat_target_through_a_gaussian_beam(algo) + preview = algo.preview_unreachable() + assert preview is not None and preview.any() + pg.run_algorithm(algo, verbose=False) + assert np.array_equal(preview, algo.unreachable_mask) + pg.set_compensation(app, 'NoCompensation') + assert algo.preview_unreachable() is None + + +def test_an_algorithm_without_compensation_has_no_unreachable_region(qapp): + """ Gerchberg-Saxton propagates the beam: the compensation does not apply to it, whatever the app says""" + app, algo = prepare('Gerchberg-Saxton', 'phase') + assert not algo.INPUT_COMPENSATION + assert algo.preview_unreachable() is None + + +def test_the_superpixel_preview_follows_its_blocks(qapp): + app, algo = prepare('Superpixel', 'amplitude') + flat_target_through_a_gaussian_beam(algo) + n = algo.settings['px'] + preview = algo.preview_unreachable() + assert np.all(preview[:n, :n] == preview[0, 0]) # one value per superpixel diff --git a/tests/test_compensation.py b/tests/test_compensation.py new file mode 100644 index 0000000..bdab075 --- /dev/null +++ b/tests/test_compensation.py @@ -0,0 +1,93 @@ +"""The compensation of the input beam: a piece of code of its own, chosen in the settings of the algorithm app like the +initial phase. Tested on arrays first, then through the algorithms that use it""" +import numpy as np +import pytest +from pyqtgraph.parametertree import Parameter + +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationFactory, register_compensations + + +@pytest.fixture(scope='module') +def factory(): + register_compensations() + return CompensationFactory() + + +def make(factory, name, **values): + """A compensation with its parameters set to the values""" + compensation_class = factory.get_compensation(name) + settings = Parameter.create(name=name, type='group', children=compensation_class.params) + for key, value in values.items(): + settings.child(key).setValue(value) + return compensation_class(settings) + + +def gaussian(shape=(32, 48), width=3.): + y, x = np.indices(shape) + return np.exp(-(((y - shape[0] / 2) / (shape[0] / width)) ** 2 + ((x - shape[1] / 2) / (shape[1] / width)) ** 2)) + + +def test_the_factory_lists_the_compensations_with_none_first(factory): + assert factory.compensations[:2] == ['NoCompensation', 'DivideByInput'] + + +def test_an_unknown_compensation_is_refused(factory): + with pytest.raises(ValueError): + factory.get_compensation('Unknown') + + +def test_no_compensation_leaves_the_target_and_has_no_unreachable_region(factory): + target = np.random.default_rng(0).random((32, 48)) + compensated, unreachable = make(factory, 'NoCompensation').compensate(target, gaussian()) + assert np.array_equal(compensated, target) and unreachable is None + + +def test_dividing_by_the_input_gives_the_transmission_that_makes_the_target(factory): + """ output = input x transmission must be the target, up to a factor: the transmission is the target over the + input, scaled to a maximum of 1, and 0 where the input is below the minimum level (relative to its maximum)""" + target, beam = np.ones((32, 48)), gaussian() + compensation = make(factory, 'DivideByInput', min_input_level=0.2) + transmission, unreachable = compensation.compensate(target, beam) + reachable = ~unreachable + assert np.array_equal(unreachable, beam < 0.2 * beam.max()) + assert unreachable.any() and reachable.any() + assert transmission.max() == pytest.approx(1.) + assert np.all(transmission[unreachable] == 0) + output = (beam * transmission)[reachable] + assert np.allclose(output, output[0]) # flat target: flat output where it can be obtained + + +def test_a_higher_minimum_level_makes_a_larger_unreachable_region(factory): + beam = gaussian() + small = make(factory, 'DivideByInput', min_input_level=0.1).unreachable(beam) + large = make(factory, 'DivideByInput', min_input_level=0.5).unreachable(beam) + assert small.sum() < large.sum() and np.all(large[small]) + + +def test_the_unreachable_region_does_not_need_the_target(factory): + """ What the preview shows before any run: the same region as the one of the compensation of a target""" + beam = gaussian() + compensation = make(factory, 'DivideByInput') + assert np.array_equal(compensation.unreachable(beam), compensation.compensate(np.ones(beam.shape), beam)[1]) + + +def test_the_input_is_averaged_over_the_blocks_of_a_superpixel(factory): + beam = gaussian() + compensation = make(factory, 'DivideByInput', min_input_level=0.3) + _, unreachable = compensation.compensate(np.ones(beam.shape), beam, block=4) + top, left = unreachable[:4, :4], unreachable[:4, :4] + assert np.all(top == top[0, 0]) and np.all(left == left[0, 0]) # one value per block + + +def test_a_null_input_is_not_compensated(factory): + target = np.ones((8, 8)) + transmission, unreachable = make(factory, 'DivideByInput').compensate(target, np.zeros((8, 8))) + assert np.array_equal(transmission, target) and unreachable is None + + +def test_an_input_of_another_shape_is_not_compensated_and_says_so(factory, caplog): + target = np.ones((8, 8)) + with caplog.at_level('WARNING'): + transmission, unreachable = make(factory, 'DivideByInput').compensate(target, gaussian()) + assert np.array_equal(transmission, target) and unreachable is None + assert 'compensat' in caplog.text diff --git a/tests/test_custom_apps.py b/tests/test_custom_apps.py index 3a0e9ef..7dca432 100644 --- a/tests/test_custom_apps.py +++ b/tests/test_custom_apps.py @@ -286,3 +286,26 @@ def test_algo_app_saves_the_pattern_of_an_amplitude_modulator_in_the_slm_node(qt assert set(np.unique(origins[('slm', 'amplitude')])) <= {0., 1.} assert not np.allclose(origins[('modulator', 'amplitude')], origins[('slm', 'amplitude')]) assert np.allclose(origins[('modulator', 'amplitude')], algo._input_field.amplitude * origins[('slm', 'amplitude')]) + + +def test_algo_app_compensation_of_the_input_beam(qtbot, dockarea): + """ The compensation is chosen in the settings of the app like the initial phase, for the algorithms that use it""" + from pymodaq_plugins_beam_shaping.algorithms.algorithm_app import AlgoApp + from pymodaq_plugins_beam_shaping.algorithms.compensations.divide_by_input import DivideByInput + + app = AlgoApp(dockarea) + group = app.settings.child('compensation_group') + assert isinstance(app.compensation, DivideByInput) # on by default + assert app.compensation.settings['min_input_level'] == 0.2 + + changes = [] + app.compensation_changed.connect(lambda: changes.append(1)) + app.settings.child('compensation_group', 'compensation_params', 'DivideByInput', 'min_input_level').setValue(0.4) + assert app.compensation.settings['min_input_level'] == 0.4 and len(changes) == 1 + group.child('compensation_factory').setValue('NoCompensation') + assert type(app.compensation).__name__ == 'NoCompensation' and len(changes) == 2 + + app.set_algorithm('Gerchberg-Saxton') + assert not group.opts['visible'] # it does not use the compensation + app.set_algorithm('Parallel Lee') + assert group.opts['visible'] diff --git a/tests/test_region_outline.py b/tests/test_region_outline.py index 4257171..52e69bc 100644 --- a/tests/test_region_outline.py +++ b/tests/test_region_outline.py @@ -223,3 +223,48 @@ def test_the_extension_sends_the_region_to_the_field_loaders(qtbot): output_viewers=types.SimpleNamespace(viewers=[]), region_outline=RegionOutline(), _target_field_loader=loader, _input_field_loader=loader), mask) assert len(regions) == 2 and all(region is mask for region in regions) + + +def _visible_outlines(viewers): + found = [] + for viewer in viewers: + image = viewer.view.data_displayer.get_image('red') + found.extend(child for child in image.childItems() if isinstance(child, pg.IsocurveItem) and child.isVisible()) + return found + + +def test_the_extension_shows_the_unreachable_region_as_soon_as_the_compensation_is_on(qtbot): + """ Before any run: the region follows the input beam, the algorithm and the compensation chosen in the app""" + from pymodaq.dashboard import create_load_dashboard + from pymodaq.utils.gui_utils.loader_utils import create_extension + from pymodaq_plugins_beam_shaping.extensions.spatial_beam_shaping import BeamShaping + + _, dashboard = create_load_dashboard() + win_ext, extension = create_extension(dashboard, BeamShaping) + try: + algo_app = extension._algorithm + algo_app.set_algorithm('Parallel Lee') + algo_app.settings.child('compensation_group', 'compensation_factory').setValue('DivideByInput') # saved settings + loaders = (extension._input_field_loader, extension._target_field_loader) + for loader in loaders: + loader.load_field() + viewers = [viewer for loader in loaders for viewer in (loader.amp_viewer, loader.phase_viewer)] + + ny, nx = extension.input_field.amplitude.shape + y, x = np.indices((ny, nx)) + input_loader = extension._input_field_loader + input_loader.field.amplitude = np.exp(-(((y - ny / 2) / (ny / 6)) ** 2 + ((x - nx / 2) / (nx / 6)) ** 2)) + input_loader.field_signal.emit(input_loader.field) # a new input beam + assert len(_visible_outlines(viewers)) == 4 # input and target loaders, amplitude and phase views + assert len(_visible_outlines(extension.target_viewers.viewers)) == 3 # intensity, amplitude, phase + + algo_app.settings.child('compensation_group', 'compensation_factory').setValue('NoCompensation') + assert _visible_outlines(viewers) == [] + + algo_app.settings.child('compensation_group', 'compensation_factory').setValue('DivideByInput') + assert len(_visible_outlines(viewers)) == 4 + + algo_app.set_algorithm('Gerchberg-Saxton') # does not use the compensation + assert _visible_outlines(viewers) == [] + finally: + extension.quit_fun() From 380478dd75c8a49a88f7faf0f31af29c94618b1f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:52:08 +0000 Subject: [PATCH 2/8] Add slm/phase to the fields of the algorithm, next to slm/amplitude, for every modulator type The phase sent to the modulator is not the modulator phase anymore once the input phase is kept in the modulator field (issue #98). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- .../algorithms/algo_base.py | 1 + .../algorithms/algorithm_app.py | 4 ++-- .../extensions/spatial_beam_shaping.py | 1 + tests/test_algo_helpers.py | 17 +++++++++++++++++ tests/test_algorithm_playground.py | 5 +++-- 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py index 4a9eed9..7fedf26 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py @@ -457,6 +457,7 @@ def get_fields_to_plot(self) -> DataToExport: self.modulator_field.amplitude_as_dwa('modulator'), self.modulator_field.phase_as_dwa('modulator'), ]) + dte.append(self.slm_field.phase_as_dwa('slm')) # what is sent to the modulator, whatever its type if self.shaper.modulator_type != ModulatorType.PHASE: # an amplitude is sent to the modulator dte.append(self.slm_field.amplitude_as_dwa('slm')) if self._unreachable_mask is not None: diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py index 7990402..df2c974 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py @@ -724,14 +724,14 @@ def process_output(self, dte: DataToExport): # the SLM field, what is sent to the modulator (not the modulator field, which contains the input beam): a # full field, with an amplitude of 1 for a phase-only modulator and a phase of 0 for an amplitude-only one - phase = dte.get_data_from_full_name('modulator/phase')[0] + phase = dte.get_data_from_full_name('slm/phase')[0] modulator_type = ModulatorType(self.shaper.modulator_type) amplitude = (np.ones_like(phase) if modulator_type == ModulatorType.PHASE else dte.get_data_from_full_name('slm/amplitude')[0]) self.slm_field_signal.emit( Field('slm', amplitude=amplitude, - phase=np.zeros_like(phase) if modulator_type == ModulatorType.AMPLITUDE else phase, + phase=phase, pixel_sizes=self._input_field.pixels_sizes)) if self.is_action_checked(Actions.SAVE_CONTINUOUS): self.save_continuous(dte) diff --git a/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py b/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py index 8ed6e7c..a74d71b 100644 --- a/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py +++ b/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py @@ -680,6 +680,7 @@ def plot_fields(self, dte: DataToExport): dte.remove(dte.get_data_from_full_name(full_name)) for full_name in ['output/amplitude', 'output/phase']]) dte_modulator = DataToExport('modulator', data=[ dte.remove(dte.get_data_from_full_name(full_name)) for full_name in ['modulator/amplitude', 'modulator/phase']]) + pop_data(dte, 'slm/phase') # in the data for the savings: the phase views are the modulator and output ones dwa_intermediate = pop_data(dte, 'intermediate/intensity') if dwa_intermediate is not None: # None means no intermediate data to plot self.intermediate_viewer.show_data(dwa_intermediate) diff --git a/tests/test_algo_helpers.py b/tests/test_algo_helpers.py index 7d55556..de33d8c 100644 --- a/tests/test_algo_helpers.py +++ b/tests/test_algo_helpers.py @@ -224,3 +224,20 @@ def test_the_superpixel_preview_follows_its_blocks(qapp): n = algo.settings['px'] preview = algo.preview_unreachable() assert np.all(preview[:n, :n] == preview[0, 0]) # one value per superpixel + + +@pytest.mark.parametrize('name, modulator_type', [('Gerchberg-Saxton', 'phase'), ('Gerchberg-Saxton', 'both'), + ('Parallel Lee', 'amplitude')]) +def test_the_phase_sent_to_the_slm_is_in_the_fields_for_every_modulator_type(qapp, name, modulator_type): + """ slm/phase is the phase of the SLM field (what is sent, without the corrections), next to slm/amplitude: the + modulator phase will not be it anymore once the input phase is kept in the modulator field""" + app, algo = prepare(name, modulator_type) + pg.run_algorithm(algo, 1, verbose=False) + dte = algo.get_fields_to_plot() + phase = dte.get_data_from_full_name('slm/phase') + assert phase is not None + assert np.array_equal(phase[0], algo.slm_field.phase) + if modulator_type == 'amplitude': + assert np.all(phase[0] == 0) # an amplitude modulator has no phase + else: + assert np.allclose(phase[0], algo.modulator_field.phase) diff --git a/tests/test_algorithm_playground.py b/tests/test_algorithm_playground.py index 9d8d027..ebaa48e 100644 --- a/tests/test_algorithm_playground.py +++ b/tests/test_algorithm_playground.py @@ -292,9 +292,10 @@ def test_no_saving_by_default(qapp): @pytest.mark.parametrize('fields, metrics, expected', [ - (True, False, {'output/amplitude', 'output/phase', 'modulator/amplitude', 'modulator/phase'}), + (True, False, {'output/amplitude', 'output/phase', 'modulator/amplitude', 'modulator/phase', 'slm/phase'}), (False, True, {'AlgoData/metrics'}), - (True, True, {'output/amplitude', 'output/phase', 'modulator/amplitude', 'modulator/phase', 'AlgoData/metrics'}), + (True, True, {'output/amplitude', 'output/phase', 'modulator/amplitude', 'modulator/phase', 'slm/phase', + 'AlgoData/metrics'}), (('modulator/phase',), True, {'modulator/phase', 'AlgoData/metrics'}), ]) def test_fields_and_metrics_saved_at_each_iteration(qapp, tmp_path, fields, metrics, expected): From eef36820b08a212c25298ebdcddedaf0dc23ede9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:52:19 +0000 Subject: [PATCH 3/8] Docs: slm/phase and slm/amplitude fields Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- docs/src/user_guide/algorithm_reference.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/src/user_guide/algorithm_reference.rst b/docs/src/user_guide/algorithm_reference.rst index f675fca..24066b6 100644 --- a/docs/src/user_guide/algorithm_reference.rst +++ b/docs/src/user_guide/algorithm_reference.rst @@ -101,7 +101,8 @@ in the review but not available. What is sent to the modulator is the *SLM field* (``slm_field`` of the algorithm, ``slm`` data): the amplitude pattern (0 and 1 for a DMD, 1 for a phase-only modulator) and the phase (0 for an amplitude-only modulator), without the corrections that the extension adds when sending. It is not the *modulator field*, the field just after the modulator: -this one is the input beam times the SLM field, and is the one used to compute the output. +this one is the input beam times the SLM field, and is the one used to compute the output. The fields of the +algorithm hold ``slm/phase`` for every type of modulator and ``slm/amplitude`` when an amplitude is sent. The two first orders of the grating carry opposite phases, and this is physical: the order at ``+ν`` carries the phase ``-φ`` of the target, the one at ``-ν`` (the order (-1, 0) of the review) carries ``+φ``. Select the order that carries From 8b8587761224f2e6fc77edc14d90a85e3896483c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:59:20 +0000 Subject: [PATCH 4/8] INPUT_COMPENSATION is the name of the default compensation of the algorithm (None: not used) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- AGENTS_BEAM_SHAPING.md | 2 +- docs/src/user_guide/algorithm_reference.rst | 5 +++-- .../algorithms/algo_base.py | 9 +++++---- .../algorithms/algorithm_app.py | 5 ++++- .../algorithms/algorithms/binary_holograms.py | 4 ++-- .../algorithms/algorithms/checker_board.py | 2 +- .../utilities/headless_algorithms.py | 2 +- tests/test_algo_helpers.py | 11 ++++++++++- tests/test_custom_apps.py | 15 +++++++++++++++ 9 files changed, 42 insertions(+), 13 deletions(-) diff --git a/AGENTS_BEAM_SHAPING.md b/AGENTS_BEAM_SHAPING.md index 2319fe0..599bb95 100644 --- a/AGENTS_BEAM_SHAPING.md +++ b/AGENTS_BEAM_SHAPING.md @@ -30,7 +30,7 @@ close to the template so that it can be updated); this file is what is specific | `algorithms/factory.py` | `AlgorithmFactory`, `register_algorithms()` and the entry point group `pymodaq_plugins_beam_shaping.algorithms` for third party algorithms. | | `algorithms/algorithms/` | The **algorithms**, one module per family (see below). | | `algorithms/ini_phases/`, `stoppings/`, `loss.py` | Initial phases, stopping criteria and loss functions used by iterative algorithms. | -| `algorithms/compensation.py`, `compensations/` | Compensation of the input beam profile (factory like the initial phases, chosen in the AlgoApp settings); an algorithm sets `INPUT_COMPENSATION = True` and calls `compensate_target`. | +| `algorithms/compensation.py`, `compensations/` | Compensation of the input beam profile (factory like the initial phases, chosen in the AlgoApp settings); an algorithm sets `INPUT_COMPENSATION` to the name of its default compensation (None: none) and calls `compensate_target`. | | `algorithms/algorithm_app.py` | `AlgoApp`: the widget running an algorithm, owning the masks, the shaper and the fields. | | `algorithms/utils.py` | Enums (`AlgoStatus`, `AlgoType`, `ApplyMaskTo`, `LensSetup`). | | `utilities/shaper.py` | `Shaper` and `ModulatorType` (phase, amplitude, both), defined in `pymodaq_plugins_utils`; `get_default_shaper()` reads the config. | diff --git a/docs/src/user_guide/algorithm_reference.rst b/docs/src/user_guide/algorithm_reference.rst index 24066b6..77f7daa 100644 --- a/docs/src/user_guide/algorithm_reference.rst +++ b/docs/src/user_guide/algorithm_reference.rst @@ -267,5 +267,6 @@ extension. It is in the ``unreachable`` data of the algorithm and its fraction o A compensation is a class of the package ``algorithms/compensations``, registered with ``CompensationFactory.register_compensation()``, with its own ``params``, like an initial phase: another type (for -instance for a 2f setup) is added by writing one more module. An algorithm that uses it sets ``INPUT_COMPENSATION = True`` -and calls ``self.compensate_target(amplitude)``. +instance for a 2f setup) is added by writing one more module. An algorithm that uses it sets ``INPUT_COMPENSATION`` to the name of its +default compensation (``'DivideByInput'`` for the algorithms above, ``None`` for an algorithm that does not use one: the +group is then hidden) and calls ``self.compensate_target(amplitude)``. diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py index 7fedf26..e7ae1f2 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py @@ -53,7 +53,8 @@ class AlgoBase(AlgoParameterManager, metaclass=ABCMeta): # the modulators the algorithm can compute a mask for (a shaper modulating both accepts any algorithm) MODULATOR_TYPES: tuple[ModulatorType] = (ModulatorType.PHASE, ) INI_PHASE = True # if True, the algorithm will init an initial phase - INPUT_COMPENSATION = False # if True, the algorithm uses the compensation of the input beam chosen in the app + INPUT_COMPENSATION: Optional[str] = None # name of the compensation of the input beam the algorithm starts + # with (the app lets the user change it), None if the algorithm does not use one ITERATIVE = False MANUAL_LOOP = True RECOMPUTE_ON_CHANGE = False # if True, the algorithm is run again when one of its settings changes @@ -289,12 +290,12 @@ def unreachable_fraction(self) -> float: @property def compensation(self) -> Optional[CompensationBase]: """ The compensation of the input beam chosen in the app, None if this algorithm does not use one""" - if not self.INPUT_COMPENSATION: + if self.INPUT_COMPENSATION is None: return None compensation = getattr(self.parent_app, 'compensation', None) - if compensation is None: # no app: the default compensation + if compensation is None: # not chosen in an app: the default one of the algorithm from pymodaq_plugins_beam_shaping.utilities.headless_algorithms import make_compensation - compensation = make_compensation() + compensation = make_compensation(self.INPUT_COMPENSATION) return compensation @property diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py index df2c974..808baa4 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py @@ -366,7 +366,10 @@ def set_algorithm(self, algo_name: str = None): plugin_config.save() self.settings.child('ini_phase_group').show(self._algorithm.INI_PHASE) - self.settings.child('compensation_group').show(self._algorithm.INPUT_COMPENSATION) + self.settings.child('compensation_group').show(self._algorithm.INPUT_COMPENSATION is not None) + if self._algorithm.INPUT_COMPENSATION is not None: # what the user saved for this algorithm is loaded after + self.settings.child('compensation_group', 'compensation_factory').setValue( + self._algorithm.INPUT_COMPENSATION) self.settings.child(str(ApplyMaskTo.INTERMEDIATE)).show(self._algorithm.SETUP_TYPE == LensSetup.FourF) self.settings.child('stopping').show(self._algorithm.ITERATIVE == True) diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py index d1ccdfa..718d7ea 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py @@ -64,7 +64,7 @@ class BinaryHologram(AlgoBase): SETUP_TYPE = LensSetup.FourF ITERATIVE = False INI_PHASE = False # an amplitude modulator has no phase to initialize - INPUT_COMPENSATION = True # the target is divided by the input beam, see encoded_amplitude + INPUT_COMPENSATION = 'DivideByInput' # the target is divided by the input beam, see encoded_amplitude RECOMPUTE_ON_CHANGE = True _params_carrier = [ @@ -221,7 +221,7 @@ class BinaryThreshold(BinaryHologram): STATUS = AlgoStatus.TESTED STATUS_NOTE = STATUS_NOTE_CODE_ONLY ALGOTYPE = AlgoType.PHASE - INPUT_COMPENSATION = False # a phase hologram: no amplitude to encode + INPUT_COMPENSATION = None # a phase hologram: no amplitude to encode params = ( BinaryHologram._params_period + diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py index c98a28b..5e8f19e 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py @@ -45,7 +45,7 @@ class OL2014(AlgoBase): ALGOTYPE = AlgoType.AMPLITUDE_PHASE SETUP_TYPE = LensSetup.FourF ITERATIVE = False - INPUT_COMPENSATION = True # cos(beta) is the amplitude of the target to divide by the input beam + INPUT_COMPENSATION = 'DivideByInput' # cos(beta) is the amplitude of the target to divide by the input beam RECOMPUTE_ON_CHANGE = True params = [ diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index 2493dd3..b3fce44 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -109,7 +109,7 @@ class HeadlessApp: def __init__(self, shaper: Shaper): self.shaper = shaper self.algorithm = None - self.compensation = make_compensation() # the compensation of the input beam, see set_compensation + self.compensation = None # the compensation of the input beam, see set_compensation (None: the default one) self.masks = {str(ApplyMaskTo.TARGET): None, str(ApplyMaskTo.INTERMEDIATE): None} shape = sizing.get_effective_needed_field_size(shaper) pixel_size = sizing.get_effective_slm_pixel_size(shaper) diff --git a/tests/test_algo_helpers.py b/tests/test_algo_helpers.py index de33d8c..c5b0db5 100644 --- a/tests/test_algo_helpers.py +++ b/tests/test_algo_helpers.py @@ -214,7 +214,7 @@ def test_the_unreachable_region_is_known_before_any_run(qapp): def test_an_algorithm_without_compensation_has_no_unreachable_region(qapp): """ Gerchberg-Saxton propagates the beam: the compensation does not apply to it, whatever the app says""" app, algo = prepare('Gerchberg-Saxton', 'phase') - assert not algo.INPUT_COMPENSATION + assert algo.INPUT_COMPENSATION is None # no default compensation: it does not use one assert algo.preview_unreachable() is None @@ -241,3 +241,12 @@ def test_the_phase_sent_to_the_slm_is_in_the_fields_for_every_modulator_type(qap assert np.all(phase[0] == 0) # an amplitude modulator has no phase else: assert np.allclose(phase[0], algo.modulator_field.phase) + + +def test_the_default_compensation_of_the_algorithm_is_used_without_the_app(qapp, monkeypatch): + """ INPUT_COMPENSATION is the name of the compensation the algorithm starts with (None: it does not use one)""" + app, algo = prepare('Parallel Lee', 'amplitude') + app.compensation = None # the app has not chosen + assert type(algo.compensation).__name__ == 'DivideByInput' + monkeypatch.setattr(type(algo), 'INPUT_COMPENSATION', 'NoCompensation') + assert type(algo.compensation).__name__ == 'NoCompensation' diff --git a/tests/test_custom_apps.py b/tests/test_custom_apps.py index 7dca432..2dfdf17 100644 --- a/tests/test_custom_apps.py +++ b/tests/test_custom_apps.py @@ -288,6 +288,21 @@ def test_algo_app_saves_the_pattern_of_an_amplitude_modulator_in_the_slm_node(qt assert np.allclose(origins[('modulator', 'amplitude')], algo._input_field.amplitude * origins[('slm', 'amplitude')]) +def test_algo_app_starts_with_the_default_compensation_of_the_algorithm(qtbot, dockarea, monkeypatch): + from pymodaq_plugins_beam_shaping.algorithms.algorithm_app import AlgoApp + from pymodaq_plugins_beam_shaping.algorithms.algorithms.binary_holograms import ParallelLee + + app = AlgoApp(dockarea) + monkeypatch.setattr(app, 'set_settings_values', lambda *args: None) # not the values saved by other runs + factory = app.settings.child('compensation_group', 'compensation_factory') + monkeypatch.setattr(ParallelLee, 'INPUT_COMPENSATION', 'NoCompensation') + app.set_algorithm('Parallel Lee') + assert factory.value() == 'NoCompensation' + monkeypatch.setattr(ParallelLee, 'INPUT_COMPENSATION', 'DivideByInput') + app.set_algorithm('Parallel Lee') + assert factory.value() == 'DivideByInput' + + def test_algo_app_compensation_of_the_input_beam(qtbot, dockarea): """ The compensation is chosen in the settings of the app like the initial phase, for the algorithms that use it""" from pymodaq_plugins_beam_shaping.algorithms.algorithm_app import AlgoApp From c68c819cd131dd69805d2f4e9e4e15b0e628a841 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 13:09:39 +0000 Subject: [PATCH 5/8] AlgoApp settings: no saving while loading, own settings of the algorithm saved and loaded Loading a setting called value_changed, which saved all the settings: the ones not loaded yet were replaced by their current values (only the first setting of the tree came back after a restart, and values leaked from an algorithm to another). Also the OL2014 name has no slash anymore (it is a section of the config file). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- docs/src/user_guide/algorithm_reference.rst | 6 +- docs/src/user_guide/algorithms.rst | 2 +- .../algorithms/algorithm_app.py | 55 ++++++- .../algorithms/algorithms/checker_board.py | 2 +- tests/test_algo_app_settings.py | 134 ++++++++++++++++++ tests/test_algo_helpers.py | 2 +- 6 files changed, 190 insertions(+), 11 deletions(-) create mode 100644 tests/test_algo_app_settings.py diff --git a/docs/src/user_guide/algorithm_reference.rst b/docs/src/user_guide/algorithm_reference.rst index 77f7daa..a02cf72 100644 --- a/docs/src/user_guide/algorithm_reference.rst +++ b/docs/src/user_guide/algorithm_reference.rst @@ -8,6 +8,10 @@ Sizes of pixels in these settings follow the shaper (see :doc:`shapers`). Settings shared by the algorithms --------------------------------- +The settings of the algorithm app (initial phase, masks, crosstalk, compensation of the input beam...) and the own +settings of each algorithm are saved in the configuration file, **per algorithm**, and loaded back when the algorithm +is selected (an algorithm never run keeps the values of the previous one). + Most algorithms start from an *initial phase* of the modulator, which is also a choice in the settings: * **Random**: a random phase. @@ -40,7 +44,7 @@ that removes the undiffracted light. Not iterative. Implements the five methods * ``Diffractive Models``: *Relative Amplitude* (method A), *Scattering* (B), *Davis* (C), *Bolduc* (D) or *Arrizon* (E). * ``Order N`` (default 10). -OL2014 - Amplitude/Phase Checkerboard +OL2014 - Amplitude-Phase Checkerboard ------------------------------------- Creates **amplitude and phase** images with a phase-only modulator in a **4f** line with a filter in the Fourier plane, diff --git a/docs/src/user_guide/algorithms.rst b/docs/src/user_guide/algorithms.rst index c1a6509..f094a15 100644 --- a/docs/src/user_guide/algorithms.rst +++ b/docs/src/user_guide/algorithms.rst @@ -36,7 +36,7 @@ BeamShaping itself, then the ones provided by other installed packages (see :doc - Amplitude images with a phase-only modulator and a filter in the Fourier plane, several diffractive models (:cite:t:`Clark2016`). * - Direct diffractive modulation - - OL2014 - Amplitude/Phase Checkerboard + - OL2014 - Amplitude-Phase Checkerboard - 4f - ❌ - ✅ diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py index 808baa4..aed3fb0 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py @@ -1,5 +1,7 @@ from abc import ABCMeta, abstractproperty from typing import Union +from contextlib import contextmanager + import numpy as np from qtpy import QtWidgets, QtCore, QtGui @@ -52,6 +54,8 @@ logger = set_logger(get_module_name(__file__)) +ALGORITHM_SETTINGS = 'algorithm_settings' # section of the config of an algorithm for its own settings + algo_factory = AlgorithmFactory() phase_factory = PhaseFactory() compensation_factory = CompensationFactory() @@ -110,6 +114,7 @@ def status_text(algo_class: type[AlgoBase]) -> str: class AlgoApp(CustomApp): save_settings = True + _loading_settings = 0 # number of loads of settings in progress ALGORITHM_COMBO_TIP = 'select the algorithm to compute the phase' h5_base_group_name = ContinuousSaver.base_name # the name of the files of the H5Manager show_h5file_statusbar_widgets = True # the LED of the state of the h5 file (and SWMR) of the H5Manager @@ -273,13 +278,44 @@ def quit_fun(self): super().quit_fun() self.close_file() + @property + def loading_settings(self) -> bool: + """ True while settings are loaded from the config: nothing is saved, nor computed, as a result of it""" + return self._loading_settings > 0 + + @contextmanager + def _loading(self): + self._loading_settings += 1 + try: + yield + finally: + self._loading_settings -= 1 + def set_settings_values(self, param: Parameter = None): - self.config_saver_loader.load_config(param) + # loading a setting calls value_changed, which saves all the settings: the ones not loaded yet would be + # replaced by their current values before they are loaded + with self._loading(): + self.config_saver_loader.load_config(param) def save_algo_parameters(self): - if self.save_settings: + if self.save_settings and not self.loading_settings: self.config_saver_loader.save_config() + def set_algorithm_settings(self): + """ Load the own settings of the algorithm saved for it, and save them from now on when they change""" + algorithm = self._algorithm + loader = ConfigSaverLoader(algorithm.settings, algo_config, [algorithm.ALGO_NAME, ALGORITHM_SETTINGS]) + with self._loading(): # the algorithm is not run, nothing is saved before all are loaded + try: + loader.load_config() + except Exception as e: # a setting that cannot be set must not prevent the use of the algorithm + logger.warning(f'The saved settings of {algorithm.ALGO_NAME} could not all be loaded: {e}') + algorithm.settings.sigTreeStateChanged.connect(lambda *args: self._save_algorithm_settings(loader)) + + def _save_algorithm_settings(self, loader: ConfigSaverLoader): + if self.save_settings and not self.loading_settings: + loader.save_config() + def save(self, fname: H5Saver | Path = None, where: str = '/RawData', group_name: str = 'Algorithm', title: str = ''): """ Save the fields, algorithm settings into a hdf5 file @@ -367,9 +403,6 @@ def set_algorithm(self, algo_name: str = None): self.settings.child('ini_phase_group').show(self._algorithm.INI_PHASE) self.settings.child('compensation_group').show(self._algorithm.INPUT_COMPENSATION is not None) - if self._algorithm.INPUT_COMPENSATION is not None: # what the user saved for this algorithm is loaded after - self.settings.child('compensation_group', 'compensation_factory').setValue( - self._algorithm.INPUT_COMPENSATION) self.settings.child(str(ApplyMaskTo.INTERMEDIATE)).show(self._algorithm.SETUP_TYPE == LensSetup.FourF) self.settings.child('stopping').show(self._algorithm.ITERATIVE == True) @@ -392,7 +425,12 @@ def set_algorithm(self, algo_name: str = None): self._iter_count_widget.setVisible(self._algorithm.ITERATIVE) self.config_saver_loader.base_path = [self._algorithm.ALGO_NAME] - self.set_settings_values() + with self._loading(): + if self._algorithm.INPUT_COMPENSATION is not None: # the default one, then what was saved for this algorithm + self.settings.child('compensation_group', 'compensation_factory').setValue( + self._algorithm.INPUT_COMPENSATION) + self.set_settings_values() + self.set_algorithm_settings() self.check_slices() self.algo_changed.emit(self._algorithm) @@ -637,6 +675,8 @@ def compute_phase_loop(self): child.setOpts(enabled=True) def compute_phase_and_or_amplitude(self): + if self.loading_settings: # a setting of the algorithm is being loaded, not changed by the user + return self.command_runner.emit(ThreadCommand(Actions.STEP, attribute=self._current_phase)) self.set_action_enabled(Actions.CONTINUOUS, True) @@ -719,7 +759,8 @@ def value_changed(self, param: Parameter): self.save_algo_parameters() def algo_settings_changed(self): - self.algo_changed.emit(self.algorithm) + if not self.loading_settings: + self.algo_changed.emit(self.algorithm) def process_output(self, dte: DataToExport): self._current_data = dte diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py index 5e8f19e..d9c1850 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py @@ -39,7 +39,7 @@ class OL2014(AlgoBase): of the used lens """ - ALGO_NAME = 'OL2014 - Amplitude/Phase Checkerboard' + ALGO_NAME = 'OL2014 - Amplitude-Phase Checkerboard' STATUS = AlgoStatus.TESTED STATUS_NOTE = 'Checked by the developer: code and real setup' ALGOTYPE = AlgoType.AMPLITUDE_PHASE diff --git a/tests/test_algo_app_settings.py b/tests/test_algo_app_settings.py new file mode 100644 index 0000000..87783e8 --- /dev/null +++ b/tests/test_algo_app_settings.py @@ -0,0 +1,134 @@ +"""The settings of the AlgoApp are saved in a config file and loaded back: the ones of the app (per algorithm) and the +own settings of the algorithm. Tested on a fake config in memory, not the one of the user""" +import pytest +from qtpy import QtWidgets + +from pymodaq_utils.config import ConfigError +from pymodaq_gui.utils.dock import DockArea + +OL2014 = 'OL2014 - Amplitude-Phase Checkerboard' + + +class FakeConfig: + """ What the ConfigSaverLoader asks to a config: a call with the path, item assignment, save""" + + def __init__(self): + self.data = {} + + def __call__(self, *path): + if tuple(path) not in self.data: + raise ConfigError(path) + return self.data[tuple(path)] + + def __setitem__(self, path, value): + self.data[tuple(path)] = value + + def save(self): + pass + + +@pytest.fixture +def config(monkeypatch): + from pymodaq_plugins_beam_shaping.algorithms import algorithm_app + fake = FakeConfig() + monkeypatch.setattr(algorithm_app, 'algo_config', fake) + return fake + + +@pytest.fixture +def make_app(qtbot, config): + windows = [] + + def make(): + from pymodaq_plugins_beam_shaping.algorithms.algorithm_app import AlgoApp + area = DockArea() + window = QtWidgets.QMainWindow() + window.setCentralWidget(area) + qtbot.addWidget(window) + window.show() + windows.append(window) + return AlgoApp(area) + + return make + + +def set_app_settings(app, values): + for path, value in values.items(): + app.settings.child(*path.split('/')).setValue(value) + + +def app_settings(app, paths): + return {path: app.settings[tuple(path.split('/'))] for path in paths} + + +APP_VALUES = {'crosstalk/apply': True, 'crosstalk/value': 0.8, 'phase_manipulation/wrap_value': 4, + 'ini_phase_group/ini_phase_factory': 'QuadraticPhase', + 'compensation_group/compensation_params/DivideByInput/min_input_level': 0.4} + + +def test_no_algorithm_has_a_slash_in_its_name(): + """ The name is a section of the config file, a slash would make a path of it""" + from pymodaq_plugins_beam_shaping.algorithms.factory import AlgorithmFactory + assert all('/' not in name for name in AlgorithmFactory.algorithms_registry) + assert OL2014 in AlgorithmFactory.algorithms_registry + + +def test_the_settings_of_the_app_are_back_after_a_restart(make_app): + """ Not only the first one of the tree: loading a setting must not save the others as they are""" + app = make_app() + app.set_algorithm('Parallel Lee') + set_app_settings(app, APP_VALUES) + restarted = make_app() + restarted.set_algorithm('Parallel Lee') + assert app_settings(restarted, APP_VALUES) == APP_VALUES + + +def test_the_settings_of_an_algorithm_do_not_leak_to_another(make_app): + app = make_app() + app.set_algorithm('Parallel Lee') + set_app_settings(app, APP_VALUES) + app.set_algorithm(OL2014) + set_app_settings(app, {'crosstalk/apply': False, 'crosstalk/value': 0.1, + 'compensation_group/compensation_params/DivideByInput/min_input_level': 0.7}) + app.set_algorithm('Parallel Lee') + assert app_settings(app, APP_VALUES) == APP_VALUES + app.set_algorithm(OL2014) + assert app_settings(app, ['crosstalk/apply', 'crosstalk/value']) == {'crosstalk/apply': False, + 'crosstalk/value': 0.1} + + +def test_the_default_compensation_of_an_algorithm_does_not_replace_what_was_saved_for_another(make_app, config): + app = make_app() + app.set_algorithm('Parallel Lee') + app.settings.child('compensation_group', 'compensation_factory').setValue('NoCompensation') + app.set_algorithm(OL2014) # its default is DivideByInput + assert config.data[('Parallel Lee', 'compensation_group', 'compensation_factory')] == 'NoCompensation' + app.set_algorithm('Parallel Lee') + assert app.settings['compensation_group', 'compensation_factory'] == 'NoCompensation' + + +def test_the_own_settings_of_the_algorithm_are_saved_and_loaded(make_app, config): + app = make_app() + app.set_algorithm('Parallel Lee') + app.algorithm.settings.child('px').setValue(8) + app.algorithm.settings.child('binarize').setValue(False) + app.set_algorithm('Gerchberg-Saxton') + app.set_algorithm('Parallel Lee') + assert app.algorithm.settings['px'] == 8 and app.algorithm.settings['binarize'] is False + restarted = make_app() + restarted.set_algorithm('Parallel Lee') + assert restarted.algorithm.settings['px'] == 8 and restarted.algorithm.settings['binarize'] is False + + +def test_loading_the_own_settings_does_not_run_the_algorithm(make_app): + """ OL2014 is recomputed when one of its settings changes: not while loading them""" + app = make_app() + app.set_algorithm(OL2014) + app.algorithm.settings.child('block_size').setValue(7) + app.set_algorithm('Parallel Lee') + commands = [] + app.command_runner.connect(commands.append) # what asks the runner to compute + app.set_algorithm(OL2014) + assert app.algorithm.settings['block_size'] == 7 and commands == [] + app.algorithm.settings.child('block_size').setValue(6) # a change of the user does run it + assert len(commands) == 1 diff --git a/tests/test_algo_helpers.py b/tests/test_algo_helpers.py index c5b0db5..5e9b1d9 100644 --- a/tests/test_algo_helpers.py +++ b/tests/test_algo_helpers.py @@ -179,7 +179,7 @@ def flat_target_through_a_gaussian_beam(algo): def test_the_checkerboard_uses_the_compensation_too(qapp): """ The phases of the checkerboard give an amplitude cos(beta) multiplied by the beam: the output is the target only for a target divided by the beam""" - app, algo = prepare('OL2014 - Amplitude/Phase Checkerboard', 'phase') + app, algo = prepare('OL2014 - Amplitude-Phase Checkerboard', 'phase') flat_target_through_a_gaussian_beam(algo) inside = algo._input_field.amplitude > 0.5 * algo._input_field.amplitude.max() sizes = pg.regions.pixel_sizes_in_um(algo.intermediate_pixel_sizes) From 997bfda8dfb88b5d13a1b4bd129c0965149dc131 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 20:02:24 +0000 Subject: [PATCH 6/8] Compensations: names as a StrEnum tied to the factory registry Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- AGENTS_BEAM_SHAPING.md | 2 +- src/pymodaq_plugins_beam_shaping/__init__.py | 3 +- .../algorithms/algo_base.py | 4 +-- .../algorithms/algorithm_app.py | 5 ++-- .../algorithms/algorithms/binary_holograms.py | 3 +- .../algorithms/algorithms/checker_board.py | 3 +- .../algorithms/compensation.py | 22 +++++++++++++-- .../utilities/headless_algorithms.py | 6 ++-- tests/conftest.py | 28 +++++++++++++++++++ tests/test_algo_app_settings.py | 27 ------------------ tests/test_algo_helpers.py | 3 +- tests/test_compensation.py | 7 +++++ tests/test_custom_apps.py | 9 +++--- 13 files changed, 75 insertions(+), 47 deletions(-) diff --git a/AGENTS_BEAM_SHAPING.md b/AGENTS_BEAM_SHAPING.md index 599bb95..9b9dcfa 100644 --- a/AGENTS_BEAM_SHAPING.md +++ b/AGENTS_BEAM_SHAPING.md @@ -30,7 +30,7 @@ close to the template so that it can be updated); this file is what is specific | `algorithms/factory.py` | `AlgorithmFactory`, `register_algorithms()` and the entry point group `pymodaq_plugins_beam_shaping.algorithms` for third party algorithms. | | `algorithms/algorithms/` | The **algorithms**, one module per family (see below). | | `algorithms/ini_phases/`, `stoppings/`, `loss.py` | Initial phases, stopping criteria and loss functions used by iterative algorithms. | -| `algorithms/compensation.py`, `compensations/` | Compensation of the input beam profile (factory like the initial phases, chosen in the AlgoApp settings); an algorithm sets `INPUT_COMPENSATION` to the name of its default compensation (None: none) and calls `compensate_target`. | +| `algorithms/compensation.py`, `compensations/` | Compensation of the input beam profile (factory like the initial phases, chosen in the AlgoApp settings); an algorithm sets `INPUT_COMPENSATION` to the `Compensations` (StrEnum, add a member for a new compensation) member of its default compensation (None: none) and calls `compensate_target`. | | `algorithms/algorithm_app.py` | `AlgoApp`: the widget running an algorithm, owning the masks, the shaper and the fields. | | `algorithms/utils.py` | Enums (`AlgoStatus`, `AlgoType`, `ApplyMaskTo`, `LensSetup`). | | `utilities/shaper.py` | `Shaper` and `ModulatorType` (phase, amplitude, both), defined in `pymodaq_plugins_utils`; `get_default_shaper()` reads the config. | diff --git a/src/pymodaq_plugins_beam_shaping/__init__.py b/src/pymodaq_plugins_beam_shaping/__init__.py index 7bf2353..e0924d5 100644 --- a/src/pymodaq_plugins_beam_shaping/__init__.py +++ b/src/pymodaq_plugins_beam_shaping/__init__.py @@ -11,7 +11,7 @@ from .field import LoaderFactory, register_loaders from .algorithms.factory import AlgorithmFactory, register_algorithms from .algorithms.ini_phase import register_phases -from .algorithms.compensation import register_compensations +from .algorithms.compensation import register_compensations, CompensationFactory from .algorithms.stopping import register_stoppings logger = set_logger(get_module_name(__file__)) @@ -30,6 +30,7 @@ logger.info('****************************************') logger.info('Registering Optical Shaping compensations of the input beam') register_compensations() +CompensationFactory.check_enum() logger.info('****************************************') diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py index e7ae1f2..33fb790 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py @@ -16,7 +16,7 @@ from pymodaq_plugins_beam_shaping.algorithms.utils import (AlgoType, AlgoStatus, ApplyMaskTo, LensSetup, CrossTalk, PhaseManipulation) from pymodaq_plugins_beam_shaping.field import Field -from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationBase +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationBase, Compensations from pymodaq_plugins_beam_shaping.utilities import sizing from pymodaq_plugins_beam_shaping.utilities.masking import MaskType @@ -53,7 +53,7 @@ class AlgoBase(AlgoParameterManager, metaclass=ABCMeta): # the modulators the algorithm can compute a mask for (a shaper modulating both accepts any algorithm) MODULATOR_TYPES: tuple[ModulatorType] = (ModulatorType.PHASE, ) INI_PHASE = True # if True, the algorithm will init an initial phase - INPUT_COMPENSATION: Optional[str] = None # name of the compensation of the input beam the algorithm starts + INPUT_COMPENSATION: Optional[Compensations] = None # name of the compensation of the input beam the algorithm starts # with (the app lets the user change it), None if the algorithm does not use one ITERATIVE = False MANUAL_LOOP = True diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py index aed3fb0..b83aba8 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py @@ -36,7 +36,7 @@ from pymodaq_plugins_beam_shaping.algorithms.factory import AlgorithmFactory from pymodaq_plugins_beam_shaping.algorithms.algo_base import AlgoBase from pymodaq_plugins_beam_shaping.algorithms.ini_phase import PhaseFactory, PhaseBase -from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationFactory, CompensationBase +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationFactory, CompensationBase, Compensations from pymodaq_plugins_beam_shaping.algorithms.stopping import StoppingFactory, StoppingBase from pymodaq_plugins_beam_shaping.algorithms.utils import (AlgoStatus, ApplyMaskTo, LensSetup, CrossTalk, PhaseManipulation) @@ -132,8 +132,7 @@ class AlgoApp(CustomApp): 'modulator from the target (they use it, the others do not show this group)', 'children': [ {'title': 'Compensation:', 'name': 'compensation_factory', 'type': 'list', - 'value': 'DivideByInput' if 'DivideByInput' in compensation_factory.compensations - else compensation_factory.compensations[0], + 'value': Compensations.DivideByInput.value, 'limits': compensation_factory.compensations}, {'title': 'Compensation Parameters', 'name': 'compensation_params', 'type': 'group', 'children': []}, ]}, diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py index 718d7ea..d45b3ca 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py @@ -29,6 +29,7 @@ from pymodaq_data import Q_ from pymodaq_plugins_beam_shaping.algorithms.factory import AlgorithmFactory +from pymodaq_plugins_beam_shaping.algorithms.compensation import Compensations from pymodaq_plugins_beam_shaping.algorithms.utils import AlgoStatus, LensSetup, ApplyMaskTo, AlgoType from pymodaq_plugins_beam_shaping.algorithms import AlgoBase from pymodaq_plugins_beam_shaping.utils import Config as PluginConfig @@ -64,7 +65,7 @@ class BinaryHologram(AlgoBase): SETUP_TYPE = LensSetup.FourF ITERATIVE = False INI_PHASE = False # an amplitude modulator has no phase to initialize - INPUT_COMPENSATION = 'DivideByInput' # the target is divided by the input beam, see encoded_amplitude + INPUT_COMPENSATION = Compensations.DivideByInput # the target is divided by the input beam, see encoded_amplitude RECOMPUTE_ON_CHANGE = True _params_carrier = [ diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py index d9c1850..9e7ca34 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py @@ -16,6 +16,7 @@ from pymodaq_data import Q_ from pymodaq_plugins_beam_shaping.algorithms.factory import AlgorithmFactory +from pymodaq_plugins_beam_shaping.algorithms.compensation import Compensations from pymodaq_plugins_beam_shaping.algorithms.utils import AlgoStatus, LensSetup, ApplyMaskTo, AlgoType from pymodaq_plugins_beam_shaping.algorithms import AlgoBase from pymodaq_plugins_beam_shaping.utils import Config as PluginConfig @@ -45,7 +46,7 @@ class OL2014(AlgoBase): ALGOTYPE = AlgoType.AMPLITUDE_PHASE SETUP_TYPE = LensSetup.FourF ITERATIVE = False - INPUT_COMPENSATION = 'DivideByInput' # cos(beta) is the amplitude of the target to divide by the input beam + INPUT_COMPENSATION = Compensations.DivideByInput # cos(beta) is the amplitude of the target to divide by the input beam RECOMPUTE_ON_CHANGE = True params = [ diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/compensation.py b/src/pymodaq_plugins_beam_shaping/algorithms/compensation.py index 7d726e5..28230db 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/compensation.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/compensation.py @@ -12,16 +12,25 @@ from abc import ABC, abstractmethod from importlib import import_module from pathlib import Path -from typing import Callable, Optional +from typing import Callable, Optional, Union import numpy as np from pymodaq_gui.parameter import Parameter +from pymodaq_utils.enums import StrEnum from pymodaq_utils.logger import set_logger, get_module_name logger = set_logger(get_module_name(__file__)) -NO_COMPENSATION = 'NoCompensation' # name of the compensation that does nothing +class Compensations(StrEnum): + """ The names of the compensations of the input beam: the name of their class in the package ``compensations`` + + A new compensation is added here as well as in its module (``test_compensation`` checks that both agree).""" + NoCompensation = 'NoCompensation' # the output is the target times the profile of the input beam + DivideByInput = 'DivideByInput' # the target is divided by the profile of the input beam + + +NO_COMPENSATION = Compensations.NoCompensation def register_compensations(parent_module_name: str = 'pymodaq_plugins_beam_shaping'): @@ -106,7 +115,7 @@ def inner_wrapper(wrapped_class: type[CompensationBase]) -> type[CompensationBas return inner_wrapper @classmethod - def get_compensation(cls, name: str) -> type[CompensationBase]: + def get_compensation(cls, name: Union[str, Compensations]) -> type[CompensationBase]: if name not in cls._registry: raise ValueError(f'{name} is not a supported compensation of the input beam.') return cls._registry[name] @@ -115,3 +124,10 @@ def get_compensation(cls, name: str) -> type[CompensationBase]: def compensations(self) -> list[str]: """ The names of the compensations, the one that does nothing first""" return sorted(self._registry, key=lambda name: (name != NO_COMPENSATION, name)) + + @classmethod + def check_enum(cls) -> None: + """ Raise if the enum and the registered compensations do not list the same names""" + names, registered = {c.value for c in Compensations}, set(cls._registry) + if names != registered: + raise ValueError(f'Compensations and registered classes differ: {sorted(names ^ registered)}') diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index b3fce44..366bba7 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -17,7 +17,7 @@ from pymodaq_plugins_beam_shaping.field.factory import LoaderFactory, register_loaders from pymodaq_plugins_beam_shaping.algorithms.factory import AlgorithmFactory, register_algorithms from pymodaq_plugins_beam_shaping.algorithms.ini_phase import PhaseFactory, register_phases -from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationFactory, register_compensations +from pymodaq_plugins_beam_shaping.algorithms.compensation import CompensationFactory, Compensations, register_compensations from pymodaq_plugins_beam_shaping.algorithms.utils import ApplyMaskTo from pymodaq_plugins_beam_shaping.utilities import regions, sizing from pymodaq_plugins_beam_shaping.utilities.masking import MaskType @@ -36,7 +36,7 @@ def ensure_qapp(): return mkQApp('AlgorithmPlayground') -def make_compensation(name: str = 'DivideByInput', params: Optional[dict] = None): +def make_compensation(name: str = Compensations.DivideByInput, params: Optional[dict] = None): """ A compensation of the input beam (see :mod:`algorithms.compensations`) with its parameters set""" from pyqtgraph.parametertree import Parameter register_compensations() @@ -47,7 +47,7 @@ def make_compensation(name: str = 'DivideByInput', params: Optional[dict] = None return compensation_class(settings) -def set_compensation(app, name: str = 'DivideByInput', params: Optional[dict] = None): +def set_compensation(app, name: str = Compensations.DivideByInput, params: Optional[dict] = None): """ Choose the compensation of the input beam of the app (as the settings of the AlgoApp do): ``'NoCompensation'`` or ``'DivideByInput'`` with the parameter ``min_input_level``""" app.compensation = make_compensation(name, params) diff --git a/tests/conftest.py b/tests/conftest.py index 9c0a49b..7584139 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -14,9 +14,37 @@ import pytest +from pymodaq_utils.config import ConfigError + @pytest.fixture(scope='session') def qapp(): """The apps read the theme set on the QApplication by mkQApp""" from pymodaq_gui.qt_utils import mkQApp return mkQApp('tests') + + +class FakeConfig: + """ What the ConfigSaverLoader asks to a config: a call with the path, item assignment, save""" + + def __init__(self): + self.data = {} + + def __call__(self, *path): + if tuple(path) not in self.data: + raise ConfigError(path) + return self.data[tuple(path)] + + def __setitem__(self, path, value): + self.data[tuple(path)] = value + + def save(self): + pass + + +@pytest.fixture +def config(monkeypatch): + from pymodaq_plugins_beam_shaping.algorithms import algorithm_app + fake = FakeConfig() + monkeypatch.setattr(algorithm_app, 'algo_config', fake) + return fake diff --git a/tests/test_algo_app_settings.py b/tests/test_algo_app_settings.py index 87783e8..f025990 100644 --- a/tests/test_algo_app_settings.py +++ b/tests/test_algo_app_settings.py @@ -3,38 +3,11 @@ import pytest from qtpy import QtWidgets -from pymodaq_utils.config import ConfigError from pymodaq_gui.utils.dock import DockArea OL2014 = 'OL2014 - Amplitude-Phase Checkerboard' -class FakeConfig: - """ What the ConfigSaverLoader asks to a config: a call with the path, item assignment, save""" - - def __init__(self): - self.data = {} - - def __call__(self, *path): - if tuple(path) not in self.data: - raise ConfigError(path) - return self.data[tuple(path)] - - def __setitem__(self, path, value): - self.data[tuple(path)] = value - - def save(self): - pass - - -@pytest.fixture -def config(monkeypatch): - from pymodaq_plugins_beam_shaping.algorithms import algorithm_app - fake = FakeConfig() - monkeypatch.setattr(algorithm_app, 'algo_config', fake) - return fake - - @pytest.fixture def make_app(qtbot, config): windows = [] diff --git a/tests/test_algo_helpers.py b/tests/test_algo_helpers.py index 5e9b1d9..96098a3 100644 --- a/tests/test_algo_helpers.py +++ b/tests/test_algo_helpers.py @@ -1,6 +1,7 @@ """Helpers of AlgoBase shared by the algorithms (4f propagation, projection step...)""" import numpy as np import pytest +from pymodaq_plugins_beam_shaping.algorithms.compensation import Compensations from pymodaq_data import Q_ from pymodaq_plugins_beam_shaping.algorithms.utils import ApplyMaskTo @@ -248,5 +249,5 @@ def test_the_default_compensation_of_the_algorithm_is_used_without_the_app(qapp, app, algo = prepare('Parallel Lee', 'amplitude') app.compensation = None # the app has not chosen assert type(algo.compensation).__name__ == 'DivideByInput' - monkeypatch.setattr(type(algo), 'INPUT_COMPENSATION', 'NoCompensation') + monkeypatch.setattr(type(algo), 'INPUT_COMPENSATION', Compensations.NoCompensation) assert type(algo.compensation).__name__ == 'NoCompensation' diff --git a/tests/test_compensation.py b/tests/test_compensation.py index bdab075..b592409 100644 --- a/tests/test_compensation.py +++ b/tests/test_compensation.py @@ -91,3 +91,10 @@ def test_an_input_of_another_shape_is_not_compensated_and_says_so(factory, caplo transmission, unreachable = make(factory, 'DivideByInput').compensate(target, gaussian()) assert np.array_equal(transmission, target) and unreachable is None assert 'compensat' in caplog.text + + +def test_the_enum_and_the_registered_compensations_agree(factory): + from pymodaq_plugins_beam_shaping.algorithms.compensation import Compensations + CompensationFactory.check_enum() + assert Compensations.DivideByInput == 'DivideByInput' # a StrEnum: still usable as the name + assert factory.get_compensation(Compensations.NoCompensation).__name__ == 'NoCompensation' diff --git a/tests/test_custom_apps.py b/tests/test_custom_apps.py index 2dfdf17..ea074e8 100644 --- a/tests/test_custom_apps.py +++ b/tests/test_custom_apps.py @@ -3,6 +3,7 @@ import types import pytest +from pymodaq_plugins_beam_shaping.algorithms.compensation import Compensations from qtpy import QtWidgets from pymodaq_gui.utils.dock import DockArea @@ -288,22 +289,22 @@ def test_algo_app_saves_the_pattern_of_an_amplitude_modulator_in_the_slm_node(qt assert np.allclose(origins[('modulator', 'amplitude')], algo._input_field.amplitude * origins[('slm', 'amplitude')]) -def test_algo_app_starts_with_the_default_compensation_of_the_algorithm(qtbot, dockarea, monkeypatch): +def test_algo_app_starts_with_the_default_compensation_of_the_algorithm(qtbot, dockarea, monkeypatch, config): from pymodaq_plugins_beam_shaping.algorithms.algorithm_app import AlgoApp from pymodaq_plugins_beam_shaping.algorithms.algorithms.binary_holograms import ParallelLee app = AlgoApp(dockarea) monkeypatch.setattr(app, 'set_settings_values', lambda *args: None) # not the values saved by other runs factory = app.settings.child('compensation_group', 'compensation_factory') - monkeypatch.setattr(ParallelLee, 'INPUT_COMPENSATION', 'NoCompensation') + monkeypatch.setattr(ParallelLee, 'INPUT_COMPENSATION', Compensations.NoCompensation) app.set_algorithm('Parallel Lee') assert factory.value() == 'NoCompensation' - monkeypatch.setattr(ParallelLee, 'INPUT_COMPENSATION', 'DivideByInput') + monkeypatch.setattr(ParallelLee, 'INPUT_COMPENSATION', Compensations.DivideByInput) app.set_algorithm('Parallel Lee') assert factory.value() == 'DivideByInput' -def test_algo_app_compensation_of_the_input_beam(qtbot, dockarea): +def test_algo_app_compensation_of_the_input_beam(qtbot, dockarea, config): """ The compensation is chosen in the settings of the app like the initial phase, for the algorithms that use it""" from pymodaq_plugins_beam_shaping.algorithms.algorithm_app import AlgoApp from pymodaq_plugins_beam_shaping.algorithms.compensations.divide_by_input import DivideByInput From 4b6e2b89cdbd5214d7ba14e7602cfbfd603272d2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 20:40:20 +0000 Subject: [PATCH 7/8] make_compensation sets its parameters with set_parameters (groups, clear error) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- .../utilities/headless_algorithms.py | 6 +++--- tests/test_compensation.py | 7 +++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index 366bba7..b9988b6 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -42,9 +42,9 @@ def make_compensation(name: str = Compensations.DivideByInput, params: Optional[ register_compensations() compensation_class = CompensationFactory.get_compensation(name) settings = Parameter.create(name=name, type='group', children=compensation_class.params) - for key, value in (params or {}).items(): - settings.child(key).setValue(value) - return compensation_class(settings) + compensation = compensation_class(settings) + set_parameters(compensation, params or {}) # names separated by '/' for the parameters in a group + return compensation def set_compensation(app, name: str = Compensations.DivideByInput, params: Optional[dict] = None): diff --git a/tests/test_compensation.py b/tests/test_compensation.py index b592409..d1de690 100644 --- a/tests/test_compensation.py +++ b/tests/test_compensation.py @@ -98,3 +98,10 @@ def test_the_enum_and_the_registered_compensations_agree(factory): CompensationFactory.check_enum() assert Compensations.DivideByInput == 'DivideByInput' # a StrEnum: still usable as the name assert factory.get_compensation(Compensations.NoCompensation).__name__ == 'NoCompensation' + + +def test_make_compensation_sets_parameters_in_groups_and_names_the_valid_ones(): + from pymodaq_plugins_beam_shaping.utilities.headless_algorithms import make_compensation + assert make_compensation('DivideByInput', {'min_input_level': 0.4}).settings['min_input_level'] == 0.4 + with pytest.raises(KeyError, match='min_input_level'): + make_compensation('DivideByInput', {'unknown': 1}) From 36394f1ac39e4d73c69ad2cc430dacba0286dcdf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 20:46:02 +0000 Subject: [PATCH 8/8] Test: the final saving also holds slm/phase Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- tests/test_algorithm_playground.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_algorithm_playground.py b/tests/test_algorithm_playground.py index 39347ad..d60bc60 100644 --- a/tests/test_algorithm_playground.py +++ b/tests/test_algorithm_playground.py @@ -413,7 +413,7 @@ def test_all_fields_saved_once_at_the_end_in_the_group_of_the_run(qapp, tmp_path assert 'Fields' not in run assert 'settings' in run.attrs # the settings of the run are those of the group holding the final data arrays = [d for d in f['RawData/Shaping000/Final/Data2D'].values()] - assert len(arrays) == 4 # output and modulator amplitude and phase + assert len(arrays) == 5 # output and modulator amplitude and phase, and the phase sent to the SLM amp = [a for a in arrays if a.attrs['origin'] == 'output'][0] assert any(np.allclose(ds[...], algo.output_field.amplitude) for ds in amp.values() if hasattr(ds, 'shape') and ds.ndim == 2)