From f194a1167ec235b8646672f9cb819d2fe9e8f948 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 10:53:06 +0000 Subject: [PATCH 01/12] Headless script: save all the fields once at the end of a run, in a sub group of the run group Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- .../scripts/algorithm_playground.py | 5 ++-- .../utilities/h5saving.py | 16 +++++++++++ .../utilities/headless_algorithms.py | 13 +++++++-- tests/test_algorithm_playground.py | 28 +++++++++++++++++++ 4 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/pymodaq_plugins_beam_shaping/scripts/algorithm_playground.py b/src/pymodaq_plugins_beam_shaping/scripts/algorithm_playground.py index 1b5d91d..e32af32 100644 --- a/src/pymodaq_plugins_beam_shaping/scripts/algorithm_playground.py +++ b/src/pymodaq_plugins_beam_shaping/scripts/algorithm_playground.py @@ -102,11 +102,12 @@ # /RawData/ShapingXXX per run, the data enlarged along a 'step' axis SAVE_FIELDS = False # True: all the fields (output, modulator, intermediate), or some, e.g. ('modulator/phase',) SAVE_METRICS = False # the metrics (fitness, efficiency...) +SAVE_FINAL = False # all the fields and the metrics of the last iteration, once at the end (sub group 'Final' of the run) SAVE_FILE = None # None: a file in the PyMoDAQ data folder for the session, or a path. The runs are added to the file pg.run_algorithm(algo, N_ITERATIONS, INITIAL_PHASE, INITIAL_PHASE_PARAMS, save_fields=SAVE_FIELDS, - save_metrics=SAVE_METRICS, h5file=SAVE_FILE) -if SAVE_FIELDS or SAVE_METRICS: + save_metrics=SAVE_METRICS, save_final=SAVE_FINAL, h5file=SAVE_FILE) +if SAVE_FIELDS or SAVE_METRICS or SAVE_FINAL: print(f'saved in {algo.saved_h5file}') print(f'fitness = {algo.fitness:.4g}, efficiency = {algo.efficiency:.4g}') diff --git a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py index 8f8c09f..5a4c094 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py @@ -4,6 +4,7 @@ import xml.etree.ElementTree as ET from pymodaq_data.h5modules.backends import GROUP, Node +from pymodaq_data.data import DataDim import numpy as np from pymodaq_data.h5modules.data_saving import (DataToExportEnlargeableSaver, DataToExport, DataToExportSaver, @@ -101,6 +102,15 @@ def add_data(self, dte: DataToExport, axis_values: List[Union[float, np.ndarray] def add_data_bundle(self, data: DataBundle): self.add_data(data.dte, axis_values=data.axis_values) + def add_final_data(self, dte: DataToExport, group_name: str = 'Final'): + """ Save data once (not enlarged along the steps) in a sub group of the last group, so that they share its + settings and attributes with the data saved at each step, e.g. all the fields at the end of a run""" + saver = DataToExportSaver(self._h5saver) # not as a context manager: it would close the file + group = saver.add_data_group(self.get_last_node(self._h5saver.raw_group), DataDim.Data2D, title=group_name, + group_name=group_name) + saver.add_data(group, dte) + return group + VERSION_ATTRIBUTE = 'pymodaq_plugins_beam_shaping_version' @@ -275,6 +285,12 @@ def add(self, dte: DataToExport): self.h5saver.settings.child('N_saved').setValue(self._step) self.h5saver.flush() # the content of the file is up to date at each step, e.g. to browse it while paused + def add_final(self, dte: DataToExport, group_name: str = 'Final'): + """ Save all the data of the output of an algorithm (every field, the metrics, the unreachable region...) once, + in the sub group ``group_name`` of the group of the current run, whatever the data saved at each step""" + self.module_saver.add_final_data(dte.deepcopy(), group_name) + self.h5saver.flush() + def finalize(self): """ Make the file consistent: end the SWMR mode if it was activated diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index ceaa5a5..3b59363 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -301,7 +301,8 @@ def run_settings(algo, app: HeadlessApp, ini_phase: Union[str, np.ndarray] = 'Fl def run_algorithm(algo, n_iterations: int = 1, ini_phase: Union[str, np.ndarray] = 'FlatPhase', ini_phase_params: Optional[dict] = None, save_fields: Union[bool, Iterable[str]] = False, - save_metrics: bool = False, h5file: Union[None, str, Path] = None, verbose: bool = True): + save_metrics: bool = False, h5file: Union[None, str, Path] = None, verbose: bool = True, + save_final: bool = False): """ Run the algorithm (iterations only for the iterative ones), the results are in its fields With ``verbose`` (default), the index of the iteration and the metrics (fitness, efficiency) are printed after each @@ -314,10 +315,14 @@ def run_algorithm(algo, n_iterations: int = 1, ini_phase: Union[str, np.ndarray] ``save_fields`` True for all the fields (output and modulator amplitude and phase, intermediate intensity) or the full names of some of them ('modulator/phase'...), ``save_metrics`` for the metrics. ``h5file``: the file to add the run to (created if needed), None for a file in the PyMoDAQ data folder as the extension, created at the first - saved run and holding the next ones. The path of the file is stored in ``algo.saved_h5file``.""" + saved run and holding the next ones. The path of the file is stored in ``algo.saved_h5file``. + + ``save_final`` saves all the fields and the metrics of the last iteration once, at the end of the run (as the Save + action of the extension), in a sub group ``Final`` of the group of the run, next to the data saved at each + iteration, so with the same settings. It can be used alone or with the two other options.""" phase = initial_phase(algo, ini_phase, ini_phase_params) if algo.INI_PHASE else np.zeros(algo.shape) saver = None - if save_fields or save_metrics: + if save_fields or save_metrics or save_final: global _data_folder_saver if h5file is not None: saver = ContinuousSaver() @@ -345,6 +350,8 @@ def run_algorithm(algo, n_iterations: int = 1, ini_phase: Union[str, np.ndarray] f'efficiency = {algo.efficiency:.4g}') if saver is not None: saver.add(algo.get_fields_to_plot()) + if saver is not None and save_final: + saver.add_final(algo.get_fields_to_plot()) finally: if saver is not None: algo.saved_h5file = saver.file_path diff --git a/tests/test_algorithm_playground.py b/tests/test_algorithm_playground.py index 9d8d027..c880d7b 100644 --- a/tests/test_algorithm_playground.py +++ b/tests/test_algorithm_playground.py @@ -378,3 +378,31 @@ def test_saving_resumed_after_a_pause_in_the_same_group(qapp, tmp_path): saver.add(algo.get_fields_to_plot()) saver.close_file() check_enlarged_nodes(tmp_path / 'pause.h5', 5) + + +def test_all_fields_saved_once_at_the_end_in_the_group_of_the_run(qapp, tmp_path): + import h5py + app, algo = prepare('Gerchberg-Saxton') + path = tmp_path / 'final.h5' + pg.run_algorithm(algo, 3, save_metrics=True, save_final=True, h5file=path) + with h5py.File(path, 'r') as f: + run = f['RawData/Shaping000'] + assert 'Final' 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 + 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) + # the metrics are still saved at each iteration, next to it + assert f['RawData/Shaping000/Data0D/CH00/EnlData00'].shape[0] == 3 + + +def test_final_saving_alone(qapp, tmp_path): + import h5py + app, algo = prepare('Gerchberg-Saxton') + path = tmp_path / 'final_only.h5' + pg.run_algorithm(algo, 2, save_final=True, h5file=path) + with h5py.File(path, 'r') as f: + assert 'Final' in f['RawData/Shaping000'] + assert 'Data2D' not in f['RawData/Shaping000'] # nothing saved at each iteration From b688c94f5ff0911203c9a9affe60ace674f162d8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 11:00:37 +0000 Subject: [PATCH 02/12] Headless script: masks in the frame of the extension (origin at the corner of the field) The slices pasted from the extension were taken as centered and shifted by half the field, so the mask landed in a corner and the algorithms did not converge. The plots stay centered, their mask outline is shifted accordingly. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- docs/src/user_guide/algorithms.rst | 4 +- .../scripts/algorithm_playground.py | 9 +++-- .../utilities/headless_algorithms.py | 40 +++++++++++++------ tests/test_algorithm_playground.py | 34 ++++++++++++---- 4 files changed, 61 insertions(+), 26 deletions(-) diff --git a/docs/src/user_guide/algorithms.rst b/docs/src/user_guide/algorithms.rst index c1a6509..34ea55b 100644 --- a/docs/src/user_guide/algorithms.rst +++ b/docs/src/user_guide/algorithms.rst @@ -291,14 +291,14 @@ cells one after the other, editing the settings on the way: * *Snap*: ``pg.snap`` runs one step of the algorithm without any mask and plots the intermediate plane of 4f setups (intensity in log scale), to see where the mask has to be placed; * *Masks*: set ``APPLY_TARGET_MASK`` or ``APPLY_INTERMEDIATE_MASK`` to ``True`` to apply a mask (algorithms such as - *Binary Threshold*, *Parallel Lee* and *Superpixel* need the one of the intermediate plane), its region being given in um around the center of the field as the slices shown by the field loader and the extension, along y then along x, that can be pasted as is (``(slice(-100, 100, None), slice(-50, 50, None))``, as text or not; ``((-100, 100), (-50, 50))`` is accepted too) (``None``: the default region + *Binary Threshold*, *Parallel Lee* and *Superpixel* need the one of the intermediate plane), its region being given in um as the slices shown by the extension, in its frame (the origin is the corner of the field), along y then along x, that can be pasted as is (``(slice(1073, 5365, None), slice(1073, 5365, None))``, as text or not; ``((1073, 5365), (1073, 5365))`` is accepted too) (``None``: the default region of the extension, centered and covering 2/3 of the effective area of the SLM in the plane, printed to be edited). The cell draws the outline of the intermediate mask on the plot of the snap, which is updated (not created again): run it again until the mask is right. The *Run* cell can save the output of each iteration: ``SAVE_FIELDS`` (``True`` for all the fields, the amplitude and phase of the output and modulator planes and the intensity of the intermediate one, or the names of some of them such -as ``('modulator/phase',)``) and ``SAVE_METRICS``, both off by default. The format is the one of the continuous saving +as ``('modulator/phase',)``) and ``SAVE_METRICS``, both off by default. ``SAVE_FINAL`` saves once, at the end of the run, all the fields and the metrics of the last iteration, as the *Save* action of the extension does, in a sub group ``Final`` of the group of the run (so with the same settings), whatever is saved at each iteration. The format is the one of the continuous saving of the extension: a group ``/RawData/ShapingXXX`` per run, holding the data enlarged along a ``step`` axis, with the settings of the run, saved as in the extension: the name of the algorithm, the number of iterations, the initial phase and its parameters, the masks (applied or not, type and slices) and the parameters of the algorithm. ``SAVE_FILE`` gives the file (created if needed, the runs being added to it); with ``None`` diff --git a/src/pymodaq_plugins_beam_shaping/scripts/algorithm_playground.py b/src/pymodaq_plugins_beam_shaping/scripts/algorithm_playground.py index e32af32..c01e755 100644 --- a/src/pymodaq_plugins_beam_shaping/scripts/algorithm_playground.py +++ b/src/pymodaq_plugins_beam_shaping/scripts/algorithm_playground.py @@ -23,7 +23,8 @@ # The plots: 'matplotlib' (figures returned, to customize further) or 'qt' (the interactive viewers of PyMoDAQ: zoom, # levels, ROI..., in Spyder set Preferences > IPython console > Graphics > Backend to Qt or Automatic) -# The axes of the plots are in um, their origin at the center of the field, as for the masks. +# The axes of the plots are in um, their origin at the center of the field (the masks are given from the corner of the +# field, as in the extension, and their outline is drawn at the right place). # Each plot_field below takes: log (intensity in log10 instead of the amplitude), clim and phase_clim (min, max of the # colors), xlim and ylim (zoom, (min, max) in um). With 'qt' they give the starting state of the viewers. PLOT_BACKEND = 'matplotlib' @@ -70,9 +71,9 @@ snap_plot = pg.plot_field(snapped_intermediate, 'intermediate (snap, no mask)', log=True, clim=None, xlim=None, ylim=None, backend=PLOT_BACKEND) -# %% Masks: slices in um, along y then along x, around the center of the field, as shown by the field loader and the -# extension: they can be pasted as is, e.g. TARGET_MASK = (slice(-100, 100, None), slice(-50, 50, None)), as text or as -# ((-100, 100), (-50, 50)). +# %% Masks: slices in um, along y then along x, in the frame of the extension (origin at the corner of the field): they +# can be pasted as is, e.g. TARGET_MASK = (slice(1073, 5365, None), slice(1073, 5365, None)), as text or as +# ((1073, 5365), (1073, 5365)). # None: the default region of the extension, centered and covering 2/3 of the effective area of the SLM in the plane # (printed below, copy and edit it). Run this cell again to adjust the intermediate mask: its outline is drawn on the # plot of the snap, which is updated diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index 3b59363..56d3aa8 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -120,11 +120,8 @@ def get_mask_as_slices(self, apply_to): else: pixel_sizes = self.algorithm._target_field.pixels_sizes shape = sizing.get_effective_needed_field_size(self.shaper) - # like in the app the user gives the region around the center of the field: shift it to array coordinates - pxl = regions.pixel_sizes_in_um(pixel_sizes) - shifted = tuple(slice(_slice.start + shape[dim] * pxl[dim] / 2, _slice.stop + shape[dim] * pxl[dim] / 2) - for dim, _slice in enumerate(slices_um)) - return regions.slices_to_indexes(shifted, pixel_sizes, shape) + # as in the app, the region is given in the frame of the extension: its origin is the corner of the field + return regions.slices_to_indexes(slices_um, pixel_sizes, shape) def algo_settings_changed(self): pass @@ -218,7 +215,11 @@ def get_target_field(algo): def set_mask(app: HeadlessApp, apply_to: ApplyMaskTo, slices_um, mask_type: str = 'elliptical'): - """ Apply a mask given by its region in um around the center of the field, None to remove it. + """ Apply a mask given by its region in um, None to remove it. + + The region is in the frame of the extension, where the origin is the corner of the field (the slices shown by the + extension and by its mask settings can be pasted as is). The plots of this module are centered on the field, their + outline of the mask is shifted accordingly. The region is given as the slices shown by the field loader and the extension, as text or not (``'(slice(-100, 100, None), slice(-50, 50, None))'``, along y then along x), so that they can be copied and pasted, @@ -235,16 +236,14 @@ def mask_to_str(slices_um) -> str: def default_mask(algo, apply_to: ApplyMaskTo, fraction: float = 2 / 3) -> tuple: """ The default region of a mask, as in the extension: centered and covering 2/3 of the effective area of the SLM - in the plane (target or intermediate), given as slices along y then along x in um around the center of the field, - rounded to the um, as shown by the field loader and the extension""" + in the plane (target or intermediate), given as slices along y then along x in um in the frame of the extension + (origin at the corner of the field), rounded to the um, as shown by the extension""" if str(apply_to) == str(ApplyMaskTo.INTERMEDIATE): pixel_sizes = algo.intermediate_pixel_sizes else: pixel_sizes = algo._target_field.pixels_sizes - shape = sizing.get_effective_needed_field_size(algo.shaper) - half_field = np.array(shape) * regions.pixel_sizes_in_um(pixel_sizes) / 2 slices = regions.default_slices(algo.shaper, pixel_sizes, fraction) - return tuple(slice(round(_slice.start - half), round(_slice.stop - half)) for _slice, half in zip(slices, half_field)) + return tuple(slice(round(_slice.start), round(_slice.stop)) for _slice in slices) def _phase_settings(phase_class): @@ -432,8 +431,24 @@ def center_axes(dte): return dte +def mask_in_plot_frame(dte, mask): + """ The mask ((slices in the frame of the extension, type) as given to :func:`set_mask`) in the frame of the plots, + centered on the field (see :func:`center_axes`, to be called first)""" + if mask is None: + return None + slices, mask_type = mask + dwa = next(dwa for dwa in dte if dwa.dim.name == 'Data2D') + centered = [] + for dim, _slice in enumerate(regions.as_slices(slices)): + axis = dwa.get_axis_from_index(dim)[0] + half_um = Q_(-axis.offset, axis.units or 'um').m_as('um') # center_axes puts the origin at the center + centered.append(slice(_slice.start - half_um, _slice.stop - half_um)) + return tuple(centered), mask_type + + def draw_mask(figure, slices_um, mask_type: str = 'elliptical', units: str = 'um', color: str = 'red'): - """ Draw the outline of a mask (slices in um around the center of the field, see :func:`set_mask`) on the 2D data of a matplotlib figure (axes in ``units``, um for the plots of this module)""" + """ Draw the outline of a mask (slices in um around the center of the field, as the plots of this module, see + :func:`mask_in_plot_frame`) on the 2D data of a matplotlib figure (axes in ``units``)""" from matplotlib.patches import Ellipse, Rectangle (y0, y1), (x0, x1) = [[Q_(value, 'um').m_as(units) for value in (_slice.start, _slice.stop)] for _slice in regions.as_slices(slices_um)] @@ -509,6 +524,7 @@ def _show(dte, backend: str, size, clims=None, xlim=None, ylim=None, show: bool """ center_axes(dte) units = (str(dte[0].get_axis_from_index(1)[0].units) if len(dte[0].axes) else '') or 'um' + mask = mask_in_plot_frame(dte, mask) if backend == 'qt': ensure_qapp() viewer = dte.plot('qt', viewer=figure) diff --git a/tests/test_algorithm_playground.py b/tests/test_algorithm_playground.py index c880d7b..c76a067 100644 --- a/tests/test_algorithm_playground.py +++ b/tests/test_algorithm_playground.py @@ -29,6 +29,13 @@ def test_run_and_plot_an_algorithm(qapp): assert pg.plot(algo, show=False) is not None +def around_center(algo, apply_to: ApplyMaskTo, half: float = 100.): + """ A mask of 2 x half um around the center of the field, in the frame of the extension (origin at the corner)""" + default = pg.default_mask(algo, apply_to) + return tuple(((_slice.start + _slice.stop) / 2 - half, (_slice.start + _slice.stop) / 2 + half) + for _slice in default) + + def test_plot_input_and_target_fields(qapp): app, algo = prepare('Gerchberg-Saxton') target = pg.get_target_field(algo) @@ -38,7 +45,7 @@ def test_plot_input_and_target_fields(qapp): def test_plot_intermediate_field_in_log_scale_and_customized(qapp): app, algo = prepare('Parallel Lee', modulator_type='amplitude') - pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, ((-100., 100.), (-100., 100.))) + pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, around_center(algo, ApplyMaskTo.INTERMEDIATE)) pg.run_algorithm(algo) log = pg.log_intensity(algo.intermediate_field, decades=4) assert log.data[0].max() - log.data[0].min() <= 4 + 1e-9 @@ -70,7 +77,7 @@ def test_masks_are_given_as_the_slices_shown_by_the_app_or_as_pairs(qapp): def test_snap_shows_the_intermediate_plane_without_mask_and_keeps_the_masks(qapp): app, algo = prepare('Parallel Lee', modulator_type='amplitude') - mask = ((-100., 100.), (-100., 100.)) + mask = around_center(algo, ApplyMaskTo.INTERMEDIATE) pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, mask) snapped = pg.snap(algo) assert app.apply_mask(ApplyMaskTo.INTERMEDIATE) # restored for the next runs @@ -80,8 +87,8 @@ def test_snap_shows_the_intermediate_plane_without_mask_and_keeps_the_masks(qapp figure = pg.plot_field(snapped, 'snap', log=True, mask=(mask, 'elliptical'), show=False) axes = pg._image_axes(figure) assert all(len(ax.patches) == 1 for ax in axes) - # the axes are centered, as the masks: the outline is around the origin - assert axes[0].patches[0].center == pytest.approx((0., 0.)) + # the plots are centered on the field, the mask is given from its corner: the outline is shifted to the origin + assert axes[0].patches[0].center == pytest.approx((0., 0.), abs=1.) # um, the default mask is rounded x = axes[0].collections[0].get_coordinates()[0, :, 0] assert x[0] < 0 < x[-1] @@ -118,10 +125,10 @@ def test_default_masks_cover_two_thirds_of_the_effective_area_around_the_center( for apply_to, pixel_sizes in ((ApplyMaskTo.INTERMEDIATE, algo.intermediate_pixel_sizes), (ApplyMaskTo.TARGET, algo._target_field.pixels_sizes)): region = pg.default_mask(algo, apply_to) - _, size = regions.get_effective_area(algo.shaper, pixel_sizes) - for _slice, full in zip(region, size): + pos, size = regions.get_effective_area(algo.shaper, pixel_sizes) + for _slice, full, origin in zip(region, size, pos): start, stop = _slice.start, _slice.stop - assert start == pytest.approx(-stop, abs=1) + assert (start + stop) / 2 == pytest.approx(origin + full / 2, abs=1) # extension frame, centered assert stop - start == pytest.approx(full * 2 / 3, abs=2) pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, pg.default_mask(algo, ApplyMaskTo.INTERMEDIATE)) pg.run_algorithm(algo) @@ -207,7 +214,7 @@ def test_unknown_initial_phase_parameter_lists_the_possible_ones(qapp): def test_parameters_are_set_without_widgets_and_masks_applied(qapp): app, algo = prepare('Parallel Lee', dict(carrier_factor=0.5), modulator_type='amplitude') - pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, ((-100., 100.), (-100., 100.))) + pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, around_center(algo, ApplyMaskTo.INTERMEDIATE)) pg.run_algorithm(algo) assert algo.settings['carrier_factor'] == 0.5 assert algo.apply_mask(ApplyMaskTo.INTERMEDIATE) @@ -406,3 +413,14 @@ def test_final_saving_alone(qapp, tmp_path): with h5py.File(path, 'r') as f: assert 'Final' in f['RawData/Shaping000'] assert 'Data2D' not in f['RawData/Shaping000'] # nothing saved at each iteration + + +def test_masks_are_in_the_extension_frame_and_selected_the_same_region_in_the_arrays(qapp): + """ The slices of the extension (origin at the corner of the field) select the region where they point""" + app, algo = prepare('Gerchberg-Saxton') + mask = around_center(algo, ApplyMaskTo.TARGET, half=150.) + pg.set_mask(app, ApplyMaskTo.TARGET, mask, 'square') + slices = app.get_mask_as_slices(ApplyMaskTo.TARGET) + shape = algo.shape + for _slice, size in zip(slices, shape): + assert _slice.start < size / 2 < _slice.stop # around the center of the array, not shifted to a corner From 6ffa1391e8e1fe999dec88620c83ed5517aa14b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 11:03:30 +0000 Subject: [PATCH 03/12] Tests: intermediate masks given in the frame of the extension Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- tests/test_algo_helpers.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tests/test_algo_helpers.py b/tests/test_algo_helpers.py index 8f92093..19d3675 100644 --- a/tests/test_algo_helpers.py +++ b/tests/test_algo_helpers.py @@ -37,9 +37,17 @@ def test_4f_helpers_conserve_energy_and_calibrate_the_output(qapp): assert np.isclose(size.m_as('um'), ref.m_as('um')) +def from_center(algo, slices): + """ A region given in um around the center of the intermediate plane, in the frame of the extension (the origin is + the corner of the field)""" + pixel_sizes = pg.regions.pixel_sizes_in_um(algo.intermediate_pixel_sizes) + return tuple(slice(_slice.start + n * size / 2, _slice.stop + n * size / 2) + for _slice, n, size in zip(slices, algo.shape, pixel_sizes)) + + def test_intermediate_mask_filters_the_intermediate_field(qapp): app, algo = prepare('Binary Threshold', 'amplitude') - pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, ((-60., 60.), (-60., 60.))) + pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, from_center(algo, (slice(-60., 60.), slice(-60., 60.)))) algo.set_amplitude_in_modulator_plane(np.random.default_rng(0).uniform(size=algo.shape)) filtered = algo.compute_intermediate_field() unfiltered = algo.compute_intermediate_field(use_mask=False) @@ -86,8 +94,8 @@ def test_the_input_beam_is_compensated_for_the_amplitude_modulators(qapp): sizes = pg.regions.pixel_sizes_in_um(algo.intermediate_pixel_sizes) half = np.hypot(*algo.order_frequency()) / 3 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))) + from_center(algo, 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.run_algorithm(algo, verbose=False) raw = algo.output_field.amplitude.copy() From 93c9a7a57a23282ff02ce5c3cd102a5f3aacbd53 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 11:03:40 +0000 Subject: [PATCH 04/12] Docs snapshot script: mask in the frame of the extension Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- docs/scripts/binary_holograms_snapshots.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/scripts/binary_holograms_snapshots.py b/docs/scripts/binary_holograms_snapshots.py index 5bcbc24..a284dae 100644 --- a/docs/scripts/binary_holograms_snapshots.py +++ b/docs/scripts/binary_holograms_snapshots.py @@ -32,7 +32,10 @@ pg.set_fields(algo, input_field, target_field) # the order to filter, as given by the algorithm, in um from the center of the intermediate plane y, x = np.array(algo.order_frequency()) * regions.pixel_sizes_in_um(algo.intermediate_pixel_sizes) - mask = ((y - MASK_HALF_SIZE, y + MASK_HALF_SIZE), (x - MASK_HALF_SIZE, x + MASK_HALF_SIZE)) + center_y, center_x = np.array(algo.shape) * regions.pixel_sizes_in_um(algo.intermediate_pixel_sizes) / 2 + # in the frame of the extension: the origin is the corner of the field + mask = ((center_y + y - MASK_HALF_SIZE, center_y + y + MASK_HALF_SIZE), + (center_x + x - MASK_HALF_SIZE, center_x + x + MASK_HALF_SIZE)) pg.set_mask(app, ApplyMaskTo.INTERMEDIATE, mask, 'elliptical') pg.run_algorithm(algo) output = algo.output_field From 4592860fcb5d801e6421661b9c79d56d83d0e24d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:26:06 +0000 Subject: [PATCH 05/12] Saving: the fields, the metrics and the final fields each in their own sub group of the run, with their own savers The groups Fields000 and Metrics000 are enlarged along their own step axis, Final000 holds the fields saved once. They are saved by ModuleSaver children of the ShapingSaver, as the control modules are in the group of an extension. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- docs/src/user_guide/algorithms.rst | 6 +- .../utilities/h5saving.py | 104 ++++++++++++++---- tests/test_algorithm_playground.py | 64 ++++++++--- tests/test_custom_apps.py | 7 +- 4 files changed, 139 insertions(+), 42 deletions(-) diff --git a/docs/src/user_guide/algorithms.rst b/docs/src/user_guide/algorithms.rst index 34ea55b..cbd6b79 100644 --- a/docs/src/user_guide/algorithms.rst +++ b/docs/src/user_guide/algorithms.rst @@ -298,9 +298,9 @@ cells one after the other, editing the settings on the way: The *Run* cell can save the output of each iteration: ``SAVE_FIELDS`` (``True`` for all the fields, the amplitude and phase of the output and modulator planes and the intensity of the intermediate one, or the names of some of them such -as ``('modulator/phase',)``) and ``SAVE_METRICS``, both off by default. ``SAVE_FINAL`` saves once, at the end of the run, all the fields and the metrics of the last iteration, as the *Save* action of the extension does, in a sub group ``Final`` of the group of the run (so with the same settings), whatever is saved at each iteration. The format is the one of the continuous saving -of the extension: a group ``/RawData/ShapingXXX`` per run, holding the data enlarged along a ``step`` axis, with the -settings of the run, saved as in the extension: the name of the algorithm, the number of iterations, the initial phase +as ``('modulator/phase',)``) and ``SAVE_METRICS``, both off by default. ``SAVE_FINAL`` saves once, at the end of the run, all the fields and the metrics of the last iteration, as the *Save* action of the extension does, whatever is saved at each iteration. The format is the one of the continuous saving +of the extension: a group ``/RawData/ShapingXXX`` per run, with the settings of the run, holding one sub group for each kind of data: ``Fields000`` (the fields saved at each iteration) and ``Metrics000`` (the metrics), each enlarged along its own ``step`` navigation axis, and ``Final000`` (the fields saved once at the end, without navigation axis). Only the sub groups of the requested data are created. The settings of the run are saved +as in the extension: the name of the algorithm, the number of iterations, the initial phase and its parameters, the masks (applied or not, type and slices) and the parameters of the algorithm. ``SAVE_FILE`` gives the file (created if needed, the runs being added to it); with ``None`` a file is created in the PyMoDAQ data folder at the first saved run and holds the next ones. Its path is printed (``algo.saved_h5file``). diff --git a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py index 5a4c094..cf387e6 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py @@ -22,9 +22,59 @@ from pymodaq_plugins_beam_shaping.utilities.shaper import ModulatorType extend_enum(GroupModuleType, 'SHAPING') +# the sub groups of the group of a run, each one saved by its own ModuleSaver (named Fields000, Metrics000, Final000) +extend_enum(GroupModuleType, 'FIELDS') +extend_enum(GroupModuleType, 'METRICS') +extend_enum(GroupModuleType, 'FINAL') + + +class ShapingChildSaver(ModuleSaver): + """ Saver of one sub group of the group of a run (the current fields, the metrics, the final fields...) + + As the savers of the control modules in the group of an extension: it owns its group, and the data saver adapted + to it, enlargeable (with its own navigation axis) or not + + Parameters + ---------- + group_type: GroupModuleType + the type of the sub group (FIELDS, METRICS or FINAL), its name is derived from it + enlargeable: bool + the data are enlarged at each step along a navigation axis, otherwise saved once + """ + def __init__(self, group_type: GroupModuleType, enlargeable: bool = True, + enl_axis_names=('step',), enl_axis_units=('',)): + self.group_type = group_type + self.title = group_type.name.capitalize() + self.enlargeable = enlargeable + self.enl_axis_names = enl_axis_names + self.enl_axis_units = enl_axis_units + self._module = self # the title of the module is the one of the group + self._module_group: GROUP = None + self._h5saver: H5Saver = None + self._datatoexport_saver: Union[DataToExportEnlargeableSaver, DataToExportSaver] = None + + def update_after_h5changed(self): + if self.enlargeable: + self._datatoexport_saver = DataToExportEnlargeableSaver( + self.h5saver, self.enl_axis_names, self.enl_axis_units) + else: + self._datatoexport_saver = DataToExportSaver(self.h5saver) + + def _add_module(self, where: Union[Node, str] = None, metadata=None) -> Node: + return self._h5saver.add_generic_group(where, title=self.title, metadata=metadata or {}, + group_type=self.group_type.name) + + def add_data(self, where: Union[Node, str], dte: DataToExport, + axis_values: List[Union[float, np.ndarray]] = None, **kwargs): + if self.enlargeable: + self._datatoexport_saver.add_data(where, dte, axis_values=axis_values) + else: + self._datatoexport_saver.add_data(where, dte) class ShapingSaver(ModuleSaver): + """ Saver of the group of a run (ShapingXXX) with the savers of its sub groups: the fields and the metrics at each + step (``fields``, ``metrics``, each enlarged along its own step axis) and the fields saved once (``final``)""" group_type = GroupModuleType.SHAPING def __init__(self): @@ -35,11 +85,14 @@ def __init__(self): self.enl_axis_names = ('step',) self.enl_axis_units = ('',) - self._datatoexport_saver: DataToExportEnlargeableSaver = None + self.fields = ShapingChildSaver(GroupModuleType.FIELDS) + self.metrics = ShapingChildSaver(GroupModuleType.METRICS) + self.final = ShapingChildSaver(GroupModuleType.FINAL, enlargeable=False) + self.children = (self.fields, self.metrics, self.final) def update_after_h5changed(self): - self._datatoexport_saver = DataToExportEnlargeableSaver( - self.h5saver, self.enl_axis_names, self.enl_axis_units) + for child in self.children: + child.h5saver = self.h5saver def get_set_node(self, where: Union[Node, str] = None, new=False, settings_as_xml= None, common_data: DataToExport = None) -> GROUP: @@ -83,8 +136,14 @@ def _add_module(self, where=None, metadata=None, settings_as_xml='') -> Node: settings_as_xml=settings_as_xml, metadata=metadata) - def add_data(self, dte: DataToExport, axis_values: List[Union[float, np.ndarray]] = None, **kwargs): - """ Append data to the last group, as the next step of the enlargeable arrays + def _child_node(self, child: ShapingChildSaver) -> GROUP: + """ The group of a child saver in the group of the current run, created at first use""" + return child.get_set_node(self.get_last_node(self._h5saver.raw_group), name=child.title) + + def add_data(self, dte: DataToExport, axis_values: List[Union[float, np.ndarray]] = None, + child: ShapingChildSaver = None, **kwargs): + """ Append data as the next step of the enlargeable arrays, in the sub group of ``child`` (by default + the group of the run) Parameters ---------- @@ -93,24 +152,23 @@ def add_data(self, dte: DataToExport, axis_values: List[Union[float, np.ndarray] axis_values: list of float the value of the 'step' axis for these data. By default, the number of data already saved (the N_saved setting of the H5Saver) + child: ShapingChildSaver + ``fields`` or ``metrics``: the sub group where to append the data, with its own step axis """ if axis_values is None: axis_values = (self.h5saver.settings['N_saved'],) - self._datatoexport_saver.add_data(self.get_last_node(self._h5saver.raw_group), dte, - axis_values=axis_values) + if child is None: + raise ValueError('The data are saved in the sub group of a child saver: fields, metrics or final') + child.add_data(self._child_node(child), dte, axis_values=axis_values) + + def add_final_data(self, dte: DataToExport): + """ Save data once in the ``Final`` sub group of the current run, so that they share its settings and + attributes with the data saved at each step, e.g. all the fields at the end of a run""" + self.final.add_data(self._child_node(self.final), dte) def add_data_bundle(self, data: DataBundle): self.add_data(data.dte, axis_values=data.axis_values) - def add_final_data(self, dte: DataToExport, group_name: str = 'Final'): - """ Save data once (not enlarged along the steps) in a sub group of the last group, so that they share its - settings and attributes with the data saved at each step, e.g. all the fields at the end of a run""" - saver = DataToExportSaver(self._h5saver) # not as a context manager: it would close the file - group = saver.add_data_group(self.get_last_node(self._h5saver.raw_group), DataDim.Data2D, title=group_name, - group_name=group_name) - saver.add_data(group, dte) - return group - VERSION_ATTRIBUTE = 'pymodaq_plugins_beam_shaping_version' @@ -280,15 +338,21 @@ def add(self, dte: DataToExport): data = select_data_to_save(dte, self.fields, self.metrics) if len(data) == 0: return - self.module_saver.add_data(data, axis_values=[self._step]) + # the metrics and the fields in their own sub group, each with its own step axis + saver = self.module_saver + for child, selected in ((saver.metrics, [dwa for dwa in data if dwa.name == 'metrics']), + (saver.fields, [dwa for dwa in data if dwa.name != 'metrics'])): + if selected: + self.module_saver.add_data(DataToExport('tosave', data=selected), axis_values=[self._step], + child=child) self._step += 1 self.h5saver.settings.child('N_saved').setValue(self._step) self.h5saver.flush() # the content of the file is up to date at each step, e.g. to browse it while paused - def add_final(self, dte: DataToExport, group_name: str = 'Final'): + def add_final(self, dte: DataToExport): """ Save all the data of the output of an algorithm (every field, the metrics, the unreachable region...) once, - in the sub group ``group_name`` of the group of the current run, whatever the data saved at each step""" - self.module_saver.add_final_data(dte.deepcopy(), group_name) + in the ``Final`` sub group of the group of the current run, whatever the data saved at each step""" + self.module_saver.add_final_data(dte.deepcopy()) self.h5saver.flush() def finalize(self): diff --git a/tests/test_algorithm_playground.py b/tests/test_algorithm_playground.py index c76a067..3b274a6 100644 --- a/tests/test_algorithm_playground.py +++ b/tests/test_algorithm_playground.py @@ -258,25 +258,39 @@ class TmpReload(Direct): +STEP_GROUPS = ('Fields000', 'Metrics000') # the sub groups of a run holding the data saved at each step + + +def saved_step_groups(loader, group='/RawData/Shaping000'): + """ The sub groups of the run with the data saved at each step""" + return [f'{group}/{name}' for name in STEP_GROUPS if name in loader.get_node(group).node] + + def load_saved(path, group='/RawData/Shaping000'): + """ The data saved at each step (fields and metrics) of a run, by full name""" from pymodaq_data.h5modules.data_saving import DataLoader with DataLoader(path) as loader: - return {dwa.get_full_name(): dwa for dwa in loader.load_all(group)} + return {dwa.get_full_name(): dwa for sub in saved_step_groups(loader, group) for dwa in loader.load_all(sub)} def check_enlarged_nodes(path, n_steps, group='/RawData/Shaping000'): - """ The attributes of the enlargeable arrays and of the step axis are the actual ones (not those of one step)""" + """ The attributes of the enlargeable arrays and of the step axis are the actual ones (not those of one step), in + each sub group (each has its own navigation axis)""" from pymodaq_data.h5modules.data_saving import DataLoader with DataLoader(path) as loader: - nodes = [node for node in loader.walk_nodes(group) if 'CLASS' in node.attrs and node.attrs['CLASS'] == 'EARRAY'] - assert len(nodes) > 1 - for node in nodes: - assert tuple(node.attrs['shape']) == tuple(node.node.shape), node.path - if node.name.startswith('EnlData') or node.path.endswith('NavAxes/Axis00'): - assert node.attrs['shape'][0] == n_steps, node.path - axis = loader.get_node(f'{group}/NavAxes/Axis00') - assert axis.attrs['size'] == n_steps - assert list(axis.read()) == list(range(n_steps)) + sub_groups = saved_step_groups(loader, group) + assert sub_groups + for sub in sub_groups: + nodes = [node for node in loader.walk_nodes(sub) + if 'CLASS' in node.attrs and node.attrs['CLASS'] == 'EARRAY'] + assert len(nodes) > 1 + for node in nodes: + assert tuple(node.attrs['shape']) == tuple(node.node.shape), node.path + if node.name.startswith('EnlData') or node.path.endswith('NavAxes/Axis00'): + assert node.attrs['shape'][0] == n_steps, node.path + axis = loader.get_node(f'{sub}/NavAxes/Axis00') + assert axis.attrs['size'] == n_steps + assert list(axis.read()) == list(range(n_steps)) def test_iterations_and_metrics_are_printed_for_iterative_algorithms(qapp, capsys): @@ -394,15 +408,17 @@ def test_all_fields_saved_once_at_the_end_in_the_group_of_the_run(qapp, tmp_path pg.run_algorithm(algo, 3, save_metrics=True, save_final=True, h5file=path) with h5py.File(path, 'r') as f: run = f['RawData/Shaping000'] - assert 'Final' in run + assert set(run) >= {'Final000', 'Metrics000'} # no per step fields were asked for + assert 'Fields000' 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()] + arrays = [d for d in f['RawData/Shaping000/Final000/Data2D'].values()] assert len(arrays) == 4 # output and modulator amplitude and phase 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) # the metrics are still saved at each iteration, next to it - assert f['RawData/Shaping000/Data0D/CH00/EnlData00'].shape[0] == 3 + assert f['RawData/Shaping000/Metrics000/Data0D/CH00/EnlData00'].shape[0] == 3 + assert f['RawData/Shaping000/Metrics000/NavAxes/Axis00'].shape[0] == 3 # each sub group has its step axis def test_final_saving_alone(qapp, tmp_path): @@ -411,8 +427,8 @@ def test_final_saving_alone(qapp, tmp_path): path = tmp_path / 'final_only.h5' pg.run_algorithm(algo, 2, save_final=True, h5file=path) with h5py.File(path, 'r') as f: - assert 'Final' in f['RawData/Shaping000'] - assert 'Data2D' not in f['RawData/Shaping000'] # nothing saved at each iteration + assert 'Final000' in f['RawData/Shaping000'] + assert 'Fields000' not in f['RawData/Shaping000'] and 'Metrics000' not in f['RawData/Shaping000'] def test_masks_are_in_the_extension_frame_and_selected_the_same_region_in_the_arrays(qapp): @@ -424,3 +440,19 @@ def test_masks_are_in_the_extension_frame_and_selected_the_same_region_in_the_ar shape = algo.shape for _slice, size in zip(slices, shape): assert _slice.start < size / 2 < _slice.stop # around the center of the array, not shifted to a corner + + +def test_fields_and_metrics_each_in_their_sub_group_with_their_step_axis(qapp, tmp_path): + import h5py + app, algo = prepare('Gerchberg-Saxton') + path = tmp_path / 'groups.h5' + pg.run_algorithm(algo, 3, save_fields=('modulator/phase', 'output/amplitude'), save_metrics=True, save_final=True, + h5file=path) + with h5py.File(path, 'r') as f: + run = f['RawData/Shaping000'] + assert set(run) >= {'Fields000', 'Metrics000', 'Final000'} + for name in ('Fields000', 'Metrics000'): + assert run[name]['NavAxes']['Axis00'].shape == (3,) + assert 'NavAxes' not in run['Final000'] + assert run['Fields000']['Data2D']['CH00']['EnlData00'].shape[0] == 3 + assert 'Data0D' not in run['Fields000'] and 'Data2D' not in run['Metrics000'] diff --git a/tests/test_custom_apps.py b/tests/test_custom_apps.py index 3a0e9ef..6fd2939 100644 --- a/tests/test_custom_apps.py +++ b/tests/test_custom_apps.py @@ -87,7 +87,8 @@ def test_algo_app_continuous_saving(qtbot, dockarea, tmp_path): with DataLoader(tmp_path / 'continuous.h5') as loader: assert loader.get_node('/RawData/Shaping000').attrs['title'] == 'BeamShaping' - saved = {dwa.get_full_name(): dwa for dwa in loader.load_all('/RawData/Shaping000')} + from test_algorithm_playground import load_saved + saved = load_saved(tmp_path / 'continuous.h5') assert set(saved) == {'modulator/phase', 'AlgoData/metrics'} assert all(dwa.shape[0] == 2 for dwa in saved.values()) @@ -218,8 +219,8 @@ def test_algo_app_saves_what_is_sent_to_the_shaper(qtbot, dockarea, tmp_path, mo app.do_save_continuous(True) app.save_continuous(algo.get_fields_to_plot()) app.close_file() - with DataLoader(tmp_path / 'sent.h5') as loader: - saved = {dwa.get_full_name() for dwa in loader.load_all('/RawData/Shaping000')} + from test_algorithm_playground import load_saved + saved = set(load_saved(tmp_path / 'sent.h5')) assert saved == expected | {'AlgoData/metrics'} From 5f69094ac6728caceb427b3a42d8dd23abe1131b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:36:09 +0000 Subject: [PATCH 06/12] Saved runs: Input and Target groups, RunSaver, code shared with the Save of the extension ContinuousSaver is renamed RunSaver (it saves a whole run). The Input and Target fields of a run are saved with the settings of their loaders by the code of the field files (add_field_group), and the Final group by the one of AlgoApp.save (add_algorithm_group). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- docs/src/user_guide/algorithms.rst | 2 +- .../algorithms/algorithm_app.py | 32 ++++++------ src/pymodaq_plugins_beam_shaping/field/h5.py | 25 +++++++-- .../utilities/h5saving.py | 51 ++++++++++++++++--- .../utilities/headless_algorithms.py | 33 ++++++++++-- tests/test_algorithm_playground.py | 37 +++++++++++--- tests/test_custom_apps.py | 2 +- 7 files changed, 140 insertions(+), 42 deletions(-) diff --git a/docs/src/user_guide/algorithms.rst b/docs/src/user_guide/algorithms.rst index cbd6b79..f6ef62d 100644 --- a/docs/src/user_guide/algorithms.rst +++ b/docs/src/user_guide/algorithms.rst @@ -299,7 +299,7 @@ cells one after the other, editing the settings on the way: The *Run* cell can save the output of each iteration: ``SAVE_FIELDS`` (``True`` for all the fields, the amplitude and phase of the output and modulator planes and the intensity of the intermediate one, or the names of some of them such as ``('modulator/phase',)``) and ``SAVE_METRICS``, both off by default. ``SAVE_FINAL`` saves once, at the end of the run, all the fields and the metrics of the last iteration, as the *Save* action of the extension does, whatever is saved at each iteration. The format is the one of the continuous saving -of the extension: a group ``/RawData/ShapingXXX`` per run, with the settings of the run, holding one sub group for each kind of data: ``Fields000`` (the fields saved at each iteration) and ``Metrics000`` (the metrics), each enlarged along its own ``step`` navigation axis, and ``Final000`` (the fields saved once at the end, without navigation axis). Only the sub groups of the requested data are created. The settings of the run are saved +of the extension: a group ``/RawData/ShapingXXX`` per run, with the settings of the run, holding one sub group for each kind of data: ``Fields000`` (the fields saved at each iteration) and ``Metrics000`` (the metrics), each enlarged along its own ``step`` navigation axis, ``Final`` (the fields saved once at the end, without navigation axis, saved as the *Algorithm* group of the extension's *Save*) and the ``Input`` and ``Target`` groups (the fields as used by the algorithm, with the settings of their loaders, as the *Input* and *Target* groups of the extension's *Save*, readable with the same function). The sub groups of the data per iteration and ``Final`` are only created if requested. The settings of the run are saved as in the extension: the name of the algorithm, the number of iterations, the initial phase and its parameters, the masks (applied or not, type and slices) and the parameters of the algorithm. ``SAVE_FILE`` gives the file (created if needed, the runs being added to it); with ``None`` a file is created in the PyMoDAQ data folder at the first saved run and holds the next ones. Its path is printed (``algo.saved_h5file``). diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py index a46e2d7..719843a 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py @@ -41,8 +41,9 @@ from pymodaq_plugins_beam_shaping.field import Field from pymodaq_plugins_beam_shaping import config as plugin_config from pymodaq_plugins_beam_shaping.algorithms.algo_config import AlgoConfig -from pymodaq_plugins_beam_shaping.utilities.h5saving import (ShapingSaver, ContinuousSaver, FIELDS_SAVED_BY_THE_APP, +from pymodaq_plugins_beam_shaping.utilities.h5saving import (ShapingSaver, RunSaver, FIELDS_SAVED_BY_THE_APP, configure_h5saver, fields_of_modulator, algorithm_name_settings, + add_algorithm_group, add_plugin_version) from pymodaq_plugins_beam_shaping.field.h5 import settings_to_xml @@ -109,7 +110,7 @@ def status_text(algo_class: type[AlgoBase]) -> str: class AlgoApp(CustomApp): save_settings = True 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 + h5_base_group_name = RunSaver.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 params = [ @@ -175,7 +176,7 @@ def __init__(self, dockarea, toolbar: QtWidgets.QToolBar=None, shaper: Shaper = self._current_phase: np.ndarray = None # cached phase to be used for subsequent optimizations # the continuous saving writes in the file of the H5Manager of the app (CustomApp.h5_manager) - self._continuous_saver = ContinuousSaver(fields=FIELDS_SAVED_BY_THE_APP, metrics=True, + self._run_saver = RunSaver(fields=FIELDS_SAVED_BY_THE_APP, metrics=True, h5saver_provider=self._get_h5saver) self._h5saver_configured = False @@ -201,7 +202,7 @@ def __init__(self, dockarea, toolbar: QtWidgets.QToolBar=None, shaper: Shaper = def _configure_h5saver(self): """ Set the H5Saver of the H5Manager for the continuous saving, before its first file is created""" if not self._h5saver_configured: - configure_h5saver(self.h5_manager.get_h5saver(create_new_file=False), ContinuousSaver.base_name) + configure_h5saver(self.h5_manager.get_h5saver(create_new_file=False), RunSaver.base_name) self._h5saver_configured = True def _get_h5saver(self) -> H5Saver: @@ -210,13 +211,13 @@ def _get_h5saver(self) -> H5Saver: return self.h5_manager.h5saver @property - def continuous_saver(self) -> ContinuousSaver: - return self._continuous_saver + def run_saver(self) -> RunSaver: + return self._run_saver @property def module_and_data_saver(self) -> Union[ShapingSaver, None]: """ The saver of the continuous saving, None until it is used""" - return self._continuous_saver.module_saver if self._continuous_saver.is_set else None + return self._run_saver.module_saver if self._run_saver.is_set else None @property def h5saver(self) -> H5Saver: @@ -228,8 +229,8 @@ def close_file(self): def _finalize_saving(self): """ Make the file consistent (SWMR ended, shapes up to date): on pause, stop and before closing it""" - if self._continuous_saver.is_set: - self._continuous_saver.finalize() + if self._run_saver.is_set: + self._run_saver.finalize() self.h5_manager.update_file_status_led() def do_save_continuous(self, dosave: bool = True): @@ -241,14 +242,14 @@ def do_save_continuous(self, dosave: bool = True): if self._algorithm is not None: settings = [algorithm_name_settings(self._algorithm.ALGO_NAME)] + settings + [self._algorithm.settings] # what is sent to the shaper: the phase for a phase modulator, the amplitude for an amplitude one... - self._continuous_saver.fields = fields_of_modulator(self.shaper.modulator_type) - self._continuous_saver.start(settings_as_xml=settings_to_xml(settings)) + self._run_saver.fields = fields_of_modulator(self.shaper.modulator_type) + self._run_saver.start(settings_as_xml=settings_to_xml(settings)) def save_continuous(self, dte: DataToExport): """ Save the part of the output of the algorithm chosen in the continuous saver (modulator phase and metrics) """ - if self._continuous_saver.is_set: - self._continuous_saver.add(dte) + if self._run_saver.is_set: + self._run_saver.add(dte) def quit_fun(self): super().quit_fun() @@ -283,9 +284,8 @@ def save(self, fname: H5Saver | Path = None, where: str = '/RawData', self.algorithm.settings)) with DataToExportSaver(fname, new_file=new_file, save_type=SaveType.custom) as saver: - group = saver.add_data_group(where, DataDim.Data2D, title=title, settings_as_xml=settings_str, - group_name=group_name) - saver.add_data(group, self.algorithm.get_fields_to_plot()) + add_algorithm_group(saver, self.algorithm.get_fields_to_plot(), where, group_name, title, + settings_as_xml=settings_str) add_plugin_version(saver) diff --git a/src/pymodaq_plugins_beam_shaping/field/h5.py b/src/pymodaq_plugins_beam_shaping/field/h5.py index ef7825c..1f26810 100644 --- a/src/pymodaq_plugins_beam_shaping/field/h5.py +++ b/src/pymodaq_plugins_beam_shaping/field/h5.py @@ -26,6 +26,25 @@ def settings_to_xml(settings: Iterable[Parameter]) -> bytes: return settings_str +def field_as_dwa(field: Field) -> DataCalculated: + """ The field (amplitude and phase) as one data object, the format of the field files and of the Input and Target + groups of the saved runs, read by :func:`load_field_from_h5`""" + return DataCalculated('Field', data=[field.amplitude, field.phase], labels=['Amplitude', 'Phase'], + axes=field.get_axes()) + + +def add_field_group(saver: DataSaverLoader, field: Field, settings: Iterable[Parameter] = (), + where: str = '/RawData', group_name: str = 'Field', title: str = ''): + """ Add to an opened file a group holding the field and the settings used to produce it (those of its loader) + + Shared by the field files, the save of the extension (Input and Target groups) and the saved runs of the + algorithm script""" + group = saver.add_data_group(where, DataDim.Data2D, title=title, settings_as_xml=settings_to_xml(settings), + group_name=group_name) + saver.add_data(group, field_as_dwa(field)) + return group + + def save_field_to_h5(field: Field, fname: Union[str, Path], settings: Iterable[Parameter] = (), where: str = '/RawData', group_name: str = 'Field', title: str = ''): """ Save the field (amplitude and phase) and the settings used to produce it into a hdf5 file @@ -33,12 +52,8 @@ def save_field_to_h5(field: Field, fname: Union[str, Path], settings: Iterable[P The field is added to the file if it exists.""" fname = Path(fname) new_file = not fname.exists() - dwa = DataCalculated('Field', data=[field.amplitude, field.phase], labels=['Amplitude', 'Phase'], - axes=field.get_axes()) with DataSaverLoader(fname, new_file=new_file) as saver: - group = saver.add_data_group(where, DataDim.Data2D, title=title, settings_as_xml=settings_to_xml(settings), - group_name=group_name) - saver.add_data(group, dwa) + add_field_group(saver, field, settings, where, group_name, title) add_plugin_version(saver) diff --git a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py index cf387e6..10099de 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py @@ -22,10 +22,9 @@ from pymodaq_plugins_beam_shaping.utilities.shaper import ModulatorType extend_enum(GroupModuleType, 'SHAPING') -# the sub groups of the group of a run, each one saved by its own ModuleSaver (named Fields000, Metrics000, Final000) +# the sub groups of the group of a run saved at each step, each one by its own ModuleSaver (Fields000, Metrics000) extend_enum(GroupModuleType, 'FIELDS') extend_enum(GroupModuleType, 'METRICS') -extend_enum(GroupModuleType, 'FINAL') class ShapingChildSaver(ModuleSaver): @@ -74,7 +73,8 @@ def add_data(self, where: Union[Node, str], dte: DataToExport, class ShapingSaver(ModuleSaver): """ Saver of the group of a run (ShapingXXX) with the savers of its sub groups: the fields and the metrics at each - step (``fields``, ``metrics``, each enlarged along its own step axis) and the fields saved once (``final``)""" + step (``fields``, ``metrics``, each enlarged along its own step axis), the fields saved once at the end (``Final``) and the + input and target fields (``Input``, ``Target``)""" group_type = GroupModuleType.SHAPING def __init__(self): @@ -87,8 +87,7 @@ def __init__(self): self.fields = ShapingChildSaver(GroupModuleType.FIELDS) self.metrics = ShapingChildSaver(GroupModuleType.METRICS) - self.final = ShapingChildSaver(GroupModuleType.FINAL, enlargeable=False) - self.children = (self.fields, self.metrics, self.final) + self.children = (self.fields, self.metrics) def update_after_h5changed(self): for child in self.children: @@ -163,13 +162,40 @@ def add_data(self, dte: DataToExport, axis_values: List[Union[float, np.ndarray] def add_final_data(self, dte: DataToExport): """ Save data once in the ``Final`` sub group of the current run, so that they share its settings and - attributes with the data saved at each step, e.g. all the fields at the end of a run""" - self.final.add_data(self._child_node(self.final), dte) + attributes with the data saved at each step, e.g. all the fields at the end of a run (as the Save of the + extension does, with the same code: :func:`add_algorithm_group`)""" + saver = DataToExportSaver(self._h5saver) # not as a context manager: it closes the file + return add_algorithm_group(saver, dte, where=self.get_last_node(self._h5saver.raw_group), + group_name='Final', title='Final Fields') + + def add_loaded_field(self, field: 'Field', settings: Iterable = (), group_name: str = 'Input'): + """ Save once a field (its amplitude and phase) in the sub group ``group_name`` of the current run, with the + settings of the loader that produced it as the metadata of the group. + + The same group (``Input`` and ``Target``) and format as the save of the extension, shared code + (:func:`add_field_group`): it can be read with :func:`load_field_from_h5`""" + from pymodaq_data.h5modules.data_saving import DataSaverLoader + from pymodaq_plugins_beam_shaping.field.h5 import add_field_group + add_field_group(DataSaverLoader(self._h5saver), field, settings, # not as a context manager: it closes the file + where=self.get_last_node(self._h5saver.raw_group), group_name=group_name, + title=f'{group_name} Field') def add_data_bundle(self, data: DataBundle): self.add_data(data.dte, axis_values=data.axis_values) +def add_algorithm_group(saver: DataToExportSaver, dte: DataToExport, where: Union[Node, str] = '/RawData', + group_name: str = 'Algorithm', title: str = '', settings_as_xml: Union[bytes, str] = ''): + """ Add to an opened file a group holding the fields of an algorithm (the output of ``get_fields_to_plot``) and, + optionally, the settings that produced them + + Shared by the Save of the extension (the ``Algorithm`` group) and by the saved runs (the ``Final`` group)""" + group = saver.add_data_group(where, DataDim.Data2D, title=title, settings_as_xml=settings_as_xml, + group_name=group_name) + saver.add_data(group, dte) + return group + + VERSION_ATTRIBUTE = 'pymodaq_plugins_beam_shaping_version' @@ -242,7 +268,7 @@ def configure_h5saver(h5saver: H5Saver, base_name: str = 'Shaping') -> H5Saver: return h5saver -class ContinuousSaver: +class RunSaver: """ Save the output of an algorithm at each iteration in a h5 file The format of the continuous saving of the AlgoApp: a group /RawData/ShapingXXX (ShapingSaver) per run, holding the @@ -349,6 +375,15 @@ def add(self, dte: DataToExport): self.h5saver.settings.child('N_saved').setValue(self._step) self.h5saver.flush() # the content of the file is up to date at each step, e.g. to browse it while paused + def add_loaded_fields(self, input_field: 'Field' = None, target_field: 'Field' = None, + input_settings: Iterable = (), target_settings: Iterable = ()): + """ Save the input and the target fields of a run, each in its sub group (``Input``, ``Target``) of the group of + the current run, with the settings of the loaders as the metadata of the group (as the extension does)""" + for name, field, settings in (('Input', input_field, input_settings), ('Target', target_field, target_settings)): + if field is not None: + self.module_saver.add_loaded_field(field, settings, name) + self.h5saver.flush() + def add_final(self, dte: DataToExport): """ Save all the data of the output of an algorithm (every field, the metrics, the unreachable region...) once, in the ``Final`` sub group of the group of the current run, whatever the data saved at each step""" diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index 56d3aa8..f61858d 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -20,7 +20,7 @@ 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 -from pymodaq_plugins_beam_shaping.utilities.h5saving import ContinuousSaver, algorithm_name_settings +from pymodaq_plugins_beam_shaping.utilities.h5saving import RunSaver, algorithm_name_settings from pymodaq_plugins_beam_shaping.field.h5 import settings_to_xml from pymodaq_plugins_beam_shaping.utilities.shaper import Shaper, get_default_shaper from pymodaq_data import Q_ @@ -91,6 +91,8 @@ class HeadlessApp: def __init__(self, shaper: Shaper): self.shaper = shaper self.algorithm = None + self.loaded_fields = [] # (field, loader) of the fields loaded with load_field, to save the loader settings + 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} shape = sizing.get_effective_needed_field_size(shaper) pixel_size = sizing.get_effective_slm_pixel_size(shaper) @@ -198,11 +200,28 @@ def load_field(loader_name: str, params: Optional[dict], app: HeadlessApp): field = loader.load_field(notify=False) shape = sizing.get_effective_needed_field_size(app.shaper) pixel_size = Q_(sizing.get_effective_slm_pixel_size(app.shaper), 'um') - return fit_to_shape(field, shape, (pixel_size, pixel_size)) + field = fit_to_shape(field, shape, (pixel_size, pixel_size)) + app.loaded_fields.append((field, loader)) + return field + + +def loader_settings(app: HeadlessApp, loader) -> list: + """ The settings of a loader to save with the field it produced, laid out as the field loader app of the extension + does when it saves a field: its settings (loader name, needed size) and the ones of the loader""" + from pyqtgraph.parametertree import Parameter + loader_app = Parameter.create(name='LoaderAppSettings', type='group', children=[ + {'name': 'loader', 'title': 'Loader', 'type': 'str', 'value': type(loader).LOADER_NAME}]) + loader_app.addChild(Parameter.create(name='needed_size', title='Needed size', type='group', children=[ + {'name': child.name(), 'title': child.title(), 'type': child.type(), 'value': child.value()} + for child in app.settings.child('needed_size').children()])) + return [loader_app, loader.settings] def set_fields(algo, input_field, target_field): """ Give the input and target fields to the algorithm, as the app does (the target is scaled by the algo)""" + app = algo.parent_app + for role, field in (('input', input_field), ('target', target_field)): # keep the loader of each, to save it + app.field_loaders[role] = next((loader for loaded, loader in app.loaded_fields if loaded is field), None) algo.set_modulator_field(input_field.deepcopy()) algo.set_input_field(input_field) algo.set_target_field(algo.scale_target_with_geometry(target_field)) @@ -324,16 +343,22 @@ def run_algorithm(algo, n_iterations: int = 1, ini_phase: Union[str, np.ndarray] if save_fields or save_metrics or save_final: global _data_folder_saver if h5file is not None: - saver = ContinuousSaver() + saver = RunSaver() saver.open_file(h5file) else: # one file in the data folder for the session (the file name has a one second resolution) if _data_folder_saver is None: - _data_folder_saver = ContinuousSaver() + _data_folder_saver = RunSaver() saver = _data_folder_saver saver.fields, saver.metrics = save_fields, save_metrics saver.start(settings_as_xml=settings_to_xml(( algorithm_name_settings(type(algo).ALGO_NAME), run_settings(algo, algo.parent_app, ini_phase, ini_phase_params, n_iterations), algo.settings))) + # the input and target fields as used by the algorithm, with the settings of their loaders + app = algo.parent_app + saver.add_loaded_fields( + algo._input_field, algo._target_field, + *[loader_settings(app, app.field_loaders[role]) if app.field_loaders[role] is not None else () + for role in ('input', 'target')]) try: algo.do_things_after_init() if algo.INI_PHASE: diff --git a/tests/test_algorithm_playground.py b/tests/test_algorithm_playground.py index 3b274a6..df8ca85 100644 --- a/tests/test_algorithm_playground.py +++ b/tests/test_algorithm_playground.py @@ -385,10 +385,10 @@ def test_runs_added_to_the_same_file(qapp, tmp_path): def test_saving_resumed_after_a_pause_in_the_same_group(qapp, tmp_path): """ finalize (pause) makes the attributes of the file right, the next steps are appended to the same group""" - from pymodaq_plugins_beam_shaping.utilities.h5saving import ContinuousSaver + from pymodaq_plugins_beam_shaping.utilities.h5saving import RunSaver app, algo = prepare('Gerchberg-Saxton') pg.run_algorithm(algo) - saver = ContinuousSaver(fields=('modulator/phase',), metrics=True) + saver = RunSaver(fields=('modulator/phase',), metrics=True) saver.open_file(tmp_path / 'pause.h5') saver.start() for _ in range(2): @@ -408,10 +408,10 @@ def test_all_fields_saved_once_at_the_end_in_the_group_of_the_run(qapp, tmp_path pg.run_algorithm(algo, 3, save_metrics=True, save_final=True, h5file=path) with h5py.File(path, 'r') as f: run = f['RawData/Shaping000'] - assert set(run) >= {'Final000', 'Metrics000'} # no per step fields were asked for + assert set(run) >= {'Final', 'Metrics000'} # no per step fields were asked for assert 'Fields000' 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/Final000/Data2D'].values()] + arrays = [d for d in f['RawData/Shaping000/Final/Data2D'].values()] assert len(arrays) == 4 # output and modulator amplitude and phase 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') @@ -427,7 +427,7 @@ def test_final_saving_alone(qapp, tmp_path): path = tmp_path / 'final_only.h5' pg.run_algorithm(algo, 2, save_final=True, h5file=path) with h5py.File(path, 'r') as f: - assert 'Final000' in f['RawData/Shaping000'] + assert 'Final' in f['RawData/Shaping000'] assert 'Fields000' not in f['RawData/Shaping000'] and 'Metrics000' not in f['RawData/Shaping000'] @@ -450,9 +450,32 @@ def test_fields_and_metrics_each_in_their_sub_group_with_their_step_axis(qapp, t h5file=path) with h5py.File(path, 'r') as f: run = f['RawData/Shaping000'] - assert set(run) >= {'Fields000', 'Metrics000', 'Final000'} + assert set(run) >= {'Fields000', 'Metrics000', 'Final'} for name in ('Fields000', 'Metrics000'): assert run[name]['NavAxes']['Axis00'].shape == (3,) - assert 'NavAxes' not in run['Final000'] + assert 'NavAxes' not in run['Final'] assert run['Fields000']['Data2D']['CH00']['EnlData00'].shape[0] == 3 assert 'Data0D' not in run['Fields000'] and 'Data2D' not in run['Metrics000'] + + +def test_input_and_target_saved_with_the_settings_of_their_loaders(qapp, tmp_path): + from pymodaq_data.h5modules.data_saving import DataLoader + app, algo = prepare('Gerchberg-Saxton') + path = tmp_path / 'loaders.h5' + pg.run_algorithm(algo, 2, save_metrics=True, h5file=path) + with DataLoader(path) as loader: + run = '/RawData/Shaping000' + for name, loader_name in (('Input', 'ImageFiles'), ('Target', 'LaguerreGaussian')): + node = loader.get_node(f'{run}/{name}') + settings = node.attrs['settings'] + settings = settings.decode() if isinstance(settings, bytes) else settings + assert loader_name in settings # the settings of the loader that produced the field + assert 'needed_size' in settings + # in the format of the field files: readable by load_field_from_h5, as the Input and Target groups of the extension + from pymodaq_plugins_beam_shaping.field.h5 import load_field_from_h5 + saved_input = load_field_from_h5(path, f'{run}/Input/Data00') + saved_target = load_field_from_h5(path, f'{run}/Target/Data00') + assert np.allclose(saved_input.amplitude, algo._input_field.amplitude) + assert np.allclose(saved_target.amplitude, algo._target_field.amplitude) # as used by the algorithm + # they are saved once (no step axis) and not part of the data saved at each iteration + assert 'input/amplitude' not in load_saved(path) diff --git a/tests/test_custom_apps.py b/tests/test_custom_apps.py index 6fd2939..cd4dfbc 100644 --- a/tests/test_custom_apps.py +++ b/tests/test_custom_apps.py @@ -79,7 +79,7 @@ def test_algo_app_continuous_saving(qtbot, dockarea, tmp_path): app.save_continuous(algo.get_fields_to_plot()) assert len(flushed) > n_flushes del app.h5saver.flush - assert app.continuous_saver.file_path == tmp_path / 'continuous.h5' + assert app.run_saver.file_path == tmp_path / 'continuous.h5' app._finalize_saving() # as when the algorithm is paused: the attributes of the arrays are up to date from test_algorithm_playground import check_enlarged_nodes check_enlarged_nodes(tmp_path / 'continuous.h5', 2) From 642a7370cd0ef1962540a23696c557b0c4ac5e0a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:37:48 +0000 Subject: [PATCH 07/12] h5saving: import Field for the type annotations (flake8 F821) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- src/pymodaq_plugins_beam_shaping/utilities/h5saving.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py index 10099de..1dcef90 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py @@ -21,6 +21,9 @@ from pymodaq_plugins_beam_shaping.utilities.shaper import ModulatorType +if TYPE_CHECKING: + from pymodaq_plugins_beam_shaping.field.field import Field + extend_enum(GroupModuleType, 'SHAPING') # the sub groups of the group of a run saved at each step, each one by its own ModuleSaver (Fields000, Metrics000) extend_enum(GroupModuleType, 'FIELDS') From 5e7b59e33196f3d597272f6daaa5fe2970887403 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:45:25 +0000 Subject: [PATCH 08/12] Saved runs: the sub groups Fields and Metrics are not indexed Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- docs/src/user_guide/algorithms.rst | 2 +- .../utilities/h5saving.py | 7 ++++--- tests/test_algorithm_playground.py | 20 +++++++++---------- 3 files changed, 15 insertions(+), 14 deletions(-) diff --git a/docs/src/user_guide/algorithms.rst b/docs/src/user_guide/algorithms.rst index f6ef62d..01d2d19 100644 --- a/docs/src/user_guide/algorithms.rst +++ b/docs/src/user_guide/algorithms.rst @@ -299,7 +299,7 @@ cells one after the other, editing the settings on the way: The *Run* cell can save the output of each iteration: ``SAVE_FIELDS`` (``True`` for all the fields, the amplitude and phase of the output and modulator planes and the intensity of the intermediate one, or the names of some of them such as ``('modulator/phase',)``) and ``SAVE_METRICS``, both off by default. ``SAVE_FINAL`` saves once, at the end of the run, all the fields and the metrics of the last iteration, as the *Save* action of the extension does, whatever is saved at each iteration. The format is the one of the continuous saving -of the extension: a group ``/RawData/ShapingXXX`` per run, with the settings of the run, holding one sub group for each kind of data: ``Fields000`` (the fields saved at each iteration) and ``Metrics000`` (the metrics), each enlarged along its own ``step`` navigation axis, ``Final`` (the fields saved once at the end, without navigation axis, saved as the *Algorithm* group of the extension's *Save*) and the ``Input`` and ``Target`` groups (the fields as used by the algorithm, with the settings of their loaders, as the *Input* and *Target* groups of the extension's *Save*, readable with the same function). The sub groups of the data per iteration and ``Final`` are only created if requested. The settings of the run are saved +of the extension: a group ``/RawData/ShapingXXX`` per run, with the settings of the run, holding one sub group for each kind of data: ``Fields`` (the fields saved at each iteration) and ``Metrics`` (the metrics), each enlarged along its own ``step`` navigation axis, ``Final`` (the fields saved once at the end, without navigation axis, saved as the *Algorithm* group of the extension's *Save*) and the ``Input`` and ``Target`` groups (the fields as used by the algorithm, with the settings of their loaders, as the *Input* and *Target* groups of the extension's *Save*, readable with the same function). The sub groups of the data per iteration and ``Final`` are only created if requested. The settings of the run are saved as in the extension: the name of the algorithm, the number of iterations, the initial phase and its parameters, the masks (applied or not, type and slices) and the parameters of the algorithm. ``SAVE_FILE`` gives the file (created if needed, the runs being added to it); with ``None`` a file is created in the PyMoDAQ data folder at the first saved run and holds the next ones. Its path is printed (``algo.saved_h5file``). diff --git a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py index 1dcef90..ee4f73d 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py @@ -25,7 +25,7 @@ from pymodaq_plugins_beam_shaping.field.field import Field extend_enum(GroupModuleType, 'SHAPING') -# the sub groups of the group of a run saved at each step, each one by its own ModuleSaver (Fields000, Metrics000) +# the sub groups of the group of a run saved at each step, each one by its own ModuleSaver (Fields, Metrics) extend_enum(GroupModuleType, 'FIELDS') extend_enum(GroupModuleType, 'METRICS') @@ -63,8 +63,9 @@ def update_after_h5changed(self): self._datatoexport_saver = DataToExportSaver(self.h5saver) def _add_module(self, where: Union[Node, str] = None, metadata=None) -> Node: - return self._h5saver.add_generic_group(where, title=self.title, metadata=metadata or {}, - group_type=self.group_type.name) + # not indexed: there is one per run, in the group of the run + return self._h5saver.add_group(self.title, self.group_type.name, where, title=self.title, + metadata=metadata or {}) def add_data(self, where: Union[Node, str], dte: DataToExport, axis_values: List[Union[float, np.ndarray]] = None, **kwargs): diff --git a/tests/test_algorithm_playground.py b/tests/test_algorithm_playground.py index df8ca85..4fe5915 100644 --- a/tests/test_algorithm_playground.py +++ b/tests/test_algorithm_playground.py @@ -258,7 +258,7 @@ class TmpReload(Direct): -STEP_GROUPS = ('Fields000', 'Metrics000') # the sub groups of a run holding the data saved at each step +STEP_GROUPS = ('Fields', 'Metrics') # the sub groups of a run holding the data saved at each step def saved_step_groups(loader, group='/RawData/Shaping000'): @@ -408,8 +408,8 @@ def test_all_fields_saved_once_at_the_end_in_the_group_of_the_run(qapp, tmp_path pg.run_algorithm(algo, 3, save_metrics=True, save_final=True, h5file=path) with h5py.File(path, 'r') as f: run = f['RawData/Shaping000'] - assert set(run) >= {'Final', 'Metrics000'} # no per step fields were asked for - assert 'Fields000' not in run + assert set(run) >= {'Final', 'Metrics'} # no per step fields were asked for + 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 @@ -417,8 +417,8 @@ def test_all_fields_saved_once_at_the_end_in_the_group_of_the_run(qapp, tmp_path assert any(np.allclose(ds[...], algo.output_field.amplitude) for ds in amp.values() if hasattr(ds, 'shape') and ds.ndim == 2) # the metrics are still saved at each iteration, next to it - assert f['RawData/Shaping000/Metrics000/Data0D/CH00/EnlData00'].shape[0] == 3 - assert f['RawData/Shaping000/Metrics000/NavAxes/Axis00'].shape[0] == 3 # each sub group has its step axis + assert f['RawData/Shaping000/Metrics/Data0D/CH00/EnlData00'].shape[0] == 3 + assert f['RawData/Shaping000/Metrics/NavAxes/Axis00'].shape[0] == 3 # each sub group has its step axis def test_final_saving_alone(qapp, tmp_path): @@ -428,7 +428,7 @@ def test_final_saving_alone(qapp, tmp_path): pg.run_algorithm(algo, 2, save_final=True, h5file=path) with h5py.File(path, 'r') as f: assert 'Final' in f['RawData/Shaping000'] - assert 'Fields000' not in f['RawData/Shaping000'] and 'Metrics000' not in f['RawData/Shaping000'] + assert 'Fields' not in f['RawData/Shaping000'] and 'Metrics' not in f['RawData/Shaping000'] def test_masks_are_in_the_extension_frame_and_selected_the_same_region_in_the_arrays(qapp): @@ -450,12 +450,12 @@ def test_fields_and_metrics_each_in_their_sub_group_with_their_step_axis(qapp, t h5file=path) with h5py.File(path, 'r') as f: run = f['RawData/Shaping000'] - assert set(run) >= {'Fields000', 'Metrics000', 'Final'} - for name in ('Fields000', 'Metrics000'): + assert set(run) >= {'Fields', 'Metrics', 'Final'} + for name in ('Fields', 'Metrics'): assert run[name]['NavAxes']['Axis00'].shape == (3,) assert 'NavAxes' not in run['Final'] - assert run['Fields000']['Data2D']['CH00']['EnlData00'].shape[0] == 3 - assert 'Data0D' not in run['Fields000'] and 'Data2D' not in run['Metrics000'] + assert run['Fields']['Data2D']['CH00']['EnlData00'].shape[0] == 3 + assert 'Data0D' not in run['Fields'] and 'Data2D' not in run['Metrics'] def test_input_and_target_saved_with_the_settings_of_their_loaders(qapp, tmp_path): From 3ece03a467b15c61d7d1af4883bcfc0074f4f271 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:51:00 +0000 Subject: [PATCH 09/12] Saved runs: the settings of the loaders are laid out as the loader app of the extension saves them All the settings of the loader app (from FieldLoaderApp.params) with the values the script used, plus the settings of the loader. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- .../utilities/headless_algorithms.py | 37 +++++++++++++------ tests/test_algorithm_playground.py | 4 ++ 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py index f61858d..6fb7eef 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/headless_algorithms.py @@ -91,7 +91,7 @@ class HeadlessApp: def __init__(self, shaper: Shaper): self.shaper = shaper self.algorithm = None - self.loaded_fields = [] # (field, loader) of the fields loaded with load_field, to save the loader settings + 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} shape = sizing.get_effective_needed_field_size(shaper) @@ -198,22 +198,34 @@ def load_field(loader_name: str, params: Optional[dict], app: HeadlessApp): loader = LoaderFactory.get_loader(loader_name)(parent=app) set_parameters(loader, params or {}) field = loader.load_field(notify=False) + ini_shape = tuple(field.shape) shape = sizing.get_effective_needed_field_size(app.shaper) pixel_size = Q_(sizing.get_effective_slm_pixel_size(app.shaper), 'um') field = fit_to_shape(field, shape, (pixel_size, pixel_size)) - app.loaded_fields.append((field, loader)) + app.loaded_fields.append((field, loader, ini_shape)) return field -def loader_settings(app: HeadlessApp, loader) -> list: - """ The settings of a loader to save with the field it produced, laid out as the field loader app of the extension - does when it saves a field: its settings (loader name, needed size) and the ones of the loader""" +def loader_settings(app: HeadlessApp, field, loader, ini_shape: tuple) -> list: + """ The settings of a loader to save with the field it produced, laid out as the loader app of the extension does + when it saves a field: all its settings (those of ``FieldLoaderApp.params``) and the ones of the loader + + The loader app does not exist here: its settings are created from the same definition, and set to what the script + did (the loader, the size of the file and the needed size, the scaling to fit the field), the other ones (flips, + smoothing, normalisation, masking, ROI) are not used by the script and keep their default value""" + import copy from pyqtgraph.parametertree import Parameter - loader_app = Parameter.create(name='LoaderAppSettings', type='group', children=[ - {'name': 'loader', 'title': 'Loader', 'type': 'str', 'value': type(loader).LOADER_NAME}]) - loader_app.addChild(Parameter.create(name='needed_size', title='Needed size', type='group', children=[ - {'name': child.name(), 'title': child.title(), 'type': child.type(), 'value': child.value()} - for child in app.settings.child('needed_size').children()])) + from pymodaq_plugins_beam_shaping.field.field_loader_app import FieldLoaderApp + loader_app = Parameter.create(name=FieldLoaderApp.settings_name, type='group', + children=copy.deepcopy(FieldLoaderApp.params)) + needed = app.settings.child('needed_size') + values = {('loader',): type(loader).LOADER_NAME, + ('ini_size', 'height'): int(ini_shape[0]), ('ini_size', 'width'): int(ini_shape[1]), + ('utils', 'sizing', 'height'): int(field.shape[0]), ('utils', 'sizing', 'width'): int(field.shape[1]), + ('utils', 'sizing', 'scaling'): float(min(np.array(field.shape) / np.array(ini_shape)))} + values.update({('needed_size', child.name()): child.value() for child in needed.children()}) + for path, value in values.items(): + loader_app.child(*path).setValue(value) return [loader_app, loader.settings] @@ -221,7 +233,8 @@ def set_fields(algo, input_field, target_field): """ Give the input and target fields to the algorithm, as the app does (the target is scaled by the algo)""" app = algo.parent_app for role, field in (('input', input_field), ('target', target_field)): # keep the loader of each, to save it - app.field_loaders[role] = next((loader for loaded, loader in app.loaded_fields if loaded is field), None) + app.field_loaders[role] = next(((field, loader, ini_shape) for loaded, loader, ini_shape in app.loaded_fields + if loaded is field), None) algo.set_modulator_field(input_field.deepcopy()) algo.set_input_field(input_field) algo.set_target_field(algo.scale_target_with_geometry(target_field)) @@ -357,7 +370,7 @@ def run_algorithm(algo, n_iterations: int = 1, ini_phase: Union[str, np.ndarray] app = algo.parent_app saver.add_loaded_fields( algo._input_field, algo._target_field, - *[loader_settings(app, app.field_loaders[role]) if app.field_loaders[role] is not None else () + *[loader_settings(app, *app.field_loaders[role]) if app.field_loaders[role] is not None else () for role in ('input', 'target')]) try: algo.do_things_after_init() diff --git a/tests/test_algorithm_playground.py b/tests/test_algorithm_playground.py index 4fe5915..adc84e9 100644 --- a/tests/test_algorithm_playground.py +++ b/tests/test_algorithm_playground.py @@ -471,6 +471,10 @@ def test_input_and_target_saved_with_the_settings_of_their_loaders(qapp, tmp_pat settings = settings.decode() if isinstance(settings, bytes) else settings assert loader_name in settings # the settings of the loader that produced the field assert 'needed_size' in settings + assert 'LoaderSettings' in settings # the settings of the loader itself are there too + # all the settings of the loader app, as the extension saves them + for entry in ('ini_size', 'utils', 'smoothing', 'normalisation', 'masking', 'roi_select'): + assert entry in settings, entry # in the format of the field files: readable by load_field_from_h5, as the Input and Target groups of the extension from pymodaq_plugins_beam_shaping.field.h5 import load_field_from_h5 saved_input = load_field_from_h5(path, f'{run}/Input/Data00') From cdd08fd7446695d3cd2f4ed5ae733d6f3ab388cf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 13:02:05 +0000 Subject: [PATCH 10/12] Extension Save: same layout as the saved runs (group Shaping without index); convergence plot script Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- .../algorithms/algorithm_app.py | 30 +++++++----- .../extensions/spatial_beam_shaping.py | 44 ++++++++++------- .../scripts/plot_convergence.py | 49 +++++++++++++++++++ .../utilities/h5saving.py | 35 ++++++++++--- tests/test_custom_apps.py | 6 ++- 5 files changed, 126 insertions(+), 38 deletions(-) create mode 100644 src/pymodaq_plugins_beam_shaping/scripts/plot_convergence.py diff --git a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py index 719843a..eb355e3 100644 --- a/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py +++ b/src/pymodaq_plugins_beam_shaping/algorithms/algorithm_app.py @@ -1,5 +1,5 @@ from abc import ABCMeta, abstractproperty -from typing import Union +from typing import Callable, Union import numpy as np from qtpy import QtWidgets, QtCore, QtGui @@ -43,7 +43,6 @@ from pymodaq_plugins_beam_shaping.algorithms.algo_config import AlgoConfig from pymodaq_plugins_beam_shaping.utilities.h5saving import (ShapingSaver, RunSaver, FIELDS_SAVED_BY_THE_APP, configure_h5saver, fields_of_modulator, algorithm_name_settings, - add_algorithm_group, add_plugin_version) from pymodaq_plugins_beam_shaping.field.h5 import settings_to_xml @@ -262,16 +261,20 @@ def save_algo_parameters(self): if self.save_settings: self.config_saver_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 + def save(self, fname: Path = None, add_to_group: Callable[[ShapingSaver], None] = None, metadata: dict = None): + """ Save the fields and the settings of the algorithm into a hdf5 file + + The layout of a saved run: a group ``Shaping`` with the settings (algorithm name, app and algorithm settings) + and, in it, the sub group ``Final`` with all the fields (the Save of the extension adds the input, the target...) Parameters ---------- fname : Path If specified, add the field in the existing (or new) file. Otherwise open a File dialog to enter a file name - where: str - the node where the data will be saved + add_to_group: callable + called with the saver of the group while the file is open, to add other groups to it + metadata: dict + the metadata of the file """ if fname is None: fname = select_file(start_path=config('data', 'data_saving','h5file', 'save_path'), @@ -279,16 +282,19 @@ def save(self, fname: H5Saver | Path = None, where: str = '/RawData', if fname != '': new_file = not fname.exists() - settings_str = settings_to_xml((algorithm_name_settings(self.algorithm.ALGO_NAME), self.settings, self.algorithm.settings)) - with DataToExportSaver(fname, new_file=new_file, save_type=SaveType.custom) as saver: - add_algorithm_group(saver, self.algorithm.get_fields_to_plot(), where, group_name, title, - settings_as_xml=settings_str) + with DataToExportSaver(fname, new_file=new_file, save_type=SaveType.custom, + metadata=metadata) as saver: + shaping_saver = ShapingSaver(indexed=False) + shaping_saver.h5saver = saver.h5saver + shaping_saver.get_set_node(new=True, settings_as_xml=settings_str) + shaping_saver.add_final_data(self.algorithm.get_fields_to_plot()) + if add_to_group is not None: + add_to_group(shaping_saver) add_plugin_version(saver) - @property def current_phase(self) -> np.ndarray: """ cached phase to be used for subsequent optimizations """ 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..9aab984 100644 --- a/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py +++ b/src/pymodaq_plugins_beam_shaping/extensions/spatial_beam_shaping.py @@ -6,7 +6,7 @@ from pymodaq_utils.logger import set_logger, get_module_name from pymodaq_utils.config import GlobalConfig -from pymodaq_data.h5modules.data_saving import DataToExportSaver, DataLoader +from pymodaq_data.h5modules.data_saving import DataLoader from pymodaq_gui.messenger import messagebox from pymodaq_gui.utils.shared_ui import MenuToolbarNames, SharedUI @@ -21,7 +21,7 @@ from pymodaq.utils.custom_ext import CustomExt from pymodaq.utils.gui_utils.loader_utils import create_extension -from pymodaq.utils.data import DataToExport, DataCalculated, DataDim +from pymodaq.utils.data import DataToExport, DataCalculated from pymodaq_plugins_beam_shaping.utils import Config as PluginConfig from pymodaq_plugins_beam_shaping.algorithms.algorithm_app import AlgoApp @@ -33,7 +33,7 @@ from pymodaq_plugins_beam_shaping.algorithms.utils import ApplyMaskTo, LensSetup from pymodaq_plugins_beam_shaping.utilities import regions from pymodaq_plugins_beam_shaping.utilities.region_outline import RegionOutline -from pymodaq_plugins_beam_shaping.utilities.h5saving import add_plugin_version +from pymodaq_plugins_beam_shaping.utilities.h5saving import ShapingSaver from pymodaq_plugins_beam_shaping.utilities.calibrating import BeamShapingCalibration, Calibration from pymodaq_plugins_beam_shaping.utilities.data import DataShaper from pymodaq_plugins_beam_shaping.utilities.shaper import Shaper, ModulatorType, get_default_shaper @@ -308,15 +308,17 @@ def save(self, fname: Path = None): dte.append(DataCalculated('Linear Phase', data=[linear_phase_array[tuple(self.get_slm_slices())]]),) dte.append(DataCalculated('Zernike Phase', data=[zernike_phase[tuple(self.get_slm_slices())]])) - with DataToExportSaver(fname, metadata={'settings': plugin_config.to_xml_string()}) as h5saver: - group = h5saver.add_data_group('/RawData', DataDim.Data2D, title='SLM Phases', group_name='SLM') - h5saver.add_data(group, dte) - add_plugin_version(h5saver) + def add_to_group(shaping_saver: ShapingSaver): + """ The phases sent to the SLM, the input and target fields with the settings of their loaders""" + shaping_saver.add_group_data(dte, 'SLM', 'SLM Phases') + for name, loader_app in (('Input', self._input_field_loader), ('Target', self._target_field_loader)): + shaping_saver.add_loaded_field(loader_app.field, (loader_app.settings, loader_app.loader.settings), + name) - self._input_field_loader.save_field(fname, where='/RawData', group_name='Input', title='Input Field') - self._target_field_loader.save_field(fname, where='/RawData', group_name='Target', title='Target Field') - - self.algorithm.save(fname, where='/RawData', group_name='Algorithm', title='Algorithm') + # one group Shaping holding the settings of the algorithm and the sub groups Final (the fields of the + # algorithm), SLM, Input and Target + self.algorithm.save(fname, add_to_group=add_to_group, + metadata={'settings': plugin_config.to_xml_string()}) def load(self, fname: Path = None): if fname is None: @@ -332,14 +334,22 @@ def load(self, fname: Path = None): dwa_input_phase = None with DataLoader(fname) as loader: + if 'Shaping' in loader.h5saver.get_children(loader.h5saver.get_node('/RawData')): + # the layout of the Save: a group Shaping with the sub groups Final, Input and Target + algo_path, target_path, input_path = ('/RawData/Shaping/Final', '/RawData/Shaping/Target', + '/RawData/Shaping/Input') + algo_settings_node = '/RawData/Shaping' + else: # files saved before: three groups at the root of the data + algo_path, target_path, input_path = '/RawData/Algorithm', '/RawData/Target', '/RawData/Input' + algo_settings_node = algo_path algo_settings = xml_string_to_parameter( - loader.h5saver.get_node('/RawData/Algorithm/').attrs['settings']) + loader.h5saver.get_node(algo_settings_node).attrs['settings']) target_settings = xml_string_to_parameter( - loader.h5saver.get_node('/RawData/Target/').attrs['settings']) + loader.h5saver.get_node(target_path).attrs['settings']) input_settings = xml_string_to_parameter( - loader.h5saver.get_node('/RawData/Input/').attrs['settings']) + loader.h5saver.get_node(input_path).attrs['settings']) - for node in loader.walk_nodes('/RawData/Algorithm/Data2D/'): + for node in loader.walk_nodes(f'{algo_path}/Data2D/'): if 'ARRAY' in node.attrs['CLASS']: if node.attrs.get('origin', '') == 'slm' and node.title == 'amplitude': dwa_slm_amplitude = loader.load_data(node.path) @@ -347,13 +357,13 @@ def load(self, fname: Path = None): dwa_modulator_amplitude = loader.load_data(node.path) elif node.attrs.get('origin', '') == 'modulator' and node.title == 'phase': dwa_modulator_phase = loader.load_data(node.path) - for node in loader.walk_nodes('/RawData/Target/'): + for node in loader.walk_nodes(f'{target_path}/'): if 'ARRAY' in node.attrs['CLASS']: if node.attrs.get('label', '') == 'Amplitude': dwa_target_amplitude = loader.load_data(node.path) elif node.attrs.get('label', '') == 'Phase': dwa_target_phase = loader.load_data(node.path) - for node in loader.walk_nodes('/RawData/Input/'): + for node in loader.walk_nodes(f'{input_path}/'): if 'ARRAY' in node.attrs['CLASS']: if node.attrs.get('label', '') == 'Amplitude': dwa_input_amplitude = loader.load_data(node.path) diff --git a/src/pymodaq_plugins_beam_shaping/scripts/plot_convergence.py b/src/pymodaq_plugins_beam_shaping/scripts/plot_convergence.py new file mode 100644 index 0000000..8ee9991 --- /dev/null +++ b/src/pymodaq_plugins_beam_shaping/scripts/plot_convergence.py @@ -0,0 +1,49 @@ +"""Plot the convergence of the metrics saved during a (headless or app) run of an algorithm. + +Metrics are saved when running with ``save_metrics=True`` in ``algorithm_playground.py`` (or with the continuous +saving of the AlgoApp), in ``/RawData/Shaping000/Metrics`` as one enlargeable dataset: one data array per metric, +all along the navigation axis ``step``. +""" +import numpy as np +from matplotlib import pyplot as plt + +from pymodaq_data.h5modules.data_saving import DataLoader + +FILE = 'Dataset_20261109_000.h5' +RUN = '/RawData/Shaping000' # the group of the run (several runs in a file: Shaping001, ...) +METRICS_TO_PLOT = None # None for all or a list of labels, for instance ['efficiency'] +LOG_SCALE = {} # labels to display in log scale, for instance {'Intensity NRMSE'} +SAVE_AS = 'convergence.pdf' # None to not save + +# plt.rcParams['text.usetex'] = True # as in the other figure scripts +font = {'family': 'arial', 'color': 'black', 'weight': 'normal', 'size': 16} +font_title = {'family': 'arial', 'color': 'black', 'weight': 'normal', 'size': 10} + +# %% load the metrics +with DataLoader(FILE) as loader: + dwa_metrics = loader.load_all(f'{RUN}/Metrics')[0] # all the metrics are in one data object, one label each + +steps = dwa_metrics.get_axis_from_index(0)[0].get_data() +metrics = {label: np.squeeze(data) for label, data in zip(dwa_metrics.labels, dwa_metrics.data)} +if METRICS_TO_PLOT is not None: + metrics = {label: metrics[label] for label in METRICS_TO_PLOT} + +# %% plot, one panel per metric (they have different scales) +fig = plt.figure('Convergence', figsize=(5., 2.2 * len(metrics))) +fig.clf() +axes = fig.subplots(len(metrics), 1, sharex=True, squeeze=False)[:, 0] +for ax, (label, values) in zip(axes, metrics.items()): + ax.plot(steps, values, '.-k', linewidth=1) + ax.set_ylabel(label, fontdict=font_title) + if label in LOG_SCALE: + ax.set_yscale('log') + ax.grid(alpha=0.3) + ax.annotate(f'{values[-1]:.3f}', (steps[-1], values[-1]), xytext=(-4, 6), textcoords='offset points', + ha='right', fontsize=8) +axes[-1].set_xlabel('Iteration', fontdict=font) +fig.tight_layout() + +# %% +if SAVE_AS is not None: + plt.savefig(SAVE_AS) +plt.show() diff --git a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py index ee4f73d..6aec499 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py @@ -81,10 +81,18 @@ class ShapingSaver(ModuleSaver): input and target fields (``Input``, ``Target``)""" group_type = GroupModuleType.SHAPING - def __init__(self): + def __init__(self, indexed: bool = True): + """ + Parameters + ---------- + indexed: bool + the group of a run is named ShapingXXX with the next index (several runs in a file), otherwise Shaping + (a file saved at once, as the Save of the extension) + """ self._module = None self._module_group: GROUP = None self._h5saver: H5Saver = None + self.indexed = indexed self.enl_axis_names = ('step',) self.enl_axis_units = ('',) @@ -135,8 +143,13 @@ def _add_module(self, where=None, metadata=None, settings_as_xml='') -> Node: where = self._h5saver.raw_group - return self._h5saver.add_incremental_group(self.group_type, where, title='BeamShaping', - settings_as_xml=settings_as_xml, metadata=metadata) + if self.indexed: + return self._h5saver.add_incremental_group(self.group_type, where, title='BeamShaping', + settings_as_xml=settings_as_xml, metadata=metadata) + group = self._h5saver.add_group('Shaping', self.group_type.name, where, title='BeamShaping', + metadata=metadata) + self._h5saver.set_attr(group, 'settings', settings_as_xml) + return group def _child_node(self, child: ShapingChildSaver) -> GROUP: @@ -164,13 +177,19 @@ def add_data(self, dte: DataToExport, axis_values: List[Union[float, np.ndarray] raise ValueError('The data are saved in the sub group of a child saver: fields, metrics or final') child.add_data(self._child_node(child), dte, axis_values=axis_values) - def add_final_data(self, dte: DataToExport): - """ Save data once in the ``Final`` sub group of the current run, so that they share its settings and - attributes with the data saved at each step, e.g. all the fields at the end of a run (as the Save of the - extension does, with the same code: :func:`add_algorithm_group`)""" + def add_group_data(self, dte: DataToExport, group_name: str, title: str = '', settings_as_xml=''): + """ Save data once in the sub group ``group_name`` of the current run (as the control modules save theirs in the + group of an extension), so that they share its settings and attributes, whatever is saved at each step + + The data and the group are saved by the code shared with the Save of the extension, see + :func:`add_algorithm_group`""" saver = DataToExportSaver(self._h5saver) # not as a context manager: it closes the file return add_algorithm_group(saver, dte, where=self.get_last_node(self._h5saver.raw_group), - group_name='Final', title='Final Fields') + group_name=group_name, title=title or group_name, settings_as_xml=settings_as_xml) + + def add_final_data(self, dte: DataToExport): + """ Save all the fields once in the ``Final`` sub group of the current run, e.g. at the end of a run""" + return self.add_group_data(dte, 'Final', 'Final Fields') def add_loaded_field(self, field: 'Field', settings: Iterable = (), group_name: str = 'Input'): """ Save once a field (its amplitude and phase) in the sub group ``group_name`` of the current run, with the diff --git a/tests/test_custom_apps.py b/tests/test_custom_apps.py index cd4dfbc..ce02b3e 100644 --- a/tests/test_custom_apps.py +++ b/tests/test_custom_apps.py @@ -281,9 +281,13 @@ def test_algo_app_saves_the_pattern_of_an_amplitude_modulator_in_the_slm_node(qt app.save(tmp_path / 'file.h5') with DataLoader(tmp_path / 'file.h5') as loader: origins = {} - for node in loader.walk_nodes('/RawData/Algorithm/Data2D/'): + for node in loader.walk_nodes('/RawData/Shaping/Final/Data2D/'): if 'ARRAY' in node.attrs['CLASS']: origins[(node.attrs.get('origin', ''), node.title)] = loader.load_data(node.path)[0] + with DataLoader(tmp_path / 'file.h5') as loader: # the layout of the Save: Shaping, not indexed, with its sub groups + assert 'Shaping' in loader.h5saver.get_children(loader.h5saver.get_node('/RawData')) + assert 'Final' in loader.h5saver.get_children(loader.h5saver.get_node('/RawData/Shaping')) + assert loader.get_node('/RawData/Shaping').attrs['settings'] 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')]) From 7df237fe9254a314ec0c314710ab58aa32291432 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 13:06:08 +0000 Subject: [PATCH 11/12] Docs: layout of the saved files (group Shaping), convergence script Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- docs/src/user_guide/algorithms.rst | 6 +- docs/src/user_guide/data_management.rst | 144 ++++++++++++++++++++---- 2 files changed, 125 insertions(+), 25 deletions(-) diff --git a/docs/src/user_guide/algorithms.rst b/docs/src/user_guide/algorithms.rst index 01d2d19..3697334 100644 --- a/docs/src/user_guide/algorithms.rst +++ b/docs/src/user_guide/algorithms.rst @@ -257,7 +257,7 @@ shaping for the MRAF algorithm using different initial phase type and mixing par .. note:: The metrics (NRMSE, Fidelity, Efficiency) are **automatically saved** in the ``.h5beam`` file under - ``/RawData/Algorithm/``. See :ref:`h5beam-structure` for details. + ``/RawData/Shaping/Final/``. See :ref:`h5beam-structure` for details. Algorithms provided by other packages ------------------------------------- @@ -299,11 +299,13 @@ cells one after the other, editing the settings on the way: The *Run* cell can save the output of each iteration: ``SAVE_FIELDS`` (``True`` for all the fields, the amplitude and phase of the output and modulator planes and the intensity of the intermediate one, or the names of some of them such as ``('modulator/phase',)``) and ``SAVE_METRICS``, both off by default. ``SAVE_FINAL`` saves once, at the end of the run, all the fields and the metrics of the last iteration, as the *Save* action of the extension does, whatever is saved at each iteration. The format is the one of the continuous saving -of the extension: a group ``/RawData/ShapingXXX`` per run, with the settings of the run, holding one sub group for each kind of data: ``Fields`` (the fields saved at each iteration) and ``Metrics`` (the metrics), each enlarged along its own ``step`` navigation axis, ``Final`` (the fields saved once at the end, without navigation axis, saved as the *Algorithm* group of the extension's *Save*) and the ``Input`` and ``Target`` groups (the fields as used by the algorithm, with the settings of their loaders, as the *Input* and *Target* groups of the extension's *Save*, readable with the same function). The sub groups of the data per iteration and ``Final`` are only created if requested. The settings of the run are saved +of the extension: a group ``/RawData/ShapingXXX`` per run, with the settings of the run, holding one sub group for each kind of data: ``Fields`` (the fields saved at each iteration) and ``Metrics`` (the metrics), each enlarged along its own ``step`` navigation axis, ``Final`` (the fields saved once at the end, without navigation axis, as in the extension's *Save*, whose main group is the same ``Shaping`` group, without index) and the ``Input`` and ``Target`` groups (the fields as used by the algorithm, with the settings of their loaders, as the *Input* and *Target* groups of the extension's *Save*, readable with the same function). The sub groups of the data per iteration and ``Final`` are only created if requested. The settings of the run are saved as in the extension: the name of the algorithm, the number of iterations, the initial phase and its parameters, the masks (applied or not, type and slices) and the parameters of the algorithm. ``SAVE_FILE`` gives the file (created if needed, the runs being added to it); with ``None`` a file is created in the PyMoDAQ data folder at the first saved run and holds the next ones. Its path is printed (``algo.saved_h5file``). +The script ``scripts/plot_convergence.py`` plots the convergence of the saved metrics (one panel per metric against the iteration) from the ``Metrics`` group of a saved run. + During the run of an iterative algorithm, the index of the iteration and the metrics (fitness and efficiency) are printed after each iteration (``verbose=False`` in ``pg.run_algorithm`` to silence it). The last cells run the algorithm, plot an overview as in the extension, then the output field and the intermediate diff --git a/docs/src/user_guide/data_management.rst b/docs/src/user_guide/data_management.rst index bd4a19b..aa10081 100644 --- a/docs/src/user_guide/data_management.rst +++ b/docs/src/user_guide/data_management.rst @@ -113,6 +113,102 @@ The ``.h5field`` file has the following hierarchy: The ``.h5beam`` file has the following hierarchy: +.. code-block:: text + + / + ├── [Global Attributes] # Metadata (date, version, etc.) + │ + └── RawData/ (GROUP) + ├── @settings: # **Global configuration** (XML) + │ # Includes: wavelength, setup_type (2f/4f/no_lens), + │ # SLM settings, default loaders, etc. + │ + ├── Shaping/ (GROUP) # **One group for the whole session** (no index) + │ ├── @settings: # Algorithm name, run settings and algorithm settings (XML) + │ │ + │ ├── Final/ (GROUP) # Algorithm results (last iteration) + │ │ ├── Data0D/CH00/Data00 # **NRMSE** (Normalized Root Mean Square Error) + │ │ │ Data01 # **Efficiency** (beam shaping efficiency) + │ │ └── Data2D/ (GROUP) + │ │ ├── CH00/ # **Output Field Amplitude** (Axis00, Axis01: coordinates) + │ │ ├── CH01/ # **Output Field Phase** + │ │ ├── CH02/ # **Modulator Amplitude** (sent to SLM) + │ │ └── CH03/ # **Modulator Phase** (sent to SLM) + │ │ + │ ├── Input/ (GROUP) # **Input Field** (source beam) + │ │ ├── @settings: # Loader app and loader settings (XML) + │ │ ├── Axis00, Axis01 # Coordinates (m) + │ │ ├── Data00 (CARRAY) # Amplitude + │ │ └── Data01 (CARRAY) # Phase + │ │ + │ ├── Target/ (GROUP) # **Target Field** (desired output), same content as Input + │ │ + │ └── SLM/ (GROUP) # **SLM Phases** + │ └── Data2D/ (GROUP) # Phases by channel + │ ├── CH00/ # **Algorithm Phase** (to be applied to SLM), e.g. (540, 960) + │ ├── CH01/ # **Quadratic Phase** (curvature correction) + │ ├── CH02/ # **Linear Phase** (tilt correction) + │ └── CH03/ # **Zernike Phase** (aberration correction) + │ + └── Logger (VLARRAY) # Log messages (optional) + +.. list-table:: **Key Attributes in .h5field** + :header-rows: 1 + :widths: 30 20 50 + :class: longtable + + * - **Location** + - **Attribute** + - **Description** + * - ``/`` + - ``date``, ``time`` + - File creation timestamp (format: ``YYYY-MM-DD``, ``HH:MM:SS.microseconds``). + * - ``/`` + - ``pymodaq_version``, ``pymodaq_data_version`` + - PyMoDAQ and pymodaq_data versions used to create the file. + * - ``/RawData/Field/Axis00`` + - ``scaling`` + - **Pixel size in meters** (e.g., ``6.494e-06`` for 6.494 µm/pixel). + * - ``/RawData/Field/Axis00`` + - ``units`` + - Physical unit for the axis (``"m"`` for meters). + * - ``/RawData/Field/Data00`` + - ``label`` + - **Data type** (``"Amplitude"`` or ``"Phase"``). + * - ``/RawData/Field/Data00`` + - ``shape`` + - Dimensions of the 2D array (e.g., ``(1024, 1024)``). + * - ``/RawData/Field`` + - ``settings`` + - **Serialized XML configuration** of the Field Loader (includes loader type, parameters, masking, etc.). + +.. note:: + - The **amplitude** and **phase** are stored as **separate datasets** (``Data00`` and ``Data01``). + - The **physical coordinates** (in meters) are defined by ``Axis00`` (X) and ``Axis01`` (Y). + - The ``scaling`` attribute of each axis gives the **pixel pitch** in meters. + +--- + +.. _h5beam-format: + +.h5beam Format +~~~~~~~~~~~~~~ + +**Purpose**: Store a **complete beam shaping session**, including: +- Input and Target fields. +- SLM phases (algorithm, quadratic, linear, Zernike). +- Algorithm results (output field, modulator field, metrics). +- Global configuration (wavelength, setup type, etc.). + +**Generated by**: Beam Shaping Extension. + +.. _h5beam-structure: + +**HDF5 Structure** +"""""""""""""""""" + +The ``.h5beam`` file has the following hierarchy: + .. code-block:: text / @@ -182,43 +278,45 @@ The ``.h5beam`` file has the following hierarchy: * - **Group** - **Purpose** - **Key Data** - * - ``/RawData/Input`` + * - ``/RawData/Shaping/Input`` - Source beam field - Amplitude + Phase (2D arrays) - * - ``/RawData/Target`` + * - ``/RawData/Shaping/Target`` - Desired output field - Amplitude + Phase (2D arrays) - * - ``/RawData/Algorithm/Data0D/CH00`` + * - ``/RawData/Shaping/Final/Data0D/CH00`` - **Performance metrics** - NRMSE (``Data00``), Efficiency (``Data01``) - * - ``/RawData/Algorithm/Data2D/CH00`` + * - ``/RawData/Shaping/Final/Data2D/CH00`` - **Output field amplitude** - 2D array (same size as Input/Target) - * - ``/RawData/Algorithm/Data2D/CH01`` + * - ``/RawData/Shaping/Final/Data2D/CH01`` - **Output field phase** - 2D array (radians) - * - ``/RawData/Algorithm/Data2D/CH02`` + * - ``/RawData/Shaping/Final/Data2D/CH02`` - **Modulator amplitude** - 2D array (sent to SLM) - * - ``/RawData/Algorithm/Data2D/CH03`` + * - ``/RawData/Shaping/Final/Data2D/CH03`` - **Modulator phase** - 2D array (radians) - * - ``/RawData/SLM/Data2D/CH00`` + * - ``/RawData/Shaping/SLM/Data2D/CH00`` - **Algorithm phase for SLM** - 2D array (shape matches SLM resolution, e.g., 540x960) - * - ``/RawData/SLM/Data2D/CH01`` + * - ``/RawData/Shaping/SLM/Data2D/CH01`` - **Quadratic phase correction** - 2D array - * - ``/RawData/SLM/Data2D/CH02`` + * - ``/RawData/Shaping/SLM/Data2D/CH02`` - **Linear phase correction** - 2D array - * - ``/RawData/SLM/Data2D/CH03`` + * - ``/RawData/Shaping/SLM/Data2D/CH03`` - **Zernike phase correction** - 2D array .. note:: - - The **SLM phases** (``/RawData/SLM/Data2D/``) are **downsampled** to match the SLM resolution (e.g., 960x540 for PLUTO, 1024x768 for LC2012). - - The **Algorithm/Data2D** results are at the **same resolution as the Input/Target fields** (e.g., 1024x1024). + - The **SLM phases** (``/RawData/Shaping/SLM/Data2D/``) are **downsampled** to match the SLM resolution (e.g., 960x540 for PLUTO, 1024x768 for LC2012). + - The **Final/Data2D** results are at the **same resolution as the Input/Target fields** (e.g., 1024x1024). + - Files written before this layout (groups ``/RawData/Algorithm``, ``Input``, ``Target`` and ``SLM`` directly under ``/RawData``) are still loaded by the extension. + - Runs of the headless playground (``pg.run_algorithm``) use the same layout, in indexed groups ``/RawData/Shaping000``, ``Shaping001``... with in addition the ``Fields`` and ``Metrics`` groups holding the data saved at each iteration (see :ref:`sec-algorithms-playground`), the SLM group being left out. - The ``@settings`` attributes contain **serialized XML configurations** (can be deserialized with ``pymodaq_utils``). @@ -235,7 +333,7 @@ You can **read `.h5beam` and `.h5field` files programmatically** using `pymodaq_ # Load data from a .h5beam file with DataLoader("my_file.h5beam") as loader: # Access SLM phases - phase_data = loader.load_data("/RawData/SLM/Data2D/CH00") # return a DataWithAxes object + phase_data = loader.load_data("/RawData/Shaping/SLM/Data2D/CH00") # return a DataWithAxes object # Access metadata print(phase_data.extra_attributes) @@ -333,30 +431,30 @@ HDF5 Attributes Reference * - **Group** - **Purpose** - **Key Data** - * - ``/RawData/Algorithm/Data0D/CH00`` + * - ``/RawData/Shaping/Final/Data0D/CH00`` - Performance metrics - NRMSE (``Data00``), Efficiency (``Data01``) - * - ``/RawData/Algorithm/Data2D/CH00`` + * - ``/RawData/Shaping/Final/Data2D/CH00`` - Output field amplitude - 2D array (same size as Input/Target) - * - ``/RawData/Algorithm/Data2D/CH01`` + * - ``/RawData/Shaping/Final/Data2D/CH01`` - Output field phase - 2D array (radians) - * - ``/RawData/Algorithm/Data2D/CH02`` + * - ``/RawData/Shaping/Final/Data2D/CH02`` - Modulator amplitude - 2D array (sent to SLM) - * - ``/RawData/Algorithm/Data2D/CH03`` + * - ``/RawData/Shaping/Final/Data2D/CH03`` - Modulator phase - 2D array (radians) - * - ``/RawData/SLM/Data2D/CH00`` + * - ``/RawData/Shaping/SLM/Data2D/CH00`` - Algorithm phase for SLM - 2D array (SLM resolution, e.g., 540x960) - * - ``/RawData/SLM/Data2D/CH01`` + * - ``/RawData/Shaping/SLM/Data2D/CH01`` - Quadratic phase - 2D array (curvature correction) - * - ``/RawData/SLM/Data2D/CH02`` + * - ``/RawData/Shaping/SLM/Data2D/CH02`` - Linear phase - 2D array (tilt correction) - * - ``/RawData/SLM/Data2D/CH03`` + * - ``/RawData/Shaping/SLM/Data2D/CH03`` - Zernike phase - 2D array (aberration correction) \ No newline at end of file From b84b6b0206856a409729a22ea4b9509f3e9f63c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 13:11:52 +0000 Subject: [PATCH 12/12] Extend GroupModuleType only once so the saving module can be reloaded Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01RKuN84WCxVCr25SiruMKcX --- src/pymodaq_plugins_beam_shaping/utilities/h5saving.py | 9 +++++---- tests/test_saved_version.py | 8 ++++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py index 6aec499..9b11c9a 100644 --- a/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py +++ b/src/pymodaq_plugins_beam_shaping/utilities/h5saving.py @@ -24,10 +24,11 @@ if TYPE_CHECKING: from pymodaq_plugins_beam_shaping.field.field import Field -extend_enum(GroupModuleType, 'SHAPING') -# the sub groups of the group of a run saved at each step, each one by its own ModuleSaver (Fields, Metrics) -extend_enum(GroupModuleType, 'FIELDS') -extend_enum(GroupModuleType, 'METRICS') +# SHAPING: the group of a run or of a saved session; FIELDS, METRICS: the sub groups of the group of a run saved at each +# step, each one by its own ModuleSaver +for _name in ('SHAPING', 'FIELDS', 'METRICS'): + if _name not in GroupModuleType.__members__: # a module reload (ipython autoreload) must not extend it again + extend_enum(GroupModuleType, _name) class ShapingChildSaver(ModuleSaver): diff --git a/tests/test_saved_version.py b/tests/test_saved_version.py index 1d52627..6ed071f 100644 --- a/tests/test_saved_version.py +++ b/tests/test_saved_version.py @@ -59,3 +59,11 @@ def test_algorithm_file_of_the_app_has_the_version(qtbot, dockarea, tmp_path): app._algorithm = algo app.save(tmp_path / 'algo.h5') check_version(tmp_path / 'algo.h5') + + +def test_saving_module_can_be_reloaded(): + """ The group types are extended only once (reloading the module, as ipython autoreload does, must not fail)""" + import importlib + from pymodaq_plugins_beam_shaping.utilities import h5saving + importlib.reload(h5saving) + assert {'SHAPING', 'FIELDS', 'METRICS'} <= set(h5saving.GroupModuleType.__members__)