-
Notifications
You must be signed in to change notification settings - Fork 3
/
5b - PCA-classification-DF.py
360 lines (294 loc) · 13.1 KB
/
5b - PCA-classification-DF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # 5b - PCA classification: Dark Field data
# Here, we will use Principal Component Analysis to reduce the dimensionality of the measured dark field spectra, to visualize the spectra and to cluster the data, automatically assigning labels to different areas.
# This notebook is nominally the same as 5a, but applied to the dark field data and resulting in the dark field figures of the paper.
#
# First some preliminaries:
# +
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import dask.array as da
from dask_ml.decomposition import PCA
from dask_ml.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.preprocessing import Normalizer
from sklearn.pipeline import Pipeline, make_pipeline
from dask.distributed import Client
import time
import os
import xarray as xr
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
def to_niceRGB(image):
"""Use basis colors as suggested by P. Kovesi http://arxiv.org/abs/1509.03700"""
A = np.array([[0.90, 0.17, 0.00],
[0.00, 0.50, 0.00],
[0.10, 0.33, 1.00]])
return np.dot(image,A)
bRed = LinearSegmentedColormap.from_list('bRed', ['black', to_niceRGB([1,0,0])], N=256)
bBlue = LinearSegmentedColormap.from_list('bBlue', ['black', to_niceRGB([0,0,1])], N=256)
bGreen = LinearSegmentedColormap.from_list('bGreen', ['black', to_niceRGB([0,1,0])], N=256)
cmaps = [bRed, bGreen, bBlue]*2
colors = [to_niceRGB([1,0,0]), to_niceRGB([0,1,0]), to_niceRGB([0,0,1])]*2
SAVEFIG=True
client = Client()
client
# -
"""Do a principle component analysis on a stack of images and use this for clustering, both using Dask"""
dimensions = 6
coarsen = 1
# +
folder = './data'
name = '20171120_215555_3.5um_583.1_IVhdr_DF2'
# Clip out anything before mirror mode and a bit more because of image distortion
Erange = slice(100, 410)
x_slice = slice(442, 1380)
y_slice = slice(92, 960)
xdata = xr.open_dataset(os.path.join(folder, name +'_driftcorrected.nc'),
chunks={'x': 10 * coarsen, 'y': 10 * coarsen})
dset = xdata.Intensity.data
IVs = dset[Erange, x_slice, y_slice].rechunk(chunks=(-1, 10 * coarsen, 10 * coarsen))
fullIVs = dset[:, x_slice, y_slice].rechunk(chunks=(-1, 10 * coarsen, 10 * coarsen))
coarseIVs = IVs[:,::coarsen, ::coarsen].reshape((IVs.shape[0],-1)).T.persist()
IVs
# -
# Get metadata from netCDF file for plotting
EGY = xdata.Energy_set
multiplier = xdata.multiplier
plt.plot(EGY, multiplier)
# ## Principal Component Analysis
# To reduce the data to a reasonable number of dimensions, we use a pipeline of a standardscaler and PCA:
pca = PCA(n_components=dimensions, whiten=True, random_state=4)
pipe = make_pipeline(StandardScaler(), pca)
pipe_names = '_'.join(pipe.named_steps.keys())
pipe.fit(coarseIVs) # Fit the standard scaler and PCA vectors to the coarsened data
plt.figure(figsize=[3.5 ,3.5])
scree = np.concatenate([[0], pipe.named_steps['pca'].explained_variance_ratio_])
plt.scatter(np.arange(dimensions)+1, scree[1:], label='relative', facecolors='none', edgecolors=colors, linewidth=2)
plt.scatter(np.arange(dimensions+1), np.cumsum(scree), marker='+', label='cumulative', color='black', linewidth=2)
plt.ylabel('Explained variance')
plt.xlabel('Number of PCA components')
plt.axhline(0, color='black', alpha=0.5)
plt.legend(fontsize='large', scatterpoints=3)
plt.tight_layout()
plt.ylim([None,1])
if SAVEFIG:
plt.savefig(f'scree_plot_DF_{pipe_names}.pdf')
f"{dimensions} PCA components explain {scree.sum():.4f} of the total variance"
# The sign of the PCA vectors has a degeneracy dependent on the random initialization: minus a PCA vector explains as much variance as plus the vector, as we take a linear span.
#
# To make the visualization reproducible, the degeneracy of the sign of the PCA components needs to be lifted. Here, we align the signs such that positive vector corresponds to being brighter in the majority of the images.
# After this we can transform all original data to the reduced number of dimensions
pipe_diffs = pipe.inverse_transform(np.eye(dimensions)).compute()
signs = np.sign(np.nanmean((np.log(pipe_diffs) -
np.log(pipe.named_steps['standardscaler'].mean_)),
axis=1))
pipe.named_steps['pca'].components_ *= signs[:,np.newaxis]
signs
rIVs = pipe.transform(IVs.reshape(IVs.shape[0], -1).T).persist()
# To visualize the dimension reduction, we calculate the spectra corresponding to the extrema of the components, as well as the spectra _occuring in the dataset_ with the extreme values of the components:
# +
argextrema = da.concatenate([rIVs[rIVs.argmin(axis=0), :],
rIVs[rIVs.argmax(axis=0), :]])
argextrema = pipe.inverse_transform(argextrema) / multiplier[Erange]
argextrema = argextrema.reshape((2, 6, -1))
extrema = da.concatenate([da.diag(rIVs.min(axis=0)),
da.diag(rIVs.max(axis=0))])
extrema = pipe.inverse_transform(extrema) / multiplier[Erange]
extrema = extrema.reshape((2, 6, -1))
argextrema, extrema = da.compute(argextrema, extrema)
# -
fig,axs = plt.subplots(2, dimensions, figsize=[10, 3.5],
sharex='row', sharey='row',
constrained_layout=True)
E = EGY[Erange]
for i in range(dimensions):
axs[0,i].imshow(rIVs[:,i].reshape(IVs.shape[1:]).T, interpolation='none', cmap=cmaps[i])
axs[0,i].set_title('PCA component {}'.format(i+1), fontsize='small')
axs[1,i].plot(E, argextrema[1][i], color=cmaps[i](1.0), linestyle=':')
axs[1,i].plot(E, argextrema[0][i], color=cmaps[i](0.0), linestyle=':')
axs[1,i].plot(E, extrema[1][i], color=cmaps[i](1.0), alpha=0.6)
axs[1,i].plot(E, extrema[0][i], color=cmaps[i](0.0), alpha=0.6)
axs[1,i].set_yscale('log')
axs[1,i].set_xlabel('$E_0$ (eV)')
axs[1,i].margins(x=0)
axs[1,0].set_ylabel('Intensity')
if SAVEFIG:
plt.savefig(f'DF_PCAcomponents_{pipe_names}.pdf')
# ## Visualization
#
# To visualize the dataset, we combine the PCA components in groups of three, and use these as RGB images in real space:
# +
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=[6, 3], constrained_layout=True)
img = rIVs[:, :3].reshape(IVs.shape[1:] + (3,)).swapaxes(0, 1)
img = img - img.min(axis=(0, 1), keepdims=True)
img = img / img.max(axis=(0, 1), keepdims=True)
ax1.imshow(to_niceRGB(img), interpolation='none')
ax1.set_title('DF PCA component 1 to 3')
img = rIVs[:, 3:6].reshape(IVs.shape[1:] + (3,)).swapaxes(0, 1)
img = img - img.min(axis=(0, 1), keepdims=True)
img = img / img.max(axis=(0, 1), keepdims=True)
ax2.imshow(to_niceRGB(img), interpolation='none')
ax2.set_title('DF PCA component 4 to 6')
if SAVEFIG:
plt.savefig(f'DF_visualization_{pipe_names}.pdf')
# -
# ## Clustering: $k$-means
# To assign labels to different spectra, we cluster using a standard unsupervised machine learning algorithm: $k$-means:
rIVs = rIVs.compute()
kmeans_d = 4
from sklearn.metrics import silhouette_samples, silhouette_score
scores = []
klabels = np.arange(3,12)
for n in klabels:
clusterer = KMeans(n_clusters=n, random_state=10)
cl_labels = clusterer.fit_predict(rIVs[::20,:kmeans_d])
print(n, "fit_predicted")
scores.append(silhouette_score(rIVs[::20,:kmeans_d], cl_labels))
print(f"{n} clusters, score = {scores[-1]}")
plt.plot(klabels, scores)
plt.ylabel('Silhoutte score')
plt.xlabel('$n_{clusters}$')
print('Performing clustering via KMeans', rIVs[:,:kmeans_d].shape)
kmeans = KMeans(n_clusters=8, random_state=10, n_jobs=-1).fit(rIVs[:,:kmeans_d])
clustering = kmeans.predict(rIVs[:,:kmeans_d])
# For visualization of curves corresponding to clusters, we grab the full spectra, filter out points where the spectrum was not measured due to drift and calculate the mean per image per spectrum.
validIVs = da.where(fullIVs == 0, np.nan, fullIVs).reshape((fullIVs.shape[0],-1))
meanIVs = [da.nanmean(validIVs[:,clustering == index], axis=1)
for index in range(kmeans.n_clusters)]
# +
tstart = time.time()
print('plotting clustering data')
fig2,axs = plt.subplots(2,4, figsize=[11,5], dpi=600)
#In case of 1 out of 1 columns figure
axs = np.transpose(axs)
coarse_2d = 3*coarsen
color = rIVs[::coarse_2d,:3]
center_colors = kmeans.cluster_centers_[:,:3] - color.min(axis=0)
color = color - color.min(axis=0, keepdims=True)
center_colors = center_colors / color.max(axis=0)
center_colors = to_niceRGB(center_colors)
color = color / color.max(axis=0,keepdims=True)
color = to_niceRGB(color)
newcmap = ListedColormap(center_colors)
colorargs = {'cmap': newcmap, 'vmin': 0, 'vmax': 8}
axs[0,0].scatter(rIVs[::coarse_2d, 0],
rIVs[::coarse_2d, 1],
c=color, s=0.2, alpha=0.2,
**colorargs, rasterized=True,
)
axs[0,1].scatter(rIVs[::coarse_2d, 0],
rIVs[::coarse_2d, 2],
c=color, s=0.2, alpha=0.2,
**colorargs, rasterized=True,
)
for i in [0,1,2]:
axs[i,0].set_ylabel("Pca dim 1", color=colors[1], fontweight=700)
axs[i,0].set_xlabel("Pca dim 0", color=colors[0], fontweight=700)
axs[i,1].set_ylabel("Pca dim 2", color=colors[2], fontweight=700)
axs[i,1].set_xlabel("Pca dim 0", color=colors[0], fontweight=700)
hist, edges = np.histogramdd(rIVs[:,:3], bins=200,
range=[axs[0,0].get_xlim(),
axs[0,0].get_ylim(),
axs[0,1].get_ylim()])
edges = np.array(edges)
#xedges, yedges, zedges = edges[0], edges[1], edges[2]
axs[1,0].imshow(hist.sum(axis=-1)[:,::-1].T,
extent=[edges[0,0], edges[0,-1],
edges[1,0], edges[1,-1]],
aspect='auto',
cmap='gray_r')
axs[1,1].imshow(hist.sum(axis=1)[:,::-1].T,
extent=[edges[0,0], edges[0,-1],
edges[2,0], edges[2,-1]],
aspect='auto',
cmap='gray_r')
colorargs['cmap'] = 'tab10'
colorargs['vmax'] = 10
axs[2,0].scatter(rIVs[::coarse_2d,0], rIVs[::coarse_2d,1], c=clustering[::coarse_2d], s=0.2, alpha=0.2,
**colorargs, rasterized=True,
)
axs[2,1].scatter(rIVs[::coarse_2d,0], rIVs[::coarse_2d,2], c=clustering[::coarse_2d], s=0.2, alpha=0.2,
**colorargs, rasterized=True,
)
clusteringimg = clustering.reshape((IVs.shape[1],IVs.shape[2]))
axs[3,0].imshow(clusteringimg.T,
**colorargs
)
for i,v in enumerate(kmeans.cluster_centers_):
axs[1,0].scatter(v[0], v[1], s=20, color=center_colors[i])
axs[1,1].scatter(v[0], v[2], s=20, color=center_colors[i])
print("Time elapsed: {}".format(time.time()-tstart))
meanIVs = da.compute(*meanIVs)
print("Time elapsed: {}".format(time.time()-tstart))
for i,meanIV in enumerate(meanIVs):
axs[3,1].plot(xdata.Energy, (meanIV / multiplier),) # color=center_colors[i], alpha=0.75)
axs[3,1].set_yscale('log')
axs[3,1].set_xlabel('Energy (eV)')
axs[3,1].set_ylabel('Reflectivity ()')
axs[3,1].margins(x=0)
axs[3,0].set_xlabel(r'$x$ (pixels)')
axs[3,0].set_ylabel(r'$y$ (pixels)')
#In case of 1 out of two columns figure
#for ax in axs[:,1]:
#ax.yaxis.set_label_position("right")
#ax.tick_params(axis='y', labelright=True, labelleft=False)
plt.tight_layout()
print("Time elapsed: {}".format(time.time()-tstart))
if SAVEFIG:
plt.savefig('clustering_DF_2_0_perp.pdf', dpi=600)
print("Total time elapsed: {}".format(time.time()-tstart))
# +
tstart = time.time()
print('plotting clustering data')
fig2 = plt.figure(figsize=[2.8,5], dpi=600)
axs = np.array([fig2.add_subplot(211), fig2.add_subplot(212)])
coarse_2d = 3*coarsen
color = rIVs[::coarse_2d,:3]
center_colors = kmeans.cluster_centers_[:,:3] - color.min(axis=0)
color = color - color.min(axis=0, keepdims=True)
center_colors = center_colors / color.max(axis=0)
center_colors = to_niceRGB(center_colors)
color = color / color.max(axis=0,keepdims=True)
color = to_niceRGB(color)
newcmap = ListedColormap(center_colors)
colorargs = {'cmap': newcmap, 'vmin': 0, 'vmax': 8}
edges = np.array(edges)
#xedges, yedges, zedges = edges[0], edges[1], edges[2]
colorargs['cmap'] = 'tab10'
colorargs['vmax'] = 10
clusteringimg = clustering.reshape((IVs.shape[1],IVs.shape[2]))
axs[0].imshow(clusteringimg.T,
**colorargs
)
for i,meanIV in enumerate(meanIVs):
axs[1].plot(xdata.Energy, (meanIV / multiplier),) # color=center_colors[i], alpha=0.75)
axs[1].set_yscale('log')
axs[1].set_xlabel('Energy (eV)')
axs[1].set_ylabel('Reflectivity')
axs[1].margins(x=0)
axs[0].set_xlabel(r'$x$ (pixels)')
axs[0].set_ylabel(r'$y$ (pixels)')
#In case of 1 out of two columns figure
#for ax in axs[:,1]:
#ax.yaxis.set_label_position("right")
#ax.tick_params(axis='y', labelright=True, labelleft=False)
plt.tight_layout()
print("Time elapsed: {}".format(time.time()-tstart))
if SAVEFIG:
plt.savefig('clustering_DF_3_0.pdf', dpi=600)
print("Total time elapsed: {}".format(time.time()-tstart))
# -