Skip to content

Monitoring

PtyLab.Monitor

Monitor

AbstractMonitor

Base class of the reconstruction monitors; on its own it shows nothing.

The engines call update with one MonitorFrame per update. A custom monitor can either override update and read the frame directly, or override the per-quantity hooks below (updateObjectProbeErrorMonitor, update_encoder, ...), which the default update calls. Every hook is a no-op here, so a subclass only implements the ones it uses.

Source code in PtyLab/Monitor/Monitor.py
class AbstractMonitor:
    """Base class of the reconstruction monitors; on its own it shows nothing.

    The engines call `update` with one `MonitorFrame` per update. A custom monitor
    can either override `update` and read the frame directly, or override the
    per-quantity hooks below (`updateObjectProbeErrorMonitor`, `update_encoder`,
    ...), which the default `update` calls. Every hook is a no-op here, so a
    subclass only implements the ones it uses.
    """

    def update(self, frame: MonitorFrame):
        """Show one snapshot of the reconstruction.

        The default forwards the frame to the per-quantity hooks, so monitors
        written against those hooks keep working. Fields the engine left empty
        (`None`) are skipped.

        Args:
            frame (MonitorFrame): Current reconstruction state.
        """
        self.updateObjectProbeErrorMonitor(
            error=frame.error,
            object_estimate=frame.object_view(),
            probe_estimate=frame.probe_view(),
            zo=frame.zo,
            purity_probe=frame.purity_probe,
            purity_object=frame.purity_object,
            encoder_positions=frame.positions,
        )
        if frame.engine_name is not None:
            self.writeEngineName(frame.engine_name)
        if frame.encoder_original is not None:
            self.update_encoder(
                corrected_positions=frame.encoder_corrected,
                original_positions=frame.encoder_original,
            )
        if frame.beam_width is not None:
            self.updateBeamWidth(*frame.beam_width)
        if frame.I_estimated is not None:
            self.updateDiffractionDataMonitor(
                Iestimated=frame.I_estimated, Imeasured=frame.I_measured
            )
        if frame.area_overlap is not None:
            self.update_overlap(frame.area_overlap, frame.linear_overlap)

    def initializeMonitors(self):
        """Create the figures or other outputs; the engine calls it before the first update."""

    def saveFigures(self, fileName="recent", dpi=150):
        """Save the monitor figures as PNG files. This monitor has none.

        Returns:
            list[Path]: Empty, as nothing is saved.
        """
        return []

    def describe_parameters(self, params):
        """Record the reconstruction parameters, e.g. as text in a log.

        Args:
            params (Params): Parameters of the reconstruction.
        """

    def update_focusing_metric(self, TV_value, AOI_image, metric_name, allmerits=None):
        """Show the result of one TV autofocus step.

        Args:
            TV_value (float): Focus metric at the current distance.
            AOI_image (np.ndarray): Propagated field in the area of interest.
            metric_name (str): Name of the focus metric, e.g. `"TV"`.
            allmerits (np.ndarray, optional): Focus metric at every distance that
                was tried. Defaults to None.
        """

    def writeEngineName(self, name):
        """Record which engine produced the current update.

        Args:
            name (str): Engine name.
        """

    def update_encoder(self, corrected_positions, original_positions, *args, **kwargs):
        """Show the scan positions before and after position correction.

        Args:
            corrected_positions (np.ndarray): Corrected encoder positions in m.
            original_positions (np.ndarray): Measured encoder positions in m.
        """

    def update_overlap(self, overlap_area, linear_overlap):
        """Show the estimated probe overlap between neighbouring scan positions.

        Args:
            overlap_area (float): Area overlap, between 0 and 1.
            linear_overlap (float): Linear overlap, between 0 and 1.
        """

    def updateObjectProbeErrorMonitor(
        self,
        error,
        object_estimate: np.ndarray,
        probe_estimate: np.ndarray,
        zo=None,
        purity_probe=None,
        purity_object=None,
        encoder_positions=None,
    ):
        """Show the object and probe estimates and the error metric.

        Args:
            error (array-like): Error metric of every iteration so far.
            object_estimate (np.ndarray): Object inside the display region.
            probe_estimate (np.ndarray): Probe inside the display region.
            zo (float, optional): Sample-detector distance in m. Defaults to None.
            purity_probe (float, optional): Probe purity. Defaults to None.
            purity_object (float, optional): Object purity. Defaults to None.
            encoder_positions (np.ndarray, optional): Scan positions in object
                pixels. Defaults to None.
        """

    def updateBeamWidth(self, beamwidth_y, beamwidth_x):
        """Show the probe width.

        Args:
            beamwidth_y (float): FWHM along y in m.
            beamwidth_x (float): FWHM along x in m.
        """

    def updateDiffractionDataMonitor(self, Iestimated, Imeasured):
        """Show the estimated and measured intensity at the last scan position.

        Args:
            Iestimated (np.ndarray): Estimated detector intensity.
            Imeasured (np.ndarray): Measured detector intensity.
        """
update(frame)

Show one snapshot of the reconstruction.

The default forwards the frame to the per-quantity hooks, so monitors written against those hooks keep working. Fields the engine left empty (None) are skipped.

Parameters:

Name Type Description Default
frame MonitorFrame

Current reconstruction state.

required
Source code in PtyLab/Monitor/Monitor.py
def update(self, frame: MonitorFrame):
    """Show one snapshot of the reconstruction.

    The default forwards the frame to the per-quantity hooks, so monitors
    written against those hooks keep working. Fields the engine left empty
    (`None`) are skipped.

    Args:
        frame (MonitorFrame): Current reconstruction state.
    """
    self.updateObjectProbeErrorMonitor(
        error=frame.error,
        object_estimate=frame.object_view(),
        probe_estimate=frame.probe_view(),
        zo=frame.zo,
        purity_probe=frame.purity_probe,
        purity_object=frame.purity_object,
        encoder_positions=frame.positions,
    )
    if frame.engine_name is not None:
        self.writeEngineName(frame.engine_name)
    if frame.encoder_original is not None:
        self.update_encoder(
            corrected_positions=frame.encoder_corrected,
            original_positions=frame.encoder_original,
        )
    if frame.beam_width is not None:
        self.updateBeamWidth(*frame.beam_width)
    if frame.I_estimated is not None:
        self.updateDiffractionDataMonitor(
            Iestimated=frame.I_estimated, Imeasured=frame.I_measured
        )
    if frame.area_overlap is not None:
        self.update_overlap(frame.area_overlap, frame.linear_overlap)
initializeMonitors()

Create the figures or other outputs; the engine calls it before the first update.

Source code in PtyLab/Monitor/Monitor.py
def initializeMonitors(self):
    """Create the figures or other outputs; the engine calls it before the first update."""
saveFigures(fileName='recent', dpi=150)

Save the monitor figures as PNG files. This monitor has none.

Returns:

Type Description
list[Path]

Empty, as nothing is saved.

Source code in PtyLab/Monitor/Monitor.py
def saveFigures(self, fileName="recent", dpi=150):
    """Save the monitor figures as PNG files. This monitor has none.

    Returns:
        list[Path]: Empty, as nothing is saved.
    """
    return []
describe_parameters(params)

Record the reconstruction parameters, e.g. as text in a log.

Parameters:

Name Type Description Default
params Params

Parameters of the reconstruction.

required
Source code in PtyLab/Monitor/Monitor.py
def describe_parameters(self, params):
    """Record the reconstruction parameters, e.g. as text in a log.

    Args:
        params (Params): Parameters of the reconstruction.
    """
update_focusing_metric(TV_value, AOI_image, metric_name, allmerits=None)

Show the result of one TV autofocus step.

Parameters:

Name Type Description Default
TV_value float

Focus metric at the current distance.

required
AOI_image ndarray

Propagated field in the area of interest.

required
metric_name str

Name of the focus metric, e.g. "TV".

required
allmerits ndarray

Focus metric at every distance that was tried. Defaults to None.

None
Source code in PtyLab/Monitor/Monitor.py
def update_focusing_metric(self, TV_value, AOI_image, metric_name, allmerits=None):
    """Show the result of one TV autofocus step.

    Args:
        TV_value (float): Focus metric at the current distance.
        AOI_image (np.ndarray): Propagated field in the area of interest.
        metric_name (str): Name of the focus metric, e.g. `"TV"`.
        allmerits (np.ndarray, optional): Focus metric at every distance that
            was tried. Defaults to None.
    """
writeEngineName(name)

Record which engine produced the current update.

Parameters:

Name Type Description Default
name str

Engine name.

required
Source code in PtyLab/Monitor/Monitor.py
def writeEngineName(self, name):
    """Record which engine produced the current update.

    Args:
        name (str): Engine name.
    """
update_encoder(corrected_positions, original_positions, *args, **kwargs)

Show the scan positions before and after position correction.

Parameters:

Name Type Description Default
corrected_positions ndarray

Corrected encoder positions in m.

required
original_positions ndarray

Measured encoder positions in m.

required
Source code in PtyLab/Monitor/Monitor.py
def update_encoder(self, corrected_positions, original_positions, *args, **kwargs):
    """Show the scan positions before and after position correction.

    Args:
        corrected_positions (np.ndarray): Corrected encoder positions in m.
        original_positions (np.ndarray): Measured encoder positions in m.
    """
update_overlap(overlap_area, linear_overlap)

Show the estimated probe overlap between neighbouring scan positions.

Parameters:

Name Type Description Default
overlap_area float

Area overlap, between 0 and 1.

required
linear_overlap float

Linear overlap, between 0 and 1.

required
Source code in PtyLab/Monitor/Monitor.py
def update_overlap(self, overlap_area, linear_overlap):
    """Show the estimated probe overlap between neighbouring scan positions.

    Args:
        overlap_area (float): Area overlap, between 0 and 1.
        linear_overlap (float): Linear overlap, between 0 and 1.
    """
updateObjectProbeErrorMonitor(error, object_estimate, probe_estimate, zo=None, purity_probe=None, purity_object=None, encoder_positions=None)

Show the object and probe estimates and the error metric.

Parameters:

Name Type Description Default
error array - like

Error metric of every iteration so far.

required
object_estimate ndarray

Object inside the display region.

required
probe_estimate ndarray

Probe inside the display region.

required
zo float

Sample-detector distance in m. Defaults to None.

None
purity_probe float

Probe purity. Defaults to None.

None
purity_object float

Object purity. Defaults to None.

None
encoder_positions ndarray

Scan positions in object pixels. Defaults to None.

None
Source code in PtyLab/Monitor/Monitor.py
def updateObjectProbeErrorMonitor(
    self,
    error,
    object_estimate: np.ndarray,
    probe_estimate: np.ndarray,
    zo=None,
    purity_probe=None,
    purity_object=None,
    encoder_positions=None,
):
    """Show the object and probe estimates and the error metric.

    Args:
        error (array-like): Error metric of every iteration so far.
        object_estimate (np.ndarray): Object inside the display region.
        probe_estimate (np.ndarray): Probe inside the display region.
        zo (float, optional): Sample-detector distance in m. Defaults to None.
        purity_probe (float, optional): Probe purity. Defaults to None.
        purity_object (float, optional): Object purity. Defaults to None.
        encoder_positions (np.ndarray, optional): Scan positions in object
            pixels. Defaults to None.
    """
updateBeamWidth(beamwidth_y, beamwidth_x)

Show the probe width.

Parameters:

