Skip to content
Merged
1 change: 1 addition & 0 deletions AGENTS_BEAM_SHAPING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` 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. |
Expand Down
49 changes: 39 additions & 10 deletions docs/src/user_guide/algorithm_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -49,6 +53,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:
Expand Down Expand Up @@ -91,22 +97,16 @@ 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*.

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
Expand Down Expand Up @@ -245,3 +245,32 @@ 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`` 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)``.
2 changes: 1 addition & 1 deletion docs/src/user_guide/algorithms.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
- ❌
- ✅
Expand Down
7 changes: 7 additions & 0 deletions src/pymodaq_plugins_beam_shaping/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, CompensationFactory
from .algorithms.stopping import register_stoppings

logger = set_logger(get_module_name(__file__))
Expand All @@ -26,6 +27,12 @@
register_phases()
logger.info('****************************************')

logger.info('****************************************')
logger.info('Registering Optical Shaping compensations of the input beam')
register_compensations()
CompensationFactory.check_enum()
logger.info('****************************************')


logger.info('****************************************')
logger.info('Registering Optical Shaping stopping criteria')
Expand Down
39 changes: 39 additions & 0 deletions src/pymodaq_plugins_beam_shaping/algorithms/algo_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, Compensations
from pymodaq_plugins_beam_shaping.utilities import sizing
from pymodaq_plugins_beam_shaping.utilities.masking import MaskType

Expand Down Expand Up @@ -52,6 +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: 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
RECOMPUTE_ON_CHANGE = False # if True, the algorithm is run again when one of its settings changes
Expand Down Expand Up @@ -284,6 +287,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 self.INPUT_COMPENSATION is None:
return None
compensation = getattr(self.parent_app, 'compensation', None)
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(self.INPUT_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()
Expand Down Expand Up @@ -420,6 +458,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:
Expand Down
Loading
Loading