{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Object-oriented FISSA interface\n", "\n", "This notebook contains a step-by-step example of how to use the object-oriented (class-based) interface to the [FISSA](https://github.com/rochefort-lab/fissa) toolbox.\n", "\n", "The object-oriented interface, which involves creating a [fissa.Experiment](https://fissa.readthedocs.io/en/latest/source/packages/fissa.core.html#fissa.core.Experiment) instance, allows more flexiblity than the [fissa.run_fissa](https://fissa.readthedocs.io/en/latest/source/packages/fissa.core.html#fissa.core.run_fissa) function.\n", "\n", "For more details about the methodology behind FISSA, please see our paper:\n", "\n", "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](https://www.doi.org/10.1038/s41598-018-21640-2).\n", "\n", "See [basic_usage.py](https://github.com/rochefort-lab/fissa/blob/master/examples/basic_usage.py) (or [basic_usage_windows.py](https://github.com/rochefort-lab/fissa/blob/master/examples/basic_usage_windows.py) for Windows users) for a short example script outside of a notebook interface." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Import packages\n", "\n", "Before we can begin, we need to import fissa." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import the FISSA toolbox\n", "import fissa" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We also need to import some plotting dependencies which we'll make use in this notebook to display the results." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# For plotting our results, import numpy and matplotlib\n", "import matplotlib.pyplot as plt\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Fetch the colormap object for Cynthia Brewer's Paired color scheme\n", "colors = plt.get_cmap(\"Paired\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Defining an experiment\n", "\n", "To run a separation step with fissa, you need create a [fissa.Experiment](https://fissa.readthedocs.io/en/latest/source/packages/fissa.core.html#fissa.core.Experiment) object, which will hold your extraction parameters and results.\n", "\n", "The mandatory inputs to `fissa.Experiment` are:\n", "\n", "- the experiment images\n", "- the regions of interest (ROIs) to extract\n", "\n", "Images can be given as a path to a folder containing tiff stacks:\n", "```python\n", "images = \"folder\"\n", "```\n", "Each of these tiff-stacks in the folder (e.g. `\"folder/trial_001.tif\"`) is a trial with many frames.\n", "Although we refer to one trial as an `image`, it is actually a video recording.\n", "\n", "Alternatively, the image data can be given as a list of paths to tiffs:\n", "```python\n", "images = [\"folder/trial_001.tif\", \"folder/trial_002.tif\", \"folder/trial_003.tif\"]\n", "```\n", "or as a list of arrays which you have already loaded into memory:\n", "```python\n", "images = [array1, array2, array3, ...]\n", "```\n", "\n", "For the regions of interest (ROIs) input, you can either provide a single set of ROIs, or a set of ROIs for every image.\n", "\n", "If the ROIs were defined using ImageJ, use ImageJ's export function to save them in a zip.\n", "Then, provide the ROI filename.\n", "```python\n", "rois = \"rois.zip\" # for a single set of ROIs used across all images\n", "```\n", "The same set of ROIs will be used for every image in `images`.\n", "\n", "Sometimes there is motion between trials causing the alignment of the ROIs to drift.\n", "In such a situation, you may need to use a slightly different location of the ROIs for each trial.\n", "This can be handled by providing FISSA with a list of ROI sets — one ROI set (i.e. one ImageJ zip file) per trial.\n", "```python\n", "rois = [\"rois1.zip\", \"rois2.zip\", ...] # for a unique roiset for each image\n", "```\n", "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.\n", "That is to say, the 1st ROI listed in each ROI set must correspond to the same item appearing in each trial, etc.\n", "\n", "In this notebook, we will demonstrate how to use FISSA with ImageJ ROI sets, saved as zip files.\n", "However, you are not restricted to providing your ROIs to FISSA in this format.\n", "FISSA will also accept ROIs which are arbitrarily defined by providing them as arrays (`numpy.ndarray` objects).\n", "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.\n", "For examples of such usage, see our [Suite2p](https://fissa.readthedocs.io/en/latest/examples/Suite2p%20example.html), [CNMF](https://fissa.readthedocs.io/en/latest/examples/cNMF%20example.html), and [SIMA](https://fissa.readthedocs.io/en/latest/examples/SIMA%20example.html) example notebooks." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As an example, we will run FISSA on a small test dataset.\n", "\n", "The test dataset can be found and downloaded from [the examples folder of the fissa repository](https://github.com/rochefort-lab/fissa/tree/master/examples), along with the source for this example notebook." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define path to imagery and to the ROI set\n", "images_location = \"exampleData/20150529\"\n", "rois_location = \"exampleData/20150429.zip\"\n", "\n", "# Create the experiment object\n", "experiment = fissa.Experiment(images_location, rois_location)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Extracting traces and separating them\n", "\n", "Now we have our experiment object, we need to call the [separate()](https://fissa.readthedocs.io/en/latest/source/packages/fissa.core.html#fissa.core.Experiment.separate) method to run FISSA on the data.\n", "FISSA will extract the traces, and then separate them." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "experiment.separate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Accessing results\n", "\n", "After running [experiment.separate()](https://fissa.readthedocs.io/en/latest/source/packages/fissa.core.html#fissa.core.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." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Mean image\n", "\n", "The temporal-mean image for each trial is stored in `experiment.means`.\n", "\n", "We can read out and plot the mean of one of the trials as follows." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trial = 0\n", "# Plot the mean image for one of the trials\n", "plt.figure(figsize=(7, 7))\n", "plt.imshow(experiment.means[trial], cmap=\"gray\")\n", "plt.title(\"Mean over Trial {}\".format(trial))\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Plotting the mean image for each trial can be useful to see if there is motion drift between trials.\n", "\n", "As a summary, you can also take the mean over all trials.\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot the mean image over all the trials\n", "plt.figure(figsize=(7, 7))\n", "plt.imshow(np.mean(experiment.means, axis=0), cmap=\"gray\")\n", "plt.title(\"Mean over all trials\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### ROI outlines\n", "\n", "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.\n", "For cell number ```c``` and TIFF number `t`, the set of ROIs for that cell and TIFF is located at\n", "```python\n", "experiment.roi_polys[c, t][0][0] # user-provided ROI, converted to polygon format\n", "experiment.roi_polys[c, t][n][0] # n = 1, 2, 3, ... the neuropil regions\n", "```\n", "\n", "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:\n", "```python\n", "experiment.roi_polys[c, t][n][i] # i iterates over the series of polygons defining the ROI\n", "```\n", "\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot one ROI along with its neuropil regions\n", "\n", "# Select which ROI and trial to plot\n", "trial = 0\n", "roi = 3\n", "\n", "# Plot the mean image for the trial\n", "plt.figure(figsize=(7, 7))\n", "plt.imshow(experiment.means[trial], cmap=\"gray\")\n", "# Get current axes limits\n", "XLIM = plt.xlim()\n", "YLIM = plt.ylim()\n", "\n", "# Check the number of neuropil regions\n", "n_npil = len(experiment.roi_polys[roi, trial]) - 1\n", "\n", "# Plot all the neuropil regions in yellow\n", "for i_npil in range(1, n_npil + 1):\n", " for contour in experiment.roi_polys[roi, trial][i_npil]:\n", " plt.fill(\n", " contour[:, 1],\n", " contour[:, 0],\n", " facecolor=\"none\",\n", " edgecolor=\"y\",\n", " alpha=0.6,\n", " )\n", "\n", "# Plot the ROI outline in red\n", "for contour in experiment.roi_polys[roi, trial][0]:\n", " plt.fill(\n", " contour[:, 1],\n", " contour[:, 0],\n", " facecolor=\"none\",\n", " edgecolor=\"r\",\n", " alpha=0.6,\n", " )\n", "\n", "# Reset axes limits to be correct for the image\n", "plt.xlim(XLIM)\n", "plt.ylim(YLIM)\n", "\n", "plt.title(\"ROI {}, and its {} neuropil regions\".format(roi, experiment.nRegions))\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, we can plot the location of all 4 ROIs used in this experiment." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot all cell ROI locations\n", "\n", "# Select which trial (TIFF index) to plot\n", "trial = 0\n", "\n", "# Plot the mean image for the trial\n", "plt.figure(figsize=(7, 7))\n", "plt.imshow(experiment.means[trial], cmap=\"gray\")\n", "\n", "# Plot each of the cell ROIs\n", "for i_roi in range(len(experiment.roi_polys)):\n", " # Plot border around ROI\n", " for contour in experiment.roi_polys[i_roi, trial][0]:\n", " plt.plot(\n", " contour[:, 1],\n", " contour[:, 0],\n", " color=colors((i_roi * 2 + 1) % colors.N),\n", " )\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### FISSA extracted traces\n", "\n", "The final signals after separation can be found in ``experiment.result`` as follows.\n", "For cell number ``c`` and TIFF number ``t``, the extracted trace is given by:\n", "```python\n", "experiment.result[c, t][0, :]\n", "```\n", "\n", "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.\n", "\n", "### Before decontamination\n", "\n", "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.\n", "\n", "As an example, plotting the raw and extracted signals for the second trial for the third cell:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot sample trace\n", "\n", "# Select the ROI and trial to plot\n", "roi = 2\n", "trial = 1\n", "\n", "# Create the figure\n", "plt.figure(figsize=(12, 6))\n", "\n", "plt.plot(\n", " experiment.raw[roi, trial][0, :],\n", " lw=2,\n", " label=\"Raw\",\n", " color=colors((roi * 2) % colors.N),\n", ")\n", "plt.plot(\n", " experiment.result[roi, trial][0, :],\n", " lw=2,\n", " label=\"Decontaminated\",\n", " color=colors((roi * 2 + 1) % colors.N),\n", ")\n", "\n", "plt.title(\"ROI {}, Trial {}\".format(roi, trial), fontsize=15)\n", "plt.xlabel(\"Time (frame number)\", fontsize=15)\n", "plt.ylabel(\"Signal intensity (candela per unit area)\", fontsize=15)\n", "plt.grid()\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can similarly plot raw and decontaminated traces for every ROI and every trial." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot all ROIs and trials\n", "\n", "# Get the number of ROIs and trials\n", "n_roi = experiment.result.shape[0]\n", "n_trial = experiment.result.shape[1]\n", "\n", "# Find the maximum signal intensities for each ROI\n", "roi_max_raw = [\n", " np.max([np.max(experiment.raw[i_roi, i_trial][0]) for i_trial in range(n_trial)])\n", " for i_roi in range(n_roi)\n", "]\n", "roi_max_result = [\n", " np.max([np.max(experiment.result[i_roi, i_trial][0]) for i_trial in range(n_trial)])\n", " for i_roi in range(n_roi)\n", "]\n", "roi_max = np.maximum(roi_max_raw, roi_max_result)\n", "\n", "# Plot our figure using subplot panels\n", "plt.figure(figsize=(16, 10))\n", "for i_roi in range(n_roi):\n", " for i_trial in range(n_trial):\n", " # Make subplot axes\n", " i_subplot = 1 + i_trial * n_roi + i_roi\n", " plt.subplot(n_trial, n_roi, i_subplot)\n", " # Plot the data\n", " plt.plot(\n", " experiment.raw[i_roi][i_trial][0, :],\n", " label=\"Raw\",\n", " color=colors((i_roi * 2) % colors.N),\n", " )\n", " plt.plot(\n", " experiment.result[i_roi][i_trial][0, :],\n", " label=\"Decontaminated\",\n", " color=colors((i_roi * 2 + 1) % colors.N),\n", " )\n", " # Labels and boiler plate\n", " plt.ylim([-0.05 * roi_max[i_roi], roi_max[i_roi] * 1.05])\n", " if i_roi == 0:\n", " plt.ylabel(\n", " \"Trial {}\\n\\nSignal intensity\\n(candela per unit area)\".format(\n", " i_trial + 1\n", " )\n", " )\n", " if i_trial == 0:\n", " plt.title(\"ROI {}\".format(i_roi))\n", " plt.legend()\n", " if i_trial == n_trial - 1:\n", " plt.xlabel(\"Time (frame number)\")\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The figure above shows the raw signal from the annotated ROI location (pale), and the result after decontaminating the signal with FISSA (dark).\n", "The hues match the ROI locations drawn above.\n", "Each column shows the results from one of the ROI, and each row shows the results from one of the three trials." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Comparing ROI signal to neuropil region signals\n", "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.\n", "\n", "Below we compare directly the raw ROI trace, the decontaminated trace, and the surrounding neuropil region traces." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Get the total number of regions\n", "nRegions = experiment.nRegions\n", "\n", "# Select the ROI and trial to plot\n", "roi = 2\n", "trial = 1\n", "\n", "# Create the figure\n", "plt.figure(figsize=(12, 12))\n", "\n", "# Plot extracted traces for each neuropil subregion\n", "plt.subplot(2, 1, 1)\n", "# Plot trace of raw ROI signal\n", "plt.plot(\n", " experiment.raw[roi, trial][0, :],\n", " lw=2,\n", " label=\"Raw ROI signal\",\n", " color=colors((roi * 2) % colors.N),\n", ")\n", "# Plot traces from each neuropil region\n", "for i_neuropil in range(1, nRegions + 1):\n", " alpha = i_neuropil / nRegions\n", " plt.plot(\n", " experiment.raw[roi, trial][i_neuropil, :],\n", " lw=2,\n", " label=\"Neuropil region {}\".format(i_neuropil),\n", " color=\"k\",\n", " alpha=alpha,\n", " )\n", "plt.ylim([0, 125])\n", "plt.grid()\n", "plt.legend()\n", "plt.ylabel(\"Signal intensity (candela per unit area)\", fontsize=15)\n", "plt.title(\"ROI {}, Trial {}, neuropil region traces\".format(roi, trial), fontsize=15)\n", "\n", "# Plot the ROI signal\n", "plt.subplot(2, 1, 2)\n", "# Plot trace of raw ROI signal\n", "plt.plot(\n", " experiment.raw[roi, trial][0, :],\n", " lw=2,\n", " label=\"Raw\",\n", " color=colors((roi * 2) % colors.N),\n", ")\n", "# Plot decontaminated signal matched to the ROI\n", "plt.plot(\n", " experiment.result[roi, trial][0, :],\n", " lw=2,\n", " label=\"Decontaminated\",\n", " color=colors((roi * 2 + 1) % colors.N),\n", ")\n", "\n", "plt.ylim([0, 125])\n", "plt.grid()\n", "plt.legend()\n", "plt.xlabel(\"Time (frame number)\", fontsize=15)\n", "plt.ylabel(\"Signal intensity (candela per unit area)\", fontsize=15)\n", "plt.title(\"ROI {}, Trial {}, raw and decontaminated\".format(roi, trial), fontsize=15)\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### df/f0\n", "\n", "It is often useful to calculate the intensity of a signal relative to the baseline value, df/f0, for the traces.\n", "This can be done with FISSA by calling the [experiment.calc_deltaf](https://fissa.readthedocs.io/en/latest/source/packages/fissa.core.html#fissa.core.Experiment.calc_deltaf) method as follows." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sampling_frequency = 10 # Hz\n", "\n", "experiment.calc_deltaf(freq=sampling_frequency)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The sampling frequency is required because we our process for determining f0 involves applying a lowpass filter to the data.\n", "\n", "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``.\n", "\n", "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.\n", "\n", "As we performed above, we can plot the raw and decontaminated df/f0 for each ROI in each trial." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot sample df/f0 trace\n", "\n", "# Select the ROI and trial to plot\n", "roi = 2\n", "trial = 1\n", "\n", "# Create the figure\n", "plt.figure(figsize=(12, 6))\n", "\n", "n_frames = experiment.deltaf_result[roi, trial].shape[1]\n", "tt = np.arange(0, n_frames, dtype=np.float64) / sampling_frequency\n", "\n", "plt.plot(\n", " tt,\n", " experiment.deltaf_raw[roi, trial][0, :],\n", " lw=2,\n", " label=\"Raw\",\n", " color=colors((roi * 2) % colors.N),\n", ")\n", "plt.plot(\n", " tt,\n", " experiment.deltaf_result[roi, trial][0, :],\n", " lw=2,\n", " label=\"Decontaminated\",\n", " color=colors((roi * 2 + 1) % colors.N),\n", ")\n", "\n", "plt.title(\"ROI {}, Trial {}\".format(roi, trial), fontsize=15)\n", "plt.xlabel(\"Time (s)\", fontsize=15)\n", "plt.ylabel(r\"$\\Delta f\\,/\\,f_0$\", fontsize=15)\n", "plt.grid()\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also plot df/f0 for the raw data to compare against the decontaminated signal for each ROI and each trial." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot df/f0 for all ROIs and trials\n", "\n", "# Find the maximum df/f0 values for each ROI\n", "roi_max_raw = [\n", " np.max(\n", " [np.max(experiment.deltaf_raw[i_roi, i_trial][0]) for i_trial in range(n_trial)]\n", " )\n", " for i_roi in range(n_roi)\n", "]\n", "roi_max_result = [\n", " np.max(\n", " [\n", " np.max(experiment.deltaf_result[i_roi, i_trial][0])\n", " for i_trial in range(n_trial)\n", " ]\n", " )\n", " for i_roi in range(n_roi)\n", "]\n", "roi_max = np.maximum(roi_max_raw, roi_max_result)\n", "\n", "# Plot our figure using subplot panels\n", "plt.figure(figsize=(16, 10))\n", "for i_roi in range(n_roi):\n", " for i_trial in range(n_trial):\n", " # Make subplot axes\n", " i_subplot = 1 + i_trial * n_roi + i_roi\n", " plt.subplot(n_trial, n_roi, i_subplot)\n", " # Plot the data\n", " n_frames = experiment.deltaf_result[i_roi, i_trial].shape[1]\n", " tt = np.arange(0, n_frames, dtype=np.float64) / sampling_frequency\n", " plt.plot(\n", " tt,\n", " experiment.deltaf_raw[i_roi][i_trial][0, :],\n", " label=\"Raw\",\n", " color=colors((i_roi * 2) % colors.N),\n", " )\n", " plt.plot(\n", " tt,\n", " experiment.deltaf_result[i_roi][i_trial][0, :],\n", " label=\"Decontaminated\",\n", " color=colors((i_roi * 2 + 1) % colors.N),\n", " )\n", " # Labels and boiler plate\n", " plt.ylim([-0.05 * roi_max[i_roi], roi_max[i_roi] * 1.05])\n", " if i_roi == 0:\n", " plt.ylabel(\"Trial {}\\n\\n\".format(i_trial + 1) + r\"$\\Delta f\\,/\\,f_0$\")\n", " if i_trial == 0:\n", " plt.title(\"ROI {}\".format(i_roi))\n", " plt.legend()\n", " if i_trial == n_trial - 1:\n", " plt.xlabel(\"Time (s)\")\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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).\n", "For each figure, the baseline value f0 is the same (taken from the raw signal).\n", "The hues match the ROI locations and fluorescence intensity traces from above.\n", "Each column shows the results from one of the ROI, and each row shows the results from one of the three trials." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Caching\n", "\n", "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.\n", "\n", "An option to cache the results is built into FISSA.\n", "If you provide ``fissa.run_fissa`` with the name of the experiment using the ``folder`` argument, it will cache results into that directory.\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define the folder where FISSA's outputs will be cached, so they can be\n", "# quickly reloaded in the future without having to recompute them.\n", "#\n", "# This argument is optional; if it is not provided, FISSA will not save its\n", "# results for later use.\n", "#\n", "# Note: you *must* use a different folder for each experiment,\n", "# otherwise FISSA will load in the folder provided instead\n", "# of computing results for the new experiment.\n", "\n", "output_folder = \"fissa-example\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Create a new experiment object set up to save results to the specified output folder\n", "experiment = fissa.Experiment(images_location, rois_location, folder=output_folder)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Because we have created a new experiment object, it is yet not populated with our results.\n", "\n", "We need to run the separate routine again to generate the outputs.\n", "But this time, our results will be saved to the directory named ``fissa-example`` for future reference." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "experiment.separate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "experiment.separate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "experiment.separate(redo_prep=True, redo_sep=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exporting to MATLAB\n", "\n", "The results can easily be exported to a MATLAB-compatible [MAT-file](https://mathworks.com/help/matlab/import_export/mat-file-versions.html) by calling the [experiment.to_matfile()](https://fissa.readthedocs.io/en/latest/source/packages/fissa.core.html#fissa.core.Experiment.to_matfile) method.\n", "\n", "The results can easily be exported to a MATLAB-compatible matfile as follows.\n", "\n", "The output file, ``\"separated.mat\"``, will appear in the `output_folder` we supplied to `experiment` when we created it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "experiment.to_matfile()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Loading the generated file (e.g. `\"output_folder/separated.mat\"`) in MATLAB will provide you with all of FISSA's outputs.\n", "\n", "These are structured similarly to `experiment.raw` and `experiment.result` described above, with a few small differences.\n", "\n", "With the python interface, the outputs are 2d numpy.ndarrays each element of which is itself a 2d numpy.ndarrays.\n", "In comparison, when the output is loaded into MATLAB this becomes a 2d cell-array each element of which is a 2d matrix.\n", "\n", "Additionally, whilst Python indexes from 0, MATLAB indexes from 1 instead.\n", "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.\n", "\n", "Our first plot in this notebook can be replicated in MATLAB as follows:\n", "```octave\n", "%% Plot example traces\n", "% Load the FISSA output data\n", "S = load('fissa-example/separated.mat')\n", "% Select the third ROI, second trial\n", "% (On Python, this would be roi = 2; trial = 1;)\n", "roi = 3; trial = 2;\n", "% Plot the raw and result traces for the ROI signal\n", "figure;\n", "hold on;\n", "plot(S.raw{roi, trial}(1, :));\n", "plot(S.result{roi, trial}(1, :));\n", "title(sprintf('ROI %d, Trial %d', roi, trial));\n", "xlabel('Time (frame number)');\n", "ylabel('Signal intensity (candela per unit area)');\n", "legend({'Raw', 'Result'});\n", "grid on;\n", "box on;\n", "set(gca,'TickDir','out');\n", "```\n", "\n", "Assuming all ROIs are contiguous and described by a single contour, the mean image and ROI locations can be plotted in MATLAB as follows:\n", "```octave\n", "%% Plot ROI locations overlaid on mean image\n", "% Load the FISSA output data\n", "S = load('fissa-example/separated.mat')\n", "trial = 1;\n", "figure;\n", "hold on;\n", "% Plot the mean image\n", "imagesc(squeeze(S.means(trial, :, :)));\n", "colormap('gray');\n", "% Plot ROI locations\n", "for i_roi = 1:size(S.result, 1);\n", " contour = S.roi_polys{i_roi, trial}{1};\n", " plot(contour(:, 2), contour(:, 1));\n", "end\n", "set(gca, 'YDir', 'reverse');\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Addendum" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Finding the TIFF files\n", "\n", "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`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "trial_of_interest = 1\n", "\n", "print(experiment.images[trial_of_interest])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## FISSA customisation settings\n", "\n", "FISSA has several user-definable settings, which can be set when defining the `fissa.Experiment` instance." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Controlling verbosity\n", "\n", "The level of verbosity of FISSA can be controlled with the `verbosity` parameter.\n", "\n", "The default is `verbosity=1`.\n", "\n", "If the verbosity parameter is higher, FISSA will print out more information while it is processing.\n", "This can be helpful for debugging puproses.\n", "The verbosity reaches its maximum at `verbosity=6`.\n", "\n", "If `verbosity=0`, FISSA will run silently." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Call FISSA with elevated verbosity\n", "experiment = fissa.Experiment(images_location, rois_location, verbosity=2)\n", "experiment.separate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Analysis parameters\n", "\n", "The analysis performed by FISSA can be controlled with several parameters." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# FISSA uses multiprocessing to speed up its processing.\n", "# By default, it will spawn one worker per CPU core on your machine.\n", "# However, if you have a lot of cores and not much memory, you many not\n", "# be able to suport so many workers simultaneously.\n", "# In particular, this can be problematic during the data preparation step\n", "# in which tiffs are loaded into memory.\n", "# The default number of cores for the data preparation and separation steps\n", "# can be changed as follows.\n", "ncores_preparation = 4 # If None, uses all available cores\n", "ncores_separation = None # if None, uses all available cores\n", "\n", "# By default, FISSA uses 4 subregions for the neuropil region.\n", "# If you have very dense data with a lot of different signals per unit area,\n", "# you may wish to increase the number of regions.\n", "nRegions = 8\n", "\n", "# By default, each surrounding region has the same area as the central ROI.\n", "# i.e. expansion = 1\n", "# However, you may wish to increase or decrease this value.\n", "expansion = 0.75\n", "\n", "# The degree of signal sparsity can be controlled with the alpha parameter.\n", "alpha = 0.02\n", "\n", "# If you change the experiment parameters, you need to change the cache directory too.\n", "# Otherwise FISSA will try to reload the results from the previous run instead of\n", "# computing the new results. FISSA will throw an error if you try to load data which\n", "# was generated with different analysis parameters to its parameters.\n", "output_folder2 = output_folder + \"_alt\"\n", "\n", "# Set up a FISSA experiment with these parameters\n", "experiment = fissa.Experiment(\n", " images_location,\n", " rois_location,\n", " output_folder2,\n", " nRegions=nRegions,\n", " expansion=expansion,\n", " alpha=alpha,\n", " ncores_preparation=ncores_preparation,\n", " ncores_separation=ncores_separation,\n", ")\n", "\n", "# Extract the data with these new parameters.\n", "experiment.separate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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.\n", "\n", "However, there will be more of a difference if your data has more neuropil sources per unit area within the image." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot one ROI along with its neuropil regions\n", "\n", "# Select which ROI and trial to plot\n", "trial = 0\n", "roi = 3\n", "\n", "# Plot the mean image for the trial\n", "plt.figure(figsize=(7, 7))\n", "plt.imshow(experiment.means[trial], cmap=\"gray\")\n", "# Get axes limits\n", "XLIM = plt.xlim()\n", "YLIM = plt.ylim()\n", "\n", "# Check the number of neuropil\n", "n_npil = len(experiment.roi_polys[roi, trial]) - 1\n", "\n", "# Plot all the neuropil regions in yellow\n", "for i_npil in range(1, n_npil + 1):\n", " for contour in experiment.roi_polys[roi, trial][i_npil]:\n", " plt.fill(\n", " contour[:, 1],\n", " contour[:, 0],\n", " facecolor=\"none\",\n", " edgecolor=\"y\",\n", " alpha=0.6,\n", " )\n", "\n", "# Plot the ROI outline in red\n", "for contour in experiment.roi_polys[roi, trial][0]:\n", " plt.fill(\n", " contour[:, 1],\n", " contour[:, 0],\n", " facecolor=\"none\",\n", " edgecolor=\"r\",\n", " alpha=0.6,\n", " )\n", "\n", "# Reset axes limits\n", "plt.xlim(XLIM)\n", "plt.ylim(YLIM)\n", "\n", "plt.title(\"ROI {}, and its {} neuropil regions\".format(roi, experiment.nRegions))\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Plot the new results\n", "roi = 2\n", "trial = 1\n", "\n", "plt.figure(figsize=(12, 6))\n", "\n", "plt.plot(\n", " experiment.raw[roi, trial][0, :],\n", " lw=2,\n", " label=\"Raw\",\n", " color=colors((roi * 2) % colors.N),\n", ")\n", "plt.plot(\n", " experiment.result[roi, trial][0, :],\n", " lw=2,\n", " label=\"Decontaminated\",\n", " color=colors((roi * 2 + 1) % colors.N),\n", ")\n", "\n", "plt.title(\"ROI {}, Trial {}\".format(roi, i_trial), fontsize=15)\n", "plt.xlabel(\"Time (frame number)\", fontsize=15)\n", "plt.ylabel(\"Signal intensity (candela per unit area)\", fontsize=15)\n", "plt.grid()\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, these settings can be refined after creating the `experiment` object, as follows." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "experiment.ncores_preparation = 8\n", "experiment.alpha = 0.02\n", "experiment.expansion = 0.75" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loading data from large tiff files\n", "\n", "By default, FISSA loads entire tiff files into memory at once and then manipulates all ROIs within the tiff.\n", "This can sometimes be problematic when working with very large tiff files which can not be loaded into memory all at once.\n", "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." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "experiment = fissa.Experiment(\n", " images_location, rois_location, output_folder, lowmemory_mode=True\n", ")\n", "experiment.separate(redo_prep=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Handling custom formats\n", "\n", "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.\n", "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.\n", "\n", "This is done by defining your own DataHandler class.\n", "Your custom data handler should be a subclass of [fissa.extraction.DataHandlerAbstract](https://fissa.readthedocs.io/en/latest/source/packages/fissa.extraction.html#fissa.extraction.DataHandlerAbstract), and implement the following methods:\n", "\n", "- `image2array(image)` takes an image of whatever format and turns it into *data* (typically a numpy.ndarray).\n", "- `getmean(data)` calculates the 2D mean for a video defined by *data*.\n", "- `rois2masks(rois, data)` creates masks from the rois inputs, of appropriate size *data*.\n", "- `extracttraces(data, masks)` applies the *masks* to *data* in order to extract traces.\n", "\n", "See [fissa.extraction.DataHandlerAbstract](https://fissa.readthedocs.io/en/latest/source/packages/fissa.extraction.html#fissa.extraction.DataHandlerAbstract) for further description for each of the methods.\n", "\n", "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](https://fissa.readthedocs.io/en/latest/source/packages/fissa.extraction.html#fissa.extraction.DataHandlerTifffile).\n", "In this case, only the `image2array` method needs to be overwritten and the other methods can be left as they are." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from fissa.extraction import DataHandlerTifffile\n", "\n", "# Define a custom datahandler class.\n", "#\n", "# By inheriting from DataHandlerTifffile, most methods are defined\n", "# appropriately. In this case, we only need to overwrite the\n", "# `image2array` method to work with our custom data format.\n", "\n", "\n", "class DataHandlerCustom(DataHandlerTifffile):\n", " @staticmethod\n", " def image2array(image):\n", " \"\"\"Open a given image file as a custom instance.\n", "\n", " Parameters\n", " ----------\n", " image : custom\n", " Your image format (avi, hdf5, etc.)\n", "\n", " Returns\n", " -------\n", " numpy.ndarray\n", " A 3D array containing the data, shaped\n", " ``(frames, y_coordinate, x_coordinate)``.\n", " \"\"\"\n", " # Some custom code\n", " pass\n", "\n", "\n", "# Then pass an instance of this class to fissa.Experiment when creating\n", "# a new experiment.\n", "datahandler = DataHandlerCustom()\n", "\n", "experiment = fissa.Experiment(\n", " images_location,\n", " rois_location,\n", " datahandler=datahandler,\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "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](https://fissa.readthedocs.io/en/latest/source/packages/fissa.extraction.html#fissa.extraction.DataHandlerAbstract).\n", "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." ] } ], "metadata": { "kernelspec": { "display_name": "Python", "language": "python", "name": "python" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 1 }