Name Type Description Default
beamwidth_y float

FWHM along y in m.

required
beamwidth_x float

FWHM along x in m.

required
Source code in PtyLab/Monitor/Monitor.py
def updateBeamWidth(self, beamwidth_y, beamwidth_x):
    """Show the probe width.

    Args:
        beamwidth_y (float): FWHM along y in m.
        beamwidth_x (float): FWHM along x in m.
    """
updateDiffractionDataMonitor(Iestimated, Imeasured)

Show the estimated and measured intensity at the last scan position.

Parameters:

Name Type Description Default
Iestimated ndarray

Estimated detector intensity.

required
Imeasured ndarray

Measured detector intensity.

required
Source code in PtyLab/Monitor/Monitor.py
def updateDiffractionDataMonitor(self, Iestimated, Imeasured):
    """Show the estimated and measured intensity at the last scan position.

    Args:
        Iestimated (np.ndarray): Estimated detector intensity.
        Imeasured (np.ndarray): Measured detector intensity.
    """

Monitor

Bases: AbstractMonitor

Live matplotlib monitor, in GUI windows or in Jupyter cell outputs.

Shows up to three figures:

  • object, probe and error metric (ObjectProbeErrorPlot), always
  • estimated vs measured intensity (DiffractionDataPlot), for verboseLevel = "high"
  • zo, theta, purity and scan positions (ParameterHistoryPlot), once the engine changes one of them and while showParameterHistory is True

Attributes:

Name Type Description
figureUpdateFrequency int

Update the figures every this many iterations.

verboseLevel str

"low", or "high" to add the diffraction figure.

objectPlot str

"complex", "abs" or "angle".

objectZoom float or None

Shrinks the shown object region around the scanned area; None or "full" shows the whole object.

probeZoom float or None

Same for the probe, around the pupil size.

objectPlotContrast float

Brightness scaling of the complex object plot.

probePlotContrast float

Brightness scaling of the complex probe plot.

showParameterHistory bool

Whether to show the third figure.

screenshot_directory str or None

If set, the first figure is saved there after every update as frame_<iteration>.png.

Source code in PtyLab/Monitor/Monitor.py
class Monitor(AbstractMonitor):
    """Live matplotlib monitor, in GUI windows or in Jupyter cell outputs.

    Shows up to three figures:

    - object, probe and error metric (`ObjectProbeErrorPlot`), always
    - estimated vs measured intensity (`DiffractionDataPlot`), for
      `verboseLevel = "high"`
    - zo, theta, purity and scan positions (`ParameterHistoryPlot`), once the
      engine changes one of them and while `showParameterHistory` is True

    Attributes:
        figureUpdateFrequency (int): Update the figures every this many iterations.
        verboseLevel (str): `"low"`, or `"high"` to add the diffraction figure.
        objectPlot (str): `"complex"`, `"abs"` or `"angle"`.
        objectZoom (float or None): Shrinks the shown object region around the
            scanned area; `None` or `"full"` shows the whole object.
        probeZoom (float or None): Same for the probe, around the pupil size.
        objectPlotContrast (float): Brightness scaling of the complex object plot.
        probePlotContrast (float): Brightness scaling of the complex probe plot.
        showParameterHistory (bool): Whether to show the third figure.
        screenshot_directory (str or None): If set, the first figure is saved
            there after every update as `frame_<iteration>.png`.
    """

    def __init__(self):
        # settings for visualization
        self._figureUpdateFrequency = 1
        self.objectPlot: ObjectPlot = "complex"
        self._verboseLevel: VerboseLevel = "low"
        self.objectZoom: Zoom = 1
        self.probeZoom: Zoom = 1
        self.objectPlotContrast = 1
        self.probePlotContrast = 1
        self.cmapDiffraction = setColorMap()
        self.defaultMonitor = None
        self.screenshot_directory = None
        self.diffractionDataMonitor = None
        # zo, theta, purity and scan positions in a third window, shown only
        # for the quantities the engine actually changes
        self.showParameterHistory = True
        self.parameterHistoryMonitor = None
        # further windows an engine adds (name -> plot with a `figure`), e.g. the
        # purityPIE scan plot; saveFigures writes them next to the built-in ones
        self.extraFigures = {}

    @property
    def figureUpdateFrequency(self) -> int:
        return self._figureUpdateFrequency

    @figureUpdateFrequency.setter
    def figureUpdateFrequency(self, value: int):
        self._figureUpdateFrequency = value
        if is_inline() and self.figureUpdateFrequency < 5:
            warnings.warn(
                "For faster update of the reconstruction plot, set `monitor.figureUpdateFrequency = 5` or higher.",
                stacklevel=2,
            )

    @property
    def verboseLevel(self) -> VerboseLevel:
        return self._verboseLevel

    @verboseLevel.setter
    def verboseLevel(self, value: VerboseLevel):
        self._verboseLevel = value
        if is_inline() and self._verboseLevel == "high":
            warnings.warn(
                "For diffraction data plot, preferably use an interactive matplotlib backend or"
                ' set `monitor.verboseLevel = "low"`. ',
                stacklevel=2,
            )

    def initializeMonitors(self):
        """Create the figures; a figure that already exists is reused."""
        if self.defaultMonitor is None:
            self.defaultMonitor = ObjectProbeErrorPlot()

        if self.verboseLevel == "high":
            self.diffractionDataMonitor = DiffractionDataPlot()

        if self.showParameterHistory and self.parameterHistoryMonitor is None:
            # creates no figure yet; that happens once a quantity changes
            self.parameterHistoryMonitor = ParameterHistoryPlot()

    def update(self, frame: MonitorFrame):
        """Draw the object, probe and error panels, plus the diffraction data when shown.

        Args:
            frame (MonitorFrame): Current reconstruction state.
        """
        plot = self.defaultMonitor
        plot.updateError(frame.error)
        plot.updateObject(
            frame.object_view(),
            objectPlot=self.objectPlot,
            pixelSize=frame.object_pixel_size,
            axisUnit="mm",
            amplitudeScalingFactor=self.objectPlotContrast,
            # purity is only defined for mixed states
            purity=frame.purity_object if frame.nosm > 1 else None,
        )
        plot.updateProbe(
            frame.probe_view(),
            pixelSize=frame.probe_pixel_size,
            axisUnit=frame.probe_axis_unit,
            label=frame.probe_label,
            amplitudeScalingFactor=self.probePlotContrast,
            purity=frame.purity_probe if frame.npsm > 1 else None,
        )
        plot.drawNow()

        if self.screenshot_directory is not None:
            plot.figure.savefig(
                Path(self.screenshot_directory) / f"frame_{frame.iteration}.png"
            )

        # the diffraction figure only exists for verboseLevel "high", and the
        # engine only fills the intensities then
        if self.diffractionDataMonitor is not None and frame.I_estimated is not None:
            self.diffractionDataMonitor.update_view(
                frame.I_estimated, frame.I_measured, cmap=self.cmapDiffraction
            )
            self.diffractionDataMonitor.drawNow()

        if self.parameterHistoryMonitor is not None:
            history = self.parameterHistoryMonitor
            history.record(frame.iteration, tracked_values(frame))
            if frame.encoder_corrected is not None:
                history.record_positions(
                    frame.encoder_original, frame.encoder_corrected
                )
            history.draw()

    def saveFigures(self, fileName="recent", dpi=150):
        """Save the current monitor figures as PNG files.

        Call it after `engine.reconstruct()` to keep the final state, or let
        `reconstruction.saveResults(fileName, snapshot=monitor)` call it next to
        the HDF5 file. Each figure that exists is written as
        `<fileName>_<figure>.png`:

        - `reconstruction`: object, probe and error metric
        - `diffraction`: estimated vs measured intensity (`verboseLevel = "high"`)
        - `history`: zo, theta, purity and scan positions, if any of them changed
        - any window an engine registered in `extraFigures`, under its key (e.g.
          `purity_scan` from purityPIE)

        Args:
            fileName (str or Path, optional): Path prefix of the PNG files; missing
                parent directories are created. Defaults to `"recent"`.
            dpi (int, optional): Resolution of the PNG files. Defaults to 150.

        Returns:
            list[Path]: The files written.
        """
        figures = {
            "reconstruction": self.defaultMonitor,
            "diffraction": self.diffractionDataMonitor,
            "history": self.parameterHistoryMonitor,
        }
        figures.update(self.extraFigures)
        prefix = Path(fileName)
        prefix.parent.mkdir(parents=True, exist_ok=True)
        saved = []
        for name, plot in figures.items():
            # a plot object can exist without a figure, e.g. the history window
            # before any quantity changed
            if plot is None or getattr(plot, "figure", None) is None:
                continue
            path = prefix.with_name(f"{prefix.name}_{name}.png")
            plot.figure.savefig(path, dpi=dpi, bbox_inches="tight")
            saved.append(path)
        return saved
initializeMonitors()

Create the figures; a figure that already exists is reused.

Source code in PtyLab/Monitor/Monitor.py
def initializeMonitors(self):
    """Create the figures; a figure that already exists is reused."""
    if self.defaultMonitor is None:
        self.defaultMonitor = ObjectProbeErrorPlot()

    if self.verboseLevel == "high":
        self.diffractionDataMonitor = DiffractionDataPlot()

    if self.showParameterHistory and self.parameterHistoryMonitor is None:
        # creates no figure yet; that happens once a quantity changes
        self.parameterHistoryMonitor = ParameterHistoryPlot()
update(frame)

Draw the object, probe and error panels, plus the diffraction data when shown.

Parameters:

Name Type Description Default
frame MonitorFrame

Current reconstruction state.

required
Source code in PtyLab/Monitor/Monitor.py
def update(self, frame: MonitorFrame):
    """Draw the object, probe and error panels, plus the diffraction data when shown.

    Args:
        frame (MonitorFrame): Current reconstruction state.
    """
    plot = self.defaultMonitor
    plot.updateError(frame.error)
    plot.updateObject(
        frame.object_view(),
        objectPlot=self.objectPlot,
        pixelSize=frame.object_pixel_size,
        axisUnit="mm",
        amplitudeScalingFactor=self.objectPlotContrast,
        # purity is only defined for mixed states
        purity=frame.purity_object if frame.nosm > 1 else None,
    )
    plot.updateProbe(
        frame.probe_view(),
        pixelSize=frame.probe_pixel_size,
        axisUnit=frame.probe_axis_unit,
        label=frame.probe_label,
        amplitudeScalingFactor=self.probePlotContrast,
        purity=frame.purity_probe if frame.npsm > 1 else None,
    )
    plot.drawNow()

    if self.screenshot_directory is not None:
        plot.figure.savefig(
            Path(self.screenshot_directory) / f"frame_{frame.iteration}.png"
        )

    # the diffraction figure only exists for verboseLevel "high", and the
    # engine only fills the intensities then
    if self.diffractionDataMonitor is not None and frame.I_estimated is not None:
        self.diffractionDataMonitor.update_view(
            frame.I_estimated, frame.I_measured, cmap=self.cmapDiffraction
        )
        self.diffractionDataMonitor.drawNow()

    if self.parameterHistoryMonitor is not None:
        history = self.parameterHistoryMonitor
        history.record(frame.iteration, tracked_values(frame))
        if frame.encoder_corrected is not None:
            history.record_positions(
                frame.encoder_original, frame.encoder_corrected
            )
        history.draw()
saveFigures(fileName='recent', dpi=150)

