{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Colocalization metrics\n\nIn this example, we demonstrate the use of different metrics to assess the\ncolocalization of two different image channels.\n\nColocalization can be split into two different concepts:\n1. Co-occurence: What proportion of a substance is localized to a particular\narea?\n2. Correlation: What is the relationship in intensity between two substances?\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Co-occurence: subcellular localization\n\nImagine that we are trying to determine the subcellular localization of a\nprotein - is it located more in the nucleus or cytoplasm compared to a\ncontrol?\n\nWe begin by segmenting the nucleus of a sample image as described in another\n[example](https://scikit-image.org/docs/stable/auto_examples/applications/plot_fluorescence_nuclear_envelope.html)\nand assume that whatever is not in the nucleus is in the cytoplasm.\nThe protein, \"protein A\", will be simulated as blobs and segmented.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom scipy import ndimage as ndi\nimport skimage as ski\n\nrng = np.random.default_rng()\n\n# segment nucleus\nnucleus = ski.data.protein_transport()[0, 0, :, :180]\nsmooth = ski.filters.gaussian(nucleus, sigma=1.5)\nthresh = smooth > ski.filters.threshold_otsu(smooth)\nfill = ndi.binary_fill_holes(thresh)\nnucleus_seg = ski.segmentation.clear_border(fill)\n\n# protein blobs of varying intensity\nproteinA = np.zeros_like(nucleus, dtype=\"float64\")\nproteinA_seg = np.zeros_like(nucleus, dtype=\"float64\")\n\nfor blob_seed in range(10):\n    blobs = ski.data.binary_blobs(\n        180, blob_size_fraction=0.5, volume_fraction=(50 / (180**2)), rng=blob_seed\n    )\n    blobs_image = ski.filters.gaussian(blobs, sigma=1.5) * rng.integers(50, 256)\n    proteinA += blobs_image\n    proteinA_seg += blobs\n\n# plot data\nfig, ax = plt.subplots(3, 2, figsize=(8, 12), sharey=True)\nax[0, 0].imshow(nucleus, cmap=plt.cm.gray)\nax[0, 0].set_title('Nucleus')\n\nax[0, 1].imshow(nucleus_seg, cmap=plt.cm.gray)\nax[0, 1].set_title('Nucleus segmentation')\n\nblack_magenta = LinearSegmentedColormap.from_list(\"\", [\"black\", \"magenta\"])\nax[1, 0].imshow(proteinA, cmap=black_magenta)\nax[1, 0].set_title('Protein A')\n\nax[1, 1].imshow(proteinA_seg, cmap=black_magenta)\nax[1, 1].set_title('Protein A segmentation')\n\nax[2, 0].imshow(proteinA, cmap=black_magenta)\nax[2, 0].imshow(nucleus_seg, cmap=plt.cm.gray, alpha=0.2)\nax[2, 0].set_title('Protein A\\nwith nucleus overlaid')\n\nax[2, 1].imshow(proteinA_seg, cmap=black_magenta)\nax[2, 1].imshow(nucleus_seg, cmap=plt.cm.gray, alpha=0.2)\nax[2, 1].set_title('Protein A segmentation\\nwith nucleus overlaid')\n\nfor a in ax.ravel():\n    a.set_axis_off()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Intersection coefficient\n\nAfter segmenting both the nucleus and the protein of interest, we can\ndetermine what fraction of the protein A segmentation overlaps with the\nnucleus segmentation.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ski.measure.intersection_coeff(proteinA_seg, nucleus_seg)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Manders' Colocalization Coefficient (MCC)\n\nThe overlap coefficient assumes that the area of protein segmentation\ncorresponds to the concentration of that protein - with larger areas\nindicating more protein. As the resolution of images are usually too small to\nmake out individual proteins, they can clump together within one pixel,\nmaking the intensity of that pixel brighter. So, to better capture the\nprotein concentration, we may choose to determine what proportion of the\n*intensity* of the protein channel is inside the nucleus. This metric is\nknown as Manders' Colocalization Coefficient.\n\nIn this image, while there are a lot of protein A spots within the nucleus\nthey are dim compared to some of the spots outside the nucleus, so the MCC is\nmuch lower than the overlap coefficient.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ski.measure.manders_coloc_coeff(proteinA, nucleus_seg)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "After choosing a co-occurence metric, we can apply the same process to\ncontrol images. If no control images are available, the Costes method could\nbe used to compare the MCC value of the original image with that of the\nrandomly scrambled image. Information about this method is given in [1]_.\n\n.. [1] J. S. Aaron, A. B. Taylor and T.-L. Chew, Image co-localization \u2013\n       co-occurrence versus correlation. J Cell Sci 1 February 2018\n       131 (3): jcs211847. doi: https://doi.org/10.1242/jcs.211847\n\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Correlation: association of two proteins\n\nNow, imagine that we want to know how closely related two proteins are.\n\nFirst, we will generate protein B and plot intensities of the two proteins in\nevery pixel to see the relationship between them.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "# generating protein B data that is correlated to protein A for demo\nproteinB = proteinA + rng.normal(loc=100, scale=10, size=proteinA.shape)\n\n# plot images\nfig, ax = plt.subplots(1, 2, figsize=(8, 8), sharey=True)\n\nax[0].imshow(proteinA, cmap=black_magenta)\nax[0].set_title('Protein A')\n\nblack_cyan = LinearSegmentedColormap.from_list(\"\", [\"black\", \"cyan\"])\nax[1].imshow(proteinB, cmap=black_cyan)\nax[1].set_title('Protein B')\n\nfor a in ax.ravel():\n    a.set_axis_off()\n\n# plot pixel intensity scatter\nfig, ax = plt.subplots()\nax.scatter(proteinA, proteinB)\nax.set_title('Pixel intensity')\nax.set_xlabel('Protein A intensity')\nax.set_ylabel('Protein B intensity')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The intensities look linearly correlated so Pearson's Correlation Coefficient\nwould give us a good measure of how strong the association is.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "pcc, pval = ski.measure.pearson_corr_coeff(proteinA, proteinB)\nprint(f\"PCC: {pcc:0.3g}, p-val: {pval:0.3g}\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Sometimes the intensities are correlated but not in a linear way. A rank-based\ncorrelation coefficient like [Spearman's](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html)\nmight give a more accurate measure of the non-linear relationship in that\ncase.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "plt.show()"
      ]
    }
  ],
  "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
}