{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Measure fluorescence intensity at the nuclear envelope\n\nThis example reproduces a well-established workflow in bioimage data analysis\nfor measuring the fluorescence intensity localized to the nuclear envelope, in\na time sequence of cell images (each with two channels and two spatial\ndimensions) which shows a process of protein re-localization from the\ncytoplasmic area to the nuclear envelope. This biological application was\nfirst presented by Andrea Boni and collaborators in [1]_; it was used in a\ntextbook by Kota Miura [2]_ as well as in other works ([3]_, [4]_).\nIn other words, we port this workflow from ImageJ Macro to Python with\nscikit-image.\n\n.. [1] Boni A, Politi AZ, Strnad P, Xiang W, Hossain MJ, Ellenberg J (2015)\n       \"Live imaging and modeling of inner nuclear membrane targeting reveals\n       its molecular requirements in mammalian cells\" J Cell Biol\n       209(5):705\u2013720. ISSN: 0021-9525.\n       :DOI:`10.1083/jcb.201409133`\n.. [2] Miura K (2020) \"Measurements of Intensity Dynamics at the Periphery of\n       the Nucleus\" in: Miura K, Sladoje N (eds) Bioimage Data Analysis\n       Workflows. Learning Materials in Biosciences. Springer, Cham.\n       :DOI:`10.1007/978-3-030-22386-1_2`\n.. [3] Klemm A (2020) \"ImageJ/Fiji Macro Language\" NEUBIAS Academy Online\n       Course: https://www.youtube.com/watch?v=o8tfkdcd3DA\n.. [4] Vorkel D and Haase R (2020) \"GPU-accelerating ImageJ Macro image\n       processing workflows using CLIJ\" https://arxiv.org/abs/2008.11799\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\nimport plotly.io\nimport plotly.express as px\nfrom scipy import ndimage as ndi\n\nimport skimage as ski"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We start with a single cell/nucleus to construct the workflow.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image_sequence = ski.data.protein_transport()\n\nprint(f'shape: {image_sequence.shape}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The dataset is a 2D image stack with 15 frames (time points) and 2 channels.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "vmin, vmax = 0, image_sequence.max()\n\nfig = px.imshow(\n    image_sequence,\n    facet_col=1,\n    animation_frame=0,\n    zmin=vmin,\n    zmax=vmax,\n    binary_string=True,\n    labels={'animation_frame': 'time point', 'facet_col': 'channel'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "To begin with, let us consider the first channel of the first image (step\n``a)`` in the figure below).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image_t_0_channel_0 = image_sequence[0, 0, :, :]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Segment the nucleus rim\nLet us apply a Gaussian low-pass filter to this image in order to smooth it\n(step ``b)``).\nNext, we segment the nuclei, finding the threshold between the background\nand foreground with Otsu's method: We get a binary image (step ``c)``). We\nthen fill the holes in the objects (step ``c-1)``).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "smooth = ski.filters.gaussian(image_t_0_channel_0, sigma=1.5)\n\nthresh_value = ski.filters.threshold_otsu(smooth)\nthresh = smooth > thresh_value\n\nfill = ndi.binary_fill_holes(thresh)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Following the original workflow, let us remove objects which touch the image\nborder (step ``c-2)``). Here, we can see that part of another nucleus was\ntouching the bottom right-hand corner.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "clear = ski.segmentation.clear_border(fill)\nclear.dtype"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We compute both the morphological dilation of this binary image\n(step ``d)``) and its morphological erosion (step ``e)``).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "dilate = ski.morphology.dilation(clear)\n\nerode = ski.morphology.erosion(clear)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Finally, we subtract the eroded from the dilated to get the nucleus rim\n(step ``f)``). This is equivalent to selecting the pixels which are in\n``dilate``, but not in ``erode``:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "mask = np.logical_and(dilate, ~erode)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us visualize these processing steps in a sequence of subplots.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig, ax = plt.subplots(2, 4, figsize=(12, 6), sharey=True)\n\nax[0, 0].imshow(image_t_0_channel_0, cmap=plt.cm.gray)\nax[0, 0].set_title('a) Raw')\n\nax[0, 1].imshow(smooth, cmap=plt.cm.gray)\nax[0, 1].set_title('b) Blur')\n\nax[0, 2].imshow(thresh, cmap=plt.cm.gray)\nax[0, 2].set_title('c) Threshold')\n\nax[0, 3].imshow(fill, cmap=plt.cm.gray)\nax[0, 3].set_title('c-1) Fill in')\n\nax[1, 0].imshow(clear, cmap=plt.cm.gray)\nax[1, 0].set_title('c-2) Keep one nucleus')\n\nax[1, 1].imshow(dilate, cmap=plt.cm.gray)\nax[1, 1].set_title('d) Dilate')\n\nax[1, 2].imshow(erode, cmap=plt.cm.gray)\nax[1, 2].set_title('e) Erode')\n\nax[1, 3].imshow(mask, cmap=plt.cm.gray)\nax[1, 3].set_title('f) Nucleus Rim')\n\nfor a in ax.ravel():\n    a.set_axis_off()\n\nfig.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Apply the segmented rim as a mask\nNow that we have segmented the nuclear membrane in the first channel, we use\nit as a mask to measure the intensity in the second channel.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "image_t_0_channel_1 = image_sequence[0, 1, :, :]\nselection = np.where(mask, image_t_0_channel_1, 0)\n\nfig, (ax0, ax1) = plt.subplots(1, 2, figsize=(12, 6), sharey=True)\n\nax0.imshow(image_t_0_channel_1)\nax0.set_title('Second channel (raw)')\nax0.set_axis_off()\n\nax1.imshow(selection)\nax1.set_title('Selection')\nax1.set_axis_off()\n\nfig.tight_layout()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Measure the total intensity\nThe mean intensity is readily available as a region property in a labeled\nimage.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "props = ski.measure.regionprops_table(\n    mask.astype(np.uint8),\n    intensity_image=image_t_0_channel_1,\n    properties=('label', 'area', 'intensity_mean'),\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We may want to check that the value for the total intensity\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "selection.sum()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "can be recovered from:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "props['area'] * props['intensity_mean']"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Process the entire image sequence\nInstead of iterating the workflow for each time point, we process the\nmultidimensional dataset directly (except for the thresholding step).\nIndeed, most scikit-image functions support nD images.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "n_z = image_sequence.shape[0]  # number of frames\n\nsmooth_seq = ski.filters.gaussian(image_sequence[:, 0, :, :], sigma=(0, 1.5, 1.5))\nthresh_values = [ski.filters.threshold_otsu(s) for s in smooth_seq[:]]\nthresh_seq = [smooth_seq[k, ...] > val for k, val in enumerate(thresh_values)]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Alternatively, we could compute ``thresh_values`` without using a list\ncomprehension, by reshaping ``smooth_seq`` to make it 2D (where the first\ndimension still corresponds to time points, but the second and last\ndimension now contains all pixel values), and applying the thresholding\nfunction on the image sequence along its second axis:\n\n  .. code-block:: python\n     :caption: NumPy's `apply_along_axis` applies a function to 1D slices of\n               `arr` along `axis`.\n\n      thresh_values = np.apply_along_axis(filters.threshold_otsu,\n                                          axis=1,\n                                          arr=smooth_seq.reshape(n_z, -1))\n\nWe use the following flat structuring element for morphological\ncomputations (``np.newaxis`` is used to prepend an axis of size 1 for time):\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "footprint = ndi.generate_binary_structure(2, 1)[np.newaxis, ...]\nfootprint"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "This way, each frame is processed independently (pixels from consecutive\nframes are never spatial neighbors).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fill_seq = ndi.binary_fill_holes(thresh_seq, structure=footprint)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "When clearing objects which touch the image border, we want to make sure\nthat the bottom (first) and top (last) frames are not considered as borders.\nIn this case, the only relevant border is the edge at the greatest (x, y)\nvalues. This can be seen in 3D by running the following code:\n\n  .. code-block:: python\n     :caption: We import the `plotly.graph_objects` module, upon which\n               `plotly.express` is built.\n\n      import plotly.graph_objects as go\n\n      sample = fill_seq\n      (n_Z, n_Y, n_X) = sample.shape\n      Z, Y, X = np.mgrid[:n_Z, :n_Y, :n_X]\n\n      fig = go.Figure(\n          data=go.Volume(\n              x=X.flatten(),\n              y=Y.flatten(),\n              z=Z.flatten(),\n              value=sample.flatten(),\n              opacity=0.5,\n              slices_z=dict(show=True, locations=[n_z // 2])\n          )\n      )\n      fig.show()\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "border_mask = np.ones_like(fill_seq)\nborder_mask[n_z // 2, -1, -1] = False\nclear_seq = ski.segmentation.clear_border(fill_seq, mask=border_mask)\n\ndilate_seq = ski.morphology.dilation(clear_seq, footprint=footprint)\nerode_seq = ski.morphology.erosion(clear_seq, footprint=footprint)\nmask_sequence = np.logical_and(dilate_seq, ~erode_seq)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us give each mask (corresponding to each time point) a different label,\nrunning from 1 to 15. We use ``np.min_scalar_type`` to determine the\nminimum-size integer dtype needed to represent the number of time points:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "label_dtype = np.min_scalar_type(n_z)\nmask_sequence = mask_sequence.astype(label_dtype)\nlabels = np.arange(1, n_z + 1, dtype=label_dtype)\nmask_sequence *= labels[:, np.newaxis, np.newaxis]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Let us compute the region properties of interest for all these labeled\nregions.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "props = ski.measure.regionprops_table(\n    mask_sequence,\n    intensity_image=image_sequence[:, 1, :, :],\n    properties=('label', 'area', 'intensity_mean'),\n)\nnp.testing.assert_array_equal(props['label'], np.arange(n_z) + 1)\n\nfluorescence_change = [\n    props['area'][i] * props['intensity_mean'][i] for i in range(n_z)\n]\n\nfluorescence_change /= fluorescence_change[0]  # normalization\n\nfig, ax = plt.subplots()\nax.plot(fluorescence_change, 'rs')\nax.grid()\nax.set_xlabel('Time point')\nax.set_ylabel('Normalized total intensity')\nax.set_title('Change in fluorescence intensity at the nuclear envelope')\nfig.tight_layout()\n\nplt.show()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Reassuringly, we find the expected result: The total fluorescence\nintensity at the nuclear envelope increases 1.3-fold in the initial five\ntime points, and then becomes roughly constant.\n\n"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.12.12"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}