Save the current monitor figures as PNG files.

Call it after engine.reconstruct() to keep the final state, or let reconstruction.saveResults(fileName, snapshot=monitor) call it next to the HDF5 file. Each figure that exists is written as <fileName>_<figure>.png:

  • reconstruction: object, probe and error metric
  • diffraction: estimated vs measured intensity (verboseLevel = "high")
  • history: zo, theta, purity and scan positions, if any of them changed
  • any window an engine registered in extraFigures, under its key (e.g. purity_scan from purityPIE)

Parameters:

Name Type Description Default
fileName str or Path

Path prefix of the PNG files; missing parent directories are created. Defaults to "recent".

'recent'
dpi int

Resolution of the PNG files. Defaults to 150.

150

Returns:

Type Description
list[Path]

The files written.

Source code in PtyLab/Monitor/Monitor.py
def saveFigures(self, fileName="recent", dpi=150):
    """Save the current monitor figures as PNG files.

    Call it after `engine.reconstruct()` to keep the final state, or let
    `reconstruction.saveResults(fileName, snapshot=monitor)` call it next to
    the HDF5 file. Each figure that exists is written as
    `<fileName>_<figure>.png`:

    - `reconstruction`: object, probe and error metric
    - `diffraction`: estimated vs measured intensity (`verboseLevel = "high"`)
    - `history`: zo, theta, purity and scan positions, if any of them changed
    - any window an engine registered in `extraFigures`, under its key (e.g.
      `purity_scan` from purityPIE)

    Args:
        fileName (str or Path, optional): Path prefix of the PNG files; missing
            parent directories are created. Defaults to `"recent"`.
        dpi (int, optional): Resolution of the PNG files. Defaults to 150.

    Returns:
        list[Path]: The files written.
    """
    figures = {
        "reconstruction": self.defaultMonitor,
        "diffraction": self.diffractionDataMonitor,
        "history": self.parameterHistoryMonitor,
    }
    figures.update(self.extraFigures)
    prefix = Path(fileName)
    prefix.parent.mkdir(parents=True, exist_ok=True)
    saved = []
    for name, plot in figures.items():
        # a plot object can exist without a figure, e.g. the history window
        # before any quantity changed
        if plot is None or getattr(plot, "figure", None) is None:
            continue
        path = prefix.with_name(f"{prefix.name}_{name}.png")
        plot.figure.savefig(path, dpi=dpi, bbox_inches="tight")
        saved.append(path)
    return saved

DummyMonitor

Bases: AbstractMonitor

Monitor that shows nothing, for runs where plotting would only cost time.

Inherits every no-op hook from AbstractMonitor, so any hook an engine calls (e.g. update_focusing_metric when params.TV_autofocus is on) exists here too.

Source code in PtyLab/Monitor/Monitor.py
class DummyMonitor(AbstractMonitor):
    """Monitor that shows nothing, for runs where plotting would only cost time.

    Inherits every no-op hook from `AbstractMonitor`, so any hook an engine calls
    (e.g. `update_focusing_metric` when `params.TV_autofocus` is on) exists here too.
    """

    objectZoom: Zoom = 1
    probeZoom: Zoom = 1
    # the engines only call the monitor every `figureUpdateFrequency` iterations
    figureUpdateFrequency = 1000000
    verboseLevel = "low"

    def update(self, frame):
        # the default would crop and copy object and probe to the CPU for nothing
        pass

NapariMonitor

Bases: DummyMonitor

Shows the object, probe and diffraction data as layers in a napari viewer.

Needs napari, which is not a PtyLab dependency.

Source code in PtyLab/Monitor/Monitor.py
class NapariMonitor(DummyMonitor):
    """Shows the object, probe and diffraction data as layers in a napari viewer.

    Needs napari, which is not a PtyLab dependency.
    """

    def initializeVisualisation(self):
        """Open the viewer and create its image layers."""
        # currently a hacky way for this class, these napari implementations must
        # later be moved an optional sub-package.
        try:
            import napari

            self.viewer = napari.Viewer()
            self.viewer.show()
        except ImportError:
            msg = "Install napari to access this `NapariMonitor` implementation"
            raise ImportError(msg)

        # object and probe are shown as complex2rgb images, so these layers must be
        # RGB from the start: napari fixes a layer's `rgb` flag when it is created
        self.viewer.add_image(
            name="object estimate", data=np.zeros((100, 100, 3)), rgb=True
        )
        self.viewer.add_image(
            name="probe estimate", data=np.zeros((100, 100, 3)), rgb=True
        )

        self.Iestimated = self.viewer.add_image(
            name="I estimated", data=np.random.rand(100, 100)
        )
        self.Imeasured = self.viewer.add_image(
            name="I measured", data=np.random.rand(100, 100)
        )
        self.rawdatamonitor = self.viewer.add_image(
            name="raw data (unset)", data=np.random.rand(100, 100), visible=False
        )

    def initializeMonitors(self):
        self.initializeVisualisation()

    def add_ptychogram(self, experimentalData):
        self.rawdatamonitor.name = "raw data"
        self.rawdatamonitor.data = experimentalData.ptychogram
        self.rawdatamonitor.visible = True

    def update_probe_image(self, new_probe):
        RGB_probe = complex2rgb(new_probe)
        self.viewer.layers["probe estimate"].data = RGB_probe

    def update_object_image(self, object_estimate):
        RGB_object = complex2rgb(object_estimate)
        self.viewer.layers["object estimate"].data = RGB_object

    def updatePlot(
        self, object_estimate, probe_estimate, zo=None, encoder_positions=None
    ):
        self.update_probe_image(probe_estimate)
        self.update_object_image(object_estimate)

    def updateObjectProbeErrorMonitor(
        self, error, object_estimate, probe_estimate, *args, **kwargs
    ):
        # this is the hook `BaseEngine.showReconstruction` calls; without it the
        # viewer never receives the estimates
        self.updatePlot(object_estimate, probe_estimate)

    def updateDiffractionDataMonitor(self, Iestimated, Imeasured):
        self.Iestimated.data = Iestimated
        self.Imeasured.data = Imeasured
initializeVisualisation()

Open the viewer and create its image layers.

Source code in PtyLab/Monitor/Monitor.py
def initializeVisualisation(self):
    """Open the viewer and create its image layers."""
    # currently a hacky way for this class, these napari implementations must
    # later be moved an optional sub-package.
    try:
        import napari

        self.viewer = napari.Viewer()
        self.viewer.show()
    except ImportError:
        msg = "Install napari to access this `NapariMonitor` implementation"
        raise ImportError(msg)

    # object and probe are shown as complex2rgb images, so these layers must be
    # RGB from the start: napari fixes a layer's `rgb` flag when it is created
    self.viewer.add_image(
        name="object estimate", data=np.zeros((100, 100, 3)), rgb=True
    )
    self.viewer.add_image(
        name="probe estimate", data=np.zeros((100, 100, 3)), rgb=True
    )

    self.Iestimated = self.viewer.add_image(
        name="I estimated", data=np.random.rand(100, 100)
    )
    self.Imeasured = self.viewer.add_image(
        name="I measured", data=np.random.rand(100, 100)
    )
    self.rawdatamonitor = self.viewer.add_image(
        name="raw data (unset)", data=np.random.rand(100, 100), visible=False
    )

tracked_values(frame)

Scalars besides object and probe that an engine may change, in display units.

Quantities the frame does not carry (None) or that are undefined for this reconstruction (purity of a single mode) are left out.

Parameters:

Name Type Description Default
frame MonitorFrame

Current reconstruction state.

required

Returns:

Type Description
dict[str, dict[str, float]]

Panel title -> line label -> value.

Source code in PtyLab/Monitor/Monitor.py
def tracked_values(frame: MonitorFrame) -> dict:
    """Scalars besides object and probe that an engine may change, in display units.

    Quantities the frame does not carry (`None`) or that are undefined for this
    reconstruction (purity of a single mode) are left out.

    Args:
        frame (MonitorFrame): Current reconstruction state.

    Returns:
        dict[str, dict[str, float]]: Panel title -> line label -> value.
    """
    values = {}
    if frame.zo is not None:
        values["zo [mm]"] = {"zo": 1e3 * float(frame.zo)}
    if frame.theta is not None:
        values["theta [deg]"] = {"theta": float(frame.theta)}
    purity = {}
    if frame.nosm > 1:
        purity["object"] = 100 * float(frame.purity_object)
    if frame.npsm > 1:
        purity["probe"] = 100 * float(frame.purity_probe)
    if purity:
        values["purity [%]"] = purity
    return values

Plots

ObjectProbeErrorPlot

Bases: _LiveFigure

Figure with the object estimate, the probe estimate and the error metric.

Call updateObject, updateProbe and updateError with the current state, then drawNow to show it. The first round of updates creates the images; later ones only replace their data.

Parameters:

Name Type Description Default
figNum int

pyplot figure number. Defaults to 1.

