Object-oriented FISSA interface

This notebook contains a step-by-step example of how to use the object-oriented (class-based) interface to the FISSA toolbox.

The object-oriented interface, which involves creating a fissa.Experiment instance, allows more flexiblity than the fissa.run_fissa function.

For more details about the methodology behind FISSA, please see our paper:

Keemink, S. W., Lowe, S. C., Pakan, J. M. P., Dylda, E., van Rossum, M. C. W., and Rochefort, N. L. FISSA: A neuropil decontamination toolbox for calcium imaging signals, Scientific Reports, 8(1):3493, 2018. doi: 10.1038/s41598-018-21640-2.

See basic_usage.py (or basic_usage_windows.py for Windows users) for a short example script outside of a notebook interface.

Import packages

Before we can begin, we need to import fissa.

We also need to import some plotting dependencies which we'll make use in this notebook to display the results.

Defining an experiment

To run a separation step with fissa, you need create a fissa.Experiment object, which will hold your extraction parameters and results.

The mandatory inputs to fissa.Experiment are:

Images can be given as a path to a folder containing tiff stacks:

images = "folder"

Each of these tiff-stacks in the folder (e.g. "folder/trial_001.tif") is a trial with many frames. Although we refer to one trial as an image, it is actually a video recording.

Alternatively, the image data can be given as a list of paths to tiffs:

images = ["folder/trial_001.tif", "folder/trial_002.tif", "folder/trial_003.tif"]

or as a list of arrays which you have already loaded into memory:

images = [array1, array2, array3, ...]

For the regions of interest (ROIs) input, you can either provide a single set of ROIs, or a set of ROIs for every image.

If the ROIs were defined using ImageJ, use ImageJ's export function to save them in a zip. Then, provide the ROI filename.

rois = "rois.zip"  # for a single set of ROIs used across all images

The same set of ROIs will be used for every image in images.

Sometimes there is motion between trials causing the alignment of the ROIs to drift. In such a situation, you may need to use a slightly different location of the ROIs for each trial. This can be handled by providing FISSA with a list of ROI sets — one ROI set (i.e. one ImageJ zip file) per trial.

rois = ["rois1.zip", "rois2.zip", ...]  # for a unique roiset for each image

Please note that the ROIs defined in each ROI set must correspond to the same physical reigons across all trials, and that the order must be consistent. That is to say, the 1st ROI listed in each ROI set must correspond to the same item appearing in each trial, etc.

In this notebook, we will demonstrate how to use FISSA with ImageJ ROI sets, saved as zip files. However, you are not restricted to providing your ROIs to FISSA in this format. FISSA will also accept ROIs which are arbitrarily defined by providing them as arrays (numpy.ndarray objects). ROIs provided in this way can be defined either as boolean-valued masks indicating the presence of a ROI per-pixel in the image, or defined as a list of coordinates defining the boundary of the ROI. For examples of such usage, see our Suite2p, CNMF, and SIMA example notebooks.

As an example, we will run FISSA on a small test dataset.

The test dataset can be found and downloaded from the examples folder of the fissa repository, along with the source for this example notebook.

Extracting traces and separating them

Now we have our experiment object, we need to call the separate() method to run FISSA on the data. FISSA will extract the traces, and then separate them.

Accessing results

After running experiment.separate() the analysis parameters, raw traces, output signals, ROI definitions, and mean images are stored as attributes of the experiment object, and can be accessed as follows.

Mean image

The temporal-mean image for each trial is stored in experiment.means.

We can read out and plot the mean of one of the trials as follows.

Plotting the mean image for each trial can be useful to see if there is motion drift between trials.

As a summary, you can also take the mean over all trials. Some cells don't appear in every trial, so the overall mean may indicate the location of more cells than the mean image from a single trial.

ROI outlines

The ROI outlines, and the definitions of the surrounding neuropil regions added by FISSA to determine the contaminating signals, are stored in the experiment.roi_polys attribute. For cell number c and TIFF number t, the set of ROIs for that cell and TIFF is located at

experiment.roi_polys[c, t][0][0]  # user-provided ROI, converted to polygon format
experiment.roi_polys[c, t][n][0]  # n = 1, 2, 3, ... the neuropil regions

