# Stack plugins

## Adding stack plugins

### Overview

A Stack plugin is a module that will be automatically added to the PyMca stack windows in order to perform user defined operations on the data stack.

Plugins can be automatically installed provided they are in the appropriate place:

> - In the user home directory (POSIX systems): ${HOME}/.pymca/plugins or ${HOME}/PyMca/plugins (older PyMca installation)

> - In “My Documents\PyMca\plugins” (Windows)

It has to inherit the `StackPluginBase` class and implement the following methods:

> - `StackPluginBase.getMethods()`

> - `StackPluginBase.getMethodToolTip()` (optional but convenient)

> - `StackPluginBase.getMethodPixmap()` (optional)

> - `StackPluginBase.applyMethod()`

and modify the static module variable `MENU_TEXT` and the static module function `getStackPluginInstance()` according to the defined plugin.

The plugin class has access to following inherited methods:

> - `StackPluginBase.addImage()`

> - `StackPluginBase.getActiveCurve()`

> - `StackPluginBase.getGraphXLabel()`

> - `StackPluginBase.getGraphXLimits()`

> - `StackPluginBase.getGraphYLabel()`

> - `StackPluginBase.getGraphYLimits()`

> - `StackPluginBase.getStackData()`

> - `StackPluginBase.getStackDataObject()`

> - `StackPluginBase.getStackDataObjectList()`

> - `StackPluginBase.getStackInfo()`

> - `StackPluginBase.getStackOriginalCurve()`

> - `StackPluginBase.getStackOriginalImage()`

> - `StackPluginBase.getStackROIImagesAndNames()`

> - `StackPluginBase.getStackSelectionMask()`

> - `StackPluginBase.isStackFinite()`

> - `StackPluginBase.removeImage()`

> - `StackPluginBase.replaceImage()`

> - `StackPluginBase.setStack()`

> - `StackPluginBase.setStackSelectionMask()`

> - `StackPluginBase.stackClosed()`

These plugins will be compatible with any stack window that provides the following methods:

> #data related

> - `getStackDataObject()`

> - `getStackData()`

> - `getStackInfo()`

> - `setStack()`

> - `getStackROIImagesAndNames()`

> - `isStackFinite()`

> - `getStackOriginalCurve()`

> - `getStackOriginalImage()`

> #mask related

> - `setStackSelectionMask()`

> - `getStackSelectionMask()`

> #displayed curves

> - `getActiveCurve()`

> - `getGraphXLimits()`

> - `getGraphYLimits()`

> - `getGraphXLabel()`

> - `getGraphYLabel()`

> #images

> - `addImage()`

> - `removeImage()`

> - `replaceImage()`

> #information method

> - `stackUpdated()`

> - `selectionMaskUpdated()`

> - `stackClosed()`

### Stack plugin API

class PyMca5.PyMcaCore.StackPluginBase.StackPluginBase(stackWindow, **kw)
  applyMethod(name)

    The plugin is asked to apply the method associated to name.

  getActiveCurve()

    Function to access the currently active curve. It returns None in case of not having an active curve.

    Output has the form:

        xvalues, yvalues, legend, dict

    where dict is a dictionary containing curve info.

    For the time being, only the plot labels associated to the curve are warranted to be present under the keys xlabel, ylabel.

  getGraphXLabel()

    Get the graph X label

  getGraphXLimits()

    Get the graph X limits.

  getGraphYLabel()

    Get the graph Y label

  getGraphYLimits()

    Get the graph Y limits.

  getMethodPixmap(name)

    Returns the pixmap associated to the particular method name or None.

  getMethodToolTip(name)

    Returns the help associated to the particular method name or None.

  getMethods()

    A list with the NAMES associated to the callable methods that are applicable to the specified stack.

  stackClosed()

    This method is called when the stack widget is closed. You can implement this to shut down the plugin (close widgets…).

    By default, widgets referenced as self.widget and self._widget are closed.

PyMca5.PyMcaCore.StackPluginBase.getStackPluginInstance(stackWindow, **kw)

  This function will be called by the stack window instantiating and calling the plugins. It passes itself as first argument, but the default implementation of the base class only keeps a weak reference to prevent circular references.

## Built-in stack plugins

### Alternative ROI options

This plugin opens a stack ROI window providing alternative views:

> - Usual sum of counts in the region

> - Channel/Energy at data Max in the region.

> - Channel/Energy at data Min in the region.

> - Map of the counts at the first channel of the region

> - Map of the counts at the middle cahnnel of the region

> - Map of the counts at the last channel of the region

> - Background counts