1
Source code in PtyLab/Monitor/Plots.py
class ObjectProbeErrorPlot(_LiveFigure):
    """Figure with the object estimate, the probe estimate and the error metric.

    Call `updateObject`, `updateProbe` and `updateError` with the current state,
    then `drawNow` to show it. The first round of updates creates the images; later
    ones only replace their data.

    Args:
        figNum (int, optional): pyplot figure number. Defaults to 1.
    """

    def __init__(self, figNum=1):
        self.figNum = figNum
        self._createFigure()

    def _createFigure(self) -> None:
        """Create the figure with an object, a probe and an error-metric panel."""
        # interactive mode only matters for GUI windows; leave notebook sessions alone
        if not is_inline():
            plt.ion()
        # a new monitor must not draw on top of an old figure with the same number;
        # the size is set separately because pyplot ignores figsize for a reused one
        self.figure = plt.figure(num=self.figNum, clear=True)
        self.figure.set_size_inches(10, 3)
        axes = self.figure.subplot_mosaic("""Ape""", empty_sentinel=" ")

        self.ax_object = axes["A"]
        self.ax_probe = axes["p"]
        self.ax_error_metric = axes["e"]
        self.txt_purityObject = self.ax_object.set_title("Object estimate")
        self.txt_purityProbe = self.ax_probe.set_title("Probe estimate")

        ax = self.ax_error_metric
        ax.set_title("Error metric")
        ax.set_xlabel("iterations")
        ax.set_ylabel("error")
        ax.set_xscale("log")
        ax.set_yscale("log")
        # plain tick labels (2, 3, 20) instead of 2x10^0, which overlap on a short
        # axis; LogFormatter still thins out the minor labels over many decades
        for axis in (ax.xaxis, ax.yaxis):
            axis.set_major_formatter(ticker.LogFormatter())
            axis.set_minor_formatter(ticker.LogFormatter(labelOnlyBase=False))
        ax.grid(True, which="major", alpha=0.4)
        ax.grid(True, which="minor", alpha=0.15)
        self.figure.tight_layout()
        self._attach_figure(self.figure)

    def updateObject(
        self,
        object_estimate,
        objectPlot,
        amplitudeScalingFactor=1,
        purity=None,
        **kwargs: Any,
    ):
        """Show the object estimate.

        Args:
            object_estimate (np.ndarray): Object, `(Ny, Nx)` or a stack of modes,
                which are tiled side by side.
            objectPlot (str): `"complex"` (phase as hue, amplitude as brightness),
                `"abs"` or `"angle"`.
            amplitudeScalingFactor (float, optional): Brightness scaling of the
                complex plot. Defaults to 1.
            purity (float, optional): Object purity, shown in the title; `None` for
                a single object mode. Defaults to None.
            **kwargs: Passed to `complexPlot` on the first call, e.g. `pixelSize`
                and `axisUnit`.
        """
        OE = modeTile(object_estimate, normalize=True)
        if objectPlot == "complex":
            OE = complex2rgb(OE, amplitudeScalingFactor=amplitudeScalingFactor)
        elif objectPlot == "abs":
            # normalise to mean + std rather than the maximum, so a few hot pixels
            # do not darken the whole image
            AOE = abs(OE)
            OE = abs(OE / (AOE.mean() + np.std(AOE)))
        elif objectPlot == "angle":
            OE = np.angle(OE)

        if self.firstrun:
            if objectPlot == "complex":
                self.im_object = complexPlot(OE, ax=self.ax_object, **kwargs)
            else:
                self.im_object = self.ax_object.imshow(OE, interpolation=None)
                divider = make_axes_locatable(self.ax_object)
                cax = divider.append_axes("right", size="5%", pad=0.1)
                self.objectCbar = self.figure.colorbar(
                    self.im_object, ax=self.ax_object, cax=cax
                )
        else:
            self.im_object.set_data(OE)
            if purity is not None:
                self.txt_purityObject.set_text(
                    f"Object estimate\nPurity: {int(100 * purity)}%"
                )

        self.im_object.autoscale()

    def updateProbe(
        self,
        probe_estimate,
        amplitudeScalingFactor=1,
        label="Probe estimate",
        purity=None,
        **kwargs: Any,
    ):
        """Show the probe (or, for FPM, pupil) estimate as a complex plot.

        Args:
            probe_estimate (np.ndarray): Probe, `(Ny, Nx)` or a stack of modes,
                which are tiled side by side.
            amplitudeScalingFactor (float, optional): Brightness scaling of the
                complex plot. Defaults to 1.
            label (str, optional): Panel title. Defaults to `"Probe estimate"`.
            purity (float, optional): Probe purity, shown in the title; `None` for
                a single probe mode. Defaults to None.
            **kwargs: Passed to `complexPlot` on the first call, e.g. `pixelSize`
                and `axisUnit`.
        """
        PE = complex2rgb(
            modeTile(probe_estimate, normalize=True),
            amplitudeScalingFactor=amplitudeScalingFactor,
        )

        if self.firstrun:
            self.im_probe = complexPlot(PE, ax=self.ax_probe, **kwargs)
            self.txt_purityProbe = self.ax_probe.set_title(label)
        else:
            self.im_probe.set_data(PE)
            # purity is NaN until it is first computed
            if purity is not None and not math.isnan(float(purity)):
                self.txt_purityProbe.set_text(f"{label}\nPurity: {100 * purity:.2f}%")
        self.im_probe.autoscale()

    def updateError(self, error_estimate) -> None:
        """Plot the error metric of every iteration so far on log-log axes.

        Args:
            error_estimate (array-like): One error value per completed iteration.
        """
        error = np.asarray(gpuUtils.asNumpyArray(error_estimate), dtype=float)
        # iterations count from 1, as 0 cannot be shown on a log axis
        iterations = np.arange(1, len(error) + 1)

        if self.firstrun:
            (self.error_metric_plot,) = self.ax_error_metric.plot(
                iterations, error, "o-", mfc="none"
            )
        else:
            self.error_metric_plot.set_data(iterations, error)

        if len(error) > 0:
            ax = self.ax_error_metric
            # rescale to the data; the log axes ignore non-positive and NaN values
            ax.relim()
            ax.autoscale_view()
            ax.set_title(f"Error metric (it {len(error)})")
updateObject(object_estimate, objectPlot, amplitudeScalingFactor=1, purity=None, **kwargs)

Show the object estimate.

Parameters:

Name Type Description Default
object_estimate ndarray

Object, (Ny, Nx) or a stack of modes, which are tiled side by side.

required
objectPlot str

"complex" (phase as hue, amplitude as brightness), "abs" or "angle".

required
amplitudeScalingFactor float

Brightness scaling of the complex plot. Defaults to 1.

1
purity float

Object purity, shown in the title; None for a single object mode. Defaults to None.

None
**kwargs Any

Passed to complexPlot on the first call, e.g. pixelSize and axisUnit.

{}
Source code in PtyLab/Monitor/Plots.py
def updateObject(
    self,
    object_estimate,
    objectPlot,
    amplitudeScalingFactor=1,
    purity=None,
    **kwargs: Any,
):
    """Show the object estimate.

    Args:
        object_estimate (np.ndarray): Object, `(Ny, Nx)` or a stack of modes,
            which are tiled side by side.
        objectPlot (str): `"complex"` (phase as hue, amplitude as brightness),
            `"abs"` or `"angle"`.
        amplitudeScalingFactor (float, optional): Brightness scaling of the
            complex plot. Defaults to 1.
        purity (float, optional): Object purity, shown in the title; `None` for
            a single object mode. Defaults to None.
        **kwargs: Passed to `complexPlot` on the first call, e.g. `pixelSize`
            and `axisUnit`.
    """
    OE = modeTile(object_estimate, normalize=True)
    if objectPlot == "complex":
        OE = complex2rgb(OE, amplitudeScalingFactor=amplitudeScalingFactor)
    elif objectPlot == "abs":
        # normalise to mean + std rather than the maximum, so a few hot pixels
        # do not darken the whole image
        AOE = abs(OE)
        OE = abs(OE / (AOE.mean() + np.std(AOE)))
    elif objectPlot == "angle":
        OE = np.angle(OE)

    if self.firstrun:
        if objectPlot == "complex":
            self.im_object = complexPlot(OE, ax=self.ax_object, **kwargs)
        else:
            self.im_object = self.ax_object.imshow(OE, interpolation=None)
            divider = make_axes_locatable(self.ax_object)
            cax = divider.append_axes("right", size="5%", pad=0.1)
            self.objectCbar = self.figure.colorbar(
                self.im_object, ax=self.ax_object, cax=cax
            )
    else:
        self.im_object.set_data(OE)
        if purity is not None:
            self.txt_purityObject.set_text(
                f"Object estimate\nPurity: {int(100 * purity)}%"
            )

    self.im_object.autoscale()
updateProbe(probe_estimate, amplitudeScalingFactor=1, label='Probe estimate', purity=None, **kwargs)

Show the probe (or, for FPM, pupil) estimate as a complex plot.

Parameters:

Name Type Description Default
probe_estimate ndarray

Probe, (Ny, Nx) or a stack of modes, which are tiled side by side.

required
amplitudeScalingFactor float

Brightness scaling of the complex plot. Defaults to 1.

1
label str

Panel title. Defaults to "Probe estimate".

'Probe estimate'
purity float

Probe purity, shown in the title; None for a single probe mode. Defaults to None.

None
**kwargs Any

Passed to complexPlot on the first call, e.g. pixelSize and axisUnit.

{}
Source code in PtyLab/Monitor/Plots.py
def updateProbe(
    self,
    probe_estimate,
    amplitudeScalingFactor=1,
    label="Probe estimate",
    purity=None,
    **kwargs: Any,
):
    """Show the probe (or, for FPM, pupil) estimate as a complex plot.

    Args:
        probe_estimate (np.ndarray): Probe, `(Ny, Nx)` or a stack of modes,
            which are tiled side by side.
        amplitudeScalingFactor (float, optional): Brightness scaling of the
            complex plot. Defaults to 1.
        label (str, optional): Panel title. Defaults to `"Probe estimate"`.
        purity (float, optional): Probe purity, shown in the title; `None` for
            a single probe mode. Defaults to None.
        **kwargs: Passed to `complexPlot` on the first call, e.g. `pixelSize`
            and `axisUnit`.
    """
    PE = complex2rgb(
        modeTile(probe_estimate, normalize=True),
        amplitudeScalingFactor=amplitudeScalingFactor,
    )

    if self.firstrun:
        self.im_probe = complexPlot(PE, ax=self.ax_probe, **kwargs)
        self.txt_purityProbe = self.ax_probe.set_title(label)
    else:
        self.im_probe.set_data(PE)
        # purity is NaN until it is first computed
        if purity is not None and not math.isnan(float(purity)):
            self.txt_purityProbe.set_text(f"{label}\nPurity: {100 * purity:.2f}%")
    self.im_probe.autoscale()
updateError(error_estimate)

Plot the error metric of every iteration so far on log-log axes.

Parameters:

Name Type Description Default
error_estimate array - like

One error value per completed iteration.

required
Source code in PtyLab/Monitor/Plots.py
def updateError(self, error_estimate) -> None:
    """Plot the error metric of every iteration so far on log-log axes.

    Args:
        error_estimate (array-like): One error value per completed iteration.
    """
    error = np.asarray(gpuUtils.asNumpyArray(error_estimate), dtype=float)
    # iterations count from 1, as 0 cannot be shown on a log axis
    iterations = np.arange(1, len(error) + 1)

    if self.firstrun:
        (self.error_metric_plot,) = self.ax_error_metric.plot(
            iterations, error, "o-", mfc="none"
        )
    else:
        self.error_metric_plot.set_data(iterations, error)

    if len(error) > 0:
        ax = self.ax_error_metric
        # rescale to the data; the log axes ignore non-positive and NaN values
        ax.relim()
        ax.autoscale_view()
        ax.set_title(f"Error metric (it {len(error)})")

DiffractionDataPlot

Bases: _LiveFigure

Figure with the estimated and measured diffraction intensity, side by side.

Both are shown as \(\log_{10}(I + 1)\), with the colour limits of the measured intensity applied to the estimate so the two can be compared directly.

Parameters:

Name Type Description Default
figNum int

pyplot figure number. Defaults to 2.