Sometimes ROIs cannot be expressed as a single polygon (e.g. a ring-ROI, which needs a line for the outside and a line for the inside); in those cases several polygons are used to describe it as:

experiment.roi_polys[c, t][n][i]  # i iterates over the series of polygons defining the ROI

As an example, we will plot the first ROI along with its surrounding neuropil subregions, overlaid on top of the mean image for one trial.

Similarly, we can plot the location of all 4 ROIs used in this experiment.

FISSA extracted traces

The final signals after separation can be found in experiment.result as follows. For cell number c and TIFF number t, the extracted trace is given by:

experiment.result[c, t][0, :]

In experiment.result one can find the signals present in the cell ROI, ordered by how strongly they are present (relative to the surrounding regions). experiment.result[c, t][0, :] gives the most strongly present signal, and is considered the cell's "true" signal. [i, :] for i=1,2,3,... gives the other signals which are present in the ROI, but driven by other cells or neuropil.

Before decontamination

The raw extracted signals can be found in experiment.raw in the same way. Now in experiment.raw[c, t][i, :], i indicates the region number, with i=0 being the cell, and i=1,2,3,... indicating the surrounding regions.

As an example, plotting the raw and extracted signals for the second trial for the third cell:

We can similarly plot raw and decontaminated traces for every ROI and every trial.

The figure above shows the raw signal from the annotated ROI location (pale), and the result after decontaminating the signal with FISSA (dark). The hues match the ROI locations drawn above. Each column shows the results from one of the ROI, and each row shows the results from one of the three trials.

Comparing ROI signal to neuropil region signals

It can be very instructive to compare the signal in the central ROI with the surrounding neuropil regions. These can be found for cell c and trial t in experiment.raw[c, t][i, :], with i=0 being the cell, and i=1,2,3,... indicating the surrounding regions.

Below we compare directly the raw ROI trace, the decontaminated trace, and the surrounding neuropil region traces.

df/f0

It is often useful to calculate the intensity of a signal relative to the baseline value, df/f0, for the traces. This can be done with FISSA by calling the experiment.calc_deltaf method as follows.

The sampling frequency is required because we our process for determining f0 involves applying a lowpass filter to the data.

Note that by default, f0 is determined as the minimum across all trials (all TIFFs) to ensure that results are directly comparable between trials, but you can normalise each trial individually instead if you prefer by providing the parameter across_trials=False.

Since FISSA is very good at removing contamination from the ROI signals, the minimum value on the decontaminated trace will typically be 0.. Consequently, we use the minimum value of the (smoothed) raw signal to provide the f0 from the raw trace for both the raw and decontaminated df/f0.

As we performed above, we can plot the raw and decontaminated df/f0 for each ROI in each trial.

We can also plot df/f0 for the raw data to compare against the decontaminated signal for each ROI and each trial.

The figure above shows the df/f0 for the raw signal from the annotated ROI location (pale), and the result after decontaminating the signal with FISSA (dark). For each figure, the baseline value f0 is the same (taken from the raw signal). The hues match the ROI locations and fluorescence intensity traces from above. Each column shows the results from one of the ROI, and each row shows the results from one of the three trials.

Caching

After using FISSA to clean the data from an experiment, you will probably want to save the output for later use, so you don't have to keep re-running FISSA on the data all the time.

An option to cache the results is built into FISSA. If you provide fissa.run_fissa with the name of the experiment using the folder argument, it will cache results into that directory. Later, if you call fissa.run_fissa again with the same experiment name (folder argument), it will load the saved results from the cache instead of recomputing them.

Because we have created a new experiment object, it is yet not populated with our results.

We need to run the separate routine again to generate the outputs. But this time, our results will be saved to the directory named fissa-example for future reference.

Calling the separate method again, or making a new Experiment with the same experiment folder name will not have to re-run FISSA because it can use load the pre-computed results from the cache instead.

If you need to force FISSA to ignore the cache and rerun the preparation and/or separation step, you can call it with redo_prep=True and/or redo_sep=True as appropriate.

Exporting to MATLAB

The results can easily be exported to a MATLAB-compatible MAT-file by calling the experiment.to_matfile() method.

The results can easily be exported to a MATLAB-compatible matfile as follows.

The output file, "separated.mat", will appear in the output_folder we supplied to experiment when we created it.

