Commit 40e3b999 authored by Unknown's avatar Unknown
Browse files

Merge remote-tracking branch 'origin/cades_dev'

parents 757fdebe 5f9d8206
......@@ -49,15 +49,26 @@ Core development
1. Check if the same process has been performed with the same paramters. When initializing the process, throw an exception. This is better than checking in the notebook stage.
2. (Gracefully) Abort and resume processing.
* consolidate _get_component_slice used in Cluster with duplicate in svd_utils
* Legacy processes **MUST** extend Process:
* Image Windowing
* Image Cleaning
* sklearn wrapper classes:
* Cluter
* Decomposition
* The computation will continue to be performed by sklearn. No need to use parallel_compute() or resume computation.
* Own classes:
* Image Windowing
* Image Cleaning
* As time permits, ensure that these can resume processing
* All these MUST implement the check for previous computations at the very least
* As time permits, ensure that these can resume processing
* Absorb functionality from Process into Model
* Bayesian GIV should actually be an analysis <-- depends on above
* Reogranize processing and analysis - promote / demote classes etc.
* multi-node computing capability in parallel_compute
* Demystify analyis / optimize. Use parallel_compute instead of optimize and guess_methods and fit_methods
* Consistency in the naming of and placement of attributes (chan or meas group) in all translators - Some put attributes in the measurement level, some in the channel level! hyperspy appears to create datagroups solely for the purpose of organizing metadata in a tree structure!
* Consider developing a generic curve fitting class a la `hyperspy <http://nbviewer.jupyter.org/github/hyperspy/hyperspy-demos/blob/master/Fitting_tutorial.ipynb>`_
......
......@@ -181,8 +181,8 @@ px.plot_utils.plot_map_stack(abun_maps, num_comps=9, heading='SVD Abundance Maps
num_clusters = 4
estimators = px.Cluster(h5_main, 'KMeans', n_clusters=num_clusters)
h5_kmeans_grp = estimators.do_cluster(h5_main)
estimators = px.Cluster(h5_main, KMeans(n_clusters=num_clusters))
h5_kmeans_grp = estimators.compute(h5_main)
h5_kmeans_labels = h5_kmeans_grp['Labels']
h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response']
......
......@@ -181,8 +181,8 @@ px.plot_utils.plot_map_stack(abun_maps, num_comps=9, heading='SVD Abundance Maps
num_clusters = 4
estimators = px.Cluster(h5_main, 'KMeans', n_clusters=num_clusters)
h5_kmeans_grp = estimators.do_cluster(h5_main)
estimators = px.Cluster(h5_main, KMeans(n_clusters=num_clusters))
h5_kmeans_grp = estimators.compute(h5_main)
h5_kmeans_labels = h5_kmeans_grp['Labels']
h5_kmeans_mean_resp = h5_kmeans_grp['Mean_Response']
......
%% Cell type:markdown id: tags:
# Image cleaning and atom finding using pycroscopy
### Suhas Somnath, Chris R. Smith, Stephen Jesse
The Center for Nanophase Materials Science and The Institute for Functional Imaging for Materials <br>
Oak Ridge National Laboratory<br>
1/19/2017
%% Cell type:markdown id: tags:
## Configure the notebook first
%% Cell type:code id: tags:
``` python
!pip install -U numpy scipy skimage h5py matplotlib Ipython ipywidgets pycroscopy
# set up notebook to show plots within the notebook
% matplotlib notebook
# Import necessary libraries:
# General utilities:
import os
import sys
from time import time
from scipy.misc import imsave
# Computation:
import numpy as np
import h5py
from skimage import measure
from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import pdist
from sklearn.cluster import KMeans
# Visualization:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from mpl_toolkits.axes_grid1 import make_axes_locatable
from IPython.display import display, HTML
import ipywidgets as widgets
from mpl_toolkits.axes_grid1 import ImageGrid
# Finally, pycroscopy itself
sys.path.append('..')
import pycroscopy as px
# Make Notebook take up most of page width
display(HTML(data="""
<style>
div#notebook-container { width: 95%; }
div#menubar-container { width: 65%; }
div#maintoolbar-container { width: 99%; }
</style>
"""))
```
%% Cell type:markdown id: tags:
## Load the image that will be cleaned:
%% Cell type:code id: tags:
``` python
image_path = px.io.uiGetFile('*.png *PNG *TIFF * TIF *tif *tiff *BMP *bmp','Images')
print('Working on: \n{}'.format(image_path))
folder_path, file_name = os.path.split(image_path)
base_name, _ = os.path.splitext(file_name)
```
%% Cell type:markdown id: tags:
## 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
#### 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 readily compatible with high-performance computing facilities
* 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.
%% Cell type:code id: tags:
``` python
# Check if an HDF5 file with the chosen image already exists.
# Only translate if it does not.
h5_path = os.path.join(folder_path, base_name+'.h5')
need_translation = True
if os.path.exists(h5_path):
try:
h5_file = h5py.File(h5_path, 'r+')
h5_raw = h5_file['Measurement_000']['Channel_000']['Raw_Data']
need_translation = False
print('HDF5 file with Raw_Data found. No need to translate.')
except KeyError:
print('Raw Data not found.')
else:
print('No HDF5 file found.')
if need_translation:
# Initialize the Image Translator
tl = px.ImageTranslator()
# create an H5 file that has the image information in it and get the reference to the dataset
h5_raw = tl.translate(image_path)
# create a reference to the file
h5_file = h5_raw.file
print('HDF5 file is located at {}.'.format(h5_file.filename))
```
%% Cell type:markdown id: tags:
### 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 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
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....
The spectroscopic information is trivial since the data at any given pixel is just a scalar value
%% Cell type:code id: tags:
``` python
print('Datasets and datagroups within the file:')
px.io.hdf_utils.print_tree(h5_file)
print('\nThe main dataset:')
print(h5_file['/Measurement_000/Channel_000/Raw_Data'])
print('\nThe ancillary datasets:')
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/Spectroscopic_Indices'])
print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Values'])
print('\nMetadata or attributes in a datagroup')
for key in h5_file['/Measurement_000'].attrs:
print('{} : {}'.format(key, h5_file['/Measurement_000'].attrs[key]))
```
%% Cell type:markdown id: tags:
## 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
%% Cell type:code id: tags:
``` python
# Initialize the windowing class
iw = px.ImageWindow(h5_raw, max_RAM_mb=1024*4)
# grab position indices from the H5 file
h5_pos = h5_raw.parent[h5_raw.attrs['Position_Indices']]
# determine the image size:
num_x = len(np.unique(h5_pos[:,0]))
num_y = len(np.unique(h5_pos[:,1]))
# extract figure data and reshape to proper numpy array
raw_image_mat = np.reshape(h5_raw[()], [num_x,num_y]);
```
%% Cell type:markdown id: tags:
## Visualize the source image:
Though the source file is actually grayscale image, we will visualize it using a color-scale
%% Cell type:code id: tags:
``` python
fig, axis = plt.subplots(figsize=(10,10))
img = axis.imshow(raw_image_mat,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower');
divider = make_axes_locatable(axis)
cax = divider.append_axes("right", size="5%", pad=0.2)
plt.colorbar(img, cax=cax)
px.plot_utils.plot_map(axis, raw_image_mat, cmap=px.plot_utils.cmap_jet_white_center())
axis.set_title('Raw Image', fontsize=16);
```