2
Source code in PtyLab/Monitor/Plots.py
class DiffractionDataPlot(_LiveFigure):
    r"""Figure with the estimated and measured diffraction intensity, side by side.

    Both are shown as $\log_{10}(I + 1)$, with the colour limits of the measured
    intensity applied to the estimate so the two can be compared directly.

    Args:
        figNum (int, optional): pyplot figure number. Defaults to 2.
    """

    def __init__(self, figNum=2):
        self.figNum = figNum
        self._createFigure()

    def _createFigure(self) -> None:
        """Create the figure with an estimated and a measured intensity panel."""
        # interactive mode only matters for GUI windows; leave notebook sessions alone
        if not is_inline():
            plt.ion()
        # see ObjectProbeErrorPlot._createFigure for why size is set separately
        self.figure = plt.figure(num=self.figNum, clear=True)
        self.figure.set_size_inches(8, 3)
        axes = self.figure.subplots(1, 2, squeeze=False)
        self.ax_Iestimated = axes[0][0]
        self.ax_Imeasured = axes[0][1]
        self.ax_Iestimated.set_title("Estimated intensity")
        self.ax_Imeasured.set_title("Measured intensity")
        self.figure.tight_layout()
        self._attach_figure(self.figure)

    def updateIestimated(self, Iestimate, cmap="gray", **kwargs):
        """Show the estimated intensity; its colour limits are set by `update_view`.

        Args:
            Iestimate (np.ndarray): Estimated detector intensity, CPU or GPU.
            cmap (str or Colormap, optional): Colour map. Defaults to `"gray"`.
        """
        Iestimate = gpuUtils.asNumpyArray(Iestimate)
        if self.firstrun:
            self.im_Iestimated: AxesImage = self.ax_Iestimated.imshow(
                np.log10(np.squeeze(Iestimate + 1)), cmap=cmap, interpolation=None
            )
            divider = make_axes_locatable(self.ax_Iestimated)
            cax = divider.append_axes("right", size="5%", pad=0.1)
            self.IestimatedCbar = self.figure.colorbar(
                self.im_Iestimated, ax=self.ax_Iestimated, cax=cax
            )
        else:
            self.im_Iestimated.set_data(np.log10(np.squeeze(Iestimate + 1)))

    def updateImeasured(self, Imeasured, cmap="gray", **kwargs):
        """Show the measured intensity, with colour limits fitted to it.

        Args:
            Imeasured (np.ndarray): Measured detector intensity, CPU or GPU.
            cmap (str or Colormap, optional): Colour map. Defaults to `"gray"`.
        """
        Imeasured = gpuUtils.asNumpyArray(Imeasured)
        if self.firstrun:
            self.im_Imeasured: AxesImage = self.ax_Imeasured.imshow(
                np.log10(np.squeeze(Imeasured + 1)), cmap=cmap, interpolation=None
            )
            divider = make_axes_locatable(self.ax_Imeasured)
            cax = divider.append_axes("right", size="5%", pad=0.1)
            self.ImeasuredCbar = self.figure.colorbar(
                self.im_Imeasured, ax=self.ax_Imeasured, cax=cax
            )
        else:
            self.im_Imeasured.set_data(np.log10(np.squeeze(Imeasured + 1)))
        self.im_Imeasured.autoscale()

    def update_view(self, Iestimated, Imeasured, cmap):
        """Show both intensities with the colour limits of the measured one.

        Args:
            Iestimated (np.ndarray): Estimated detector intensity.
            Imeasured (np.ndarray): Measured detector intensity.
            cmap (str or Colormap): Colour map of both panels.
        """
        self.updateImeasured(Imeasured, cmap=cmap)
        self.updateIestimated(Iestimated, cmap=cmap)
        self.im_Iestimated.set_clim(*self.im_Imeasured.get_clim())
updateIestimated(Iestimate, cmap='gray', **kwargs)

Show the estimated intensity; its colour limits are set by update_view.

Parameters:

Name Type Description Default
Iestimate ndarray

Estimated detector intensity, CPU or GPU.

required
cmap str or Colormap

Colour map. Defaults to "gray".

'gray'
Source code in PtyLab/Monitor/Plots.py
def updateIestimated(self, Iestimate, cmap="gray", **kwargs):
    """Show the estimated intensity; its colour limits are set by `update_view`.

    Args:
        Iestimate (np.ndarray): Estimated detector intensity, CPU or GPU.
        cmap (str or Colormap, optional): Colour map. Defaults to `"gray"`.
    """
    Iestimate = gpuUtils.asNumpyArray(Iestimate)
    if self.firstrun:
        self.im_Iestimated: AxesImage = self.ax_Iestimated.imshow(
            np.log10(np.squeeze(Iestimate + 1)), cmap=cmap, interpolation=None
        )
        divider = make_axes_locatable(self.ax_Iestimated)
        cax = divider.append_axes("right", size="5%", pad=0.1)
        self.IestimatedCbar = self.figure.colorbar(
            self.im_Iestimated, ax=self.ax_Iestimated, cax=cax
        )
    else:
        self.im_Iestimated.set_data(np.log10(np.squeeze(Iestimate + 1)))
updateImeasured(Imeasured, cmap='gray', **kwargs)

Show the measured intensity, with colour limits fitted to it.

Parameters:

Name Type Description Default
Imeasured ndarray

Measured detector intensity, CPU or GPU.

required
cmap str or Colormap

Colour map. Defaults to "gray".

'gray'
Source code in PtyLab/Monitor/Plots.py
def updateImeasured(self, Imeasured, cmap="gray", **kwargs):
    """Show the measured intensity, with colour limits fitted to it.

    Args:
        Imeasured (np.ndarray): Measured detector intensity, CPU or GPU.
        cmap (str or Colormap, optional): Colour map. Defaults to `"gray"`.
    """
    Imeasured = gpuUtils.asNumpyArray(Imeasured)
    if self.firstrun:
        self.im_Imeasured: AxesImage = self.ax_Imeasured.imshow(
            np.log10(np.squeeze(Imeasured + 1)), cmap=cmap, interpolation=None
        )
        divider = make_axes_locatable(self.ax_Imeasured)
        cax = divider.append_axes("right", size="5%", pad=0.1)
        self.ImeasuredCbar = self.figure.colorbar(
            self.im_Imeasured, ax=self.ax_Imeasured, cax=cax
        )
    else:
        self.im_Imeasured.set_data(np.log10(np.squeeze(Imeasured + 1)))
    self.im_Imeasured.autoscale()
update_view(Iestimated, Imeasured, cmap)

Show both intensities with the colour limits of the measured one.

Parameters:

Name Type Description Default
Iestimated ndarray

Estimated detector intensity.

required
Imeasured ndarray

Measured detector intensity.

required
cmap str or Colormap

Colour map of both panels.

required
Source code in PtyLab/Monitor/Plots.py
def update_view(self, Iestimated, Imeasured, cmap):
    """Show both intensities with the colour limits of the measured one.

    Args:
        Iestimated (np.ndarray): Estimated detector intensity.
        Imeasured (np.ndarray): Measured detector intensity.
        cmap (str or Colormap): Colour map of both panels.
    """
    self.updateImeasured(Imeasured, cmap=cmap)
    self.updateIestimated(Iestimated, cmap=cmap)
    self.im_Iestimated.set_clim(*self.im_Imeasured.get_clim())

ParameterHistoryPlot

Bases: _LiveFigure

Traces of the quantities an engine changes besides object and probe.

Each update records one value per line, grouped into panels (e.g. the panel "purity [%]" with lines "object" and "probe"). A panel is only drawn once one of its lines has changed from its first value, so quantities the engine never touches (a fixed zo, a single-mode purity) stay hidden. The scan-position panel appears once position correction has moved a position.

The figure is created on the first draw that has something to show, so no window opens for a reconstruction that changes nothing.

Source code in PtyLab/Monitor/Plots.py
class ParameterHistoryPlot(_LiveFigure):
    """Traces of the quantities an engine changes besides object and probe.

    Each update records one value per line, grouped into panels (e.g. the panel
    "purity [%]" with lines "object" and "probe"). A panel is only drawn once one of
    its lines has changed from its first value, so quantities the engine never
    touches (a fixed zo, a single-mode purity) stay hidden. The scan-position
    panel appears once position correction has moved a position.

    The figure is created on the first draw that has something to show, so no
    window opens for a reconstruction that changes nothing.
    """

    def __init__(self, figNum=3):
        self.figNum = figNum
        self.figure = None
        # panel title -> line label -> ([iterations], [values])
        self.history = {}
        # (measured, corrected) positions in m, only kept once they differ
        self.positions = None

    def record(self, iteration, values):
        """Append one value per line.

        Args:
            iteration (int): Iteration the values belong to.
            values (dict[str, dict[str, float]]): Panel title -> line label -> value.
        """
        for panel, lines in values.items():
            for label, value in lines.items():
                its, vals = self.history.setdefault(panel, {}).setdefault(
                    label, ([], [])
                )
                its.append(iteration)
                vals.append(value)

    def record_positions(self, measured, corrected):
        """Keep the scan positions if position correction has moved any of them."""
        measured = gpuUtils.asNumpyArray(measured)
        corrected = gpuUtils.asNumpyArray(corrected)
        if not np.array_equal(measured, corrected):
            # corrected is edited in place by the engine, so keep a copy
            self.positions = (measured, corrected.copy())

    def active_panels(self):
        """Titles of the panels whose values have changed, in recording order."""
        return [
            panel
            for panel, lines in self.history.items()
            if any(
                not np.allclose(vals, vals[0], rtol=1e-6, atol=0)
                for _, vals in lines.values()
            )
        ]

    def draw(self):
        """Redraw every active panel; does nothing while no panel is active."""
        panels = self.active_panels()
        n = len(panels) + (self.positions is not None)
        if n == 0:
            return

        if self.figure is None:
            # interactive mode only matters for GUI windows
            if not is_inline():
                plt.ion()
            self._attach_figure(plt.figure(num=self.figNum, clear=True))
        else:
            # the number of panels can grow, so rebuild the axes on every draw;
            # a handful of line plots is cheap next to the object/probe images
            self.figure.clf()
        self.figure.set_size_inches(3.2 * n, 3, forward=True)

        axes = np.atleast_1d(self.figure.subplots(1, n))
        for ax, panel in zip(axes, panels):
            for label, (its, vals) in self.history[panel].items():
                ax.plot(its, vals, ".-", label=label)
            ax.set_title(panel)
            ax.set_xlabel("iterations")
            # show absolute values (49.99 mm), not an offset plus tiny ticks
            ax.ticklabel_format(axis="y", useOffset=False)
            ax.grid(True, alpha=0.3)
            if len(self.history[panel]) > 1:
                ax.legend(fontsize="small")

        if self.positions is not None:
            measured, corrected = self.positions
            ax = axes[-1]
            # encoder positions are (y, x) in m; plot x horizontally, in mm
            ax.plot(
                measured[:, 1] * 1e3,
                measured[:, 0] * 1e3,
                "o",
                mfc="none",
                label="measured",
            )
            ax.plot(
                corrected[:, 1] * 1e3, corrected[:, 0] * 1e3, ".", label="corrected"
            )
            ax.set_title("scan positions [mm]")
            ax.set_aspect("equal", adjustable="datalim")
            ax.legend(fontsize="small")

        self.figure.tight_layout()
        self.drawNow()
record(iteration, values)

Append one value per line.

Parameters:

Name Type Description Default
iteration int

Iteration the values belong to.

required
values dict[str, dict[str, float]]

Panel title -> line label -> value.

required
Source code in PtyLab/Monitor/Plots.py
def record(self, iteration, values):
    """Append one value per line.

    Args:
        iteration (int): Iteration the values belong to.
        values (dict[str, dict[str, float]]): Panel title -> line label -> value.
    """
    for panel, lines in values.items():
        for label, value in lines.items():
            its, vals = self.history.setdefault(panel, {}).setdefault(
                label, ([], [])
            )
            its.append(iteration)
            vals.append(value)
record_positions(measured, corrected)

Keep the scan positions if position correction has moved any of them.

Source code in PtyLab/Monitor/Plots.py
def record_positions(self, measured, corrected):
    """Keep the scan positions if position correction has moved any of them."""
    measured = gpuUtils.asNumpyArray(measured)
    corrected = gpuUtils.asNumpyArray(corrected)
    if not np.array_equal(measured, corrected):
        # corrected is edited in place by the engine, so keep a copy
        self.positions = (measured, corrected.copy())
active_panels()

Titles of the panels whose values have changed, in recording order.

Source code in PtyLab/Monitor/Plots.py
def active_panels(self):
    """Titles of the panels whose values have changed, in recording order."""
    return [
        panel
        for panel, lines in self.history.items()
        if any(
            not np.allclose(vals, vals[0], rtol=1e-6, atol=0)
            for _, vals in lines.values()
        )
    ]
draw()

Redraw every active panel; does nothing while no panel is active.

