From 6d799ebfb13673aceae9ba54c2d3e6359b19ccf0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 22:14:38 +0000 Subject: [PATCH] Keep the input phase in the modulator field, optional compensation of the input phase (#98) The modulator field is the input field times the SLM field: its phase is the input phase plus the SLM phase, the SLM field never holds the input phase. Back-propagated phases go through slm_phase_from_modulator_phase. The algorithms controlling the output phase (ALGOTYPE not AMPLITUDE) encode target_phase(): minus the input phase when the new checkbox 'Compensate input phase' (Input Compensation group, default on) is checked. Docs: fields and planes table, compensations of the input beam. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RKuN83BLrbGKe3ynHHvZQm --- AGENTS_BEAM_SHAPING.md | 2 +- docs/src/_images/fields_and_compensations.svg | 45 +++++ docs/src/user_guide/algorithm_reference.rst | 106 +++++++++-- .../algorithms/algo_base.py | 44 ++++- .../algorithms/algorithm_app.py | 16 +- .../algorithms/algorithms/binary_holograms.py | 14 +- .../algorithms/algorithms/checker_board.py | 5 +- .../algorithms/algorithms/direct.py | 4 +- .../algorithms/algorithms/torch_base.py | 6 +- .../utilities/headless_algorithms.py | 7 + tests/test_algo_helpers.py | 5 +- tests/test_input_phase.py | 171 ++++++++++++++++++ 12 files changed, 397 insertions(+), 28 deletions(-) create mode 100644 docs/src/_images/fields_and_compensations.svg create mode 100644 tests/test_input_phase.py diff --git a/AGENTS_BEAM_SHAPING.md b/AGENTS_BEAM_SHAPING.md index 9b9dcfa..358db2c 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 `Compensations` (StrEnum, add a member for a new compensation) member 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`. Input phase (issue #98): modulator field = input field x SLM field, so `set_phase_in_modulator_plane` takes the SLM phase and adds `input_phase`; a back-propagated phase goes through `slm_phase_from_modulator_phase`; algorithms with `ALGOTYPE` not AMPLITUDE encode `target_phase()` (minus the input phase when the `Compensate input phase` checkbox is on). | | `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/_images/fields_and_compensations.svg b/docs/src/_images/fields_and_compensations.svg new file mode 100644 index 0000000..0d32dc2 --- /dev/null +++ b/docs/src/_images/fields_and_compensations.svg @@ -0,0 +1,45 @@ + + + +The output always includes the input phase; the SLM field never does + +Input field +amplitude and +phase of the beam + + +Algorithm +sees the true +input field + + +SLM field +what is sent: +SLM phase, no +input phase + + +Modulator field +input × SLM field +phase: input ++ SLM phase + + +Output field +propagated from the +modulator field + + + +Amplitude compensation (list) +Divide by input: target ÷ input amplitude +Min input level sets the unreachable region +Lee, Superpixel, OL2014 + +Compensate input phase (checkbox, on) +Encoded phase: target phase − input phase, +so the output has the target phase. +Shown when ALGOTYPE is not AMPLITUDE: +Direct, Threshold, Lee, Superpixel, OL2014 +Intensity-only algorithms (GS, Projections) have no checkbox but always see the input phase. + \ No newline at end of file diff --git a/docs/src/user_guide/algorithm_reference.rst b/docs/src/user_guide/algorithm_reference.rst index a02cf72..698d6ba 100644 --- a/docs/src/user_guide/algorithm_reference.rst +++ b/docs/src/user_guide/algorithm_reference.rst @@ -53,7 +53,7 @@ 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 input beam is compensated (see *Compensations of the input beam* 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). @@ -97,7 +97,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). -* The compensation of the input beam is not a setting of the algorithm: see *Input compensation* below. +* The compensation of the input beam is not a setting of the algorithm: see *Compensations of the input beam* 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*. @@ -105,8 +105,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. The fields of the -algorithm hold ``slm/phase`` for every type of modulator and ``slm/amplitude`` when an amplitude is sent. +this one is the input beam times the SLM field (input phase included), and is the one used to compute the output. See +:ref:`sec-algorithm-fields`. 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 @@ -247,13 +247,77 @@ Minimize and TorchOptim trust-ncg, trust-exact or trust-krylov. -Input compensation ------------------- +.. _sec-algorithm-fields: + +Fields and planes +----------------- + +An algorithm works on the fields of the planes of the setup. The modulator multiplies the field of the input beam by +what it is sent: the **modulator field** is the input field times the **SLM field**, so its amplitude is the input +amplitude times the amplitude pattern and **its phase is the input phase plus the SLM phase**. The SLM field never +contains the input phase. The output is always computed from the modulator field, so it shows the effect of the +input beam, phase included, whatever the algorithm does with it. + +.. list-table:: **Fields of an algorithm** (full names of the data plotted and saved) + :header-rows: 1 + :widths: 25 20 55 + + * - **Field** + - **Data** + - **Description** + * - Input field + - *Input* group of a saved run + - The beam arriving on the modulator (amplitude and phase), from the input loader. + * - Target field + - *Target* group of a saved run + - What is asked in the output plane (amplitude and phase), from the target loader, normalised to the power of the + input. + * - SLM field + - ``slm/phase``, ``slm/amplitude`` + - What is sent to the modulator (``slm_field``): the phase computed by the algorithm (wrapped, quantised, with + crosstalk, including the initial phase) and the amplitude pattern (0 and 1 for a DMD, 1 for a phase-only + modulator, only plotted when an amplitude is sent). Without the input phase and without the corrections that the + extension adds when sending. + * - Modulator field + - ``modulator/amplitude``, ``modulator/phase`` + - The field just after the modulator (``modulator_field``): input field times SLM field. Its phase is the input + phase plus the SLM phase (the input phase alone for an amplitude modulator, whose SLM phase is 0). + * - Intermediate field + - ``intermediate`` (intensity) + - 4f setups: the Fourier plane of the first lens, filtered by the intermediate mask (``intermediate_field``). + * - Output field + - ``output/amplitude``, ``output/phase`` + - The field in the target plane (``output_field``), propagated from the modulator field. + * - Unreachable region + - ``unreachable`` + - Where the amplitude compensation cannot give the target (see below), only when there is one. + * - Metrics + - ``metrics`` + - The fitness of the output against the target and the efficiency. + +The algorithms see the true input field, phase included. An iterative algorithm that propagates back to the modulator +plane (Gerchberg-Saxton, Projections) gets the phase of the modulator field and removes the input phase to get the SLM +phase (``slm_phase_from_modulator_phase``). The initial phase is an SLM phase: before the first iteration the +modulator field is the input field times the initial phase. + +.. figure:: /_images/fields_and_compensations.svg + :alt: fields and compensations + + The planes and fields of an algorithm, and the two compensations of the input beam. + + +Compensations of the input beam +------------------------------- + +The group ``Input Compensation`` of the settings of the algorithm app holds two independent corrections. It is shown +for the algorithms that can use at least one of them, and each one is shown only where it applies. + +Amplitude +~~~~~~~~~ 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: +``Compensation`` list 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 @@ -271,6 +335,26 @@ 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`` 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)``. +instance for a 2f setup) is added by writing one more module and adding its name to the ``Compensations`` enum. An +algorithm that uses it sets ``INPUT_COMPENSATION`` to the member of ``Compensations`` of its default compensation +(``Compensations.DivideByInput`` for the algorithms above, ``None`` for an algorithm that does not use one) and calls +``self.compensate_target(amplitude)``. + +Phase +~~~~~ + +``Compensate input phase`` (default checked) removes the input phase from the target phase: the phase encoded is +``target phase - input phase`` (``target_phase()`` of the algorithm), so that the modulator field, and so the output, +has the target phase. Unchecked, the target phase is encoded as given and the output carries the input phase on top +of it. + +It is shown for the algorithms that control the output phase, those whose ``ALGOTYPE`` is not ``AMPLITUDE`` +(``can_compensate_input_phase``): *Direct*, *Binary Threshold*, *Parallel Lee*, *Superpixel* and *OL2014*. The +algorithms that shape the intensity only (``ALGOTYPE = AMPLITUDE``: Gerchberg-Saxton, Projections, the torch based +ones) have no target phase to correct; they still see the input phase, so that the intensity they compute is the one of +the setup. In a script: ``set_compensate_input_phase(app, False)`` of ``headless_algorithms``. + +.. note:: + + Before this version the input phase was dropped from the modulator field: the results change for any input beam + whose phase is not flat. Loading an input with a flat phase gives the previous results. diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py index 33fb790..0d6ce5d 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py @@ -29,6 +29,11 @@ plugin_config = Config() + +def wrap_phase(phase: np.ndarray) -> np.ndarray: + """ The phase brought back to [-pi, pi)""" + return (np.asarray(phase) + np.pi) % (2 * np.pi) - np.pi + class AlgoParameterManager(ParameterManager): settings_name = 'algo_settings' @@ -248,6 +253,41 @@ def set_amplitude_in_modulator_plane(self, amplitude: np.ndarray): phase=self._slm_phase_or_zeros(pattern.shape), pixel_sizes=self._input_field.pixels_sizes) self._modulator_field.amplitude = self._input_field.amplitude * pattern + self._modulator_field.phase = wrap_phase(self.input_phase + self._slm_field.phase) + + @property + def input_phase(self) -> np.ndarray: + """ The phase of the input beam on the modulator (zeros if the input does not have the shape of the + modulator field)""" + phase = getattr(self._input_field, 'phase', None) + if phase is None or phase.shape != tuple(self._modulator_field.shape): + return np.zeros(self._modulator_field.shape) + return phase + + def slm_phase_from_modulator_phase(self, phase: np.ndarray) -> np.ndarray: + """ The SLM phase giving this phase in the modulator plane: the input phase removed (the phase of a field + back-propagated to the modulator plane is the phase of the modulator field, input phase included)""" + return wrap_phase(phase - self.input_phase) + + @property + def can_compensate_input_phase(self) -> bool: + """ The algorithm controls the output phase (ALGOTYPE not AMPLITUDE): it can compensate the input phase in + the target phase""" + return self.ALGOTYPE != AlgoType.AMPLITUDE + + @property + def compensate_input_phase(self) -> bool: + """ The target phase is corrected for the input phase (Compensate input phase in the app, on by default), + only for the algorithms that can do it""" + return self.can_compensate_input_phase and bool(getattr(self.parent_app, 'compensate_input_phase', True)) + + def target_phase(self) -> np.ndarray: + """ The phase to encode for the target: the target phase minus the input phase if the input phase is + compensated (the modulator field then has the target phase), the target phase otherwise""" + phase = self._target_field.phase + if self.compensate_input_phase and phase.shape == tuple(self._modulator_field.shape): + return phase - self.input_phase + return phase def _slm_phase_or_zeros(self, shape) -> np.ndarray: return self._slm_field.phase.copy() if self._slm_field.phase.shape == tuple(shape) else np.zeros(shape) @@ -333,7 +373,7 @@ def set_phase_in_modulator_plane(self, phase: np.ndarray, induced_amplitude: np. if self.crosstalk.apply: phase = gaussian_filter(phase, self.crosstalk.value) - self._modulator_field.phase = phase + self._modulator_field.phase = wrap_phase(self.input_phase + phase) # input field times SLM field self._slm_field = Field('slm', amplitude=self._slm_field.amplitude if self._slm_field.amplitude.shape == phase.shape else np.ones(phase.shape), phase=phase, pixel_sizes=self._input_field.pixels_sizes) @@ -579,7 +619,7 @@ def back_propagate_amplitude(self, amplitude: np.ndarray): given amplitude, propagate back to the modulator plane and set the phase obtained as the modulator one""" corrected = Field(amplitude=amplitude, phase=self._output_field.phase, pixel_sizes=self._output_field.pixels_sizes) - self.set_phase_in_modulator_plane(self.compute_backward_fft(corrected).phase) + self.set_phase_in_modulator_plane(self.slm_phase_from_modulator_phase(self.compute_backward_fft(corrected).phase)) def value_changed(self, param: Parameter): if self.RECOMPUTE_ON_CHANGE: diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py index e4001dd..7429687 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py @@ -135,6 +135,10 @@ class AlgoApp(CustomApp): 'value': Compensations.DivideByInput.value, 'limits': compensation_factory.compensations}, {'title': 'Compensation Parameters', 'name': 'compensation_params', 'type': 'group', 'children': []}, + {'title': 'Compensate input phase:', 'name': 'compensate_input_phase', 'type': 'bool', 'value': True, + 'tip': 'The phase of the input beam is removed from the target phase, so that the modulator field ' + '(input times SLM field) has the target phase. Shown for the algorithms that control the output ' + 'phase'}, ]}, {'title': 'Stopping Criteria:', 'name': 'stopping', 'expanded': True, 'type': 'group', 'children': [ @@ -407,7 +411,12 @@ 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 is not None) + amplitude_compensation = self._algorithm.INPUT_COMPENSATION is not None + phase_compensation = self._algorithm.can_compensate_input_phase + self.settings.child('compensation_group').show(amplitude_compensation or phase_compensation) + for name in ('compensation_factory', 'compensation_params'): + self.settings.child('compensation_group', name).show(amplitude_compensation) + self.settings.child('compensation_group', 'compensate_input_phase').show(phase_compensation) self.settings.child(str(ApplyMaskTo.INTERMEDIATE)).show(self._algorithm.SETUP_TYPE == LensSetup.FourF) self.settings.child('stopping').show(self._algorithm.ITERATIVE == True) @@ -458,6 +467,11 @@ def compensation(self) -> CompensationBase: return compensation_factory.get_compensation(name)( self.settings.child('compensation_group', 'compensation_params', name)) + @property + def compensate_input_phase(self) -> bool: + """ The input phase is removed from the target phase (for the algorithms that control the output phase)""" + return self.settings['compensation_group', 'compensate_input_phase'] + @property def ini_stopping_criteria(self) -> StoppingBase: return stopping_factory.get_stop_class(self.settings['stopping', 'stopping_type'])( 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 d45b3ca..0f969f5 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/binary_holograms.py @@ -32,6 +32,7 @@ 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.algorithms.algo_base import wrap_phase from pymodaq_plugins_beam_shaping.utils import Config as PluginConfig from pymodaq_plugins_beam_shaping.field import Field from pymodaq_plugins_beam_shaping.field.operations.compute import centered_grid, remove_linear_phase, spectrum_centroid @@ -191,9 +192,10 @@ def compute_phase_and_or_amplitude(self, do_step=True, **kwargs): amplitude_pattern = self.compute_amplitude_pattern() self.set_amplitude_in_modulator_plane(amplitude_pattern) - # an amplitude modulator does not modulate the phase: whatever phase was set on the modulator field (an - # initial phase for instance) would be multiplied to the pattern and wash the diffraction orders out - self._modulator_field.phase = np.zeros(self.shape) + # an amplitude modulator does not modulate the phase: its SLM phase is null (an initial phase would be + # multiplied to the pattern and wash the diffraction orders out), the modulator field has the input phase + self._slm_field.phase = np.zeros(self.shape) + self._modulator_field.phase = wrap_phase(self.input_phase) self.compute_intermediate_field() self.compute_output_from_intermediate() @@ -235,7 +237,7 @@ class BinaryThreshold(BinaryHologram): BinaryHologram._params_carrier) def compute_amplitude_pattern(self) -> np.ndarray: - amplitude_dmd = 1 / 2 * (1 + np.cos(self.carrier_phase() - self._target_field.phase)) + amplitude_dmd = 1 / 2 * (1 + np.cos(self.carrier_phase() - self.target_phase())) if self.settings['binarize']: amplitude_dmd = (amplitude_dmd > self.settings['threshold']).astype(float) return amplitude_dmd @@ -272,7 +274,7 @@ class ParallelLee(BinaryHologram): def compute_amplitude_pattern(self) -> np.ndarray: modulation_depth = self.encoded_amplitude() # 1 where the amplitude to encode is the largest - phase = self.carrier_phase() - self._target_field.phase + phase = self.carrier_phase() - self.target_phase() if self.settings['binarize']: # the pixel is on where cos(phase) > cos(pi q): stripes of relative width q = arcsin(A) / pi. Where A = 0 # the pixels are off @@ -363,7 +365,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() * reach * np.exp(1j * self._target_field.phase) + target = self.encoded_amplitude() * reach * np.exp(1j * self.target_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 9e7ca34..17beb5a 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/checker_board.py @@ -71,8 +71,9 @@ def compute_phase_and_or_amplitude(self, do_step=True, **kwargs): # 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) + phase = self.target_phase() # minus the input phase if it is compensated + theta_field = Field('theta', phase=phase + beta) + alpha_field = Field('alpha', phase=phase - beta) theta_field.phase *= odd_mask alpha_field.phase *= even_mask diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/direct.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/direct.py index d92621b..4f0c7db 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/direct.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/direct.py @@ -60,7 +60,9 @@ def get_target_pixels_size(self, input_size: Tuple[Q_, Q_] = None) -> list[Q_]: return self._input_field.pixels_sizes def compute_phase_and_or_amplitude(self, do_step=True, **kwargs): - self.set_field_in_modulator_plane(self.normalize_wrt(self._target_field, self._input_field)) + field = self.normalize_wrt(self._target_field, self._input_field).deepcopy() + field.phase = self.target_phase() # minus the input phase if it is compensated + self.set_field_in_modulator_plane(field) diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/torch_base.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/torch_base.py index 3b616f5..03061a3 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/torch_base.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithms/torch_base.py @@ -118,8 +118,9 @@ def normalize_intensity_wrt(self, tensor: torch.Tensor, tensor_ref: torch.Tensor def do_things_after_init(self): # Initialize phase distribution as trainable parameter - self.phase_distribution = self.modulator_field.phase + self.phase_distribution = self.slm_field.phase # the SLM phase, the input phase is added in the model self._amplitude_tensor = torch.from_numpy(self.modulator_field.amplitude) + self._input_phase_tensor = torch.from_numpy(self.input_phase) if not self._algo_init: self._algo_init = True @@ -147,7 +148,8 @@ def phase_distribution(self, value: np.ndarray): def compute_image_field(self, phase_input: torch.Tensor) -> torch.Tensor: output_tensor = torch.fft.fftshift( - torch.fft.fft2(self._amplitude_tensor * torch.exp(1j * phase_input), norm='forward' + torch.fft.fft2(self._amplitude_tensor * torch.exp(1j * (phase_input + self._input_phase_tensor)), + norm='forward' ) ) return output_tensor diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index 8172c7b..4c1a143 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -53,6 +53,12 @@ def set_compensation(app, name: str = Compensations.DivideByInput, params: Optio app.compensation = make_compensation(name, params) +def set_compensate_input_phase(app, compensate: bool = True): + """ Compensate the input phase in the target phase (as the checkbox of the AlgoApp): only used by the + algorithms that control the output phase (ALGOTYPE not AMPLITUDE)""" + app.compensate_input_phase = bool(compensate) + + def set_parameters(manager, values: dict): """ Set the values of the parameters of an algorithm or a loader, without using the Parameter objects. @@ -110,6 +116,7 @@ def __init__(self, shaper: Shaper): self.shaper = shaper self.algorithm = None self.compensation = None # the compensation of the input beam, see set_compensation (None: the default one) + self.compensate_input_phase = True # the target phase is corrected for the input phase, see set_compensate_input_phase self.loaded_fields = [] # (field, loader, shape before fitting) of the fields loaded with load_field self.field_loaders = {'input': None, 'target': None} # the loaders of the fields given to the algorithm self.masks = {str(ApplyMaskTo.TARGET): None, str(ApplyMaskTo.INTERMEDIATE): None} diff --git a/tests/test_algo_helpers.py b/tests/test_algo_helpers.py index 6945aa5..9b68e83 100644 --- a/tests/test_algo_helpers.py +++ b/tests/test_algo_helpers.py @@ -146,7 +146,8 @@ def test_the_slm_field_holds_the_phase_without_correction_and_the_pattern(qapp): app, algo = prepare('Gerchberg-Saxton', 'both') pg.run_algorithm(algo, 1, verbose=False) slm = algo.slm_field - assert np.allclose(slm.phase, algo.modulator_field.phase) # the phase sent, nothing added to it + assert np.allclose(np.exp(1j * slm.phase), # the phase sent, nothing added to it (the modulator adds the input phase) + np.exp(1j * (algo.modulator_field.phase - algo.input_phase))) assert np.all(slm.amplitude == 1) # a phase algorithm does not shape the amplitude assert 'slm/amplitude' in [dwa.get_full_name() for dwa in algo.get_fields_to_plot()] app, algo = prepare('Gerchberg-Saxton', 'phase') @@ -249,7 +250,7 @@ def test_the_phase_sent_to_the_slm_is_in_the_fields_for_every_modulator_type(qap 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) + assert np.allclose(np.exp(1j * phase[0]), np.exp(1j * (algo.modulator_field.phase - algo.input_phase))) def test_the_default_compensation_of_the_algorithm_is_used_without_the_app(qapp, monkeypatch): diff --git a/tests/test_input_phase.py b/tests/test_input_phase.py new file mode 100644 index 0000000..2ddb8ea --- /dev/null +++ b/tests/test_input_phase.py @@ -0,0 +1,171 @@ +"""The phase of the input beam (issue #98): the modulator field is the input field times the SLM field, so its phase +is the input phase plus the SLM phase; the SLM field (what is sent) never holds the input phase. The algorithms see the +true input field, and those that control the output phase (ALGOTYPE not AMPLITUDE) can compensate the input phase in +the target phase (checkbox Compensate input phase, on by default).""" +import numpy as np +import pytest +from qtpy import QtWidgets + +from pymodaq_gui.utils.dock import DockArea + +from pymodaq_plugins_beam_shaping.field import Field +from pymodaq_plugins_beam_shaping.utilities import headless_algorithms as pg + + +def prepare(name, modulator_type): + pg.ensure_qapp() + app = pg.HeadlessApp(pg.make_shaper(width=128, height=128, pixel_size=8., modulator_type=modulator_type)) + algo = pg.create_algorithm(pg.reload_algorithm(name), app) + pg.set_fields(algo, pg.load_field('GaussianIntensity', None, app), + pg.load_field('ImageFiles', {'phase/load': False}, app)) + return app, algo + + +def curved_phase(shape, strength=30.): + """ A defocus like phase, large enough to blur the output if it is ignored""" + y, x = np.indices(shape) + return strength * (((x - shape[1] / 2) / shape[1]) ** 2 + ((y - shape[0] / 2) / shape[0]) ** 2) + + +QUANTUM = 2 * np.pi / 2 ** 8 # the SLM phase is quantised on 8 bits by default + + +def tilted_phase(shape): + y, x = np.indices(shape) + return 2 * np.pi * (3 * x / shape[1] + 2 * y / shape[0]) + + +def same_phase(a, b, where=None, atol=1e-8) -> bool: + """ Equal modulo 2 pi (where the amplitude is not null if given)""" + diff = np.exp(1j * a) - np.exp(1j * b) + if where is not None: + diff = diff[where] + return np.allclose(diff, 0., atol=atol) + + +def physical_output(algo) -> np.ndarray: + """ The output computed from the input field and the SLM field only (2f: one Fourier transform, as the algorithm)""" + modulator = Field(amplitude=algo._input_field.amplitude * algo.slm_field.amplitude, + phase=algo._input_field.phase + algo.slm_field.phase, + pixel_sizes=algo._input_field.pixels_sizes) + return (modulator.fft2(norm='forward') * np.prod(modulator.shape)).field + + +def test_the_modulator_phase_is_the_input_phase_plus_the_slm_phase(qapp): + app, algo = prepare('Gerchberg-Saxton', 'phase') + algo._input_field.phase = curved_phase(algo.shape) + slm = tilted_phase(algo.shape) % (2 * np.pi) - np.pi + algo.set_phase_in_modulator_plane(slm) + assert same_phase(algo.slm_field.phase, slm) # the SLM field never holds the input phase + assert same_phase(algo.modulator_field.phase, algo._input_field.phase + slm) + assert np.allclose(algo.modulator_field.amplitude, algo._input_field.amplitude) + + +def test_gerchberg_saxton_with_a_curved_input_corrects_it_on_the_slm(qapp): + app, algo = prepare('Gerchberg-Saxton', 'phase') + pg.run_algorithm(algo, 10) + flat_nrmse = algo.nrmse + + app, algo = prepare('Gerchberg-Saxton', 'phase') + algo._input_field.phase = curved_phase(algo.shape) + pg.run_algorithm(algo, 10) + algo.compute_forward_fft(update_plots=False) # the output of the last SLM phase + # the output is the one of the true modulator field: input field times what is sent to the SLM + assert np.allclose(physical_output(algo), algo.output_field.field, atol=1e-6 * np.abs(algo.output_field.field).max()) + assert same_phase(algo.modulator_field.phase, algo._input_field.phase + algo.slm_field.phase) + # and the algorithm corrected the input phase: as good as with a flat input + assert algo.nrmse <= 1.2 * flat_nrmse + 1e-3 + + +def test_the_initial_phase_goes_on_top_of_the_input_phase(qapp): + app, algo = prepare('Gerchberg-Saxton', 'phase') + algo._input_field.phase = curved_phase(algo.shape) + ini = tilted_phase(algo.shape) % (2 * np.pi) - np.pi + algo.define_input_phase(ini) + assert same_phase(algo.slm_field.phase, ini) + assert same_phase(algo.modulator_field.phase, algo._input_field.phase + ini) + + +def test_a_binary_hologram_keeps_the_input_phase_in_the_modulator_field(qapp): + app, algo = prepare('Parallel Lee', 'amplitude') + algo._input_field.phase = curved_phase(algo.shape) + pg.run_algorithm(algo) + assert same_phase(algo.modulator_field.phase, algo._input_field.phase) # the SLM phase of a DMD is null + assert np.allclose(algo.slm_field.phase, 0.) + + +def test_the_compensation_of_the_input_phase_is_offered_to_the_algorithms_shaping_the_output_phase(qapp): + for name, modulator, expected in (('Parallel Lee', 'amplitude', True), ('Superpixel', 'amplitude', True), + ('Binary Threshold', 'amplitude', True), ('Direct', 'both', True), + ('OL2014 - Amplitude-Phase Checkerboard', 'phase', True), + ('Gerchberg-Saxton', 'phase', False)): + app, algo = prepare(name, modulator) + assert algo.can_compensate_input_phase is expected, name + assert algo.compensate_input_phase is expected, name # on by default where it is offered + pg.set_compensate_input_phase(app, False) + assert algo.compensate_input_phase is False + + +@pytest.mark.parametrize('name, modulator', [('Parallel Lee', 'amplitude'), ('Superpixel', 'amplitude'), + ('Binary Threshold', 'amplitude'), + ('OL2014 - Amplitude-Phase Checkerboard', 'phase')]) +def test_compensating_the_input_phase_encodes_the_target_phase_minus_the_input_phase(qapp, name, modulator): + app, algo = prepare(name, modulator) + target_phase = tilted_phase(algo.shape) * 0.3 + input_phase = curved_phase(algo.shape) + algo._target_field.phase = target_phase.copy() + algo._input_field.phase = input_phase.copy() + pg.run_algorithm(algo) # on by default + compensated = algo.slm_field.deepcopy() + + app, algo = prepare(name, modulator) + pg.set_compensate_input_phase(app, False) + algo._target_field.phase = target_phase - input_phase # what the compensation asks for, with a flat input + pg.run_algorithm(algo) + assert np.allclose(compensated.amplitude, algo.slm_field.amplitude) + assert same_phase(compensated.phase, algo.slm_field.phase) + + +def test_direct_with_the_compensation_gives_the_target_phase_in_the_modulator_plane(qapp): + app, algo = prepare('Direct', 'both') + input_field = algo._input_field.deepcopy() + input_field.phase = curved_phase(algo.shape) + target = Field(amplitude=input_field.amplitude.copy(), phase=tilted_phase(algo.shape) * 0.3, + pixel_sizes=input_field.pixels_sizes) # Direct sends the target as is: same shape as the modulator + pg.set_fields(algo, input_field, target) + pg.run_algorithm(algo) + where = algo.modulator_field.amplitude > 1e-6 * algo.modulator_field.amplitude.max() + assert same_phase(algo.modulator_field.phase, algo._target_field.phase, where, QUANTUM) + assert same_phase(algo.slm_field.phase, algo._target_field.phase - algo._input_field.phase, where, QUANTUM) + + pg.set_compensate_input_phase(app, False) + pg.run_algorithm(algo) + assert same_phase(algo.slm_field.phase, algo._target_field.phase, where, QUANTUM) + assert same_phase(algo.modulator_field.phase, algo._target_field.phase + algo._input_field.phase, where, QUANTUM) + + +@pytest.fixture +def dockarea(qtbot): + window = QtWidgets.QMainWindow() + area = DockArea() + window.setCentralWidget(area) + qtbot.addWidget(window) + window.show() + yield area + + +def test_the_algo_app_shows_the_checkbox_for_the_algorithms_that_can_use_it(qtbot, dockarea, config): + from pymodaq_plugins_beam_shaping.algorithms.algorithm_app import AlgoApp + + app = AlgoApp(dockarea) + group = app.settings.child('compensation_group') + checkbox = group.child('compensate_input_phase') + for name, shown in (('Parallel Lee', True), ('Direct', True), ('Gerchberg-Saxton', False)): + app.set_algorithm(name) + assert checkbox.opts['visible'] is shown, name + assert group.opts['visible'] is (shown or app.algorithm.INPUT_COMPENSATION is not None), name + app.set_algorithm('Direct') # no amplitude compensation: only the checkbox in the group + assert not group.child('compensation_factory').opts['visible'] + assert app.compensate_input_phase is True + checkbox.setValue(False) + assert app.algorithm.compensate_input_phase is False