This window also provides a median filter tool, with a configurable filter width, to get rid of outlier pixel.

The mask of this plot widget is synchronized with the master stack widget.

### Silx Alternative ROI options

### External Images Tool

This plugin open a file selection dialog to open one or more images in a new window. Usual image data formats are supported, as well as standard image formats (JPG, PNG).

The tool is meant to view an alternative view of the data, such as a photograph of the sample or a different type of scientific measurement of the same sample.

The window offer a cropping tool, to crop the image to the current visible zoomed area and then resize it to fit the original size.

The mask of this plot widget is synchronized with the master stack widget.

### Silx External Images Tool

### Image Alignment Tool

This plugin provides two methods to align stack images, one based on a FFT algorithm and the other one based on the SIFT algorithm (on GPU).

The result of the alignment computation may be applied directly to the data, or saved to a file.

This plugin also allows to apply the results from a file.

### Image Browser with Median Filter

This plugin open a new stack window with a configurable median filter applied to the data.

The user can select the frame and modify the filter width.

He can also choose to apply a conditional median filter instead of the regular median filter. With a regular median filter, each pixel value is replaced with the median value of all pixels in the window. With the conditional option enabled, the pixel value is only replaced if it is the minimum or the maximum value in the smoothing window.

### Load positioners from file

This plugin is used to load motor positions from a CSV or HDF5 file.

The number of values associated with a given positioner should be equal to the number of pixels in the stack image. A single scalar value can also be provided for a motor, if it didn’t move during the experiment.

A CSV file should have unique motor names in the header line, and can have an arbitrary number of motors/columns.

Motor positions in a HDF5 files are 1-dimensional datasets whose names are the motor names. The user is allowed to select the HDF5 group containing all motor datasets.

Data loaded with this plugin can then be used by other tools, such as the “Stack motor positions” plugin.

### PyMca PCA

This plugin opens a window allowing to configure and compute the principal component analysis. Each spectrum is considered an observation, and each channel is considered a variable.

The user can configure following parameters:

> - PCA method (Covariance, Expectation Max, Covariance Multiple Arrays)

> - Number of Principal Components

> - Spectral Binning

> - Spectral Regions

After the configuration dialog is validated, the eigenimages and the eigenvectors are computed and displayed in another window.

### Show Spectra

This plugin opens a scan window displaying a number of spectra.

The user can choose to display 10, 100, 1000 or all spectra.

### Stack Axes Options

This plugin can be used to replace the stack’s X data with data from a text file, or with the MCA curve’s X or Y data.

When loading from a file, the data should be in a format that can be loaded using numpy.loadtxt, i.e. must be a CSV file without a header line and with a single column.

### Stack Filtering Options

This stack plugin provides filtering and background subtraction methods:

> - Savitzky-Golay Filtering (smoothing)

> - Deglitch with SNIP 1D Background

> - Subtract SNIP 1D Background

> - Subtract SNIP 2D Background

> - Subtract active curve

### Stack Image Browser

This plugin open a plot window with a browser to browse all images in the stack.

A averaging filter with a configurable width is provided, to display an average of several consecutive frames rather than a single frame.

The plot has also mask tools synchronized with the mask in the master window.

### Stack Normalization

This plugin provides normalisation methods.

Two methods can be applied to normalize the stack based on the active curve (I0):

> - I/I0 Normalization: divide all spectra by the active curve

> - -log(I/I0) Normalization

> - -log10(I) Particular case not needing an active curve, for FTIR for instance

> - -log10(I/100) Same as above for data expressed in percentage.

Three methods are provided to normalize the stack images based on an external image (I0) read from a file:

> - Image I/I0 Normalization

> - Image I * (max(I0)/I0) Scaling

> - Image -log(I/I0) Normalization

External images can be read from following file formats:

> - EDF

> - HDF5

> - ASCII

If a multiframe EDF file is opened, the first frame is used. In case a HDF5 file is selected, a browser is used to select a 2D dataset.

### Stack Row or Column Reversing

This plugin offers 4 methods for rearranging spectra within the stack data cube:

> - Reverse Odd Rows

> - Reverse Even Rows

> - Reverse Odd Columns

> - Reverse Even Columns

### Stack Scan Window Plugin

This plugin opens a scan window the first time it is called. The user can then send the current active curve to it, for further analysis.

### Stack Simple Fitting

This plugin allows to configure and execute a batch fitting for all spectra in the stack.

The user can select the fit function and a background function from a selection of functions, and must provide the initial estimation for the iterative fit.

The fit result is saved to file, at the end. A 2D map is created for each fitted parameter, and saved in EDF and ASCII formats.