Source code in PtyLab/Monitor/Plots.py
def draw(self):
    """Redraw every active panel; does nothing while no panel is active."""
    panels = self.active_panels()
    n = len(panels) + (self.positions is not None)
    if n == 0:
        return

    if self.figure is None:
        # interactive mode only matters for GUI windows
        if not is_inline():
            plt.ion()
        self._attach_figure(plt.figure(num=self.figNum, clear=True))
    else:
        # the number of panels can grow, so rebuild the axes on every draw;
        # a handful of line plots is cheap next to the object/probe images
        self.figure.clf()
    self.figure.set_size_inches(3.2 * n, 3, forward=True)

    axes = np.atleast_1d(self.figure.subplots(1, n))
    for ax, panel in zip(axes, panels):
        for label, (its, vals) in self.history[panel].items():
            ax.plot(its, vals, ".-", label=label)
        ax.set_title(panel)
        ax.set_xlabel("iterations")
        # show absolute values (49.99 mm), not an offset plus tiny ticks
        ax.ticklabel_format(axis="y", useOffset=False)
        ax.grid(True, alpha=0.3)
        if len(self.history[panel]) > 1:
            ax.legend(fontsize="small")

    if self.positions is not None:
        measured, corrected = self.positions
        ax = axes[-1]
        # encoder positions are (y, x) in m; plot x horizontally, in mm
        ax.plot(
            measured[:, 1] * 1e3,
            measured[:, 0] * 1e3,
            "o",
            mfc="none",
            label="measured",
        )
        ax.plot(
            corrected[:, 1] * 1e3, corrected[:, 0] * 1e3, ".", label="corrected"
        )
        ax.set_title("scan positions [mm]")
        ax.set_aspect("equal", adjustable="datalim")
        ax.legend(fontsize="small")

    self.figure.tight_layout()
    self.drawNow()

is_inline()

Whether matplotlib draws inline, as in a Jupyter notebook.

Returns:

Type Description
bool

True for an inline backend, False for a GUI or file backend.

Source code in PtyLab/Monitor/Plots.py
def is_inline():
    """Whether matplotlib draws inline, as in a Jupyter notebook.

    Returns:
        bool: True for an inline backend, False for a GUI or file backend.
    """
    return "inline" in mpl.get_backend().lower()

TensorboardMonitor

TensorboardMonitor

Bases: AbstractMonitor

