# Basic data analysis - Spectral Unmixing, KMeans, PCA, NFINDR etc.
R. K. Vasudevan<sup>1,2</sup>, S. Somnath<sup>3</sup>
*<sup>1</sup>Center for Nanophase Materials Sciences
*<sup>2</sup>Institute for Functional Imaging of Materials
*<sup>3</sup>Advanced Data and Workflows Group
Oak Ridge National Laboratory, Oak Ridge TN 37831, USA
#### In this notebook we load some spectral data, and perform basic data analysis, including:
* KMeans Clustering
* Non-negative Matrix Factorization
* Principal Component Analysis
* NFINDR
%% Cell type:markdown id: tags:
## Software Prerequisites:
* Standard distribution of ___Anaconda__ (includes numpy, scipy, matplotlib and sci-kit learn)
* __pysptools__ (will automatically be installed in the next step)
* __cvxopt__ for fully constrained least squares fitting
* install in a terminal via __`conda install -c https://conda.anaconda.org/omnia cvxopt`__
* __pycroscopy__ : Though pycroscopy is mainly used here for plotting purposes only, it's true capabilities are realized through the ability to seamlessly perform these analyses on any imaging dataset (regardless of origin, size, complexity) and storing the results back into the same dataset among other things
%% Cell type:code id: tags:
``` python
# Installing sotware prerequisites via the python package index:
!pipinstall-Unumpymatplotlibsklearnpysptoolswget
#Import packages
# Ensure that this code works on both python 2 and python 3
# configure the notebook to place plots after code cells within the notebook:
%matplotlibinline
```
%% Cell type:markdown id: tags:
## The Data
In this example, we will work on __Infrared (IR) Spectra__ data obtained from an Anasys Instruments Nano IR as one of the simplest examples of data. This dataset contains a single IR spectra collected at each position on a single line of spatial points. Thus, this two dimensional dataset has one position dimension (lets say X) and one spectral dimension (wavelength).
In the event that the spectra were collected on a 2D grid of spatial locations (two spatial dimensions - X, Y), the resultant three dimensional dataset (X, Y, wavelength) would need to be reshaped to a two dimensional dataset of (position, wavelength) since this is the standard format that is accepted by all statistical analysis, machine learning, spectral unmixing algorithms. The same reshaping of data would need to be performed if there are more than two spectroscopic dimensions.
#### Working with the specific Nano IR dataset:
We will begin by downloading the data file from Github, followed by reshaping and decimation of the dataset
# See if a tree has been created within the hdf5 file:
px.hdf_utils.print_tree(h5_file)
```
%% Cell type:markdown id: tags:
## Extracting the data and parameters
All necessary information to understand, plot, analyze, and process the data is present in the H5 file now. Here, we show how to extract some basic parameters to plot the data
SVD is an eigenvector decomposition that is defined statistically, and therefore typically produces non-physical eigenvectors. Consequently, the interpretation of eigenvectors and abundance maps from SVD requires care and caution in interpretation. Nontheless, it is a good method for quickly visualizing the major trends in the dataset since the resultant eigenvectors are sorted in descending order of variance or importance. Furthermore, SVD is also very well suited for data cleaning through the reconstruction of the dataset using only the first N (most significant) components.
SVD results in three matrices:
* V - Eigenvectors sorted by variance in descending order
* U - corresponding bundance maps
* S - Variance or importance of each of these components
%% Cell type:code id: tags:
``` python
h5_svd_grp=px.processing.doSVD(h5_main)
U=h5_svd_grp['U']
S=h5_svd_grp['S']
V=h5_svd_grp['V']
# Visualize the variance / statistical importance of each component:
px.plot_utils.plotScree(S,title='Note the exponential drop of variance with number of components')
KMeans clustering is a quick and easy method to determine the types of spectral responses present in the data. It is not a decomposition method, but a basic clustering method. The user inputs the number of clusters (sets) to partition the data into. The algorithm proceeds to find the optimal labeling (ie., assignment of each spectra as belonging to the k<sup>th</sup> set) such that the within-cluster sum of squares is minimized.
NMF, or non-negative matrix factorization, is a method that is useful towards unmixing of spectral data. It only works on data with positive real values. It operates by approximate determination of factors (matrices) W and H, given a matrix V, as shown below
NFINDR is a geometric decomposition technique that can aid in determination of constitent spectra in data. The basic idea is as follows. Assume that at any point <i>x</i>, the spectra measured <i>A(w,x)</i> is a linear superposition of <i>k</i> 'pure' spectra, i.e.
In this case, our task consists of first determining the pure spectra {a<sub>0</sub>,...,a<sub>k</sub>}, and then determining the coefficients {c<sub>0</sub>,...,c<sub>k</sub>}. NFINDR determines the 'pure' spectra by first projecting the data into a low-dimensional sub-space (typically using PCA), and then taking the convex hull of the points in this space. Then, points are picked at random along the convex hull and the volume of the simplex that the points form is determined. If (k+1) pure spectra are needed, the data is reduced to (k) dimensions for this purpose. The points that maximize the volume of the simples are taken as the most representative pure spectra available in the dataset. One way to think of this is that any spectra that lie within the given volume can be represented as a superposition of these constituent spectra; thus maximizing this volume allows the purest spectra to be determined.
The second task is to determine the coefficients. This is done usign the fully constrained least squares optimization, and involves the sum-to-one constraint, to allow quantitative comparisons to be made. More information can be found in the paper below:
[Winter, Michael E. "N-FINDR: An algorithm for fast autonomous spectral end-member determination in hyperspectral data." SPIE's International Symposium on Optical Science, Engineering, and Instrumentation. International Society for Optics and Photonics, 1999.](http://proceedings.spiedigitallibrary.org/proceeding.aspx?articleid=994814)