{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Track solidification of a metallic alloy\n\nIn this example, we identify and track the solid-liquid (S-L) interface in a\nnickel-based alloy undergoing solidification. Tracking the solidification over\ntime enables the calculation of the solidification velocity. This is\nimportant to characterize the solidified structure of the sample and will be\nused to inform research into additive manufacturing of metals. The image\nsequence was obtained by the Center for Advanced Non-Ferrous Structural Alloys\n(CANFSA) using synchrotron x-radiography at the Advanced Photon Source (APS)\nat Argonne National Laboratory (ANL). This analysis was first presented at\na conference [1]_.\n\n.. [1] Corvellec M. and Becker C. G. (2021, May 17-18)\n       \"Quantifying solidification of metallic alloys with scikit-image\"\n       [Conference presentation]. BIDS ImageXD 2021 (Image Analysis Across\n       Domains). Virtual participation.\n       https://www.youtube.com/watch?v=cB1HTgmWTd8\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport plotly.io\n\nimport skimage as ski\n\nimage_sequence = ski.data.nickel_solidification()\n\ny0, y1, x0, x1 = 0, 180, 100, 330\n\nimage_sequence = image_sequence[:, y0:y1, x0:x1]\n\nprint(f'shape: {image_sequence.shape}')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "The dataset is a 2D image stack with 11 frames (time points).\nWe visualize and analyze it in a workflow where the first image processing\nsteps are performed on the entire three-dimensional dataset (i.e., across\nspace and time),\nsuch that the removal of localized, transient noise is favored as\nopposed to that of physical features (e.g., bubbles, splatters, etc.), which\nexist in roughly the same position from one frame to the next.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = px.imshow(\n    image_sequence,\n    animation_frame=0,\n    binary_string=True,\n    labels={'animation_frame': 'time point'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Compute image deltas\nLet us first apply a Gaussian low-pass filter in order to smooth\nthe images and reduce noise.\nNext, we compute the image deltas, i.e., the sequence of differences\nbetween two consecutive frames. To do this, we subtract the image sequence\nending at the second-to-last frame from the image sequence starting\nat the second frame.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "smoothed = ski.filters.gaussian(image_sequence)\nimage_deltas = smoothed[1:, :, :] - smoothed[:-1, :, :]\n\nfig = px.imshow(\n    image_deltas,\n    animation_frame=0,\n    binary_string=True,\n    labels={'animation_frame': 'time point'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Clip lowest and highest intensities\nWe now calculate the 5th and 95th percentile intensities of ``image_deltas``:\nWe want to clip the intensities which lie below the 5th percentile\nintensity and above the 95th percentile intensity, while also rescaling\nthe intensity values to [0, 1].\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "p_low, p_high = np.percentile(image_deltas, [5, 95])\nclipped = image_deltas - p_low\nclipped[clipped < 0.0] = 0.0\nclipped = clipped / p_high\nclipped[clipped > 1.0] = 1.0\n\nfig = px.imshow(\n    clipped,\n    animation_frame=0,\n    binary_string=True,\n    labels={'animation_frame': 'time point'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Invert and denoise\nWe invert the ``clipped`` images so the regions of highest intensity\nwill include the region we are interested in tracking (i.e., the\nS-L interface). Then, we apply a total variation denoising filter to reduce\nnoise beyond the interface.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "inverted = 1 - clipped\ndenoised = ski.restoration.denoise_tv_chambolle(inverted, weight=0.15)\n\nfig = px.imshow(\n    denoised,\n    animation_frame=0,\n    binary_string=True,\n    labels={'animation_frame': 'time point'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Binarize\nOur next step is to create binary images, splitting the images\ninto foreground and background: We want the S-L interface\nto be the most prominent feature in the foreground of each binary image,\nso that it can eventually be separated from the rest of the image.\n\nWe need\na threshold value ``thresh_val`` to create our binary images, ``binarized``.\nThis can be set manually, but we shall use an automated minimum threshold\nmethod from the ``filters`` submodule of scikit-image (there are other\nmethods that may work better for different applications).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "thresh_val = ski.filters.threshold_minimum(denoised)\nbinarized = denoised > thresh_val\n\nfig = px.imshow(\n    binarized,\n    animation_frame=0,\n    binary_string=True,\n    labels={'animation_frame': 'time point'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Select largest region\nIn our binary images, the S-L interface appears as the largest region of\nconnected pixels. For this step of the workflow, we will operate on each\n2D image separately, as opposed to the entire 3D dataset, because we are\ninterested in a single moment in time for each region.\n\nWe apply :func:`skimage.measure.label()` on the binary images so that each\nregion has its own label. Then, we select the largest region in each image\nby computing region properties, including the ``area`` property, and\nsorting by ``area`` values. Function\n:func:`skimage.measure.regionprops_table()` returns a table of region\nproperties which can be read into a Pandas ``DataFrame``.\nTo begin with, let us consider the first image delta at this stage of the\nworkflow, ``binarized[0, :, :]``.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "labeled_0 = ski.measure.label(binarized[0, :, :])\nprops_0 = ski.measure.regionprops_table(labeled_0, properties=('label', 'area', 'bbox'))\nprops_0_df = pd.DataFrame(props_0)\nprops_0_df = props_0_df.sort_values('area', ascending=False)\n# Show top five rows\nprops_0_df.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can thus select the largest region by matching its label with the one\nfound in the first row of the above (sorted) table. Let us visualize it,\nalong with its bounding box (bbox) in red.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "largest_region_0 = labeled_0 == props_0_df.iloc[0]['label']\nminr, minc, maxr, maxc = (props_0_df.iloc[0][f'bbox-{i}'] for i in range(4))\nfig = px.imshow(largest_region_0, binary_string=True)\nfig.add_shape(type='rect', x0=minc, y0=minr, x1=maxc, y1=maxr, line=dict(color='Red'))\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We can see how the lower bounds of the box align with the bottom of the\nS-L interface by overlaying the same bounding box onto the 0th raw image.\nThis bounding box was calculated from the image delta between\nthe 0th and 1st images, but the bottom-most region of the box\ncorresponds to the location of the interface earlier\nin time (0th image) because the interface is moving upward.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "fig = px.imshow(image_sequence[0, :, :], binary_string=True)\nfig.add_shape(type='rect', x0=minc, y0=minr, x1=maxc, y1=maxr, line=dict(color='Red'))\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "We are now ready to perform this selection for all image deltas in the\nsequence. We shall also store\nthe bbox information, which will be used to track the\nposition of the S-L interface.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "largest_region = np.empty_like(binarized)\nbboxes = []\n\nfor i in range(binarized.shape[0]):\n    labeled = ski.measure.label(binarized[i, :, :])\n    props = ski.measure.regionprops_table(labeled, properties=('label', 'area', 'bbox'))\n    props_df = pd.DataFrame(props)\n    props_df = props_df.sort_values('area', ascending=False)\n    largest_region[i, :, :] = labeled == props_df.iloc[0]['label']\n    bboxes.append([props_df.iloc[0][f'bbox-{i}'] for i in range(4)])\nfig = px.imshow(\n    largest_region,\n    animation_frame=0,\n    binary_string=True,\n    labels={'animation_frame': 'time point'},\n)\nplotly.io.show(fig)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Plot interface location over time\nThe final step in this analysis is to plot the location of the S-L\ninterfaces over time. This can be achieved by plotting ``maxr``\n(third element in bbox)\nover time since this value shows the `y` location of the bottom of\nthe interface. The pixel size in this experiment was 1.93 microns\nand the framerate was 80,000 frames per second, so these values\nare used to convert pixels and image number to physical units.\nWe calculate the average solidfication velocity by fitting a linear\npolynomial to the scatter plot. The velocity is the first-order coefficient.\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "ums_per_pixel = 1.93\nfps = 80000\ninterface_y_um = [ums_per_pixel * bbox[2] for bbox in bboxes]\ntime_us = 1e6 / fps * np.arange(len(interface_y_um))\nfig, ax = plt.subplots(dpi=100)\nax.scatter(time_us, interface_y_um)\nc0, c1 = np.polynomial.polynomial.polyfit(time_us, interface_y_um, 1)\nax.plot(time_us, c1 * time_us + c0, label=f'Velocity: {abs(round(c1, 3))} m/s')\nax.set_title('S-L interface location vs. time')\nax.set_ylabel(r'Location ($\\mu$m)')\nax.set_xlabel(r'Time ($\\mu$s)')\nplt.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
}