Loading the generated file (e.g. "output_folder/separated.mat") in MATLAB will provide you with all of FISSA's outputs.

These are structured similarly to experiment.raw and experiment.result described above, with a few small differences.

With the python interface, the outputs are 2d numpy.ndarrays each element of which is itself a 2d numpy.ndarrays. In comparison, when the output is loaded into MATLAB this becomes a 2d cell-array each element of which is a 2d matrix.

Additionally, whilst Python indexes from 0, MATLAB indexes from 1 instead. As a consequence of this, the results seen on Python for a given roi and trial experiment.result[roi, trial] correspond to the index S.result{roi + 1, trial + 1} on MATLAB.

Our first plot in this notebook can be replicated in MATLAB as follows:

%% Plot example traces
% Load the FISSA output data
S = load('fissa-example/separated.mat')
% Select the third ROI, second trial
% (On Python, this would be roi = 2; trial = 1;)
roi = 3; trial = 2;
% Plot the raw and result traces for the ROI signal
figure;
hold on;
plot(S.raw{roi, trial}(1, :));
plot(S.result{roi, trial}(1, :));
title(sprintf('ROI %d, Trial %d', roi, trial));
xlabel('Time (frame number)');
ylabel('Signal intensity (candela per unit area)');
legend({'Raw', 'Result'});
grid on;
box on;
set(gca,'TickDir','out');

Assuming all ROIs are contiguous and described by a single contour, the mean image and ROI locations can be plotted in MATLAB as follows:

%% Plot ROI locations overlaid on mean image
% Load the FISSA output data
S = load('fissa-example/separated.mat')
trial = 1;
figure;
hold on;
% Plot the mean image
imagesc(squeeze(S.means(trial, :, :)));
colormap('gray');
% Plot ROI locations
for i_roi = 1:size(S.result, 1);
    contour = S.roi_polys{i_roi, trial}{1};
    plot(contour(:, 2), contour(:, 1));
end
set(gca, 'YDir', 'reverse');

Addendum

Finding the TIFF files

If you find something noteworthy in one of the traces and need to backreference to the corresponding TIFF file, you can look up the path to the TIFF file with experiment.images.

FISSA customisation settings

FISSA has several user-definable settings, which can be set when defining the fissa.Experiment instance.

Controlling verbosity

The level of verbosity of FISSA can be controlled with the verbosity parameter.

The default is verbosity=1.

If the verbosity parameter is higher, FISSA will print out more information while it is processing. This can be helpful for debugging puproses. The verbosity reaches its maximum at verbosity=6.

If verbosity=0, FISSA will run silently.

Analysis parameters

The analysis performed by FISSA can be controlled with several parameters.

We can plot the new results for our example trace from before. Although we doubled the number of neuropil regions around the cell, very little has changed for this example because there were not many sources of contamination.

However, there will be more of a difference if your data has more neuropil sources per unit area within the image.

Alternatively, these settings can be refined after creating the experiment object, as follows.

Loading data from large tiff files

By default, FISSA loads entire tiff files into memory at once and then manipulates all ROIs within the tiff. This can sometimes be problematic when working with very large tiff files which can not be loaded into memory all at once. If you have out-of-memory problems, you can activate FISSA's low memory mode, which will cause it to manipulate each tiff file frame-by-frame.

Handling custom formats

By default, FISSA can use tiff files or numpy arrays as its input image data, and numpy arrays or ImageJ zip files for the ROI definitions. However, it is also possible to extend this functionality and integrate other data formats into FISSA in order to work with other custom and/or proprietary formats that might be used in your lab.

This is done by defining your own DataHandler class. Your custom data handler should be a subclass of fissa.extraction.DataHandlerAbstract, and implement the following methods:

See fissa.extraction.DataHandlerAbstract for further description for each of the methods.

If you only need to handle a new image input format, which is converted to a numpy.ndarray, you may find it is easier to create a subclass of the default datahandler, fissa.extraction.DataHandlerTifffile. In this case, only the image2array method needs to be overwritten and the other methods can be left as they are.

For advanced users that want to entirely replace the DataHandler with their own methods, you can also inherit a class from the abstract class, fissa.extraction.DataHandlerAbstract. This can be useful if you want to integrate FISSA into your workflow without changing everything into the numpy array formats that FISSA usually uses internally.