Commit 9d6383a4 authored by Unknown's avatar Unknown
Browse files

Image Cleaning notebook bugfix

parent fd1812c2
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Image cleaning and atom finding using pycroscopy # Image cleaning and atom finding using pycroscopy
### Suhas Somnath, Chris R. Smith, Stephen Jesse ### Suhas Somnath, Chris R. Smith, Stephen Jesse
The Center for Nanophase Materials Science and The Institute for Functional Imaging for Materials <br> The Center for Nanophase Materials Science and The Institute for Functional Imaging for Materials <br>
Oak Ridge National Laboratory<br> Oak Ridge National Laboratory<br>
1/19/2017 1/19/2017
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Configure the notebook first ## Configure the notebook first
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
!pip install -U numpy scipy skimage h5py matplotlib Ipython ipywidgets pycroscopy !pip install -U numpy scipy skimage h5py matplotlib Ipython ipywidgets pycroscopy
# set up notebook to show plots within the notebook # set up notebook to show plots within the notebook
% matplotlib notebook % matplotlib notebook
# Import necessary libraries: # Import necessary libraries:
# General utilities: # General utilities:
import os import os
import sys import sys
from time import time from time import time
from scipy.misc import imsave from scipy.misc import imsave
# Computation: # Computation:
import numpy as np import numpy as np
import h5py import h5py
from skimage import measure from skimage import measure
from scipy.cluster.hierarchy import linkage, dendrogram from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import pdist from scipy.spatial.distance import pdist
# Visualization: # Visualization:
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import matplotlib.patches as patches import matplotlib.patches as patches
from mpl_toolkits.axes_grid1 import make_axes_locatable from mpl_toolkits.axes_grid1 import make_axes_locatable
from IPython.display import display, HTML from IPython.display import display, HTML
import ipywidgets as widgets import ipywidgets as widgets
from mpl_toolkits.axes_grid1 import ImageGrid from mpl_toolkits.axes_grid1 import ImageGrid
# Finally, pycroscopy itself # Finally, pycroscopy itself
sys.path.append('..') sys.path.append('..')
import pycroscopy as px import pycroscopy as px
# Make Notebook take up most of page width # Make Notebook take up most of page width
display(HTML(data=""" display(HTML(data="""
<style> <style>
div#notebook-container { width: 95%; } div#notebook-container { width: 95%; }
div#menubar-container { width: 65%; } div#menubar-container { width: 65%; }
div#maintoolbar-container { width: 99%; } div#maintoolbar-container { width: 99%; }
</style> </style>
""")) """))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Load the image that will be cleaned: ## Load the image that will be cleaned:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
image_path = px.io.uiGetFile('*.png *PNG *TIFF * TIF *tif *tiff *BMP *bmp','Images') image_path = px.io.uiGetFile('*.png *PNG *TIFF * TIF *tif *tiff *BMP *bmp','Images')
print('Working on: \n{}'.format(image_path)) print('Working on: \n{}'.format(image_path))
folder_path, file_name = os.path.split(image_path) folder_path, file_name = os.path.split(image_path)
base_name, _ = os.path.splitext(file_name) base_name, _ = os.path.splitext(file_name)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Make the image file pycroscopy compatible ## Make the image file pycroscopy compatible
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 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
#### H5 files: #### H5 files:
* 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. * 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.
* are readily compatible with high-performance computing facilities * are readily compatible with high-performance computing facilities
* scale very efficiently from few kilobytes to several terabytes * scale very efficiently from few kilobytes to several terabytes
* can be read and modified using any language including Python, Matlab, C/C++, Java, Fortran, Igor Pro, etc. * can be read and modified using any language including Python, Matlab, C/C++, Java, Fortran, Igor Pro, etc.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Check if an HDF5 file with the chosen image already exists. # Check if an HDF5 file with the chosen image already exists.
# Only translate if it does not. # Only translate if it does not.
h5_path = os.path.join(folder_path, base_name+'.h5') h5_path = os.path.join(folder_path, base_name+'.h5')
need_translation = True need_translation = True
if os.path.exists(h5_path): if os.path.exists(h5_path):
try: try:
h5_file = h5py.File(h5_path, 'r+') h5_file = h5py.File(h5_path, 'r+')
h5_raw = h5_file['Measurement_000']['Channel_000']['Raw_Data'] h5_raw = h5_file['Measurement_000']['Channel_000']['Raw_Data']
need_translation = False need_translation = False
print('HDF5 file with Raw_Data found. No need to translate.') print('HDF5 file with Raw_Data found. No need to translate.')
except KeyError: except KeyError:
print('Raw Data not found.') print('Raw Data not found.')
else: else:
print('No HDF5 file found.') print('No HDF5 file found.')
if need_translation: if need_translation:
# Initialize the Image Translator # Initialize the Image Translator
tl = px.ImageTranslator() tl = px.ImageTranslator()
# create an H5 file that has the image information in it and get the reference to the dataset # create an H5 file that has the image information in it and get the reference to the dataset
h5_raw = tl.translate(image_path) h5_raw = tl.translate(image_path)
# create a reference to the file # create a reference to the file
h5_file = h5_raw.file h5_file = h5_raw.file
print('HDF5 file is located at {}.'.format(h5_file.filename)) print('HDF5 file is located at {}.'.format(h5_file.filename))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Inspect the contents of this h5 data file ### Inspect the contents of this h5 data file
The file contents are stored in a tree structure, just like files on a contemporary computer. The file contents are stored in a tree structure, just like files on a contemporary computer.
The data is stored as a 2D matrix (position, spectroscopic value) regardless of the dimensionality of the data. The data is stored as a 2D matrix (position, spectroscopic value) regardless of the dimensionality of the data.
In the case of these 2D images, the data is stored as a N x 1 dataset In the case of these 2D images, the data is stored as a N x 1 dataset
The main dataset is always accompanied by four ancillary datasets that explain the position and spectroscopic value of any given element in the dataset. The main dataset is always accompanied by four ancillary datasets that explain the position and spectroscopic value of any given element in the dataset.
In the case of the 2d images, the positions will be arranged as row0-col0, row0-col1.... row0-colN, row1-col0.... In the case of the 2d images, the positions will be arranged as row0-col0, row0-col1.... row0-colN, row1-col0....
The spectroscopic information is trivial since the data at any given pixel is just a scalar value The spectroscopic information is trivial since the data at any given pixel is just a scalar value
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print('Datasets and datagroups within the file:') print('Datasets and datagroups within the file:')
px.io.hdf_utils.print_tree(h5_file) px.io.hdf_utils.print_tree(h5_file)
print('\nThe main dataset:') print('\nThe main dataset:')
print(h5_file['/Measurement_000/Channel_000/Raw_Data']) print(h5_file['/Measurement_000/Channel_000/Raw_Data'])
print('\nThe ancillary datasets:') print('\nThe ancillary datasets:')
print(h5_file['/Measurement_000/Channel_000/Position_Indices']) print(h5_file['/Measurement_000/Channel_000/Position_Indices'])
print(h5_file['/Measurement_000/Channel_000/Position_Values']) print(h5_file['/Measurement_000/Channel_000/Position_Values'])
print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Indices']) print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Indices'])
print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Values']) print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Values'])
print('\nMetadata or attributes in a datagroup') print('\nMetadata or attributes in a datagroup')
for key in h5_file['/Measurement_000'].attrs: for key in h5_file['/Measurement_000'].attrs:
print('{} : {}'.format(key, h5_file['/Measurement_000'].attrs[key])) print('{} : {}'.format(key, h5_file['/Measurement_000'].attrs[key]))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Initialize an object that will perform image windowing on the .h5 file ## Initialize an object that will perform image windowing on the .h5 file
* Note that after you run this, the H5 file is opened. If you want to re-run this cell, close the H5 file first * 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 id: tags: %% Cell type:code id: tags:
``` python ``` python
# Initialize the windowing class # Initialize the windowing class
iw = px.ImageWindow(h5_raw, max_RAM_mb=1024*4) iw = px.ImageWindow(h5_raw, max_RAM_mb=1024*4)
# grab position indices from the H5 file # grab position indices from the H5 file
h5_pos = h5_raw.parent[h5_raw.attrs['Position_Indices']] h5_pos = h5_raw.parent[h5_raw.attrs['Position_Indices']]
# determine the image size: # determine the image size:
num_x = len(np.unique(h5_pos[:,0])) num_x = len(np.unique(h5_pos[:,0]))
num_y = len(np.unique(h5_pos[:,1])) num_y = len(np.unique(h5_pos[:,1]))
# extract figure data and reshape to proper numpy array # extract figure data and reshape to proper numpy array
raw_image_mat = np.reshape(h5_raw[()], [num_x,num_y]); raw_image_mat = np.reshape(h5_raw[()], [num_x,num_y]);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Visualize the source image: ## Visualize the source image:
Though the source file is actually grayscale image, we will visualize it using a color-scale Though the source file is actually grayscale image, we will visualize it using a color-scale
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
fig, axis = plt.subplots(figsize=(10,10)) fig, axis = plt.subplots(figsize=(10,10))
img = axis.imshow(raw_image_mat,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower'); img = axis.imshow(raw_image_mat,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower');
divider = make_axes_locatable(axis) divider = make_axes_locatable(axis)
cax = divider.append_axes("right", size="5%", pad=0.2) cax = divider.append_axes("right", size="5%", pad=0.2)
plt.colorbar(img, cax=cax) plt.colorbar(img, cax=cax)
axis.set_title('Raw Image', fontsize=16); axis.set_title('Raw Image', fontsize=16);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Extract the optimal window size from the image ## Extract the optimal window size from the image
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
num_peaks = 2 num_peaks = 2
win_size , psf_width = iw.window_size_extract(num_peaks, save_plots=False, show_plots=True) win_size , psf_width = iw.window_size_extract(num_peaks, save_plots=False, show_plots=True)
print('Window size = {}'.format(win_size)) print('Window size = {}'.format(win_size))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Uncomment this line if you need to manually specify a window size # Uncomment this line if you need to manually specify a window size
# win_size = 8 # win_size = 8
# plot a single window # plot a single window
row_offset = int(0.5*(num_x-win_size)) row_offset = int(0.5*(num_x-win_size))
col_offset = int(0.5*(num_y-win_size)) col_offset = int(0.5*(num_y-win_size))
plt.figure() plt.figure()
plt.imshow(raw_image_mat[row_offset:row_offset+win_size, plt.imshow(raw_image_mat[row_offset:row_offset+win_size,
col_offset:col_offset+win_size], col_offset:col_offset+win_size],
cmap=px.plot_utils.cmap_jet_white_center(), cmap=px.plot_utils.cmap_jet_white_center(),
origin='lower'); origin='lower');
# the result should be about the size of a unit cell # the result should be about the size of a unit cell
# if it is the wrong size, just choose on manually by setting the win_size # if it is the wrong size, just choose on manually by setting the win_size
plt.show() plt.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Now break the image into a sequence of small windows ## Now break the image into a sequence of small windows
We do this by sliding a small window across the image. This artificially baloons the size of the data. We do this by sliding a small window across the image. This artificially baloons the size of the data.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
windowing_parms = { windowing_parms = {
'fft_mode': None, # Options are None, 'abs', 'data+abs', or 'complex' 'fft_mode': None, # Options are None, 'abs', 'data+abs', or 'complex'
'win_x': win_size, 'win_x': win_size,
'win_y': win_size, 'win_y': win_size,
'win_step_x': 1, 'win_step_x': 1,
'win_step_y': 1, 'win_step_y': 1,
} }
win_parms_copy = windowing_parms.copy() win_parms_copy = windowing_parms.copy()
if windowing_parms['fft_mode'] is None: if windowing_parms['fft_mode'] is None:
win_parms_copy['fft_mode'] = 'data' win_parms_copy['fft_mode'] = 'data'
h5_wins_grp = px.hdf_utils.check_for_old(h5_raw, 'Windowing', h5_wins_grp = px.hdf_utils.check_for_old(h5_raw, 'Windowing',
win_parms_copy) win_parms_copy)
if h5_wins_grp is None: if h5_wins_grp is None:
print('Windows either do not exist or were created with different parameters') print('Windows either do not exist or were created with different parameters')
t0 = time() t0 = time()
h5_wins = iw.do_windowing(win_x=windowing_parms['win_x'], h5_wins = iw.do_windowing(win_x=windowing_parms['win_x'],
win_y=windowing_parms['win_y'], win_y=windowing_parms['win_y'],
save_plots=False, save_plots=False,
show_plots=False, show_plots=False,
win_fft=windowing_parms['fft_mode']) win_fft=windowing_parms['fft_mode'])
print( 'Windowing took {} seconds.'.format(round(time()-t0, 2))) print( 'Windowing took {} seconds.'.format(round(time()-t0, 2)))
else: else:
print('Taking existing windows dataset') print('Taking existing windows dataset')
h5_wins = h5_wins_grp['Image_Windows'] h5_wins = h5_wins_grp['Image_Windows']
print('\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape)) print('\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape))
print('Now each position (window) is descibed by a set of pixels') print('Now each position (window) is descibed by a set of pixels')
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Peek at a few random windows # Peek at a few random windows
num_rand_wins = 9 num_rand_wins = 9
rand_positions = np.random.randint(0, high=h5_wins.shape[0], size=num_rand_wins) rand_positions = np.random.randint(0, high=h5_wins.shape[0], size=num_rand_wins)
example_wins = np.zeros(shape=(windowing_parms['win_x'], windowing_parms['win_y'], num_rand_wins), dtype=np.float32) example_wins = np.zeros(shape=(windowing_parms['win_x'], windowing_parms['win_y'], num_rand_wins), dtype=np.float32)
for rand_ind, rand_pos in enumerate(rand_positions): for rand_ind, rand_pos in enumerate(rand_positions):
example_wins[:, :, rand_ind] = np.reshape(h5_wins[rand_pos], (windowing_parms['win_x'], windowing_parms['win_y'])) example_wins[:, :, rand_ind] = np.reshape(h5_wins[rand_pos], (windowing_parms['win_x'], windowing_parms['win_y']))
px.plot_utils.plot_map_stack(example_wins, heading='Example Windows', cmap=px.plot_utils.cmap_jet_white_center(), px.plot_utils.plot_map_stack(example_wins, heading='Example Windows', cmap=px.plot_utils.cmap_jet_white_center(),
title=['Window # ' + str(win_pos) for win_pos in rand_positions]); title=['Window # ' + str(win_pos) for win_pos in rand_positions]);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Performing Singular Value Decompostion (SVD) on the windowed data ## Performing Singular Value Decompostion (SVD) on the windowed data
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. 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.
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 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 id: tags: %% Cell type:code id: tags:
``` python ``` python
# check to make sure number of components is correct: # check to make sure number of components is correct:
num_comp = 1024 num_comp = 1024
num_comp = min(num_comp, num_comp = min(num_comp,
min(h5_wins.shape)*len(h5_wins.dtype)) min(h5_wins.shape)*len(h5_wins.dtype))
h5_svd = px.hdf_utils.check_for_old(h5_wins, 'SVD', {'num_components':num_comp}) h5_svd = px.hdf_utils.check_for_old(h5_wins, 'SVD', {'num_components':num_comp})
if h5_svd is None: if h5_svd is None:
print('SVD was either not performed or was performed with different parameters') print('SVD was either not performed or was performed with different parameters')
h5_svd = px.processing.doSVD(h5_wins, num_comps=num_comp) h5_svd = px.processing.doSVD(h5_wins, num_comps=num_comp)
else: else:
print('Taking existing SVD results') print('Taking existing SVD results')
h5_U = h5_svd['U'] h5_U = h5_svd['U']
h5_S = h5_svd['S'] h5_S = h5_svd['S']
h5_V = h5_svd['V'] h5_V = h5_svd['V']
# extract parameters of the SVD results # extract parameters of the SVD results
h5_pos = iw.hdf.file[h5_wins.attrs['Position_Indices']] h5_pos = iw.hdf.file[h5_wins.attrs['Position_Indices']]
num_rows = len(np.unique(h5_pos[:, 0])) num_rows = len(np.unique(h5_pos[:, 0]))
num_cols = len(np.unique(h5_pos[:, 1])) num_cols = len(np.unique(h5_pos[:, 1]))
num_comp = h5_S.size num_comp = h5_S.size
print("There are a total of {} components.".format(num_comp)) print("There are a total of {} components.".format(num_comp))
print('\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape)) print('\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape))
print('Now each position (window) is descibed by a set of pixels') print('Now each position (window) is descibed by a set of pixels')
plot_comps = 49 plot_comps = 49
U_map_stack = np.reshape(h5_U[:, :plot_comps], [num_rows, num_cols, -1]) U_map_stack = np.reshape(h5_U[:, :plot_comps], [num_rows, num_cols, -1])
V_map_stack = np.reshape(h5_V, [num_comp, win_size, win_size]) V_map_stack = np.reshape(h5_V, [num_comp, win_size, win_size])
V_map_stack = np.transpose(V_map_stack,(2,1,0)) V_map_stack = np.transpose(V_map_stack,(2,1,0))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Visualize the SVD results ## Visualize the SVD results
##### S (variance): ##### S (variance):
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. 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.
Note also that the plot below is a log-log plot. The importance of each subsequent component drops exponentially. Note also that the plot below is a log-log plot. The importance of each subsequent component drops exponentially.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
fig_S, ax_S = px.plot_utils.plotScree(h5_S[()]); fig_S, ax_S = px.plot_utils.plotScree(h5_S[()]);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### V (Eigenvectors or end-members) #### V (Eigenvectors or end-members)
The V dataset contains the end members for each component The V dataset contains the end members for each component
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for field in V_map_stack.dtype.names: for field in V_map_stack.dtype.names:
fig_V, ax_V = px.plot_utils.plot_map_stack(V_map_stack[:,:,:][field], heading='', title='Vector-'+field, num_comps=plot_comps, fig_V, ax_V = px.plot_utils.plot_map_stack(V_map_stack[:,:,:][field], heading='', title='Vector-'+field, num_comps=plot_comps,
color_bar_mode='each', cmap=px.plot_utils.cmap_jet_white_center()) color_bar_mode='each', cmap=px.plot_utils.cmap_jet_white_center())
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### U (Abundance maps): #### U (Abundance maps):
The plot below shows the spatial distribution of each component The plot below shows the spatial distribution of each component
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
fig_U, ax_U = px.plot_utils.plot_map_stack(U_map_stack[:,:,:25], heading='', title='Component', num_comps=plot_comps, fig_U, ax_U = px.plot_utils.plot_map_stack(U_map_stack[:,:,:25], heading='', title='Component', num_comps=plot_comps,
color_bar_mode='each', cmap=px.plot_utils.cmap_jet_white_center()) color_bar_mode='each', cmap=px.plot_utils.cmap_jet_white_center())
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Reconstruct image (while removing noise) ## Reconstruct image (while removing noise)
Since SVD is just a decomposition technique, it is possible to reconstruct the data with U, S, V matrices. Since SVD is just a decomposition technique, it is possible to reconstruct the data with U, S, V matrices.
It is also possible to reconstruct a version of the data with a set of components. It is also possible to reconstruct a version of the data with a set of components.
Thus, by reconstructing with the first few components, we can remove the statistical noise in the data. Thus, by reconstructing with the first few components, we can remove the statistical noise in the data.
##### The key is to select the appropriate (number of) components to reconstruct the image without the noise ##### The key is to select the appropriate (number of) components to reconstruct the image without the noise
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
clean_components = range(36) # np.append(range(5,9),(17,18)) clean_components = range(36) # np.append(range(5,9),(17,18))
num_components=len(clean_components) num_components=len(clean_components)
# Check if the image has been reconstructed with the same parameters: # Check if the image has been reconstructed with the same parameters:
# First, gather all groups created by this tool: # First, gather all groups created by this tool:
h5_clean_image = None h5_clean_image = None
for item in h5_svd: for item in h5_svd:
if item.startswith('Cleaned_Image_') and isinstance(h5_svd[item],h5py.Group): if item.startswith('Cleaned_Image_') and isinstance(h5_svd[item],h5py.Group):
grp = h5_svd[item] grp = h5_svd[item]
old_comps = px.hdf_utils.get_attr(grp, 'components_used') old_comps = px.hdf_utils.get_attr(grp, 'components_used')
if old_comps.size == len(list(clean_components)): if old_comps.size == len(list(clean_components)):
if np.all(np.isclose(old_comps, np.array(clean_components))): if np.all(np.isclose(old_comps, np.array(clean_components))):
h5_clean_image = grp['Cleaned_Image'] h5_clean_image = grp['Cleaned_Image']
print( 'Existing clean image found. No need to rebuild.') print( 'Existing clean image found. No need to rebuild.')
break break
if h5_clean_image is None: if h5_clean_image is None:
t0 = time() t0 = time()
#h5_clean_image = iw.clean_and_build_batch(h5_win=h5_wins, components=clean_components) #h5_clean_image = iw.clean_and_build_batch(h5_win=h5_wins, components=clean_components)
h5_clean_image = iw.clean_and_build_separate_components(h5_win=h5_wins, components=clean_components) h5_clean_image = iw.clean_and_build_separate_components(h5_win=h5_wins, components=clean_components)
print( 'Cleaning and rebuilding image took {} seconds.'.format(round(time()-t0, 2))) print( 'Cleaning and rebuilding image took {} seconds.'.format(round(time()-t0, 2)))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Building a stack of images from here: # Building a stack of images from here:
image_vec_components = h5_clean_image[()] image_vec_components = h5_clean_image[()]
# summing over the components: # summing over the components:
for comp_ind in range(1, h5_clean_image.shape[1]): for comp_ind in range(1, h5_clean_image.shape[1]):
image_vec_components[:, comp_ind] = np.sum(h5_clean_image[:, :comp_ind+1], axis=1) image_vec_components[:, comp_ind] = np.sum(h5_clean_image[:, :comp_ind+1], axis=1)
# converting to 3D: # converting to 3D:
image_components = np.reshape(image_vec_components, [num_x, num_y, -1]) image_components = np.reshape(image_vec_components, [num_x, num_y, -1])
# calculating the removed noise: # calculating the removed noise:
noise_components = image_components - np.reshape(np.tile(h5_raw[()], [1, h5_clean_image.shape[1]]), image_components.shape) noise_components = image_components - np.reshape(np.tile(h5_raw[()], [1, h5_clean_image.shape[1]]), image_components.shape)
# defining a helper function to get the FFTs of a stack of images # defining a helper function to get the FFTs of a stack of images
def get_fft_stack(image_stack): def get_fft_stack(image_stack):
blackman_window_rows = np.blackman(image_stack.shape[0]) blackman_window_rows = np.blackman(image_stack.shape[0])
blackman_window_cols = np.blackman(image_stack.shape[1]) blackman_window_cols = np.blackman(image_stack.shape[1])
fft_stack = np.zeros(image_stack.shape, dtype=np.float) fft_stack = np.zeros(image_stack.shape, dtype=np.float)
for image_ind in range(image_stack.shape[2]): for image_ind in range(image_stack.shape[2]):
layer = image_stack[:, :, image_ind] layer = image_stack[:, :, image_ind]
windowed = blackman_window_rows[:, np.newaxis] * layer * blackman_window_cols[np.newaxis, :] windowed = blackman_window_rows[:, np.newaxis] * layer * blackman_window_cols[np.newaxis, :]
fft_stack[:, :, image_ind] = np.abs(np.fft.fftshift(np.fft.fft2(windowed, axes=(0,1)), axes=(0,1))) fft_stack[:, :, image_ind] = np.abs(np.fft.fftshift(np.fft.fft2(windowed, axes=(0,1)), axes=(0,1)))
return fft_stack return fft_stack
# get the FFT of the cleaned image and the removed noise: # get the FFT of the cleaned image and the removed noise:
fft_image_components = get_fft_stack(image_components) fft_image_components = get_fft_stack(image_components)
fft_noise_components = get_fft_stack(noise_components) fft_noise_components = get_fft_stack(noise_components)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
fig_U, ax_U = px.plot_utils.plot_map_stack(image_components[:,:,:25], heading='', evenly_spaced=False, fig_U, ax_U = px.plot_utils.plot_map_stack(image_components[:,:,:25], heading='', evenly_spaced=False,
title='Upto component', num_comps=plot_comps, color_bar_mode='single', title='Upto component', num_comps=plot_comps, color_bar_mode='single',
cmap=px.plot_utils.cmap_jet_white_center()) cmap=px.plot_utils.cmap_jet_white_center())
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Reconstruct the image with the first N components ## Reconstruct the image with the first N components
slide the bar to pick the the number of components such that the noise is removed while maintaining the integrity of the image 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 id: tags: %% Cell type:code id: tags:
``` python ``` python
num_comps = min(16, image_components.shape[2]) num_comps = min(16, image_components.shape[2])
img_stdevs = 3 img_stdevs = 3
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(14, 14)) fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(14, 14))
axes.flat[0].loglog(h5_S[()], '*-') axes.flat[0].loglog(h5_S[()], '*-')
axes.flat[0].set_xlim(left=1, right=h5_S[()].size) axes.flat[0].set_xlim(left=1, right=h5_S[()].size)
axes.flat[0].set_ylim(bottom=np.min(h5_S[()]), top=np.max(h5_S[()])) axes.flat[0].set_ylim(bottom=np.min(h5_S[()]), top=np.max(h5_S[()]))
axes.flat[0].set_title('Variance', fontsize=16) axes.flat[0].set_title('Variance', fontsize=16)
vert_line = axes.flat[0].axvline(x=num_comps, color='r') vert_line = axes.flat[0].axvline(x=num_comps, color='r')
clean_image_mat = image_components[:, :, num_comps] clean_image_mat = image_components[:, :, num_comps]
img_clean = axes.flat[1].imshow(clean_image_mat, cmap=px.plot_utils.cmap_jet_white_center(), origin='lower') img_clean = axes.flat[1].imshow(clean_image_mat, cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')
mean_val = np.mean(clean_image_mat) mean_val = np.mean(clean_image_mat)
std_val = np.std(clean_image_mat) std_val = np.std(clean_image_mat)
img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val) img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val)
axes.flat[1].get_yaxis().set_visible(False) axes.flat[1].get_yaxis().set_visible(False)
axes.flat[1].get_xaxis().set_visible(False) axes.flat[1].get_xaxis().set_visible(False)
axes.flat[1].set_title('Cleaned Image', fontsize=16) axes.flat[1].set_title('Cleaned Image', fontsize=16)
fft_std_dev = np.max(np.std(fft_image_components[:, :, num_comps])) fft_std_dev = np.max(np.std(fft_image_components[:, :, num_comps]))
img_noise_fft = axes.flat[2].imshow(fft_noise_components[:, :, num_comps], cmap=plt.cm.jet, img_noise_fft = axes.flat[2].imshow(fft_noise_components[:, :, num_comps], cmap=plt.cm.jet,
vmin=0, vmax=4*fft_std_dev, origin='lower') vmin=0, vmax=4*fft_std_dev, origin='lower')
axes.flat[2].get_yaxis().set_visible(False) axes.flat[2].get_yaxis().set_visible(False)
axes.flat[2].get_xaxis().set_visible(False) axes.flat[2].get_xaxis().set_visible(False)
axes.flat[2].set_title('FFT of removed noise', fontsize=16) axes.flat[2].set_title('FFT of removed noise', fontsize=16)
img_clean_fft = axes.flat[3].imshow(fft_image_components[:, :, num_comps], cmap=plt.cm.jet, img_clean_fft = axes.flat[3].imshow(fft_image_components[:, :, num_comps], cmap=plt.cm.jet,
vmin=0, vmax=4*fft_std_dev, origin='lower') vmin=0, vmax=4*fft_std_dev, origin='lower')
axes.flat[3].set_title('FFT of cleaned image', fontsize=16) axes.flat[3].set_title('FFT of cleaned image', fontsize=16)
axes.flat[3].get_yaxis().set_visible(False) axes.flat[3].get_yaxis().set_visible(False)
axes.flat[3].get_xaxis().set_visible(False) axes.flat[3].get_xaxis().set_visible(False)
plt.show() plt.show()
def move_comp_line(num_comps): def move_comp_line(num_comps):
vert_line.set_xdata((num_comps, num_comps)) vert_line.set_xdata((num_comps, num_comps))
clean_image_mat = image_components[:, :, num_comps] clean_image_mat = image_components[:, :, num_comps]
img_clean.set_data(clean_image_mat) img_clean.set_data(clean_image_mat)
mean_val = np.mean(clean_image_mat) mean_val = np.mean(clean_image_mat)
std_val = np.std(clean_image_mat) std_val = np.std(clean_image_mat)
img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val) img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val)
img_noise_fft.set_data(fft_noise_components[:, :, num_comps]) img_noise_fft.set_data(fft_noise_components[:, :, num_comps])
img_clean_fft.set_data(fft_image_components[:, :, num_comps]) img_clean_fft.set_data(fft_image_components[:, :, num_comps])
clean_components = range(num_comps) clean_components = range(num_comps)
fig.canvas.draw() fig.canvas.draw()
# display(fig) # display(fig)
widgets.interact(move_comp_line, num_comps=(1, image_components.shape[2]-1, 1)); widgets.interact(move_comp_line, num_comps=(1, image_components.shape[2]-1, 1));
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Check the cleaned image now: ## Check the cleaned image now:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
num_comps = 12 num_comps = 12
fig, axis = plt.subplots(figsize=(7, 7)) fig, axis = plt.subplots(figsize=(7, 7))
clean_image_mat = image_components[:, :, num_comps] clean_image_mat = image_components[:, :, num_comps]
img_clean = axis.imshow(clean_image_mat, cmap=px.plot_utils.cmap_jet_white_center(), origin='lower') img_clean = axis.imshow(clean_image_mat, cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')
mean_val = np.mean(clean_image_mat) mean_val = np.mean(clean_image_mat)
std_val = np.std(clean_image_mat) std_val = np.std(clean_image_mat)
img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val) img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val)
axis.get_yaxis().set_visible(False) axis.get_yaxis().set_visible(False)
axis.get_xaxis().set_visible(False) axis.get_xaxis().set_visible(False)
axis.set_title('Cleaned Image', fontsize=16); axis.set_title('Cleaned Image', fontsize=16);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Atom Finding # Atom Finding
We will attempt to find the positions and the identities of atoms in the image now We will attempt to find the positions and the identities of atoms in the image now
## Perform clustering on the dataset ## Perform clustering on the dataset
Clustering divides data into k clusters such that the variance within each cluster is minimized.<br> Clustering divides data into k clusters such that the variance within each cluster is minimized.<br>
Here, we will be performing k-means clustering on a set of components in the U matrix from SVD.<br> Here, we will be performing k-means clustering on a set of components in the U matrix from SVD.<br>
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. 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 id: tags: %% Cell type:code id: tags:
``` python ``` python
clean_components = 12 clean_components = 12
num_clusters = 32 num_clusters = 32
# Check for existing Clustering results # Check for existing Clustering results
estimator = px.Cluster(h5_U, 'KMeans', num_comps=clean_components, n_clusters=num_clusters) estimator = px.Cluster(h5_U, 'KMeans', num_comps=clean_components, n_clusters=num_clusters)
do_cluster = False do_cluster = False
# See if there are existing cluster results # See if there are existing cluster results
try: try:
h5_kmeans = h5_svd['U-Cluster_000'] h5_kmeans = h5_svd['U-Cluster_000']
print( 'Clustering results loaded. Will now check parameters') print( 'Clustering results loaded. Will now check parameters')
except: except Exception:
print( 'Could not load Clustering results.') print( 'Could not load Clustering results.')
do_cluster = True do_cluster = True
# Check that the same components are used # Check that the same components are used
if not do_cluster: if not do_cluster:
new_clean = estimator.data_slice[1] new_clean = estimator.data_slice[1]
if isinstance(new_clean, np.ndarray): if isinstance(new_clean, np.ndarray):
new_clean = new_clean.tolist() new_clean = new_clean.tolist()
else: else:
# print(new_clean) # print(new_clean)
if new_clean.step is None: if new_clean.step is None:
new_clean = range(new_clean.start, new_clean.stop) new_clean = range(new_clean.start, new_clean.stop)
else: else:
new_clean = range(new_clean.start, new_clean.stop, new_clean.step) new_clean = range(new_clean.start, new_clean.stop, new_clean.step)
if all(h5_kmeans.attrs['components_used']==new_clean): if all(h5_kmeans.attrs['components_used']==new_clean):
print( 'Clustering results used the same components as those requested.') print( 'Clustering results used the same components as those requested.')
else: else:
do_cluster = True do_cluster = True
print( 'Clustering results used the different components from those requested.') print( 'Clustering results used the different components from those requested.')
# Check that the same number of clusters were used # Check that the same number of clusters were used
if not do_cluster: if not do_cluster:
old_clusters = len(np.unique(h5_kmeans['Cluster_Indices'])) old_clusters = len(np.unique(h5_kmeans['Cluster_Indices']))
if old_clusters==num_clusters: if old_clusters==num_clusters:
print( 'Clustering results used the same number of clusters as requested.') print( 'Clustering results used the same number of clusters as requested.')
else: else:
do_cluster = True do_cluster = True
print( 'Clustering results used a different number of clusters from those requested.') print( 'Clustering results used a different number of clusters from those requested.')
# Perform k-means clustering on the U matrix now using the list of components only if needed: # Perform k-means clustering on the U matrix now using the list of components only if needed:
if do_cluster: if do_cluster:
t0 = time() t0 = time()
h5_kmeans = estimator.do_cluster() h5_kmeans = estimator.do_cluster()
print( 'kMeans took {} seconds.'.format(round(time()-t0, 2))) print( 'kMeans took {} seconds.'.format(round(time()-t0, 2)))
else: else:
print( 'Using existing results.') print( 'Using existing results.')
print( 'Clustering results in {}.'.format(h5_kmeans.name)) print( 'Clustering results in {}.'.format(h5_kmeans.name))
half_wind = int(win_size*0.5) half_wind = int(win_size*0.5)
# generate a cropped image that was effectively the area that was used for pattern searching # generate a cropped image that was effectively the area that was used for pattern searching
# Need to get the math righ on the counting # Need to get the math righ on the counting
cropped_clean_image = clean_image_mat[half_wind:-half_wind + 1, half_wind:-half_wind + 1] cropped_clean_image = clean_image_mat[half_wind:-half_wind + 1, half_wind:-half_wind + 1]
# Plot cluster results Get the labels dataset # Plot cluster results Get the labels dataset
labels_mat = np.reshape(h5_kmeans['Labels'][()], [num_rows, num_cols]) labels_mat = np.reshape(h5_kmeans['Labels'][()], [num_rows, num_cols])
fig, axes = plt.subplots(ncols=2, figsize=(14,7)) fig, axes = plt.subplots(ncols=2, figsize=(14,7))
axes[0].imshow(cropped_clean_image,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower') axes[0].imshow(cropped_clean_image,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')
axes[0].set_title('Cleaned Image', fontsize=16) axes[0].set_title('Cleaned Image', fontsize=16)
axes[1].imshow(labels_mat, aspect=1, interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), origin='lower') axes[1].imshow(labels_mat, aspect=1, interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')
axes[1].set_title('K-means cluster labels', fontsize=16); axes[1].set_title('K-means cluster labels', fontsize=16);
for axis in axes: for axis in axes:
axis.get_yaxis().set_visible(False) axis.get_yaxis().set_visible(False)
axis.get_xaxis().set_visible(False) axis.get_xaxis().set_visible(False)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Visualize the hierarchical clustering #### Visualize the hierarchical clustering
The vertical length of the branches indicates the relative separation between neighboring clusters. The vertical length of the branches indicates the relative separation between neighboring clusters.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Plot dendrogram here # Plot dendrogram here
#Get the distrance between cluster means #Get the distrance between cluster means
distance_mat = pdist(h5_kmeans['Mean_Response'][()]) distance_mat = pdist(h5_kmeans['Mean_Response'][()])
#get hierachical pairings of clusters #get hierachical pairings of clusters
linkage_pairing = linkage(distance_mat,'weighted') linkage_pairing = linkage(distance_mat,'weighted')
# Normalize the pairwise distance with the maximum distance # Normalize the pairwise distance with the maximum distance
linkage_pairing[:,2] = linkage_pairing[:,2]/max(linkage_pairing[:,2]) linkage_pairing[:,2] = linkage_pairing[:,2]/max(linkage_pairing[:,2])
# Visualize dendrogram # Visualize dendrogram
fig = plt.figure(figsize=(10,3)) fig = plt.figure(figsize=(10,3))
retval = dendrogram(linkage_pairing, count_sort=True, retval = dendrogram(linkage_pairing, count_sort=True,
distance_sort=True, leaf_rotation=90) distance_sort=True, leaf_rotation=90)
#fig.axes[0].set_title('Dendrogram') #fig.axes[0].set_title('Dendrogram')
fig.axes[0].set_xlabel('Cluster number', fontsize=20) fig.axes[0].set_xlabel('Cluster number', fontsize=20)
fig.axes[0].set_ylabel('Cluster separation', fontsize=20) fig.axes[0].set_ylabel('Cluster separation', fontsize=20)
px.plot_utils.set_tick_font_size(fig.axes[0], 12) px.plot_utils.set_tick_font_size(fig.axes[0], 12)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
vert_line.get_xdata() vert_line.get_xdata()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Identifiying the principal patterns ## Identifiying the principal patterns
Here, we will interactively identify N windows, each centered on a distinct class / kind of atom. Here, we will interactively identify N windows, each centered on a distinct class / kind of atom.
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. 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 id: tags: %% Cell type:code id: tags:
``` python ``` python
motif_win_size = win_size motif_win_size = win_size
half_wind = int(motif_win_size*0.5) half_wind = int(motif_win_size*0.5)
row, col = [int(0.5*cropped_clean_image.shape[0]), int(0.5*cropped_clean_image.shape[1])] row, col = [int(0.5*cropped_clean_image.shape[0]), int(0.5*cropped_clean_image.shape[1])]
fig, axes = plt.subplots(ncols=2, figsize=(14,7)) fig, axes = plt.subplots(ncols=2, figsize=(14,7))
clean_img = axes[0].imshow(cropped_clean_image,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower') clean_img = axes[0].imshow(cropped_clean_image,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')
axes[0].set_title('Cleaned Image', fontsize=16) axes[0].set_title('Cleaned Image', fontsize=16)
axes[1].set_title('Zoomed area', fontsize=16) axes[1].set_title('Zoomed area', fontsize=16)
vert_line = axes[0].axvline(x=col, color='k') vert_line = axes[0].axvline(x=col, color='k')
hor_line = axes[0].axhline(y=row, color='k') hor_line = axes[0].axhline(y=row, color='k')
motif_box = axes[0].add_patch(patches.Rectangle((col - half_wind, row - half_wind), motif_box = axes[0].add_patch(patches.Rectangle((col - half_wind, row - half_wind),
motif_win_size, motif_win_size, fill=False, motif_win_size, motif_win_size, fill=False,
color='black', linewidth=2)) color='black', linewidth=2))
indices = (slice(row - half_wind, row + half_wind), indices = (slice(row - half_wind, row + half_wind),
slice(col - half_wind, col + half_wind)) slice(col - half_wind, col + half_wind))
motif_img = axes[1].imshow(cropped_clean_image[indices],cmap=px.plot_utils.cmap_jet_white_center(), motif_img = axes[1].imshow(cropped_clean_image[indices],cmap=px.plot_utils.cmap_jet_white_center(),
vmax=np.max(cropped_clean_image), vmin=np.min(cropped_clean_image), origin='lower') vmax=np.max(cropped_clean_image), vmin=np.min(cropped_clean_image), origin='lower')
axes[1].axvline(x=half_wind, color='k') axes[1].axvline(x=half_wind, color='k')
axes[1].axhline(y=half_wind, color='k') axes[1].axhline(y=half_wind, color='k')
plt.show() plt.show()
def _update_motif_img(row, col): def _update_motif_img(row, col):
current_center[0] = row
current_center[1] = col
indices = (slice(row - half_wind, row + half_wind), indices = (slice(row - half_wind, row + half_wind),
slice(col - half_wind, col + half_wind)) slice(col - half_wind, col + half_wind))
motif_box.set_x(col - half_wind) motif_box.set_x(col - half_wind)
motif_box.set_y(row - half_wind) motif_box.set_y(row - half_wind)
motif_img.set_data(cropped_clean_image[indices]) motif_img.set_data(cropped_clean_image[indices])
def move_zoom_box(event): def move_zoom_box(event):
if not clean_img.axes.in_axes(event): if not clean_img.axes.in_axes(event):
return return
col = int(round(event.xdata)) col = int(round(event.xdata))
row = int(round(event.ydata)) row = int(round(event.ydata))
vert_line.set_xdata((col, col)) vert_line.set_xdata((col, col))
hor_line.set_ydata((row, row)) hor_line.set_ydata((row, row))
_update_motif_img(row, col) _update_motif_img(row, col)
fig.canvas.draw() fig.canvas.draw()
def _motif_fine_select(event): def _motif_fine_select(event):
if not motif_img.axes.in_axes(event): if not motif_img.axes.in_axes(event):
return return
col_shift = int(round(event.xdata)) - half_wind col_shift = int(round(event.xdata)) - half_wind
row_shift = int(round(event.ydata)) - half_wind row_shift = int(round(event.ydata)) - half_wind
col = vert_line.get_xdata()[0] + col_shift col = vert_line.get_xdata()[0] + col_shift
row = hor_line.get_ydata()[0] + row_shift row = hor_line.get_ydata()[0] + row_shift
vert_line.set_xdata((col, col)) vert_line.set_xdata((col, col))
hor_line.set_ydata((row, row)) hor_line.set_ydata((row, row))
_update_motif_img(row, col) _update_motif_img(row, col)
fig.canvas.draw() fig.canvas.draw()
motif_win_centers = list() motif_win_centers = list()
add_motif_button = widgets.Button(description="Set as motif") add_motif_button = widgets.Button(description="Set as motif")
display(add_motif_button) display(add_motif_button)
def add_motif(butt): def add_motif(butt):
row = hor_line.get_ydata()[0] row = hor_line.get_ydata()[0]
col = vert_line.get_xdata()[0] col = vert_line.get_xdata()[0]
#print("Setting motif with coordinates ({}, {})".format(current_center[0], current_center[1])) #print("Setting motif with coordinates ({}, {})".format(current_center[0], current_center[1]))
axes[0].add_patch(patches.Rectangle((col - int(0.5*motif_win_size), axes[0].add_patch(patches.Rectangle((col - int(0.5*motif_win_size),
row - int(0.5*motif_win_size)), row - int(0.5*motif_win_size)),
motif_win_size, motif_win_size, fill=False, motif_win_size, motif_win_size, fill=False,
color='black', linewidth=2)) color='black', linewidth=2))
motif_win_centers.append((current_center[0], current_center[1])) motif_win_centers.append((current_center[0], current_center[1]))
cid = clean_img.figure.canvas.mpl_connect('button_press_event', move_zoom_box) cid = clean_img.figure.canvas.mpl_connect('button_press_event', move_zoom_box)
cid2 = motif_img.figure.canvas.mpl_connect('button_press_event', _motif_fine_select) cid2 = motif_img.figure.canvas.mpl_connect('button_press_event', _motif_fine_select)
add_motif_button.on_click(add_motif) add_motif_button.on_click(add_motif)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Visualize the motifs that were selected above ### Visualize the motifs that were selected above
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# select motifs from the cluster labels using the component list: # select motifs from the cluster labels using the component list:
# motif_win_centers = [(117, 118), (109, 110)] # motif_win_centers = [(117, 118), (109, 110)]
print('Coordinates of the centers of the chosen motifs:') print('Coordinates of the centers of the chosen motifs:')
print(motif_win_centers) print(motif_win_centers)
motif_win_size = win_size motif_win_size = win_size
half_wind = int(motif_win_size*0.5) half_wind = int(motif_win_size*0.5)
# Effectively, we end up cropping the image again by the window size while matching patterns so: # Effectively, we end up cropping the image again by the window size while matching patterns so:
double_cropped_image = cropped_clean_image[half_wind:-half_wind, half_wind:-half_wind] double_cropped_image = cropped_clean_image[half_wind:-half_wind, half_wind:-half_wind]
# motif_win_size = 15 # Perhaps the motif should be smaller than the original window # motif_win_size = 15 # Perhaps the motif should be smaller than the original window
num_motifs = len(motif_win_centers) num_motifs = len(motif_win_centers)
motifs = list() motifs = list()
fig, axes = plt.subplots(ncols=3, nrows=num_motifs, figsize=(14,6 * num_motifs)) fig, axes = plt.subplots(ncols=3, nrows=num_motifs, figsize=(14,6 * num_motifs))
for window_center, ax_row in zip(motif_win_centers, np.atleast_2d(axes)): for window_center, ax_row in zip(motif_win_centers, np.atleast_2d(axes)):
indices = (slice(window_center[0] - half_wind, window_center[0] + half_wind), indices = (slice(window_center[0] - half_wind, window_center[0] + half_wind),
slice(window_center[1] - half_wind, window_center[1] + half_wind)) slice(window_center[1] - half_wind, window_center[1] + half_wind))
motifs.append(labels_mat[indices]) motifs.append(labels_mat[indices])
ax_row[0].hold(True) ax_row[0].hold(True)
ax_row[0].imshow(cropped_clean_image, interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), origin='lower') ax_row[0].imshow(cropped_clean_image, interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')
ax_row[0].add_patch(patches.Rectangle((window_center[1] - int(0.5*motif_win_size), ax_row[0].add_patch(patches.Rectangle((window_center[1] - int(0.5*motif_win_size),
window_center[0] - int(0.5*motif_win_size)), window_center[0] - int(0.5*motif_win_size)),
motif_win_size, motif_win_size, fill=False, motif_win_size, motif_win_size, fill=False,
color='black', linewidth=2)) color='black', linewidth=2))
ax_row[0].hold(False) ax_row[0].hold(False)
ax_row[1].hold(True) ax_row[1].hold(True)
ax_row[1].imshow(cropped_clean_image[indices], interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), ax_row[1].imshow(cropped_clean_image[indices], interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(),
vmax=np.max(cropped_clean_image), vmin=np.min(cropped_clean_image), origin='lower') vmax=np.max(cropped_clean_image), vmin=np.min(cropped_clean_image), origin='lower')
ax_row[1].plot([0, motif_win_size-2],[int(0.5*motif_win_size), int(0.5*motif_win_size)], 'k--') ax_row[1].plot([0, motif_win_size-2],[int(0.5*motif_win_size), int(0.5*motif_win_size)], 'k--')
ax_row[1].plot([int(0.5*motif_win_size), int(0.5*motif_win_size)], [0, motif_win_size-2], 'k--') ax_row[1].plot([int(0.5*motif_win_size), int(0.5*motif_win_size)], [0, motif_win_size-2], 'k--')
# ax_row[1].axis('tight') # ax_row[1].axis('tight')
ax_row[1].set_title('Selected window for motif around (row {}, col {})'.format(window_center[0], window_center[1])) ax_row[1].set_title('Selected window for motif around (row {}, col {})'.format(window_center[0], window_center[1]))
ax_row[1].hold(False) ax_row[1].hold(False)
ax_row[2].imshow(labels_mat[indices], interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), ax_row[2].imshow(labels_mat[indices], interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(),
vmax=num_clusters-1, vmin=0, origin='lower') vmax=num_clusters-1, vmin=0, origin='lower')
ax_row[2].set_title('Motif from K-means labels'); ax_row[2].set_title('Motif from K-means labels');
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Calculate matching scores for each motif ## Calculate matching scores for each motif
We do this by sliding each motif across the cluster labels image to find how the motif matches with the image We do this by sliding each motif across the cluster labels image to find how the motif matches with the image
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
motif_match_coeffs = list() motif_match_coeffs = list()
for motif_mat in motifs: for motif_mat in motifs:
match_mat = np.zeros(shape=(num_rows-motif_win_size, num_cols-motif_win_size)) match_mat = np.zeros(shape=(num_rows-motif_win_size, num_cols-motif_win_size))
for row_count, row_pos in enumerate(range(half_wind, num_rows - half_wind - 1, 1)): for row_count, row_pos in enumerate(range(half_wind, num_rows - half_wind - 1, 1)):
for col_count, col_pos in enumerate(range(half_wind, num_cols - half_wind - 1, 1)): for col_count, col_pos in enumerate(range(half_wind, num_cols - half_wind - 1, 1)):
local_cluster_mat = labels_mat[row_pos-half_wind : row_pos+half_wind, local_cluster_mat = labels_mat[row_pos-half_wind : row_pos+half_wind,
col_pos-half_wind : col_pos+half_wind] col_pos-half_wind : col_pos+half_wind]
match_mat[row_count, col_count] = np.sum(local_cluster_mat == motif_mat) match_mat[row_count, col_count] = np.sum(local_cluster_mat == motif_mat)
# Normalize the dataset: # Normalize the dataset:
match_mat = match_mat/np.max(match_mat) match_mat = match_mat/np.max(match_mat)
motif_match_coeffs.append(match_mat) motif_match_coeffs.append(match_mat)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Visualize the matching scores ## Visualize the matching scores
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: 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:
* clustering again with a different set of SVD components * clustering again with a different set of SVD components
* increasing the number of clusters * increasing the number of clusters
* Choosing a different fft mode ('data+fft' for better identify subtle but important variations) before performing windowing on the data * Choosing a different fft mode ('data+fft' for better identify subtle but important variations) before performing windowing on the data
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
show_legend = True show_legend = True
base_color_map = plt.cm.get_cmap('jet') base_color_map = plt.cm.get_cmap('jet')
fig = plt.figure(figsize=(8, 8)) fig = plt.figure(figsize=(8, 8))
im = plt.imshow(double_cropped_image, cmap="gray", origin='lower') im = plt.imshow(double_cropped_image, cmap="gray", origin='lower')
if num_motifs > 1: if num_motifs > 1:
motif_colors = [base_color_map(int(255 * motif_ind / (num_motifs - 1))) for motif_ind in range(num_motifs)] motif_colors = [base_color_map(int(255 * motif_ind / (num_motifs - 1))) for motif_ind in range(num_motifs)]
else: else:
motif_colors = [base_color_map(0)] motif_colors = [base_color_map(0)]
handles = list() handles = list()
for motif_ind, current_solid_color, match_mat in zip(range(num_motifs), motif_colors, motif_match_coeffs): for motif_ind, current_solid_color, match_mat in zip(range(num_motifs), motif_colors, motif_match_coeffs):
my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1) my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1)
im = plt.imshow(match_mat, cmap=my_cmap, origin='lower'); im = plt.imshow(match_mat, cmap=my_cmap, origin='lower');
current_solid_color = list(current_solid_color) current_solid_color = list(current_solid_color)
current_solid_color[3] = 0.5 # maximum alpha value current_solid_color[3] = 0.5 # maximum alpha value
handles.append(patches.Patch(color=current_solid_color, label='Motif {}'.format(motif_ind))) handles.append(patches.Patch(color=current_solid_color, label='Motif {}'.format(motif_ind)))
if show_legend: if show_legend:
plt.legend(handles=handles, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0., fontsize=14) plt.legend(handles=handles, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0., fontsize=14)
axis = fig.get_axes()[0] axis = fig.get_axes()[0]
axis.set_title('Pattern matching scores', fontsize=22) axis.set_title('Pattern matching scores', fontsize=22)
axis.set_xticklabels([]) axis.set_xticklabels([])
axis.set_yticklabels([]) axis.set_yticklabels([])
axis.get_xaxis().set_visible(False) axis.get_xaxis().set_visible(False)
axis.get_yaxis().set_visible(False) axis.get_yaxis().set_visible(False)
plt.show() plt.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Convert matching scores to binary ## Convert matching scores to binary
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. 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.
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. 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.
Use the sliders below to interactively set the threshold values Use the sliders below to interactively set the threshold values
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
thresholds = [0.25 for x in range(num_motifs)] thresholds = [0.25 for x in range(num_motifs)]
thresholded_maps = list() thresholded_maps = list()
motif_imgs = list() motif_imgs = list()
base_color_map = plt.cm.jet base_color_map = plt.cm.jet
fig, axis = plt.subplots(figsize=(10, 10)) fig, axis = plt.subplots(figsize=(10, 10))
plt.hold(True); plt.hold(True);
plt.imshow(double_cropped_image, cmap="gray") plt.imshow(double_cropped_image, cmap="gray")
handles = list() handles = list()
if num_motifs > 1: if num_motifs > 1:
motif_colors = [base_color_map(int(255 * motif_ind / (num_motifs - 1))) for motif_ind in range(num_motifs)] motif_colors = [base_color_map(int(255 * motif_ind / (num_motifs - 1))) for motif_ind in range(num_motifs)]
else: else:
motif_colors = [base_color_map(0)] motif_colors = [base_color_map(0)]
for motif_ind, match_mat, t_hold, current_solid_color in zip(range(num_motifs), motif_match_coeffs, for motif_ind, match_mat, t_hold, current_solid_color in zip(range(num_motifs), motif_match_coeffs,
thresholds, motif_colors): thresholds, motif_colors):
my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1, max_alpha=0.5) my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1, max_alpha=0.5)
bin_map = np.where(match_mat > t_hold, bin_map = np.where(match_mat > t_hold,
np.ones(shape=match_mat.shape, dtype=np.uint8), np.ones(shape=match_mat.shape, dtype=np.uint8),
np.zeros(shape=match_mat.shape, dtype=np.uint8)) np.zeros(shape=match_mat.shape, dtype=np.uint8))
thresholded_maps.append(bin_map) thresholded_maps.append(bin_map)
motif_imgs.append(plt.imshow(bin_map, interpolation='none', cmap=my_cmap)) motif_imgs.append(plt.imshow(bin_map, interpolation='none', cmap=my_cmap))
current_solid_color = list(current_solid_color) current_solid_color = list(current_solid_color)
current_solid_color[3] = 0.5 current_solid_color[3] = 0.5
handles.append(patches.Patch(color=current_solid_color,label='Motif {}'.format(motif_ind))) handles.append(patches.Patch(color=current_solid_color,label='Motif {}'.format(motif_ind)))
axis.set_xticklabels([]) axis.set_xticklabels([])
axis.set_yticklabels([]) axis.set_yticklabels([])
axis.get_xaxis().set_visible(False) axis.get_xaxis().set_visible(False)
axis.get_yaxis().set_visible(False) axis.get_yaxis().set_visible(False)
plt.legend(handles=handles, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.) plt.legend(handles=handles, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)
plt.hold(False); plt.hold(False);
def threshold_images(thresholds): def threshold_images(thresholds):
# thresholded_maps = list() # thresholded_maps = list()
# empty the thresholded maps: # empty the thresholded maps:
del thresholded_maps[:] del thresholded_maps[:]
for motif_ind, match_mat, t_hold, current_solid_color in zip(range(num_motifs), motif_match_coeffs, thresholds, motif_colors): for motif_ind, match_mat, t_hold, current_solid_color in zip(range(num_motifs), motif_match_coeffs, thresholds, motif_colors):
my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1, max_alpha=0.5) my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1, max_alpha=0.5)
bin_map = np.where(match_mat > t_hold, bin_map = np.where(match_mat > t_hold,
np.ones(shape=match_mat.shape, dtype=np.uint8), np.ones(shape=match_mat.shape, dtype=np.uint8),
np.zeros(shape=match_mat.shape, dtype=np.uint8)) np.zeros(shape=match_mat.shape, dtype=np.uint8))
thresholded_maps.append(bin_map) thresholded_maps.append(bin_map)
def interaction_unpacker(**kwargs): def interaction_unpacker(**kwargs):
#threshs = range(num_motifs) #threshs = range(num_motifs)
for motif_ind in range(num_motifs): for motif_ind in range(num_motifs):
thresholds[motif_ind] = kwargs['Motif ' + str(motif_ind)] thresholds[motif_ind] = kwargs['Motif ' + str(motif_ind)]
threshold_images(thresholds) threshold_images(thresholds)
for img_handle, th_image in zip(motif_imgs, thresholded_maps): for img_handle, th_image in zip(motif_imgs, thresholded_maps):
img_handle.set_data(th_image) img_handle.set_data(th_image)
fig.canvas.draw() fig.canvas.draw()
temp_thresh = dict() temp_thresh = dict()
for motif_ind in range(num_motifs): for motif_ind in range(num_motifs):
temp_thresh['Motif ' + str(motif_ind)] = (0,1,0.025) temp_thresh['Motif ' + str(motif_ind)] = (0,1,0.025)
widgets.interact(interaction_unpacker, **temp_thresh); widgets.interact(interaction_unpacker, **temp_thresh);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Find the atom centers from the binary maps ## Find the atom centers from the binary maps
The centers of the atoms will be inferred from the centroid of each of the blobs. The centers of the atoms will be inferred from the centroid of each of the blobs.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(thresholds) print(thresholds)
atom_labels = list() atom_labels = list()
for thresh_map in thresholded_maps: for thresh_map in thresholded_maps:
labled_atoms = measure.label(thresh_map, background=0) labled_atoms = measure.label(thresh_map, background=0)
map_props = measure.regionprops(labled_atoms) map_props = measure.regionprops(labled_atoms)
atom_centroids = np.zeros(shape=(len(map_props),2)) atom_centroids = np.zeros(shape=(len(map_props),2))
for atom_ind, atom in enumerate(map_props): for atom_ind, atom in enumerate(map_props):
atom_centroids[atom_ind] = np.array(atom.centroid) atom_centroids[atom_ind] = np.array(atom.centroid)
atom_labels.append(atom_centroids) atom_labels.append(atom_centroids)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Visualize the atom positions ## Visualize the atom positions
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# overlay atom positions on original image # overlay atom positions on original image
fig, axis = plt.subplots(figsize=(8,8)) fig, axis = plt.subplots(figsize=(8,8))
axis.hold(True) axis.hold(True)
col_map = plt.cm.jet col_map = plt.cm.jet
axis.imshow(double_cropped_image, interpolation='none',cmap="gray") axis.imshow(double_cropped_image, interpolation='none',cmap="gray")
legend_handles = list() legend_handles = list()
for atom_type_ind, atom_centroids in enumerate(atom_labels): for atom_type_ind, atom_centroids in enumerate(atom_labels):
axis.scatter(atom_centroids[:,1], atom_centroids[:,0], color=col_map(int(255 * atom_type_ind / (num_motifs-1))), axis.scatter(atom_centroids[:,1], atom_centroids[:,0], color=col_map(int(255 * atom_type_ind / (num_motifs-1))),
label='Motif {}'.format(atom_type_ind), s=30) label='Motif {}'.format(atom_type_ind), s=30)
axis.set_xlim(0, double_cropped_image.shape[0]) axis.set_xlim(0, double_cropped_image.shape[0])
axis.set_ylim(0, double_cropped_image.shape[1]); axis.set_ylim(0, double_cropped_image.shape[1]);
axis.invert_yaxis() axis.invert_yaxis()
axis.set_xticklabels([]) axis.set_xticklabels([])
axis.set_yticklabels([]) axis.set_yticklabels([])
axis.get_xaxis().set_visible(False) axis.get_xaxis().set_visible(False)
axis.get_yaxis().set_visible(False) axis.get_yaxis().set_visible(False)
axis.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=14) axis.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=14)
axis.set_title('Atom Positions', fontsize=22) axis.set_title('Atom Positions', fontsize=22)
fig.tight_layout() fig.tight_layout()
#plt.show() #plt.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Save and close ### Save and close
* Save the .h5 file that we are working on by closing it. <br> * Save the .h5 file that we are working on by closing it. <br>
* Also, consider exporting this notebook as a notebook or an html file. <br> To do this, go to File >> Download as >> HTML * Also, consider exporting this notebook as a notebook or an html file. <br> To do this, go to File >> Download as >> HTML
* Finally consider saving this notebook if necessary * Finally consider saving this notebook if necessary
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
h5_file.close() h5_file.close()
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment