{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Image cleaning and atom finding using pycroscopy\n", "### Suhas Somnath, Chris R. Smith, Stephen Jesse\n", "The Center for Nanophase Materials Science and The Institute for Functional Imaging for Materials
\n", "Oak Ridge National Laboratory
\n", "1/19/2017
\n", "Advanced Structural and Chemical Imaging - \n", "https://ascimaging.springeropen.com/articles/10.1186/s40679-018-0052-y\n", "\n", "### References:\n", "This Jupyter notebook uses [pycroscopy](https://pycroscopy.github.io/pycroscopy/about.html) to analyze Band Excitation data. We request you to reference the following papers if you use this notebook for your research: \n", "\n", "* [Arxiv paper](https://arxiv.org/abs/1903.09515) titled \"*USID and Pycroscopy - Open frameworks for storing and analyzing spectroscopic and imaging data*\"\n", "* [Advanced Structural and Chemical Imaging paper](https://ascimaging.springeropen.com/articles/10.1186/s40679-018-0052-y) titled \"*Feature extraction via similarity search: application to atom finding and denoising in electron and scanning probe microscopy imaging*\"\n", "* Dataset used here is available via [OSTI / OLCF](https://www.osti.gov/dataexplorer/biblio/1463696)\n", "\n", "### About the Notebook:\n", "\n", "This is a Jupyter Notebook - it contains text and executable code `cells`. To learn more about how to use it, please see [this video](https://www.youtube.com/watch?v=jZ952vChhuI). Please see the image below for some basic tips on using this notebook.\n", "\n", "![notebook_rules.png](https://raw.githubusercontent.com/pycroscopy/pycroscopy/master/jupyter_notebooks/notebook_rules.png)\n", "\n", "Image courtesy of Jean Bilheux from the [neutron imaging](https://github.com/neutronimaging/python_notebooks) GitHub repository.\n", "\n", "### A note about software versions:\n", "**Note: This notebook was written for the pycroscopy version listed below and is not guaranteed to work on past or future versions of the package**\n", "\n", "`pycroscopy` version: `0.59.8`\n", "\n", "If you have a different version of `pycroscopy` installed, you may consider using the notebook as is and accept the possibility of errors. The cell below will attempt to install the correct versions of the packages. However, if you experience trouble, uninstall the existing version of pycroscopy and install the required version above by executing the following commands in a terminal (Linux / MacOS) / Anaconda prompt (Windows): \n", "\n", "```bash\n", "pip uninstall pycroscopy\n", "pip install -I pycroscopy==0.59.8\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Configure the notebook first" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Make sure needed packages are installed and up-to-date\n", "import sys\n", "!conda install --yes --prefix {sys.prefix} numpy scipy matplotlib scikit-learn Ipython ipywidgets h5py\n", "!{sys.executable} -m pip install -U --no-deps pycroscopy==0.59.8" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Import necessary libraries:\n", "# Ensure python 3 compatibility\n", "from __future__ import division, print_function, absolute_import\n", "\n", "# General utilities:\n", "import os\n", "from time import time\n", "from scipy.misc import imsave\n", "\n", "# Computation:\n", "import numpy as np\n", "import h5py\n", "from skimage import measure\n", "from scipy.cluster.hierarchy import linkage, dendrogram\n", "from scipy.spatial.distance import pdist \n", "from sklearn.cluster import KMeans\n", "\n", "# Visualization:\n", "import matplotlib.pyplot as plt\n", "import matplotlib.patches as patches\n", "from mpl_toolkits.axes_grid1 import make_axes_locatable\n", "from IPython.display import display, HTML\n", "import ipywidgets as widgets\n", "from mpl_toolkits.axes_grid1 import ImageGrid\n", "\n", "# Import pyUSID\n", "import pyUSID as usid\n", "# Finally, pycroscopy itself\n", "sys.path.append('..')\n", "import pycroscopy as px\n", "\n", "# Make Notebook take up most of page width\n", "display(HTML(data=\"\"\"\n", "\n", "\"\"\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# set up notebook to show plots within the notebook\n", "% matplotlib notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Set some basic parameters for computation\n", "This notebook performs some functional fitting whose duration can be substantially decreased by using more memory and CPU cores. We have provided default values below but you may choose to change them if necessary." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "max_mem = 1024*8 # Maximum memory to use, in Mbs. Default = 8192\n", "max_cores = None # Number of logical cores to use in fitting. None uses all but 2 available cores." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Load the image that will be cleaned:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "image_path = px.io_utils.file_dialog('*.png *PNG *TIFF * TIF *tif *tiff *BMP *bmp','Images')\n", "\n", "print('Working on: \\n{}'.format(image_path))\n", "\n", "folder_path, file_name = os.path.split(image_path)\n", "base_name, _ = os.path.splitext(file_name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Make the image file pycroscopy compatible\n", "Convert the source image file into a pycroscopy compatible hierarchical data format (HDF or .h5) file. This simple translation gives you access to the powerful data functions within pycroscopy\n", "\n", "#### H5 files:\n", "* are like smart containers that can store matrices with data, folders to organize these datasets, images, metadata like experimental parameters, links or shortcuts to datasets, etc.\n", "* are readily compatible with high-performance computing facilities\n", "* scale very efficiently from few kilobytes to several terabytes\n", "* can be read and modified using any language including Python, Matlab, C/C++, Java, Fortran, Igor Pro, etc." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Check if an HDF5 file with the chosen image already exists.\n", "# Only translate if it does not.\n", "h5_path = os.path.join(folder_path, base_name+'.h5')\n", "need_translation = True\n", "if os.path.exists(h5_path):\n", " try:\n", " h5_file = h5py.File(h5_path, 'r+')\n", " h5_raw = h5_file['Measurement_000']['Channel_000']['Raw_Data']\n", " need_translation = False\n", " print('HDF5 file with Raw_Data found. No need to translate.')\n", " except KeyError:\n", " print('Raw Data not found.')\n", "else:\n", " print('No HDF5 file found.')\n", "\n", "if need_translation:\n", " # Initialize the Image Translator\n", " tl = px.ImageTranslator()\n", "\n", " # create an H5 file that has the image information in it and get the reference to the dataset\n", " h5_raw = tl.translate(image_path)\n", "\n", " # create a reference to the file\n", " h5_file = h5_raw.file\n", "\n", "print('HDF5 file is located at {}.'.format(h5_file.filename))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Inspect the contents of this h5 data file\n", "The file contents are stored in a tree structure, just like files on a contemporary computer.\n", "The data is stored as a 2D matrix (position, spectroscopic value) regardless of the dimensionality of the data. \n", "In the case of these 2D images, the data is stored as a N x 1 dataset\n", "\n", "The main dataset is always accompanied by four ancillary datasets that explain the position and spectroscopic value of any given element in the dataset.\n", "In the case of the 2d images, the positions will be arranged as row0-col0, row0-col1.... row0-colN, row1-col0....\n", "The spectroscopic information is trivial since the data at any given pixel is just a scalar value" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "print('Datasets and datagroups within the file:')\n", "px.hdf_utils.print_tree(h5_file)\n", " \n", "print('\\nThe main dataset:')\n", "print(h5_file['/Measurement_000/Channel_000/Raw_Data'])\n", "print('\\nThe ancillary datasets:')\n", "print(h5_file['/Measurement_000/Channel_000/Position_Indices'])\n", "print(h5_file['/Measurement_000/Channel_000/Position_Values'])\n", "print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Indices'])\n", "print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Values'])\n", "\n", "print('\\nMetadata or attributes in a datagroup')\n", "for key in h5_file['/Measurement_000'].attrs:\n", " print('{} : {}'.format(key, h5_file['/Measurement_000'].attrs[key]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Initialize an object that will perform image windowing on the .h5 file\n", "* Note that after you run this, the H5 file is opened. If you want to re-run this cell, close the H5 file first" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Initialize the windowing class\n", "iw = px.processing.ImageWindow(h5_raw, max_RAM_mb=max_mem)\n", "\n", "# grab position indices from the H5 file\n", "h5_pos = h5_raw.h5_pos_inds\n", "\n", "# determine the image size:\n", "num_x, num_y = h5_raw.pos_dim_sizes\n", "\n", "# extract figure data and reshape to proper numpy array\n", "raw_image_mat = np.reshape(h5_raw[()], [num_x,num_y]);" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualize the source image:\n", "Though the source file is actually grayscale image, we will visualize it using a color-scale" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "fig, axis = plt.subplots(figsize=(10,10))\n", "px.plot_utils.plot_map(axis, raw_image_mat, cmap=px.plot_utils.cmap_jet_white_center())\n", "axis.set_title('Raw Image', fontsize=16)\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Raw_Image.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Extract the optimal window size from the image" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "num_peaks = 2\n", "win_size , psf_width = iw.window_size_extract(num_peaks, save_plots=False, show_plots=True)\n", "\n", "print('Window size = {}'.format(win_size))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Uncomment this line if you need to manually specify a window size\n", "# win_size = 32\n", "\n", "# plot a single window\n", "row_offset = int(0.5*(num_x-win_size))\n", "col_offset = int(0.5*(num_y-win_size))\n", "fig, axis = plt.subplots(figsize=(5, 5))\n", "px.plot_utils.plot_map(axis, raw_image_mat[row_offset:row_offset+win_size,\n", " col_offset:col_offset+win_size], \n", " cmap=px.plot_utils.cmap_jet_white_center())\n", "# the result should be about the size of a unit cell\n", "# if it is the wrong size, just choose on manually by setting the win_size\n", "axis.set_title('Example window', fontsize=18)\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Example_window.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Now break the image into a sequence of small windows\n", "We do this by sliding a small window across the image. This artificially baloons the size of the data." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "windowing_parms = {\n", " 'fft_mode': None, # Options are None, 'abs', 'data+abs', or 'complex'\n", " 'win_x': win_size,\n", " 'win_y': win_size,\n", " 'win_step_x': 1,\n", " 'win_step_y': 1,\n", "}\n", "\n", "win_parms_copy = windowing_parms.copy()\n", "if windowing_parms['fft_mode'] is None:\n", " win_parms_copy['fft_mode'] = 'data'\n", "\n", "h5_wins_grp = px.hdf_utils.check_for_old(h5_raw, 'Windowing',\n", " win_parms_copy)\n", "if h5_wins_grp==[]:\n", " print('Windows either do not exist or were created with different parameters')\n", " t0 = time()\n", " h5_wins = iw.do_windowing(win_x=windowing_parms['win_x'],\n", " win_y=windowing_parms['win_y'],\n", " save_plots=False,\n", " show_plots=False,\n", " win_fft=windowing_parms['fft_mode'])\n", " print( 'Windowing took {} seconds.'.format(round(time()-t0, 2)))\n", "else:\n", " print('Taking existing windows dataset')\n", " h5_wins = px.PycroDataset(h5_wins_grp[0]['Image_Windows'])\n", " \n", "print('\\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape))\n", "print('Now each position (window) is descibed by a set of pixels')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "# Peek at a few random windows\n", "num_rand_wins = 9\n", "rand_positions = np.random.randint(0, high=h5_wins.shape[0], size=num_rand_wins)\n", "example_wins = np.zeros(shape=(windowing_parms['win_x'], windowing_parms['win_y'], num_rand_wins), dtype=np.float32)\n", "\n", "for rand_ind, rand_pos in enumerate(rand_positions):\n", " example_wins[:, :, rand_ind] = np.reshape(h5_wins[rand_pos], (windowing_parms['win_x'], windowing_parms['win_y']))\n", " \n", "fig, axes = px.plot_utils.plot_map_stack(example_wins.T, title='Example Windows', cmap=px.plot_utils.cmap_jet_white_center(), \n", " subtitle=['Window # ' + str(win_pos) for win_pos in rand_positions], title_yoffset=0.93)\n", "\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Example_Windows.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Performing Singular Value Decompostion (SVD) on the windowed data\n", "SVD decomposes data (arranged as position x value) into a sequence of orthogonal components arranged in descending order of variance. The first component contains the most significant trend in the data. The second component contains the next most significant trend orthogonal to all previous components (just the first component). Each component consists of the trend itself (eigenvector), the spatial variaion of this trend (eigenvalues), and the variance (statistical importance) of the component.\n", "\n", "Since the data consists of the large sequence of small windows, SVD essentially compares every single window with every other window to find statistically significant trends in the image" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# check to make sure number of components is correct:\n", "num_comp = 128\n", "num_comp = min(num_comp, \n", " min(h5_wins.shape)*len(h5_wins.dtype))\n", "\n", "proc = px.processing.SVD(h5_wins, num_components=num_comp)\n", "\n", "if proc.duplicate_h5_groups==[]:\n", " print('SVD not performed with these parameters')\n", " h5_svd = proc.compute()\n", "else:\n", " print('Taking existing results!')\n", " h5_svd = proc.duplicate_h5_groups \n", " \n", "h5_U = h5_svd['U']\n", "h5_S = h5_svd['S']\n", "h5_V = h5_svd['V']\n", "\n", "# extract parameters of the SVD results \n", "h5_pos = iw.hdf.file[h5_wins.attrs['Position_Indices']]\n", "num_rows = len(np.unique(h5_pos[:, 0]))\n", "num_cols = len(np.unique(h5_pos[:, 1]))\n", "\n", "num_comp = h5_S.size\n", "print(\"There are a total of {} components.\".format(num_comp))\n", " \n", "print('\\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape))\n", "print('Now each position (window) is descibed by a set of pixels')\n", "\n", "plot_comps = 49\n", "U_map_stack = np.reshape(h5_U[:, :plot_comps], [num_rows, num_cols, -1])\n", "V_map_stack = np.reshape(h5_V, [num_comp, win_size, win_size])\n", "V_map_stack = np.transpose(V_map_stack,(2,1,0))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualize the SVD results\n", "\n", "##### S (variance):\n", "The plot below shows the variance or statistical significance of the SVD components. The first few components contain the most significant information while the last few components mainly contain noise. \n", "\n", "Note also that the plot below is a log-log plot. The importance of each subsequent component drops exponentially." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "fig_S, ax_S = px.plot_utils.plot_scree(h5_S[()]);\n", "usid.jupyter_utils.save_fig_filebox_button(fig_S, 'Scree_of_Windows.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### V (Eigenvectors or end-members)\n", "The V dataset contains the end members for each component" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "for field in V_map_stack.dtype.names:\n", " fig_V, ax_V = px.plot_utils.plot_map_stack(V_map_stack[:,:,:][field].T, title='', subtitle='Vector-'+field, num_comps=plot_comps, \n", " color_bar_mode='each', cmap=px.plot_utils.cmap_jet_white_center())\n", " display(usid.jupyter_utils.save_fig_filebox_button(fig_V, 'Vector-{}.png'.format(field)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### U (Abundance maps):\n", "The plot below shows the spatial distribution of each component" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "fig_U, ax_U = px.plot_utils.plot_map_stack(U_map_stack[:,:,:25].T, title='', subtitle='Component', num_comps=plot_comps, \n", " color_bar_mode='each', cmap=px.plot_utils.cmap_jet_white_center())\n", "usid.jupyter_utils.save_fig_filebox_button(fig_U, 'Projection_of_Windows.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reconstruct image (while removing noise)\n", "Since SVD is just a decomposition technique, it is possible to reconstruct the data with U, S, V matrices. \n", "\n", "It is also possible to reconstruct a version of the data with a set of components. \n", "\n", "Thus, by reconstructing with the first few components, we can remove the statistical noise in the data. \n", "\n", "##### The key is to select the appropriate (number of) components to reconstruct the image without the noise" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "clean_components = range(36) # np.append(range(5,9),(17,18))\n", "num_components=len(clean_components)\n", "\n", "# Check if the image has been reconstructed with the same parameters:\n", "\n", "# First, gather all groups created by this tool:\n", "h5_clean_image = None\n", "for item in h5_svd:\n", " if item.startswith('Cleaned_Image_') and isinstance(h5_svd[item],h5py.Group):\n", " grp = h5_svd[item]\n", " old_comps = px.hdf_utils.get_attr(grp, 'components_used')\n", " if '-' in old_comps:\n", " start, stop = old_comps.split('-')\n", " old_comps = np.arange(px.hdf_utils.get_attr(h5_svd, 'num_components'))[int(start):int(stop)]\n", " \n", " if old_comps.size == num_components:\n", " if np.all(np.isclose(old_comps, np.array(clean_components))):\n", " h5_clean_image = grp['Cleaned_Image']\n", " print( 'Existing clean image found. No need to rebuild.')\n", " break\n", "\n", "if h5_clean_image is None:\n", " t0 = time()\n", " #h5_clean_image = iw.clean_and_build_batch(h5_win=h5_wins, components=clean_components)\n", " h5_clean_image = iw.clean_and_build_separate_components(h5_win=h5_wins, components=clean_components)\n", " print( 'Cleaning and rebuilding image took {} seconds.'.format(round(time()-t0, 2)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Building a stack of images from here:\n", "image_vec_components = h5_clean_image[()]\n", "\n", "# summing over the components:\n", "for comp_ind in range(1, h5_clean_image.shape[1]):\n", " image_vec_components[:, comp_ind] = np.sum(h5_clean_image[:, :comp_ind+1], axis=1)\n", " \n", "# converting to 3D:\n", "image_components = np.reshape(image_vec_components, [num_x, num_y, -1])\n", "\n", "# calculating the removed noise:\n", "noise_components = image_components - np.reshape(np.tile(h5_raw[()], [1, h5_clean_image.shape[1]]), image_components.shape)\n", "\n", "# defining a helper function to get the FFTs of a stack of images\n", "def get_fft_stack(image_stack):\n", " blackman_window_rows = np.blackman(image_stack.shape[0])\n", " blackman_window_cols = np.blackman(image_stack.shape[1])\n", " fft_stack = np.zeros(image_stack.shape, dtype=np.float)\n", " for image_ind in range(image_stack.shape[2]):\n", " layer = image_stack[:, :, image_ind]\n", " windowed = blackman_window_rows[:, np.newaxis] * layer * blackman_window_cols[np.newaxis, :]\n", " fft_stack[:, :, image_ind] = np.abs(np.fft.fftshift(np.fft.fft2(windowed, axes=(0,1)), axes=(0,1)))\n", " return fft_stack\n", "\n", "# get the FFT of the cleaned image and the removed noise:\n", "fft_image_components = get_fft_stack(image_components)\n", "fft_noise_components = get_fft_stack(noise_components)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "fig, ax = px.plot_utils.plot_map_stack(image_components[:,:,:25].T, title='', evenly_spaced=False,\n", " subtitle='Upto component', num_comps=plot_comps, color_bar_mode='single', \n", " cmap=px.plot_utils.cmap_jet_white_center())\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Reconstructed_Components.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reconstruct the image with the first N components\n", "\n", "slide the bar to pick the the number of components such that the noise is removed while maintaining the integrity of the image" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "num_comps = min(16, image_components.shape[2])\n", "\n", "img_stdevs = 3\n", "\n", "fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(14, 14))\n", "axes.flat[0].loglog(h5_S[()], '*-')\n", "axes.flat[0].set_xlim(left=1, right=h5_S[()].size)\n", "axes.flat[0].set_ylim(bottom=np.min(h5_S[()]), top=np.max(h5_S[()]))\n", "axes.flat[0].set_title('Variance', fontsize=16)\n", "vert_line = axes.flat[0].axvline(x=num_comps, color='r')\n", "\n", "clean_image_mat = image_components[:, :, num_comps]\n", "img_clean = axes.flat[1].imshow(clean_image_mat, cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n", "mean_val = np.mean(clean_image_mat)\n", "std_val = np.std(clean_image_mat)\n", "img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val)\n", "axes.flat[1].get_yaxis().set_visible(False)\n", "axes.flat[1].get_xaxis().set_visible(False)\n", "axes.flat[1].set_title('Cleaned Image', fontsize=16)\n", "\n", "fft_std_dev = np.max(np.std(fft_image_components[:, :, num_comps]))\n", "img_noise_fft = axes.flat[2].imshow(fft_noise_components[:, :, num_comps], cmap=plt.cm.jet,\n", " vmin=0, vmax=4*fft_std_dev, origin='lower')\n", "axes.flat[2].get_yaxis().set_visible(False)\n", "axes.flat[2].get_xaxis().set_visible(False)\n", "axes.flat[2].set_title('FFT of removed noise', fontsize=16)\n", "img_clean_fft = axes.flat[3].imshow(fft_image_components[:, :, num_comps], cmap=plt.cm.jet,\n", " vmin=0, vmax=4*fft_std_dev, origin='lower')\n", "axes.flat[3].set_title('FFT of cleaned image', fontsize=16)\n", "axes.flat[3].get_yaxis().set_visible(False)\n", "axes.flat[3].get_xaxis().set_visible(False)\n", "\n", "plt.show()\n", "\n", "def move_comp_line(num_comps):\n", " vert_line.set_xdata((num_comps, num_comps))\n", " clean_image_mat = image_components[:, :, num_comps]\n", " img_clean.set_data(clean_image_mat)\n", " mean_val = np.mean(clean_image_mat)\n", " std_val = np.std(clean_image_mat)\n", " img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val)\n", " img_noise_fft.set_data(fft_noise_components[:, :, num_comps])\n", " img_clean_fft.set_data(fft_image_components[:, :, num_comps])\n", " clean_components = range(num_comps)\n", " fig.canvas.draw()\n", "# display(fig)\n", " \n", "widgets.interact(move_comp_line, num_comps=(1, image_components.shape[2]-1, 1));\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Clean_Image_Tool.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check the cleaned image now:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "num_comps = 24\n", "\n", "fig, axis = plt.subplots(figsize=(7, 7))\n", "clean_image_mat = image_components[:, :, num_comps]\n", "_ = px.plot_utils.plot_map(axis, clean_image_mat, cmap=px.plot_utils.cmap_jet_white_center())\n", "axis.set_title('Cleaned Image', fontsize=16);\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Cleaned_Image.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Atom Finding\n", "We will attempt to find the positions and the identities of atoms in the image now\n", "\n", "## Perform clustering on the dataset\n", "Clustering divides data into k clusters such that the variance within each cluster is minimized.
\n", "Here, we will be performing k-means clustering on a set of components in the U matrix from SVD.
\n", "We want a large enough number of clusters so that K-means identifies fine nuances in the data. At the same time, we want to minimize computational time by reducing the number of clusters. We recommend 32 - 64 clusters." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "num_clusters = 4\n", "estimator = px.processing.Cluster(h5_U, KMeans(n_clusters=num_clusters), num_comps=num_comps)\n", "\n", "if estimator.duplicate_h5_groups==[]:\n", " t0 = time()\n", " h5_kmeans = estimator.compute()\n", " print('kMeans took {} seconds.'.format(round(time()-t0, 2)))\n", "else:\n", " h5_kmeans = estimator.duplicate_h5_groups[-1]\n", " print( 'Using existing results.') \n", " \n", "print( 'Clustering results in {}.'.format(h5_kmeans.name))\n", "\n", "half_wind = int(win_size*0.5)\n", "# generate a cropped image that was effectively the area that was used for pattern searching\n", "# Need to get the math righ on the counting\n", "cropped_clean_image = clean_image_mat[half_wind:-half_wind + 1, half_wind:-half_wind + 1]\n", "\n", "# Plot cluster results Get the labels dataset\n", "labels_mat = np.reshape(h5_kmeans['Labels'][()], [num_rows, num_cols])\n", "\n", "fig, axes = plt.subplots(ncols=2, figsize=(14,7))\n", "axes[0].imshow(cropped_clean_image,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n", "axes[0].set_title('Cleaned Image', fontsize=16)\n", "axes[1].imshow(labels_mat, aspect=1, interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n", "axes[1].set_title('K-means cluster labels', fontsize=16);\n", "for axis in axes:\n", " axis.get_yaxis().set_visible(False)\n", " axis.get_xaxis().set_visible(False)\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Clustered_Clean_Image.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Visualize the hierarchical clustering\n", "The vertical length of the branches indicates the relative separation between neighboring clusters." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Plot dendrogram here\n", "#Get the distrance between cluster means \n", "distance_mat = pdist(h5_kmeans['Mean_Response'][()]) \n", " \n", "#get hierachical pairings of clusters \n", "linkage_pairing = linkage(distance_mat,'weighted') \n", "\n", "# Normalize the pairwise distance with the maximum distance\n", "linkage_pairing[:,2] = linkage_pairing[:,2]/max(linkage_pairing[:,2]) \n", "\n", "# Visualize dendrogram\n", "fig = plt.figure(figsize=(10,3)) \n", "retval = dendrogram(linkage_pairing, count_sort=True, \n", " distance_sort=True, leaf_rotation=90) \n", "#fig.axes[0].set_title('Dendrogram') \n", "fig.axes[0].set_xlabel('Cluster number', fontsize=20) \n", "fig.axes[0].set_ylabel('Cluster separation', fontsize=20)\n", "px.plot_utils.set_tick_font_size(fig.axes[0], 12)\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Cluster_Dendrogram.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Identifiying the principal patterns\n", "Here, we will interactively identify N windows, each centered on a distinct class / kind of atom.\n", "\n", "Use the coarse and fine positions sliders to center the window onto target atoms. Click the \"Set as motif\" button to add this window to the list of patterns we will search for in the next step. Avoid duplicates." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "motif_win_size = win_size\n", "half_wind = int(motif_win_size*0.5)\n", "\n", "row, col = [int(0.5*cropped_clean_image.shape[0]), int(0.5*cropped_clean_image.shape[1])]\n", "\n", "fig, axes = plt.subplots(ncols=2, figsize=(14,7))\n", "\n", "clean_img = axes[0].imshow(cropped_clean_image,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n", "axes[0].set_title('Cleaned Image', fontsize=16)\n", "axes[1].set_title('Zoomed area', fontsize=16)\n", "vert_line = axes[0].axvline(x=col, color='k')\n", "hor_line = axes[0].axhline(y=row, color='k')\n", "motif_box = axes[0].add_patch(patches.Rectangle((col - half_wind, row - half_wind),\n", " motif_win_size, motif_win_size, fill=False,\n", " color='black', linewidth=2))\n", "\n", "indices = (slice(row - half_wind, row + half_wind), \n", " slice(col - half_wind, col + half_wind))\n", "motif_img = axes[1].imshow(cropped_clean_image[indices],cmap=px.plot_utils.cmap_jet_white_center(), \n", " vmax=np.max(cropped_clean_image), vmin=np.min(cropped_clean_image), origin='lower')\n", "axes[1].axvline(x=half_wind, color='k')\n", "axes[1].axhline(y=half_wind, color='k')\n", "\n", "plt.show()\n", "\n", "def _update_motif_img(row, col):\n", " indices = (slice(row - half_wind, row + half_wind), \n", " slice(col - half_wind, col + half_wind))\n", " motif_box.set_x(col - half_wind)\n", " motif_box.set_y(row - half_wind)\n", " \n", " motif_img.set_data(cropped_clean_image[indices])\n", "\n", "def move_zoom_box(event):\n", " if not clean_img.axes.in_axes(event):\n", " return\n", " \n", " col = int(round(event.xdata))\n", " row = int(round(event.ydata))\n", " \n", " vert_line.set_xdata((col, col))\n", " hor_line.set_ydata((row, row))\n", " \n", " _update_motif_img(row, col)\n", " \n", " fig.canvas.draw()\n", "\n", "def _motif_fine_select(event):\n", " if not motif_img.axes.in_axes(event):\n", " return\n", " \n", " col_shift = int(round(event.xdata)) - half_wind\n", " row_shift = int(round(event.ydata)) - half_wind\n", " \n", " col = vert_line.get_xdata()[0] + col_shift\n", " row = hor_line.get_ydata()[0] + row_shift\n", " \n", " vert_line.set_xdata((col, col))\n", " hor_line.set_ydata((row, row))\n", " \n", " _update_motif_img(row, col)\n", " \n", " fig.canvas.draw()\n", " \n", "motif_win_centers = list()\n", "\n", "add_motif_button = widgets.Button(description=\"Set as motif\")\n", "display(add_motif_button)\n", "\n", "def add_motif(butt):\n", " row = hor_line.get_ydata()[0]\n", " col = vert_line.get_xdata()[0]\n", " #print(\"Setting motif with coordinates ({}, {})\".format(current_center[0], current_center[1]))\n", " axes[0].add_patch(patches.Rectangle((col - int(0.5*motif_win_size), \n", " row - int(0.5*motif_win_size)),\n", " motif_win_size, motif_win_size, fill=False,\n", " color='black', linewidth=2))\n", " motif_win_centers.append((row, col))\n", "\n", "cid = clean_img.figure.canvas.mpl_connect('button_press_event', move_zoom_box)\n", "cid2 = motif_img.figure.canvas.mpl_connect('button_press_event', _motif_fine_select)\n", "add_motif_button.on_click(add_motif)\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Clean_Image_Atom_Motifs.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Visualize the motifs that were selected above" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "# select motifs from the cluster labels using the component list:\n", "# motif_win_centers = [(117, 118), (109, 110)]\n", "print('Coordinates of the centers of the chosen motifs:')\n", "print(motif_win_centers)\n", "motif_win_size = win_size\n", "half_wind = int(motif_win_size*0.5)\n", "\n", "# Effectively, we end up cropping the image again by the window size while matching patterns so:\n", "double_cropped_image = cropped_clean_image[half_wind:-half_wind, half_wind:-half_wind]\n", "\n", "# motif_win_size = 15 # Perhaps the motif should be smaller than the original window\n", "num_motifs = len(motif_win_centers)\n", "motifs = list()\n", "fig, axes = plt.subplots(ncols=3, nrows=num_motifs, figsize=(14,6 * num_motifs))\n", "\n", "for window_center, ax_row in zip(motif_win_centers, np.atleast_2d(axes)):\n", " indices = (slice(window_center[0] - half_wind, window_center[0] + half_wind), \n", " slice(window_center[1] - half_wind, window_center[1] + half_wind))\n", " motifs.append(labels_mat[indices])\n", " \n", "# ax_row[0].hold(True)\n", " ax_row[0].imshow(cropped_clean_image, interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n", " ax_row[0].add_patch(patches.Rectangle((window_center[1] - int(0.5*motif_win_size), \n", " window_center[0] - int(0.5*motif_win_size)),\n", " motif_win_size, motif_win_size, fill=False,\n", " color='black', linewidth=2))\n", "# ax_row[0].hold(False)\n", "# ax_row[1].hold(True)\n", " ax_row[1].imshow(cropped_clean_image[indices], interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(),\n", " vmax=np.max(cropped_clean_image), vmin=np.min(cropped_clean_image), origin='lower')\n", " ax_row[1].plot([0, motif_win_size-2],[int(0.5*motif_win_size), int(0.5*motif_win_size)], 'k--')\n", " ax_row[1].plot([int(0.5*motif_win_size), int(0.5*motif_win_size)], [0, motif_win_size-2], 'k--')\n", " # ax_row[1].axis('tight')\n", " ax_row[1].set_title('Selected window for motif around (row {}, col {})'.format(window_center[0], window_center[1]))\n", "# ax_row[1].hold(False)\n", " ax_row[2].imshow(labels_mat[indices], interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(),\n", " vmax=num_clusters-1, vmin=0, origin='lower')\n", " ax_row[2].set_title('Motif from K-means labels');\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Chosen_Motifs.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Calculate matching scores for each motif\n", "We do this by sliding each motif across the cluster labels image to find how the motif matches with the image" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "motif_match_coeffs = list()\n", "\n", "for motif_mat in motifs:\n", " \n", " match_mat = np.zeros(shape=(num_rows-motif_win_size, num_cols-motif_win_size))\n", " for row_count, row_pos in enumerate(range(half_wind, num_rows - half_wind - 1, 1)):\n", " for col_count, col_pos in enumerate(range(half_wind, num_cols - half_wind - 1, 1)):\n", " local_cluster_mat = labels_mat[row_pos-half_wind : row_pos+half_wind, \n", " col_pos-half_wind : col_pos+half_wind]\n", " match_mat[row_count, col_count] = np.sum(local_cluster_mat == motif_mat)\n", " # Normalize the dataset:\n", " match_mat = match_mat/np.max(match_mat)\n", " \n", " motif_match_coeffs.append(match_mat)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualize the matching scores\n", "Note: If a pair of motifs are always matching for the same set of atoms, perhaps this may be a duplicate motif. Alternatively, if these motifs do indeed identify distinct classes of atoms, consider:\n", "* clustering again with a different set of SVD components\n", "* increasing the number of clusters\n", "* Choosing a different fft mode ('data+fft' for better identify subtle but important variations) before performing windowing on the data" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "show_legend = True\n", "\n", "base_color_map = plt.cm.get_cmap('jet')\n", "fig = plt.figure(figsize=(8, 8))\n", "plt.imshow(double_cropped_image, cmap=\"gray\", origin='lower')\n", "\n", "if num_motifs > 1:\n", " motif_colors = [base_color_map(int(255 * motif_ind / (num_motifs - 1))) for motif_ind in range(num_motifs)]\n", "else:\n", " motif_colors = [base_color_map(0)]\n", "handles = list()\n", "for motif_ind, current_solid_color, match_mat in zip(range(num_motifs), motif_colors, motif_match_coeffs):\n", " my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1)\n", " plt.imshow(match_mat, cmap=my_cmap, origin='lower');\n", " current_solid_color = list(current_solid_color)\n", " current_solid_color[3] = 0.5 # maximum alpha value\n", " handles.append(patches.Patch(color=current_solid_color, label='Motif {}'.format(motif_ind)))\n", "if show_legend:\n", " plt.legend(handles=handles, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0., fontsize=14)\n", "axis = fig.get_axes()[0]\n", "axis.set_title('Pattern matching scores', fontsize=22)\n", "axis.set_xticklabels([])\n", "axis.set_yticklabels([])\n", "axis.get_xaxis().set_visible(False)\n", "axis.get_yaxis().set_visible(False)\n", "plt.show()\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Motif_Matching_Scores.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Convert matching scores to binary\n", "We do this by thresholding the matching scores such that a score beyond the threshold is set to 1 and all other values are set to 0. \n", "\n", "The goal is to set the thresholds such that we avoid overlaps between two clusters and also shrink the blobs such that they are only centered over a single atom wherever possible.\n", "\n", "Use the sliders below to interactively set the threshold values" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "scrolled": false }, "outputs": [], "source": [ "thresholds = [0.25 for x in range(num_motifs)]\n", "thresholded_maps = list()\n", "motif_imgs = list()\n", "\n", "base_color_map = plt.cm.jet\n", "fig = plt.figure(figsize=(10, 10))\n", "plt.imshow(double_cropped_image, cmap=\"gray\")\n", "axis = plt.gca()\n", "handles = list()\n", "\n", "if num_motifs > 1:\n", " motif_colors = [base_color_map(int(255 * motif_ind / (num_motifs - 1))) for motif_ind in range(num_motifs)]\n", "else:\n", " motif_colors = [base_color_map(0)]\n", "\n", "for motif_ind, match_mat, t_hold, current_solid_color in zip(range(num_motifs), motif_match_coeffs, \n", " thresholds, motif_colors):\n", " my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1, max_alpha=0.5)\n", " bin_map = np.where(match_mat > t_hold, \n", " np.ones(shape=match_mat.shape, dtype=np.uint8),\n", " np.zeros(shape=match_mat.shape, dtype=np.uint8))\n", " thresholded_maps.append(bin_map)\n", " motif_imgs.append(plt.imshow(bin_map, interpolation='none', cmap=my_cmap))\n", " current_solid_color = list(current_solid_color)\n", " current_solid_color[3] = 0.5\n", " handles.append(patches.Patch(color=current_solid_color,label='Motif {}'.format(motif_ind)))\n", "\n", "axis.set_xticklabels([])\n", "axis.set_yticklabels([])\n", "axis.get_xaxis().set_visible(False)\n", "axis.get_yaxis().set_visible(False)\n", "plt.legend(handles=handles, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)\n", "\n", "def threshold_images(thresholds):\n", " # thresholded_maps = list()\n", " # empty the thresholded maps:\n", " del thresholded_maps[:]\n", " for motif_ind, match_mat, t_hold, current_solid_color in zip(range(num_motifs), motif_match_coeffs, thresholds, motif_colors):\n", " my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1, max_alpha=0.5)\n", " bin_map = np.where(match_mat > t_hold, \n", " np.ones(shape=match_mat.shape, dtype=np.uint8),\n", " np.zeros(shape=match_mat.shape, dtype=np.uint8))\n", " thresholded_maps.append(bin_map)\n", " \n", "def interaction_unpacker(**kwargs):\n", " #threshs = range(num_motifs)\n", " for motif_ind in range(num_motifs):\n", " thresholds[motif_ind] = kwargs['Motif ' + str(motif_ind)]\n", " threshold_images(thresholds)\n", " for img_handle, th_image in zip(motif_imgs, thresholded_maps):\n", " img_handle.set_data(th_image)\n", " fig.canvas.draw()\n", " \n", "temp_thresh = dict()\n", "for motif_ind in range(num_motifs):\n", " temp_thresh['Motif ' + str(motif_ind)] = (0,1,0.025)\n", "widgets.interact(interaction_unpacker, **temp_thresh)\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Motif_Threshold_Maps.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Find the atom centers from the binary maps\n", "The centers of the atoms will be inferred from the centroid of each of the blobs." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "print(thresholds)\n", "\n", "atom_labels = list()\n", "for thresh_map in thresholded_maps:\n", " labled_atoms = measure.label(thresh_map, background=0)\n", " map_props = measure.regionprops(labled_atoms)\n", " atom_centroids = np.zeros(shape=(len(map_props),2))\n", " for atom_ind, atom in enumerate(map_props):\n", " atom_centroids[atom_ind] = np.array(atom.centroid)\n", " atom_labels.append(atom_centroids)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Visualize the atom positions" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# overlay atom positions on original image\n", "fig, axis = plt.subplots(figsize=(8,8))\n", "\n", "col_map = plt.cm.jet\n", "axis.imshow(double_cropped_image, interpolation='none',cmap=\"gray\")\n", "legend_handles = list()\n", "for atom_type_ind, atom_centroids in enumerate(atom_labels): \n", " axis.scatter(atom_centroids[:,1], atom_centroids[:,0], color=col_map(int(255 * atom_type_ind / (num_motifs-1))),\n", " label='Motif {}'.format(atom_type_ind), s=30)\n", "axis.set_xlim(0, double_cropped_image.shape[0])\n", "axis.set_ylim(0, double_cropped_image.shape[1]);\n", "axis.invert_yaxis()\n", "\n", "axis.set_xticklabels([])\n", "axis.set_yticklabels([])\n", "axis.get_xaxis().set_visible(False)\n", "axis.get_yaxis().set_visible(False)\n", "axis.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=14)\n", "axis.set_title('Atom Positions', fontsize=22)\n", "\n", "fig.tight_layout()\n", "usid.jupyter_utils.save_fig_filebox_button(fig, 'Atomic_Positions.png')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Save and close\n", "* Save the .h5 file that we are working on by closing it.
\n", "* Also, consider exporting this notebook as a notebook or an html file.
To do this, go to File >> Download as >> HTML\n", "* Finally consider saving this notebook if necessary" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "h5_file.close()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "celltoolbar": "Raw Cell Format", "kernelspec": { "display_name": "Python [default]", "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.5.5" } }, "nbformat": 4, "nbformat_minor": 1 }