Source code in PtyLab/Monitor/TensorboardMonitor.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
class TensorboardMonitor(AbstractMonitor):
    # maximum number of probe state mixtures that we want to show
    max_npsm = 10
    # maximum number of object state mixtures we want to show
    max_nosm = 10
    # remove any phase slant from the object
    center_angle_object = False
    # Turn on to show the FFT of the object. Usually not useful.
    show_farfield_object = False

    # the probe is shown as an inset in the object. This specifies how much to downsample it
    probe_downsampling = 2

    # downsample all images by the same amount to make it run a bit faster
    downsample_everything = 1

    def __init__(self, logdir="./logs_tensorboard", name=None):
        super().__init__()
        # if true, all phases are centered in such a way that the average phase in the center of any RGB plot is zero.
        self.center_phases = True
        if name is None:
            starttime = time.strftime("%H%M")
            name = f"Start {starttime}"
            print("Name", name)
        path = Path(logdir) / name
        self.writer: tfs.SummaryWriter = tfs.create_file_writer(
            logdir=str(path), name=name
        )
        self.i = 0

    # These are the codes that have to be implemented

    def updatePlot(
        self,
        object_estimate,
        probe_estimate,
        highres=True,
        zo=None,
        encoder_positions=None,
    ):
        self.i += 1

        if not highres:
            Np = probe_estimate.shape[-1]
            No = object_estimate.shape[-1]
            xmax, ymax = np.clip(encoder_positions.max(axis=0) + 2 * Np // 3, 0, No)
            xmin, ymin = np.clip(encoder_positions.min(axis=0) + Np // 3, 0, No)

            probe_estimate = probe_estimate[..., ::4, ::4]
            object_estimate = object_estimate[..., ymin:ymax, xmin:xmax]
        probe_estimate_rgb = self._update_probe_estimate(
            probe_estimate, highres=highres
        )
        self._update_object_estimate(
            object_estimate, probe_estimate_rgb, highres=highres, zo=zo
        )

    def visualize_probe_engine(self, engine):
        RGB_image = complex2rgb_vectorized(
            engine.get_fundamental(), center_phase=self.center_phases
        )
        self.__safe_upload_image("original probe", np.squeeze(RGB_image), self.i)

    def updateObjectProbeErrorMonitor(
        self,
        error,
        object_estimate,
        probe_estimate,
        zo,
        purity_object=None,
        purity_probe=None,
        encoder_positions=None,
        *args,
        **kwargs,
    ):
        object_estimate = asNumpyArray(object_estimate)
        probe_estimate = asNumpyArray(probe_estimate)
        # The input can be either an empty array, an array with length 1 or a list of all the errors so far.
        # In the last case, we only want the last value.
        # or just a number. This part should account of all of them.
        if encoder_positions is None:
            raise ValueError("Please submit encoder positions or the code won't work.")
        self._update_error_estimate(error)

        self.updatePlot(
            object_estimate,
            probe_estimate,
            highres=self.i % 5 == 0,
            encoder_positions=encoder_positions,
            zo=zo,
        )

        self.update_z(zo)
        self.update_purities(asNumpyArray(purity_probe), asNumpyArray(purity_object))

    def updateDiffractionDataMonitor(self, Iestimated, Imeasured):

        Itotal = np.hstack([Iestimated, Imeasured])
        Itotal = Itotal[None, ..., None]
        Itotal = Itotal / Itotal.max() * 255
        Itotal = Itotal.astype(np.uint8)
        self.__safe_upload_image(
            "Estimated and measured intensity example", Itotal, self.i, 1
        )

    def writeEngineName(self, name, *args, **kwargs):
        with self.writer.as_default():
            tfs.text(
                "reconstructor type",
                name,
                step=self.i,
                description="reconstruction name",
            )

    def update_focusing_metric(self, TV_value, AOI_image, metric_name, allmerits=None):
        if TV_value is not None:
            self.__safe_upload_scalar(
                f"Autofocus {metric_name}",
                TV_value,
                self.i,
                "Total Variation of the object",
            )
        if AOI_image is not None:
            # print(AOI_image)

            self.__smart_upload_image_couldbecomplex(
                f"Autofocus {metric_name} AOI",
                AOI_image,
                self.i,
                1,
                "AOI used by autofocus",
                center_phase=True,
            )
        if allmerits is not None:
            import matplotlib.pyplot as plt

            allmerits, new_z = allmerits
            fig, ax = plt.subplot_mosaic("A")
            ax = ax["A"]
            ax.plot(allmerits[0], allmerits[1], "-ro")
            ax.vlines(new_z, *ax.get_ylim())
            ax.set_title(f"{metric_name}")
            buf = io.BytesIO()
            fig.savefig(buf, format="png", dpi=70)
            plt.close(fig)
            buf.seek(0)
            with self.writer.as_default():
                img = image.decode_png(buf.getvalue(), channels=4)
                img = np.expand_dims(img, 0)
                tfs.image("Autofocus dz score", img, self.i)

    def updateBeamWidth(self, beamwidth_y, beamwidth_x):
        self.__safe_upload_scalar("beamwidth/x_um", beamwidth_x * 1e6, step=self.i)
        self.__safe_upload_scalar("beamwidth/y_um", beamwidth_y * 1e6, step=self.i)

    def update_overlap(self, overlap_area, linear_overlap):
        self.__safe_upload_scalar("overlap/area", overlap_area, step=self.i)
        self.__safe_upload_scalar("overlap/linear", linear_overlap, step=self.i)

    def update_encoder(
        self,
        corrected_positions: np.ndarray,
        original_positions: np.ndarray,
        scaling: float = 1.0,
        beamwidth=None,
    ) -> None:
        """
        Update the stage position images.
        :param corrected_positions:
        :param original_positions:
        :param scaling:
        :return:
        """
        # set them to mean 0
        corrected_positions = corrected_positions - corrected_positions.mean(
            axis=0, keepdims=True
        )
        original_positions = original_positions - original_positions.mean(
            axis=0, keepdims=True
        )

        matplotlib.use("Agg")  # no images output
        import matplotlib.pyplot as plt

        # make a fov that makes sense
        scale_0 = max(1.1, scaling)

        position_range = (
            np.min(original_positions.flatten()),
            np.max(original_positions.flatten()),
        )
        diff = np.diff(position_range)
        mean = np.mean(position_range)
        position_range = mean - scale_0 * diff / 2, mean + scale_0 * diff / 2
        fig, axes = plt.subplot_mosaic(
            """
        ONS""",
            constrained_layout=True,
            figsize=(15, 8),
        )

        meandiff = np.mean(abs(1e6 * corrected_positions - 1e6 * original_positions))

        self.__safe_upload_scalar(
            "mean position displacement in micron",
            meandiff,
            self.i,
            "mean absolute displacement",
        )

        axes["O"].set_title("Original positions")
        axes["N"].set_title("Updated positions")
        axes["S"].set_title(rf"Diff. Mean: {meandiff} $\mu$m")

        # plot the original one everywhere

        for ax in axes.values():
            ax.scatter(
                original_positions[:, 0],
                original_positions[:, 1],
                color="C0",
                marker=".",
                label="original",
            )
            ax.set_xlabel("X")
            ax.set_ylabel("Y")
            ax.set_aspect(1)
            ax.xaxis.set_major_formatter(EngFormatter(unit="m"))
            ax.yaxis.set_major_formatter(EngFormatter(unit="m"))
            ax.set_xlim(ax.set_ylim(position_range))

        # plot the new one in the middle image
        axes["N"].scatter(
            corrected_positions[:, 0],
            corrected_positions[:, 1],
            color="C1",
            marker="x",
            label="new",
        )
        # scaled version on the right (should only show displacement, not magnification)
        diff = corrected_positions - original_positions
        axes["S"].quiver(
            original_positions[:, 0],
            original_positions[:, 1],
            diff[:, 0],
            diff[:, 1],
            angles="xy",
            units="xy",
            scale=1,
        )

        buf = io.BytesIO()
        fig.savefig(buf, format="png", dpi=70)
        plt.close(fig)
        buf.seek(0)
        with self.writer.as_default():
            img = image.decode_png(buf.getvalue(), channels=4)
            img = np.expand_dims(img, 0)
            tfs.image("position correction", img, self.i)

    # internal use for tensorboardMonitor
    def _update_object_estimate(
        self,
        object_estimate,
        probe_estimate_rgb,
        highres=True,
        zo=None,
    ):
        """
        Update the object estimate. This ensures that within the web interface the object and the probe estimate are available.


        :param object_estimate:
        :param probe_estimate_rgb:
        :param highres:
        :param z: Object-detector distance. Not required.
        :return:
        """
        if self.center_angle_object:
            object_estimate, shift1 = center_angle(object_estimate)
            object_estimate, shift2 = center_angle(object_estimate)
            print("Angle shifts: ", shift1, shift2)

        # convert the object estimate to colour
        object_estimate_rgb = complex2rgb_vectorized(
            object_estimate, center_phase=self.center_phases
        )

        # ensure it's 4 d as that's what is needed by tensorflow
        if object_estimate_rgb.ndim == 3:
            object_estimate_rgb = object_estimate_rgb[None]

        # patch in an image of the first probe in the top right
        object_estimate_rgb = self.__pad_probe_in_object_estimate(
            probe_estimate_rgb, object_estimate_rgb
        )

        # Add an object, but if it's the low-resolution version add it to the (low_res) version.
        tag = "object estimate"
        if not highres:
            tag += "(low res)"
        if self.show_farfield_object:
            I_ff = asNumpyArray(
                abs(
                    fft2c(
                        object_estimate
                        - object_estimate.mean(axis=(-2, -1), keepdims=True)
                    )
                )
                ** 2
            ) ** (0.2)
            I_ff = I_ff / I_ff.max() * 255
            I_ff = np.clip(I_ff, 0, 255).astype(np.uint8)
            self.__safe_upload_image("I ff estimate", I_ff, self.i, self.max_nosm)

        self.__safe_upload_image(tag, object_estimate_rgb, self.i, self.max_npsm)

        if highres:
            I_object = abs(object_estimate**2)

            min_int = 0
            N = I_object.shape[-1]
            roi = slice(N // 2 - N // 5, N // 2 + N // 5)
            from scipy import ndimage

            max_int = ndimage.gaussian_filter(I_object, 3)[..., roi, roi].max()

            if min_int == max_int:
                max_int += 1

            I_object = (I_object - min_int) / (
                max_int - min_int
            )  # +1 to ensure that this always works
            logI = np.log(255 * I_object.astype(float) + 1)
            logI -= logI.min()
            logI /= logI.max() / 255
            I_object = np.clip(I_object * 255, 0, 255).astype(np.uint8)
            self.__safe_upload_image(
                "I object estimate", I_object, self.i, self.max_nosm
            )

            self.__safe_upload_image(
                "I object log estimate", logI.astype(np.uint8), self.i, self.max_nosm
            )
            self.save_intensities = False
            if self.save_intensities:
                p = Path("./intensities")
                p.mkdir(exist_ok=True)

                import matplotlib.pyplot as plt

                plt.clf()
                im = plt.imshow(I_object)
                plt.colorbar(im)
                if zo is not None:
                    plt.title(f"z = {zo * 1e3:.3f} mm")
                plt.savefig(f"intensities/{self.i}.png")
                plt.savefig("intensities/AAA.png")

    def _update_probe_estimate(self, probe_estimate, highres=True):
        # first, convert it to images
        # while probe_estimate.ndim <= 3:
        #     probe_estimate = probe_estimate[None]
        probe_estimate_rgb = complex2rgb_vectorized(
            probe_estimate, center_phase=self.center_phases
        )
        # ensure it's 4 d as that's what is needed by tensorflow
        tag = "probe estimate"
        if not highres:
            tag += "(low res)"
        self.__safe_upload_image(tag, probe_estimate_rgb, self.i, self.max_npsm)

        if highres:
            ff_probe = fft2c(probe_estimate)
            ff_probe = complex2rgb_vectorized(ff_probe, center_phase=self.center_phases)
            self.__safe_upload_image("FF " + tag, ff_probe, self.i, self.max_npsm)

        # make a probe COM estimate
        from scipy import ndimage

        P = probe_estimate
        while P.ndim > 2:
            P = P[0]
        cy, cx = ndimage.center_of_mass(abs(P**2))
        N = probe_estimate.shape[-1]
        self.__safe_upload_scalar("com/cy", cy - N // 2, self.i)
        self.__safe_upload_scalar("com/cx", cx - N // 2, self.i)
        return probe_estimate_rgb

    def __smart_upload_image_couldbecomplex(
        self,
        name,
        data,
        step,
        max_outputs=3,
        description=None,
        center_phase=False,
    ):
        """
        Safely upload an image that could be complex. If it is, cast it to colour before uploading.

        """
        data = asNumpyArray(data)

        if np.iscomplexobj(data):
            if center_phase:
                phexp = data.sum((-2, -1), keepdims=True)
                phexp = phexp.conj() / (abs(phexp) + 1e-9)
            else:
                phexp = 1
            print("Got complex datatype")
            data = complex2rgb_vectorized(data * phexp)
        else:
            print("Got real datatype")
            # auto scale
            data = data / data.max() * 255
            data = data.astype(np.uint8)
            # convert to black-white

        self.__safe_upload_image(name, data, step, max_outputs, description)

    def __safe_upload_image(self, name, data, step, max_outputs=3, description=None):
        data = asNumpyArray(data)
        if data.shape[-1] not in [1, 3]:
            data = data[..., None]
        while data.ndim < 4:
            data = data[None]
        with self.writer.as_default():
            tfs.image(
                name,
                data[
                    ..., :: self.downsample_everything, :: self.downsample_everything, :
                ],
                step,
                max_outputs=max_outputs,
                description=description,
            )

    def __safe_upload_scalar(self, name, data, step, description=None):
        if isinstance(data, list) and data == []:
            return  # initialization, not required for tensorboard, ignore it
        data = asNumpyArray(data)
        try:
            # only take the last one in case of a list
            data = np.array(data).ravel()[-1]
        except:
            data = float(data)

        with self.writer.as_default():
            tfs.scalar(name, data, step, description)

    def update_z(self, z):
        self.__safe_upload_scalar(
            "zo (mm)", 1e3 * z, step=self.i, description="Propagation distance"
        )

    def _update_error_estimate(self, error):
        self.__safe_upload_scalar(
            "error metric", error, self.i, "Error metric (single image)"
        )

    def _update_probe_purity(self, probe_purity):
        if probe_purity is None:
            return
        self.__safe_upload_scalar("probe purity", probe_purity, self.i, "probe purity")

    def _update_object_purity(self, object_purity):

        if object_purity is None:
            return
        self.__safe_upload_scalar(
            "object purity", object_purity, self.i, "object purity"
        )

    def update_purities(self, probe_purity, object_purity):
        self._update_object_purity(object_purity)
        self._update_probe_purity(probe_purity)

    def describe_parameters(self, params: Params):
        text = "\n".join([f"{k}: {d}" for (k, d) in params.__dict__.items()])
        with self.writer.as_default():
            tfs.text(
                "summary parameters", text, step=self.i, description="initial settings"
            )

    def __pad_probe_in_object_estimate(self, probe_estimate_rgb, object_estimate_rgb):
        probe_estimate_rgb_ss = probe_estimate_rgb[
            ..., :: self.probe_downsampling, :: self.probe_downsampling, :
        ]

        self.__safe_upload_scalar(
            "probe downsampling in inset",
            self.probe_downsampling,
            self.i,
            "probe downsampling in the inset images",
        )
        Ny, Nx, _ = probe_estimate_rgb_ss.shape[-3:]
        if object_estimate_rgb.shape[-2] < Nx:
            raise RuntimeError(
                "The downsampled probe size would be larger than the downsampled object size."
                ""
                "Try setting monitor.probe_downsampling higher or monitor.object_downsampling lower."
            )
        # add a red marker around the edge
        probe_estimate_rgb_ss[..., -1, -1] = 255
        probe_estimate_rgb_ss[..., -1, :, -1] = 255

        # last channel is for color
        # print(Ny, Nx, object_estimate_rgb.shape, probe_estimate_rgb_ss.shape)
        object_estimate_rgb[..., :Ny, :Nx, :] = probe_estimate_rgb_ss[0]

        return object_estimate_rgb
update_encoder(corrected_positions, original_positions, scaling=1.0, beamwidth=None)

Update the stage position images. :param corrected_positions: :param original_positions: :param scaling: :return:

Source code in PtyLab/Monitor/TensorboardMonitor.py
def update_encoder(
    self,
    corrected_positions: np.ndarray,
    original_positions: np.ndarray,
    scaling: float = 1.0,
    beamwidth=None,
) -> None:
    """
    Update the stage position images.
    :param corrected_positions:
    :param original_positions:
    :param scaling:
    :return:
    """
    # set them to mean 0
    corrected_positions = corrected_positions - corrected_positions.mean(
        axis=0, keepdims=True
    )
    original_positions = original_positions - original_positions.mean(
        axis=0, keepdims=True
    )

    matplotlib.use("Agg")  # no images output
    import matplotlib.pyplot as plt

    # make a fov that makes sense
    scale_0 = max(1.1, scaling)

    position_range = (
        np.min(original_positions.flatten()),
        np.max(original_positions.flatten()),
    )
    diff = np.diff(position_range)
    mean = np.mean(position_range)
    position_range = mean - scale_0 * diff / 2, mean + scale_0 * diff / 2
    fig, axes = plt.subplot_mosaic(
        """
    ONS""",
        constrained_layout=True,
        figsize=(15, 8),
    )

    meandiff = np.mean(abs(1e6 * corrected_positions - 1e6 * original_positions))

    self.__safe_upload_scalar(
        "mean position displacement in micron",
        meandiff,
        self.i,
        "mean absolute displacement",
    )

    axes["O"].set_title("Original positions")
    axes["N"].set_title("Updated positions")
    axes["S"].set_title(rf"Diff. Mean: {meandiff} $\mu$m")

    # plot the original one everywhere

    for ax in axes.values():
        ax.scatter(
            original_positions[:, 0],
            original_positions[:, 1],
            color="C0",
            marker=".",
            label="original",
        )
        ax.set_xlabel("X")
        ax.set_ylabel("Y")
        ax.set_aspect(1)
        ax.xaxis.set_major_formatter(EngFormatter(unit="m"))
        ax.yaxis.set_major_formatter(EngFormatter(unit="m"))
        ax.set_xlim(ax.set_ylim(position_range))

    # plot the new one in the middle image
    axes["N"].scatter(
        corrected_positions[:, 0],
        corrected_positions[:, 1],
        color="C1",
        marker="x",
        label="new",
    )
    # scaled version on the right (should only show displacement, not magnification)
    diff = corrected_positions - original_positions
    axes["S"].quiver(
        original_positions[:, 0],
        original_positions[:, 1],
        diff[:, 0],
        diff[:, 1],
        angles="xy",
        units="xy",
        scale=1,
    )

    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=70)
    plt.close(fig)
    buf.seek(0)
    with self.writer.as_default():
        img = image.decode_png(buf.getvalue(), channels=4)
        img = np.expand_dims(img, 0)
        tfs.image("position correction", img, self.i)
__smart_upload_image_couldbecomplex(name, data, step, max_outputs=3, description=None, center_phase=False)

Safely upload an image that could be complex. If it is, cast it to colour before uploading.

Source code in PtyLab/Monitor/TensorboardMonitor.py
def __smart_upload_image_couldbecomplex(
    self,
    name,
    data,
    step,
    max_outputs=3,
    description=None,
    center_phase=False,
):
    """
    Safely upload an image that could be complex. If it is, cast it to colour before uploading.

    """
    data = asNumpyArray(data)

    if np.iscomplexobj(data):
        if center_phase:
            phexp = data.sum((-2, -1), keepdims=True)
            phexp = phexp.conj() / (abs(phexp) + 1e-9)
        else:
            phexp = 1
        print("Got complex datatype")
        data = complex2rgb_vectorized(data * phexp)
    else:
        print("Got real datatype")
        # auto scale
        data = data / data.max() * 255
        data = data.astype(np.uint8)
        # convert to black-white

    self.__safe_upload_image(name, data, step, max_outputs, description)

frame

MonitorFrame dataclass

One snapshot of the reconstruction state, handed to a monitor.

The engine builds one frame per monitor update and passes it to AbstractMonitor.update. The monitor decides what to show from it.

The array fields are references to the live reconstruction arrays (CPU or GPU), not copies, so building a frame is cheap even when the monitor ignores it. They are only valid during the update call; a monitor that keeps data for later must copy it, e.g. through object_view and probe_view.

Attributes:

Name Type Description
error ndarray

Error metric of every iteration so far.

object Any

reconstruction.object. For FPM this is the object spectrum; object_view transforms it to real space.

probe Any

reconstruction.probe (the pupil for FPM).

operation_mode str

"CPM" or "FPM".

object_roi tuple[slice, slice]

Region of the object to display.

probe_roi tuple[slice, slice]

Region of the probe to display.

object_pixel_size float

Axis step of the object panel in meters.

probe_pixel_size float

Axis step of the probe panel, in meters for CPM and in 1/m for FPM.

probe_axis_unit str

Unit of the probe panel axes.

probe_label str

Title of the probe panel.

nosm int

Number of object state mixtures.

npsm int

Number of probe state mixtures.

purity_object Any

Object purity, meaningful only when nosm > 1.

purity_probe Any

Probe purity, meaningful only when npsm > 1.

zo Any

Sample-detector distance in meters.

theta Any

Reflection angle in degrees (aPIE), None if not used.

positions ndarray | None

Scan positions in object pixels.

engine_name str | None

Name of the engine that produced the frame.

encoder_original ndarray | None

Measured encoder positions.

encoder_corrected ndarray | None

Encoder positions after position correction.

beam_width tuple[float, float] | None

(y, x) probe FWHM in meters.

I_estimated ndarray | None

Estimated detector intensity at the last scan position, only filled for verboseLevel == "high".

I_measured ndarray | None

Measured detector intensity at the same position.

area_overlap float | None

Estimated probe area overlap.

linear_overlap float | None

Estimated probe linear overlap.

Source code in PtyLab/Monitor/frame.py
@dataclass
class MonitorFrame:
    """One snapshot of the reconstruction state, handed to a monitor.

    The engine builds one frame per monitor update and passes it to
    `AbstractMonitor.update`. The monitor decides what to show from it.

    The array fields are references to the live reconstruction arrays (CPU or GPU),
    not copies, so building a frame is cheap even when the monitor ignores it. They
    are only valid during the `update` call; a monitor that keeps data for later
    must copy it, e.g. through `object_view` and `probe_view`.

    Attributes:
        error (np.ndarray): Error metric of every iteration so far.
        object (Any): `reconstruction.object`. For FPM this is the object spectrum;
            `object_view` transforms it to real space.
        probe (Any): `reconstruction.probe` (the pupil for FPM).
        operation_mode (str): `"CPM"` or `"FPM"`.
        object_roi (tuple[slice, slice]): Region of the object to display.
        probe_roi (tuple[slice, slice]): Region of the probe to display.
        object_pixel_size (float): Axis step of the object panel in meters.
        probe_pixel_size (float): Axis step of the probe panel, in meters for CPM
            and in 1/m for FPM.
        probe_axis_unit (str): Unit of the probe panel axes.
        probe_label (str): Title of the probe panel.
        nosm (int): Number of object state mixtures.
        npsm (int): Number of probe state mixtures.
        purity_object (Any): Object purity, meaningful only when `nosm > 1`.
        purity_probe (Any): Probe purity, meaningful only when `npsm > 1`.
        zo (Any): Sample-detector distance in meters.
        theta (Any): Reflection angle in degrees (aPIE), `None` if not used.
        positions (np.ndarray | None): Scan positions in object pixels.
        engine_name (str | None): Name of the engine that produced the frame.
        encoder_original (np.ndarray | None): Measured encoder positions.
        encoder_corrected (np.ndarray | None): Encoder positions after position
            correction.
        beam_width (tuple[float, float] | None): `(y, x)` probe FWHM in meters.
        I_estimated (np.ndarray | None): Estimated detector intensity at the
            last scan position, only filled for `verboseLevel == "high"`.
        I_measured (np.ndarray | None): Measured detector intensity at the same
            position.
        area_overlap (float | None): Estimated probe area overlap.
        linear_overlap (float | None): Estimated probe linear overlap.
    """

    error: np.ndarray
    object: Any
    probe: Any
    operation_mode: str = "CPM"
    object_roi: tuple = FULL_ROI
    probe_roi: tuple = FULL_ROI
    object_pixel_size: float = 1.0
    probe_pixel_size: float = 1.0
    probe_axis_unit: str = "mm"
    probe_label: str = "Probe estimate"
    nosm: int = 1
    npsm: int = 1
    purity_object: Any = None
    purity_probe: Any = None
    zo: Any = None
    theta: Any = None
    positions: np.ndarray | None = None
    engine_name: str | None = None
    encoder_original: np.ndarray | None = None
    encoder_corrected: np.ndarray | None = None
    beam_width: tuple | None = None
    I_estimated: np.ndarray | None = None
    I_measured: np.ndarray | None = None
    area_overlap: float | None = None
    linear_overlap: float | None = None

    @classmethod
    def from_reconstruction(cls, reconstruction, **fields: Any) -> "MonitorFrame":
        """Fill the fields that follow from the reconstruction state.

        The panel sampling comes from `panel_geometry`. The engine must have
        initialised `reconstruction.error` first.

        Args:
            reconstruction (Reconstruction): Current reconstruction state.
            **fields: Further `MonitorFrame` fields (ROIs, engine name, encoder,
                beam width, diffraction data, overlaps), passed through unchanged.

        Returns:
            MonitorFrame: The snapshot.
        """
        return cls(
            error=reconstruction.error,
            object=reconstruction.object,
            probe=reconstruction.probe,
            operation_mode=reconstruction.data.operationMode,
            **panel_geometry(reconstruction),
            nosm=reconstruction.nosm,
            npsm=reconstruction.npsm,
            purity_object=reconstruction.purityObject,
            purity_probe=reconstruction.purityProbe,
            zo=reconstruction.zo,
            theta=reconstruction.theta,
            positions=reconstruction.positions,
            **fields,
        )

    @property
    def iteration(self) -> int:
        """Number of completed iterations."""
        return len(self.error)

    def object_view(self) -> np.ndarray:
        """Real-space object inside `object_roi`, as a squeezed NumPy array.

        Leading singleton axes of the 6D array `(nlambda, nosm, 1, nslice, No, No)`
        are dropped, so a single-mode object comes back as `(Ny, Nx)`.
        """
        # FPM stores the object spectrum; the monitor shows its fft2c, as it always has
        obj = fft2c(self.object) if self.operation_mode == "FPM" else self.object
        # crop before moving to the CPU so only the displayed region is copied
        return np.squeeze(
            asNumpyArray(obj[..., self.object_roi[0], self.object_roi[1]])
        )

    def probe_view(self) -> np.ndarray:
        """Probe inside `probe_roi`, as a squeezed NumPy array."""
        probe = self.probe[..., self.probe_roi[0], self.probe_roi[1]]
        return np.squeeze(asNumpyArray(probe))
iteration property

Number of completed iterations.

from_reconstruction(reconstruction, **fields) classmethod

Fill the fields that follow from the reconstruction state.

The panel sampling comes from panel_geometry. The engine must have initialised reconstruction.error first.

Parameters:

Name Type Description Default
reconstruction Reconstruction

Current reconstruction state.

required
**fields Any

Further MonitorFrame fields (ROIs, engine name, encoder, beam width, diffraction data, overlaps), passed through unchanged.

{}

Returns:

Type Description
MonitorFrame

The snapshot.

Source code in PtyLab/Monitor/frame.py
@classmethod
def from_reconstruction(cls, reconstruction, **fields: Any) -> "MonitorFrame":
    """Fill the fields that follow from the reconstruction state.

    The panel sampling comes from `panel_geometry`. The engine must have
    initialised `reconstruction.error` first.

    Args:
        reconstruction (Reconstruction): Current reconstruction state.
        **fields: Further `MonitorFrame` fields (ROIs, engine name, encoder,
            beam width, diffraction data, overlaps), passed through unchanged.

    Returns:
        MonitorFrame: The snapshot.
    """
    return cls(
        error=reconstruction.error,
        object=reconstruction.object,
        probe=reconstruction.probe,
        operation_mode=reconstruction.data.operationMode,
        **panel_geometry(reconstruction),
        nosm=reconstruction.nosm,
        npsm=reconstruction.npsm,
        purity_object=reconstruction.purityObject,
        purity_probe=reconstruction.purityProbe,
        zo=reconstruction.zo,
        theta=reconstruction.theta,
        positions=reconstruction.positions,
        **fields,
    )
object_view()

Real-space object inside object_roi, as a squeezed NumPy array.

Leading singleton axes of the 6D array (nlambda, nosm, 1, nslice, No, No) are dropped, so a single-mode object comes back as (Ny, Nx).

Source code in PtyLab/Monitor/frame.py
def object_view(self) -> np.ndarray:
    """Real-space object inside `object_roi`, as a squeezed NumPy array.

    Leading singleton axes of the 6D array `(nlambda, nosm, 1, nslice, No, No)`
    are dropped, so a single-mode object comes back as `(Ny, Nx)`.
    """
    # FPM stores the object spectrum; the monitor shows its fft2c, as it always has
    obj = fft2c(self.object) if self.operation_mode == "FPM" else self.object
    # crop before moving to the CPU so only the displayed region is copied
    return np.squeeze(
        asNumpyArray(obj[..., self.object_roi[0], self.object_roi[1]])
    )
probe_view()

Probe inside probe_roi, as a squeezed NumPy array.

Source code in PtyLab/Monitor/frame.py
def probe_view(self) -> np.ndarray:
    """Probe inside `probe_roi`, as a squeezed NumPy array."""
    probe = self.probe[..., self.probe_roi[0], self.probe_roi[1]]
    return np.squeeze(asNumpyArray(probe))

panel_geometry(reconstruction)

Axis steps, units and labels of the object and probe panels.

FPM reconstructs the object spectrum and a pupil, so the panels use the FPM object sampling dxo_fpm and the pupil-plane step dfp (a spatial frequency) instead of dxo and dxp.

Parameters:

Name Type Description Default
reconstruction Reconstruction

Reconstruction whose sampling is shown.

required

Returns:

Type Description
dict

The MonitorFrame fields object_pixel_size, probe_pixel_size, probe_axis_unit and probe_label.

Source code in PtyLab/Monitor/frame.py
def panel_geometry(reconstruction) -> dict:
    """Axis steps, units and labels of the object and probe panels.

    FPM reconstructs the object spectrum and a pupil, so the panels use the FPM
    object sampling `dxo_fpm` and the pupil-plane step `dfp` (a spatial frequency)
    instead of `dxo` and `dxp`.

    Args:
        reconstruction (Reconstruction): Reconstruction whose sampling is shown.

    Returns:
        dict: The `MonitorFrame` fields `object_pixel_size`, `probe_pixel_size`,
            `probe_axis_unit` and `probe_label`.
    """
    if reconstruction.data.operationMode == "FPM":
        return {
            "object_pixel_size": reconstruction.dxo_fpm,
            "probe_pixel_size": reconstruction.dfp,
            "probe_axis_unit": "1/um",
            "probe_label": "Pupil estimate",
        }
    return {
        "object_pixel_size": reconstruction.dxo,
        "probe_pixel_size": reconstruction.dxp,
        "probe_axis_unit": "mm",
        "probe_label": "Probe estimate",
    }