Image_Cleaning_Atom_Finding.ipynb 46.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Image cleaning and atom finding using pycroscopy\n",
    "### Suhas Somnath, Chris R. Smith, Stephen Jesse\n",
    "The Center for Nanophase Materials Science and The Institute for Functional Imaging for Materials <br>\n",
    "Oak Ridge National Laboratory<br>\n",
    "1/19/2017"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configure the notebook first"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
24
   "metadata": {},
25
26
   "outputs": [],
   "source": [
Unknown's avatar
Unknown committed
27
    "!pip install -U numpy scipy skimage h5py matplotlib Ipython ipywidgets pycroscopy\n",
28
    "# set up notebook to show plots within the notebook\n",
Unknown's avatar
Unknown committed
29
    "% matplotlib notebook\n",
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
    "\n",
    "# Import necessary libraries:\n",
    "# General utilities:\n",
    "import os\n",
    "import sys\n",
    "from time import time\n",
    "from scipy.misc import imsave\n",
    "\n",
    "# Computation:\n",
    "import numpy as np\n",
    "import h5py\n",
    "from skimage import measure\n",
    "from scipy.cluster.hierarchy import linkage, dendrogram\n",
    "from scipy.spatial.distance import pdist \n",
    "\n",
    "# Visualization:\n",
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.patches as patches\n",
    "from mpl_toolkits.axes_grid1 import make_axes_locatable\n",
Unknown's avatar
Unknown committed
49
    "from IPython.display import display, HTML\n",
50
51
52
53
    "import ipywidgets as widgets\n",
    "from mpl_toolkits.axes_grid1 import ImageGrid\n",
    "\n",
    "# Finally, pycroscopy itself\n",
Unknown's avatar
Unknown committed
54
55
56
57
58
59
60
61
62
63
64
    "sys.path.append('..')\n",
    "import pycroscopy as px\n",
    "\n",
    "# Make Notebook take up most of page width\n",
    "display(HTML(data=\"\"\"\n",
    "<style>\n",
    "    div#notebook-container    { width: 95%; }\n",
    "    div#menubar-container     { width: 65%; }\n",
    "    div#maintoolbar-container { width: 99%; }\n",
    "</style>\n",
    "\"\"\"))"
65
66
67
68
69
70
71
72
73
74
75
76
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load the image that will be cleaned:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
77
   "metadata": {},
78
79
   "outputs": [],
   "source": [
Unknown's avatar
Unknown committed
80
    "image_path = px.io.uiGetFile('*.png *PNG *TIFF * TIF *tif *tiff *BMP *bmp','Images')\n",
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
    "\n",
    "print('Working on: \\n{}'.format(image_path))\n",
    "\n",
    "folder_path, file_name = os.path.split(image_path)\n",
    "base_name, _ = os.path.splitext(file_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Make the image file pycroscopy compatible\n",
    "Convert the source image file into a pycroscopy compatible hierarchical data format (HDF or .h5) file. This simple translation gives you access to the powerful data functions within pycroscopy\n",
    "\n",
    "#### H5 files:\n",
    "* are like smart containers that can store matrices with data, folders to organize these datasets, images, metadata like experimental parameters, links or shortcuts to datasets, etc.\n",
    "* are readily compatible with high-performance computing facilities\n",
    "* scale very efficiently from few kilobytes to several terabytes\n",
    "* can be read and modified using any language including Python, Matlab, C/C++, Java, Fortran, Igor Pro, etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
105
   "metadata": {},
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
   "outputs": [],
   "source": [
    "# Check if an HDF5 file with the chosen image already exists.\n",
    "# Only translate if it does not.\n",
    "h5_path = os.path.join(folder_path, base_name+'.h5')\n",
    "need_translation = True\n",
    "if os.path.exists(h5_path):\n",
    "    try:\n",
    "        h5_file = h5py.File(h5_path, 'r+')\n",
    "        h5_raw = h5_file['Measurement_000']['Channel_000']['Raw_Data']\n",
    "        need_translation = False\n",
    "        print('HDF5 file with Raw_Data found.  No need to translate.')\n",
    "    except KeyError:\n",
    "        print('Raw Data not found.')\n",
    "else:\n",
    "    print('No HDF5 file found.')\n",
    "\n",
    "if need_translation:\n",
    "    # Initialize the Image Translator\n",
    "    tl = px.ImageTranslator()\n",
    "\n",
    "    # create an H5 file that has the image information in it and get the reference to the dataset\n",
    "    h5_raw = tl.translate(image_path)\n",
    "\n",
    "    # create a reference to the file\n",
    "    h5_file = h5_raw.file\n",
    "\n",
    "print('HDF5 file is located at {}.'.format(h5_file.filename))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Inspect the contents of this h5 data file\n",
    "The file contents are stored in a tree structure, just like files on a contemporary computer.\n",
    "The data is stored as a 2D matrix (position, spectroscopic value) regardless of the dimensionality of the data.  \n",
    "In the case of these 2D images, the data is stored as a N x 1 dataset\n",
    "\n",
    "The main dataset is always accompanied by four ancillary datasets that explain the position and spectroscopic value of any given element in the dataset.\n",
    "In the case of the 2d images, the positions will be arranged as row0-col0, row0-col1.... row0-colN, row1-col0....\n",
    "The spectroscopic information is trivial since the data at any given pixel is just a scalar value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
153
   "metadata": {},
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
   "outputs": [],
   "source": [
    "print('Datasets and datagroups within the file:')\n",
    "px.io.hdf_utils.print_tree(h5_file)\n",
    " \n",
    "print('\\nThe main dataset:')\n",
    "print(h5_file['/Measurement_000/Channel_000/Raw_Data'])\n",
    "print('\\nThe ancillary datasets:')\n",
    "print(h5_file['/Measurement_000/Channel_000/Position_Indices'])\n",
    "print(h5_file['/Measurement_000/Channel_000/Position_Values'])\n",
    "print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Indices'])\n",
    "print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Values'])\n",
    "\n",
    "print('\\nMetadata or attributes in a datagroup')\n",
    "for key in h5_file['/Measurement_000'].attrs:\n",
    "    print('{} : {}'.format(key, h5_file['/Measurement_000'].attrs[key]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initialize an object that will perform image windowing on the .h5 file\n",
    "* Note that after you run this, the H5 file is opened. If you want to re-run this cell, close the H5 file first"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
183
   "metadata": {},
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
   "outputs": [],
   "source": [
    "# Initialize the windowing class\n",
    "iw = px.ImageWindow(h5_raw, max_RAM_mb=1024*4)\n",
    "\n",
    "# grab position indices from the H5 file\n",
    "h5_pos = h5_raw.parent[h5_raw.attrs['Position_Indices']]\n",
    "\n",
    "# determine the image size:\n",
    "num_x = len(np.unique(h5_pos[:,0]))\n",
    "num_y = len(np.unique(h5_pos[:,1]))\n",
    "\n",
    "# extract figure data and reshape to proper numpy array\n",
    "raw_image_mat = np.reshape(h5_raw[()], [num_x,num_y]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualize the source image:\n",
    "Though the source file is actually grayscale image, we will visualize it using a color-scale"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
211
   "metadata": {},
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
   "outputs": [],
   "source": [
    "fig, axis = plt.subplots(figsize=(10,10))\n",
    "img = axis.imshow(raw_image_mat,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower');\n",
    "divider = make_axes_locatable(axis)\n",
    "cax = divider.append_axes(\"right\", size=\"5%\", pad=0.2)\n",
    "plt.colorbar(img, cax=cax)\n",
    "axis.set_title('Raw Image', fontsize=16);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extract the optimal window size from the image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
232
   "metadata": {},
233
234
235
236
237
238
239
240
241
242
243
   "outputs": [],
   "source": [
    "num_peaks = 2\n",
    "win_size , psf_width = iw.window_size_extract(num_peaks, save_plots=False, show_plots=True)\n",
    "\n",
    "print('Window size = {}'.format(win_size))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
244
   "metadata": {},
245
246
247
248
249
250
251
252
   "outputs": [],
   "source": [
    "# Uncomment this line if you need to manually specify a window size\n",
    "# win_size = 8\n",
    "\n",
    "# plot a single window\n",
    "row_offset = int(0.5*(num_x-win_size))\n",
    "col_offset = int(0.5*(num_y-win_size))\n",
Unknown's avatar
Unknown committed
253
    "plt.figure()\n",
254
255
256
    "plt.imshow(raw_image_mat[row_offset:row_offset+win_size,\n",
    "                         col_offset:col_offset+win_size], \n",
    "           cmap=px.plot_utils.cmap_jet_white_center(),\n",
Unknown's avatar
Unknown committed
257
    "           origin='lower');\n",
258
259
    "\n",
    "# the result should be about the size of a unit cell\n",
Unknown's avatar
Unknown committed
260
261
    "# if it is the wrong size, just choose on manually by setting the win_size\n",
    "plt.show()"
262
263
264
265
266
267
268
269
270
271
272
273
274
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Now break the image into a sequence of small windows\n",
    "We do this by sliding a small window across the image. This artificially baloons the size of the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
275
   "metadata": {},
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
   "outputs": [],
   "source": [
    "windowing_parms = {\n",
    "    'fft_mode': None, # Options are None, 'abs', 'data+abs', or 'complex'\n",
    "    'win_x': win_size,\n",
    "    'win_y': win_size,\n",
    "    'win_step_x': 1,\n",
    "    'win_step_y': 1,\n",
    "}\n",
    "\n",
    "win_parms_copy = windowing_parms.copy()\n",
    "if windowing_parms['fft_mode'] is None:\n",
    "        win_parms_copy['fft_mode'] = 'data'\n",
    "\n",
    "h5_wins_grp = px.hdf_utils.check_for_old(h5_raw, 'Windowing',\n",
    "                           win_parms_copy)\n",
    "if h5_wins_grp is None:\n",
    "    print('Windows either do not exist or were created with different parameters')\n",
    "    t0 = time()\n",
    "    h5_wins = iw.do_windowing(win_x=windowing_parms['win_x'],\n",
    "                              win_y=windowing_parms['win_y'],\n",
    "                              save_plots=False,\n",
    "                              show_plots=False,\n",
    "                              win_fft=windowing_parms['fft_mode'])\n",
    "    print( 'Windowing took {} seconds.'.format(round(time()-t0, 2)))\n",
    "else:\n",
    "    print('Taking existing windows dataset')\n",
    "    h5_wins = h5_wins_grp['Image_Windows']\n",
    "    \n",
    "print('\\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape))\n",
    "print('Now each position (window) is descibed by a set of pixels')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
312
   "metadata": {},
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
   "outputs": [],
   "source": [
    "# Peek at a few random windows\n",
    "num_rand_wins = 9\n",
    "rand_positions = np.random.randint(0, high=h5_wins.shape[0], size=num_rand_wins)\n",
    "example_wins = np.zeros(shape=(windowing_parms['win_x'], windowing_parms['win_y'], num_rand_wins), dtype=np.float32)\n",
    "\n",
    "for rand_ind, rand_pos in enumerate(rand_positions):\n",
    "    example_wins[:, :, rand_ind] = np.reshape(h5_wins[rand_pos], (windowing_parms['win_x'], windowing_parms['win_y']))\n",
    "    \n",
    "px.plot_utils.plot_map_stack(example_wins, heading='Example Windows', cmap=px.plot_utils.cmap_jet_white_center(),\n",
    "                             title=['Window # ' + str(win_pos) for win_pos in rand_positions]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Performing Singular Value Decompostion (SVD) on the windowed data\n",
    "SVD decomposes data (arranged as position x value) into a sequence of orthogonal components arranged in descending order of variance. The first component contains the most significant trend in the data. The second component contains the next most significant trend orthogonal to all previous components (just the first component). Each component consists of the trend itself (eigenvector), the spatial variaion of this trend (eigenvalues), and the variance (statistical importance) of the component.\n",
    "\n",
    "Since the data consists of the large sequence of small windows, SVD essentially compares every single window with every other window to find statistically significant trends in the image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
340
   "metadata": {},
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
   "outputs": [],
   "source": [
    "# check to make sure number of components is correct:\n",
    "num_comp = 1024\n",
    "num_comp = min(num_comp, \n",
    "                min(h5_wins.shape)*len(h5_wins.dtype))\n",
    "\n",
    "h5_svd = px.hdf_utils.check_for_old(h5_wins, 'SVD', {'num_components':num_comp})\n",
    "if h5_svd is None:\n",
    "    print('SVD was either not performed or was performed with different parameters')\n",
    "    h5_svd = px.processing.doSVD(h5_wins, num_comps=num_comp)\n",
    "else:\n",
    "    print('Taking existing SVD results')\n",
    "    \n",
    "h5_U = h5_svd['U']\n",
    "h5_S = h5_svd['S']\n",
    "h5_V = h5_svd['V']\n",
    "\n",
    "# extract parameters of the SVD results \n",
    "h5_pos = iw.hdf.file[h5_wins.attrs['Position_Indices']]\n",
    "num_rows = len(np.unique(h5_pos[:, 0]))\n",
    "num_cols = len(np.unique(h5_pos[:, 1]))\n",
    "\n",
    "num_comp = h5_S.size\n",
    "print(\"There are a total of {} components.\".format(num_comp))\n",
    "    \n",
    "print('\\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape))\n",
    "print('Now each position (window) is descibed by a set of pixels')\n",
    "\n",
    "plot_comps = 49\n",
    "U_map_stack = np.reshape(h5_U[:, :plot_comps], [num_rows, num_cols, -1])\n",
    "V_map_stack = np.reshape(h5_V, [num_comp, win_size, win_size])\n",
    "V_map_stack = np.transpose(V_map_stack,(2,1,0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualize the SVD results\n",
    "\n",
    "##### S (variance):\n",
    "The plot below shows the variance or statistical significance of the SVD components. The first few components contain the most significant information while the last few components mainly contain noise. \n",
    "\n",
    "Note also that the plot below is a log-log plot. The importance of each subsequent component drops exponentially."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
391
   "metadata": {},
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
   "outputs": [],
   "source": [
    "fig_S, ax_S = px.plot_utils.plotScree(h5_S[()]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### V (Eigenvectors or end-members)\n",
    "The V dataset contains the end members for each component"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
Unknown's avatar
Unknown committed
409
    "scrolled": true
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
   },
   "outputs": [],
   "source": [
    "for field in V_map_stack.dtype.names:\n",
    "    fig_V, ax_V = px.plot_utils.plot_map_stack(V_map_stack[:,:,:][field], heading='', title='Vector-'+field, num_comps=plot_comps, \n",
    "                                               color_bar_mode='each', cmap=px.plot_utils.cmap_jet_white_center())   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### U (Abundance maps):\n",
    "The plot below shows the spatial distribution of each component"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
Unknown's avatar
Unknown committed
430
    "scrolled": true
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
   },
   "outputs": [],
   "source": [
    "fig_U, ax_U = px.plot_utils.plot_map_stack(U_map_stack[:,:,:25], heading='', title='Component', num_comps=plot_comps, \n",
    "                                           color_bar_mode='each', cmap=px.plot_utils.cmap_jet_white_center())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reconstruct image (while removing noise)\n",
    "Since SVD is just a decomposition technique, it is possible to reconstruct the data with U, S, V matrices. \n",
    "\n",
    "It is also possible to reconstruct a version of the data with a set of components. \n",
    "\n",
    "Thus, by reconstructing with the first few components, we can remove the statistical noise in the data. \n",
    "\n",
    "##### The key is to select the appropriate (number of) components to reconstruct the image without the noise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
455
   "metadata": {},
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
   "outputs": [],
   "source": [
    "clean_components = range(36) # np.append(range(5,9),(17,18))\n",
    "num_components=len(clean_components)\n",
    "\n",
    "# Check if the image has been reconstructed with the same parameters:\n",
    "\n",
    "# First, gather all groups created by this tool:\n",
    "h5_clean_image = None\n",
    "for item in h5_svd:\n",
    "    if item.startswith('Cleaned_Image_') and isinstance(h5_svd[item],h5py.Group):\n",
    "        grp = h5_svd[item]\n",
    "        old_comps = px.hdf_utils.get_attr(grp, 'components_used')\n",
    "        if old_comps.size == len(list(clean_components)):\n",
    "            if np.all(np.isclose(old_comps, np.array(clean_components))):\n",
    "                h5_clean_image = grp['Cleaned_Image']\n",
    "                print( 'Existing clean image found.  No need to rebuild.')\n",
    "                break\n",
    "\n",
    "if h5_clean_image is None:\n",
    "    t0 = time()\n",
    "    #h5_clean_image = iw.clean_and_build_batch(h5_win=h5_wins, components=clean_components)\n",
    "    h5_clean_image = iw.clean_and_build_separate_components(h5_win=h5_wins, components=clean_components)\n",
    "    print( 'Cleaning and rebuilding image took {} seconds.'.format(round(time()-t0, 2)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
485
   "metadata": {},
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
   "outputs": [],
   "source": [
    "# Building a stack of images from here:\n",
    "image_vec_components = h5_clean_image[()]\n",
    "\n",
    "# summing over the components:\n",
    "for comp_ind in range(1, h5_clean_image.shape[1]):\n",
    "    image_vec_components[:, comp_ind] = np.sum(h5_clean_image[:, :comp_ind+1], axis=1)\n",
    "    \n",
    "# converting to 3D:\n",
    "image_components = np.reshape(image_vec_components, [num_x, num_y, -1])\n",
    "\n",
    "# calculating the removed noise:\n",
    "noise_components = image_components - np.reshape(np.tile(h5_raw[()], [1, h5_clean_image.shape[1]]), image_components.shape)\n",
    "\n",
    "# defining a helper function to get the FFTs of a stack of images\n",
    "def get_fft_stack(image_stack):\n",
    "    blackman_window_rows = np.blackman(image_stack.shape[0])\n",
    "    blackman_window_cols = np.blackman(image_stack.shape[1])\n",
    "    fft_stack = np.zeros(image_stack.shape, dtype=np.float)\n",
    "    for image_ind in range(image_stack.shape[2]):\n",
    "        layer = image_stack[:, :, image_ind]\n",
    "        windowed = blackman_window_rows[:, np.newaxis] * layer * blackman_window_cols[np.newaxis, :]\n",
    "        fft_stack[:, :, image_ind] = np.abs(np.fft.fftshift(np.fft.fft2(windowed, axes=(0,1)), axes=(0,1)))\n",
    "    return fft_stack\n",
    "\n",
    "# get the FFT of the cleaned image and the removed noise:\n",
    "fft_image_components = get_fft_stack(image_components)\n",
    "fft_noise_components = get_fft_stack(noise_components)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
Unknown's avatar
Unknown committed
521
    "scrolled": true
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
   },
   "outputs": [],
   "source": [
    "fig_U, ax_U = px.plot_utils.plot_map_stack(image_components[:,:,:25], heading='', evenly_spaced=False,\n",
    "                                           title='Upto component', num_comps=plot_comps, color_bar_mode='single', \n",
    "                                           cmap=px.plot_utils.cmap_jet_white_center())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reconstruct the image with the first N components\n",
    "\n",
    "slide the bar to pick the the number of components such that the noise is removed while maintaining the integrity of the image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
Unknown's avatar
Unknown committed
543
    "scrolled": false
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
   },
   "outputs": [],
   "source": [
    "num_comps = min(16, image_components.shape[2])\n",
    "\n",
    "img_stdevs = 3\n",
    "\n",
    "fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(14, 14))\n",
    "axes.flat[0].loglog(h5_S[()], '*-')\n",
    "axes.flat[0].set_xlim(left=1, right=h5_S[()].size)\n",
    "axes.flat[0].set_ylim(bottom=np.min(h5_S[()]), top=np.max(h5_S[()]))\n",
    "axes.flat[0].set_title('Variance', fontsize=16)\n",
    "vert_line = axes.flat[0].axvline(x=num_comps, color='r')\n",
    "\n",
    "clean_image_mat = image_components[:, :, num_comps]\n",
    "img_clean = axes.flat[1].imshow(clean_image_mat, cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n",
    "mean_val = np.mean(clean_image_mat)\n",
    "std_val = np.std(clean_image_mat)\n",
    "img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val)\n",
    "axes.flat[1].get_yaxis().set_visible(False)\n",
    "axes.flat[1].get_xaxis().set_visible(False)\n",
    "axes.flat[1].set_title('Cleaned Image', fontsize=16)\n",
    "\n",
    "fft_std_dev =  np.max(np.std(fft_image_components[:, :, num_comps]))\n",
    "img_noise_fft = axes.flat[2].imshow(fft_noise_components[:, :, num_comps], cmap=plt.cm.jet,\n",
    "                                    vmin=0, vmax=4*fft_std_dev, origin='lower')\n",
    "axes.flat[2].get_yaxis().set_visible(False)\n",
    "axes.flat[2].get_xaxis().set_visible(False)\n",
    "axes.flat[2].set_title('FFT of removed noise', fontsize=16)\n",
    "img_clean_fft = axes.flat[3].imshow(fft_image_components[:, :, num_comps], cmap=plt.cm.jet,\n",
    "                                    vmin=0, vmax=4*fft_std_dev, origin='lower')\n",
    "axes.flat[3].set_title('FFT of cleaned image', fontsize=16)\n",
    "axes.flat[3].get_yaxis().set_visible(False)\n",
    "axes.flat[3].get_xaxis().set_visible(False)\n",
    "\n",
Unknown's avatar
Unknown committed
579
580
    "plt.show()\n",
    "\n",
581
582
583
584
585
586
587
588
589
590
    "def move_comp_line(num_comps):\n",
    "    vert_line.set_xdata((num_comps, num_comps))\n",
    "    clean_image_mat = image_components[:, :, num_comps]\n",
    "    img_clean.set_data(clean_image_mat)\n",
    "    mean_val = np.mean(clean_image_mat)\n",
    "    std_val = np.std(clean_image_mat)\n",
    "    img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val)\n",
    "    img_noise_fft.set_data(fft_noise_components[:, :, num_comps])\n",
    "    img_clean_fft.set_data(fft_image_components[:, :, num_comps])\n",
    "    clean_components = range(num_comps)\n",
Unknown's avatar
Unknown committed
591
592
    "    fig.canvas.draw()\n",
    "#     display(fig)\n",
593
594
595
596
597
598
599
600
601
602
603
604
605
606
    "    \n",
    "widgets.interact(move_comp_line, num_comps=(1, image_components.shape[2]-1, 1));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Check the cleaned image now:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
607
   "metadata": {},
608
609
   "outputs": [],
   "source": [
Unknown's avatar
Unknown committed
610
    "num_comps = 12\n",
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
    "\n",
    "fig, axis = plt.subplots(figsize=(7, 7))\n",
    "clean_image_mat = image_components[:, :, num_comps]\n",
    "img_clean = axis.imshow(clean_image_mat, cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n",
    "mean_val = np.mean(clean_image_mat)\n",
    "std_val = np.std(clean_image_mat)\n",
    "img_clean.set_clim(vmin=mean_val-img_stdevs*std_val, vmax=mean_val+img_stdevs*std_val)\n",
    "axis.get_yaxis().set_visible(False)\n",
    "axis.get_xaxis().set_visible(False)\n",
    "axis.set_title('Cleaned Image', fontsize=16);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Atom Finding\n",
    "We will attempt to find the positions and the identities of atoms in the image now\n",
    "\n",
    "## Perform clustering on the dataset\n",
    "Clustering divides data into k clusters such that the variance within each cluster is minimized.<br>\n",
    "Here, we will be performing k-means clustering on a set of components in the U matrix from SVD.<br>\n",
    "We want a large enough number of clusters so that K-means identifies fine nuances in the data. At the same time, we want to minimize computational time by reducing the number of clusters. We recommend 32 - 64 clusters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
Unknown's avatar
Unknown committed
644
    "clean_components = 12\n",
645
646
647
648
649
650
651
652
653
654
    "num_clusters = 32\n",
    "\n",
    "# Check for existing Clustering results\n",
    "estimator = px.Cluster(h5_U, 'KMeans', num_comps=clean_components, n_clusters=num_clusters)\n",
    "do_cluster = False\n",
    "\n",
    "# See if there are existing cluster results\n",
    "try:\n",
    "    h5_kmeans = h5_svd['U-Cluster_000']\n",
    "    print( 'Clustering results loaded.  Will now check parameters')\n",
Unknown's avatar
Unknown committed
655
    "except Exception:\n",
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
    "    print( 'Could not load Clustering results.')\n",
    "    do_cluster = True\n",
    "\n",
    "# Check that the same components are used\n",
    "if not do_cluster:\n",
    "    new_clean = estimator.data_slice[1]\n",
    "    if isinstance(new_clean, np.ndarray):\n",
    "        new_clean = new_clean.tolist()\n",
    "    else:\n",
    "        # print(new_clean)\n",
    "        if new_clean.step is None:\n",
    "            new_clean = range(new_clean.start, new_clean.stop)\n",
    "        else:\n",
    "            new_clean = range(new_clean.start, new_clean.stop, new_clean.step)\n",
    "    \n",
    "    if all(h5_kmeans.attrs['components_used']==new_clean):\n",
    "        print( 'Clustering results used the same components as those requested.')\n",
    "    else:\n",
    "        do_cluster = True\n",
    "        print( 'Clustering results used the different components from those requested.')\n",
    "\n",
    "# Check that the same number of clusters were used\n",
    "if not do_cluster:\n",
    "    old_clusters = len(np.unique(h5_kmeans['Cluster_Indices']))\n",
    "    \n",
    "    if old_clusters==num_clusters:\n",
    "        print( 'Clustering results used the same number of clusters as requested.')\n",
    "    else:\n",
    "        do_cluster = True\n",
    "        print( 'Clustering results used a different number of clusters from those requested.')\n",
    "\n",
    "# Perform k-means clustering on the U matrix now using the list of components only if needed:\n",
    "if do_cluster:\n",
    "    t0 = time()\n",
    "    h5_kmeans = estimator.do_cluster()\n",
    "    print( 'kMeans took {} seconds.'.format(round(time()-t0, 2)))\n",
    "else:\n",
    "    print( 'Using existing results.')\n",
    "\n",
    "print( 'Clustering results in {}.'.format(h5_kmeans.name))\n",
    "\n",
    "half_wind = int(win_size*0.5)\n",
    "# generate a cropped image that was effectively the area that was used for pattern searching\n",
    "# Need to get the math righ on the counting\n",
    "cropped_clean_image = clean_image_mat[half_wind:-half_wind + 1, half_wind:-half_wind + 1]\n",
    "\n",
    "# Plot cluster results Get the labels dataset\n",
    "labels_mat = np.reshape(h5_kmeans['Labels'][()], [num_rows, num_cols])\n",
    "\n",
    "fig, axes = plt.subplots(ncols=2, figsize=(14,7))\n",
    "axes[0].imshow(cropped_clean_image,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n",
    "axes[0].set_title('Cleaned Image', fontsize=16)\n",
    "axes[1].imshow(labels_mat, aspect=1, interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n",
    "axes[1].set_title('K-means cluster labels', fontsize=16);\n",
    "for axis in axes:\n",
    "    axis.get_yaxis().set_visible(False)\n",
    "    axis.get_xaxis().set_visible(False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Visualize the hierarchical clustering\n",
    "The vertical length of the branches indicates the relative separation between neighboring clusters."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
726
   "metadata": {},
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
   "outputs": [],
   "source": [
    "# Plot dendrogram here\n",
    "#Get the distrance between cluster means \n",
    "distance_mat = pdist(h5_kmeans['Mean_Response'][()]) \n",
    " \n",
    "#get hierachical pairings of clusters \n",
    "linkage_pairing = linkage(distance_mat,'weighted') \n",
    "\n",
    "# Normalize the pairwise distance with the maximum distance\n",
    "linkage_pairing[:,2] = linkage_pairing[:,2]/max(linkage_pairing[:,2]) \n",
    "\n",
    "# Visualize dendrogram\n",
    "fig = plt.figure(figsize=(10,3)) \n",
    "retval = dendrogram(linkage_pairing, count_sort=True, \n",
    "           distance_sort=True, leaf_rotation=90) \n",
    "#fig.axes[0].set_title('Dendrogram') \n",
    "fig.axes[0].set_xlabel('Cluster number', fontsize=20) \n",
    "fig.axes[0].set_ylabel('Cluster separation', fontsize=20)\n",
    "px.plot_utils.set_tick_font_size(fig.axes[0], 12)"
   ]
  },
Unknown's avatar
Unknown committed
749
750
751
752
753
754
755
756
757
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vert_line.get_xdata()"
   ]
  },
758
759
760
761
762
763
764
765
766
767
768
769
770
771
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Identifiying the principal patterns\n",
    "Here, we will interactively identify N windows, each centered on a distinct class / kind of atom.\n",
    "\n",
    "Use the coarse and fine positions sliders to center the window onto target atoms. Click the \"Set as motif\" button to add this window to the list of patterns we will search for in the next step. Avoid duplicates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
Unknown's avatar
Unknown committed
772
    "scrolled": false
773
774
775
776
777
778
   },
   "outputs": [],
   "source": [
    "motif_win_size = win_size\n",
    "half_wind = int(motif_win_size*0.5)\n",
    "\n",
Unknown's avatar
Unknown committed
779
    "row, col = [int(0.5*cropped_clean_image.shape[0]), int(0.5*cropped_clean_image.shape[1])]\n",
780
781
    "\n",
    "fig, axes = plt.subplots(ncols=2, figsize=(14,7))\n",
Unknown's avatar
Unknown committed
782
783
    "\n",
    "clean_img = axes[0].imshow(cropped_clean_image,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n",
784
785
    "axes[0].set_title('Cleaned Image', fontsize=16)\n",
    "axes[1].set_title('Zoomed area', fontsize=16)\n",
Unknown's avatar
Unknown committed
786
787
788
    "vert_line = axes[0].axvline(x=col, color='k')\n",
    "hor_line = axes[0].axhline(y=row, color='k')\n",
    "motif_box = axes[0].add_patch(patches.Rectangle((col - half_wind, row - half_wind),\n",
789
790
791
    "                                          motif_win_size, motif_win_size, fill=False,\n",
    "                                         color='black', linewidth=2))\n",
    "\n",
Unknown's avatar
Unknown committed
792
793
794
795
796
797
    "indices = (slice(row - half_wind, row + half_wind), \n",
    "           slice(col - half_wind, col + half_wind))\n",
    "motif_img = axes[1].imshow(cropped_clean_image[indices],cmap=px.plot_utils.cmap_jet_white_center(), \n",
    "                           vmax=np.max(cropped_clean_image), vmin=np.min(cropped_clean_image), origin='lower')\n",
    "axes[1].axvline(x=half_wind, color='k')\n",
    "axes[1].axhline(y=half_wind, color='k')\n",
798
    "\n",
Unknown's avatar
Unknown committed
799
800
801
    "plt.show()\n",
    "\n",
    "def _update_motif_img(row, col):\n",
802
803
804
805
    "    indices = (slice(row - half_wind, row + half_wind), \n",
    "               slice(col - half_wind, col + half_wind))\n",
    "    motif_box.set_x(col - half_wind)\n",
    "    motif_box.set_y(row - half_wind)\n",
Unknown's avatar
Unknown committed
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
    "    \n",
    "    motif_img.set_data(cropped_clean_image[indices])\n",
    "\n",
    "def move_zoom_box(event):\n",
    "    if not clean_img.axes.in_axes(event):\n",
    "        return\n",
    "    \n",
    "    col = int(round(event.xdata))\n",
    "    row = int(round(event.ydata))\n",
    "    \n",
    "    vert_line.set_xdata((col, col))\n",
    "    hor_line.set_ydata((row, row))\n",
    "    \n",
    "    _update_motif_img(row, col)\n",
    "    \n",
    "    fig.canvas.draw()\n",
    "\n",
    "def _motif_fine_select(event):\n",
    "    if not motif_img.axes.in_axes(event):\n",
    "        return\n",
    "    \n",
    "    col_shift = int(round(event.xdata)) - half_wind\n",
    "    row_shift = int(round(event.ydata)) - half_wind\n",
    "    \n",
    "    col = vert_line.get_xdata()[0] + col_shift\n",
    "    row = hor_line.get_ydata()[0] + row_shift\n",
    "    \n",
    "    vert_line.set_xdata((col, col))\n",
    "    hor_line.set_ydata((row, row))\n",
    "    \n",
    "    _update_motif_img(row, col)\n",
    "    \n",
Unknown's avatar
Unknown committed
838
    "    fig.canvas.draw()\n",
839
840
841
    "    \n",
    "motif_win_centers = list()\n",
    "\n",
Unknown's avatar
Unknown committed
842
843
844
    "add_motif_button = widgets.Button(description=\"Set as motif\")\n",
    "display(add_motif_button)\n",
    "\n",
845
    "def add_motif(butt):\n",
Unknown's avatar
Unknown committed
846
847
    "    row = hor_line.get_ydata()[0]\n",
    "    col = vert_line.get_xdata()[0]\n",
848
    "    #print(\"Setting motif with coordinates ({}, {})\".format(current_center[0], current_center[1]))\n",
Unknown's avatar
Unknown committed
849
850
851
    "    axes[0].add_patch(patches.Rectangle((col - int(0.5*motif_win_size), \n",
    "                                         row - int(0.5*motif_win_size)),\n",
    "                                         motif_win_size, motif_win_size, fill=False,\n",
852
853
    "                                         color='black', linewidth=2))\n",
    "    motif_win_centers.append((current_center[0], current_center[1]))\n",
Unknown's avatar
Unknown committed
854
855
856
    "\n",
    "cid = clean_img.figure.canvas.mpl_connect('button_press_event', move_zoom_box)\n",
    "cid2 = motif_img.figure.canvas.mpl_connect('button_press_event', _motif_fine_select)\n",
857
858
859
860
861
862
863
864
865
866
867
868
869
    "add_motif_button.on_click(add_motif)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visualize the motifs that were selected above"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
870
871
872
   "metadata": {
    "scrolled": false
   },
873
874
875
   "outputs": [],
   "source": [
    "# select motifs from the cluster labels using the component list:\n",
Unknown's avatar
Unknown committed
876
    "# motif_win_centers = [(117, 118), (109, 110)]\n",
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
    "print('Coordinates of the centers of the chosen motifs:')\n",
    "print(motif_win_centers)\n",
    "motif_win_size = win_size\n",
    "half_wind = int(motif_win_size*0.5)\n",
    "\n",
    "# Effectively, we end up cropping the image again by the window size while matching patterns so:\n",
    "double_cropped_image = cropped_clean_image[half_wind:-half_wind, half_wind:-half_wind]\n",
    "\n",
    "# motif_win_size = 15  # Perhaps the motif should be smaller than the original window\n",
    "num_motifs = len(motif_win_centers)\n",
    "motifs = list()\n",
    "fig, axes = plt.subplots(ncols=3, nrows=num_motifs, figsize=(14,6 * num_motifs))\n",
    "\n",
    "for window_center, ax_row in zip(motif_win_centers, np.atleast_2d(axes)):\n",
    "    indices = (slice(window_center[0] - half_wind, window_center[0] + half_wind), \n",
    "               slice(window_center[1] - half_wind, window_center[1] + half_wind))\n",
    "    motifs.append(labels_mat[indices])\n",
    "    \n",
    "    ax_row[0].hold(True)\n",
    "    ax_row[0].imshow(cropped_clean_image, interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(), origin='lower')\n",
    "    ax_row[0].add_patch(patches.Rectangle((window_center[1] - int(0.5*motif_win_size), \n",
    "                                           window_center[0] - int(0.5*motif_win_size)),\n",
    "                                          motif_win_size, motif_win_size, fill=False,\n",
    "                                         color='black', linewidth=2))\n",
    "    ax_row[0].hold(False)\n",
    "    ax_row[1].hold(True)\n",
    "    ax_row[1].imshow(cropped_clean_image[indices], interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(),\n",
    "                     vmax=np.max(cropped_clean_image), vmin=np.min(cropped_clean_image), origin='lower')\n",
    "    ax_row[1].plot([0, motif_win_size-2],[int(0.5*motif_win_size), int(0.5*motif_win_size)], 'k--')\n",
    "    ax_row[1].plot([int(0.5*motif_win_size), int(0.5*motif_win_size)], [0, motif_win_size-2], 'k--')\n",
    "    # ax_row[1].axis('tight')\n",
    "    ax_row[1].set_title('Selected window for motif around (row {}, col {})'.format(window_center[0], window_center[1]))\n",
    "    ax_row[1].hold(False)\n",
    "    ax_row[2].imshow(labels_mat[indices], interpolation='none',cmap=px.plot_utils.cmap_jet_white_center(),\n",
    "                     vmax=num_clusters-1, vmin=0, origin='lower')\n",
    "    ax_row[2].set_title('Motif from K-means labels');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Calculate matching scores for each motif\n",
    "We do this by sliding each motif across the cluster labels image to find how the motif matches with the image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
926
   "metadata": {},
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
   "outputs": [],
   "source": [
    "motif_match_coeffs = list()\n",
    "\n",
    "for motif_mat in motifs:\n",
    "    \n",
    "    match_mat = np.zeros(shape=(num_rows-motif_win_size, num_cols-motif_win_size))\n",
    "    for row_count, row_pos in enumerate(range(half_wind, num_rows - half_wind - 1, 1)):\n",
    "        for col_count, col_pos in enumerate(range(half_wind, num_cols - half_wind - 1, 1)):\n",
    "            local_cluster_mat = labels_mat[row_pos-half_wind : row_pos+half_wind, \n",
    "                                           col_pos-half_wind : col_pos+half_wind]\n",
    "            match_mat[row_count, col_count] = np.sum(local_cluster_mat == motif_mat)\n",
    "    # Normalize the dataset:\n",
    "    match_mat = match_mat/np.max(match_mat)\n",
    "    \n",
    "    motif_match_coeffs.append(match_mat)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualize the matching scores\n",
    "Note: If a pair of motifs are always matching for the same set of atoms, perhaps this may be a duplicate motif. Alternatively, if these motifs do indeed identify distinct classes of atoms, consider:\n",
    "* clustering again with a different set of SVD components\n",
    "* increasing the number of clusters\n",
    "* Choosing a different fft mode ('data+fft' for better identify subtle but important variations) before performing windowing on the data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
959
   "metadata": {},
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
   "outputs": [],
   "source": [
    "show_legend = True\n",
    "\n",
    "base_color_map = plt.cm.get_cmap('jet')\n",
    "fig = plt.figure(figsize=(8, 8))\n",
    "im = plt.imshow(double_cropped_image, cmap=\"gray\", origin='lower')\n",
    "\n",
    "if num_motifs > 1:\n",
    "    motif_colors = [base_color_map(int(255 * motif_ind / (num_motifs - 1))) for motif_ind in range(num_motifs)]\n",
    "else:\n",
    "    motif_colors = [base_color_map(0)]\n",
    "handles = list()\n",
    "for motif_ind, current_solid_color, match_mat in zip(range(num_motifs), motif_colors, motif_match_coeffs):\n",
    "    my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1)\n",
    "    im = plt.imshow(match_mat, cmap=my_cmap, origin='lower');\n",
    "    current_solid_color = list(current_solid_color)\n",
    "    current_solid_color[3] = 0.5 # maximum alpha value\n",
    "    handles.append(patches.Patch(color=current_solid_color, label='Motif {}'.format(motif_ind)))\n",
    "if show_legend:\n",
    "    plt.legend(handles=handles, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0., fontsize=14)\n",
    "axis = fig.get_axes()[0]\n",
    "axis.set_title('Pattern matching scores', fontsize=22)\n",
    "axis.set_xticklabels([])\n",
    "axis.set_yticklabels([])\n",
    "axis.get_xaxis().set_visible(False)\n",
    "axis.get_yaxis().set_visible(False)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Convert matching scores to binary\n",
    "We do this by thresholding the matching scores such that a score beyond the threshold is set to 1 and all other values are set to 0. \n",
    "\n",
    "The goal is to set the thresholds such that we avoid overlaps between two clusters and also shrink the blobs such that they are only centered over a single atom wherever possible.\n",
    "\n",
    "Use the sliders below to interactively set the threshold values"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
1005
   "metadata": {},
1006
1007
1008
1009
1010
1011
1012
1013
   "outputs": [],
   "source": [
    "thresholds = [0.25 for x in range(num_motifs)]\n",
    "thresholded_maps = list()\n",
    "motif_imgs = list()\n",
    "\n",
    "base_color_map = plt.cm.jet\n",
    "fig, axis = plt.subplots(figsize=(10, 10))\n",
Unknown's avatar
Unknown committed
1014
1015
    "plt.hold(True);\n",
    "plt.imshow(double_cropped_image, cmap=\"gray\")\n",
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
    "handles = list()\n",
    "if num_motifs > 1:\n",
    "    motif_colors = [base_color_map(int(255 * motif_ind / (num_motifs - 1))) for motif_ind in range(num_motifs)]\n",
    "else:\n",
    "    motif_colors = [base_color_map(0)]\n",
    "\n",
    "for motif_ind, match_mat, t_hold, current_solid_color in zip(range(num_motifs), motif_match_coeffs, \n",
    "                                                             thresholds, motif_colors):\n",
    "    my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1, max_alpha=0.5)\n",
    "    bin_map = np.where(match_mat > t_hold, \n",
    "                       np.ones(shape=match_mat.shape, dtype=np.uint8),\n",
    "                       np.zeros(shape=match_mat.shape, dtype=np.uint8))\n",
    "    thresholded_maps.append(bin_map)\n",
Unknown's avatar
Unknown committed
1029
    "    motif_imgs.append(plt.imshow(bin_map, interpolation='none', cmap=my_cmap))\n",
1030
1031
1032
1033
1034
1035
1036
1037
1038
    "    current_solid_color = list(current_solid_color)\n",
    "    current_solid_color[3] = 0.5\n",
    "    handles.append(patches.Patch(color=current_solid_color,label='Motif {}'.format(motif_ind)))\n",
    "\n",
    "axis.set_xticklabels([])\n",
    "axis.set_yticklabels([])\n",
    "axis.get_xaxis().set_visible(False)\n",
    "axis.get_yaxis().set_visible(False)\n",
    "plt.legend(handles=handles, bbox_to_anchor=(1.01, 1), loc=2, borderaxespad=0.)\n",
Unknown's avatar
Unknown committed
1039
    "plt.hold(False);\n",
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
    "\n",
    "def threshold_images(thresholds):\n",
    "    # thresholded_maps = list()\n",
    "    # empty the thresholded maps:\n",
    "    del thresholded_maps[:]\n",
    "    for motif_ind, match_mat, t_hold, current_solid_color in zip(range(num_motifs), motif_match_coeffs, thresholds, motif_colors):\n",
    "        my_cmap = px.plot_utils.make_linear_alpha_cmap('fdfd', current_solid_color, 1, max_alpha=0.5)\n",
    "        bin_map = np.where(match_mat > t_hold, \n",
    "                           np.ones(shape=match_mat.shape, dtype=np.uint8),\n",
    "                           np.zeros(shape=match_mat.shape, dtype=np.uint8))\n",
    "        thresholded_maps.append(bin_map)\n",
    "    \n",
    "def interaction_unpacker(**kwargs):\n",
    "    #threshs = range(num_motifs)\n",
    "    for motif_ind in range(num_motifs):\n",
    "        thresholds[motif_ind] = kwargs['Motif ' + str(motif_ind)]\n",
    "    threshold_images(thresholds)\n",
    "    for img_handle, th_image in zip(motif_imgs, thresholded_maps):\n",
    "        img_handle.set_data(th_image)\n",
Unknown's avatar
Unknown committed
1059
    "    fig.canvas.draw()\n",
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
    "    \n",
    "temp_thresh = dict()\n",
    "for motif_ind in range(num_motifs):\n",
    "    temp_thresh['Motif ' + str(motif_ind)] = (0,1,0.025)\n",
    "widgets.interact(interaction_unpacker, **temp_thresh);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Find the atom centers from the binary maps\n",
    "The centers of the atoms will be inferred from the centroid of each of the blobs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
1078
   "metadata": {},
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
   "outputs": [],
   "source": [
    "print(thresholds)\n",
    "\n",
    "atom_labels = list()\n",
    "for thresh_map in thresholded_maps:\n",
    "    labled_atoms = measure.label(thresh_map, background=0)\n",
    "    map_props = measure.regionprops(labled_atoms)\n",
    "    atom_centroids = np.zeros(shape=(len(map_props),2))\n",
    "    for atom_ind, atom in enumerate(map_props):\n",
    "        atom_centroids[atom_ind] = np.array(atom.centroid)\n",
    "    atom_labels.append(atom_centroids)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualize the atom positions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
1103
   "metadata": {},
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
   "outputs": [],
   "source": [
    "# overlay atom positions on original image\n",
    "fig, axis = plt.subplots(figsize=(8,8))\n",
    "axis.hold(True)\n",
    "col_map = plt.cm.jet\n",
    "axis.imshow(double_cropped_image, interpolation='none',cmap=\"gray\")\n",
    "legend_handles = list()\n",
    "for atom_type_ind, atom_centroids in enumerate(atom_labels):    \n",
    "    axis.scatter(atom_centroids[:,1], atom_centroids[:,0], color=col_map(int(255 * atom_type_ind / (num_motifs-1))),\n",
    "                 label='Motif {}'.format(atom_type_ind), s=30)\n",
    "axis.set_xlim(0, double_cropped_image.shape[0])\n",
    "axis.set_ylim(0, double_cropped_image.shape[1]);\n",
    "axis.invert_yaxis()\n",
    "\n",
    "axis.set_xticklabels([])\n",
    "axis.set_yticklabels([])\n",
    "axis.get_xaxis().set_visible(False)\n",
    "axis.get_yaxis().set_visible(False)\n",
    "axis.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=14)\n",
    "axis.set_title('Atom Positions', fontsize=22)\n",
    "\n",
    "fig.tight_layout()\n",
    "#plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Save and close\n",
    "* Save the .h5 file that we are working on by closing it. <br>\n",
    "* Also, consider exporting this notebook as a notebook or an html file. <br> To do this, go to File >> Download as >> HTML\n",
    "* Finally consider saving this notebook if necessary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
1143
   "metadata": {},
1144
1145
1146
1147
1148
1149
1150
1151
   "outputs": [],
   "source": [
    "h5_file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
Unknown's avatar
Unknown committed
1152
   "metadata": {},
1153
1154
1155
1156
1157
1158
1159
1160
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "celltoolbar": "Raw Cell Format",
  "kernelspec": {
Unknown's avatar
Unknown committed
1161
   "display_name": "Python 3",
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  },
  "widgets": {
   "state": {
    "29604cba705348bebab931e8c5a8f33b": {
     "views": [
      {
       "cell_index": 41
      }
     ]
    },
    "3148e6a4894e42d2856f6c31aa70805a": {
     "views": [
      {
       "cell_index": 33
      }
     ]
    },
    "4c6e4e0c659542ca937b2ca85f7f33cf": {
     "views": [
      {
       "cell_index": 49
      }
     ]
    },
    "9236753466b34d9eb471907b4a33fd73": {
     "views": [
      {
       "cell_index": 38
      }
     ]
    },
    "ba247d838fef4411b7c74d7055033284": {
     "views": [
      {
       "cell_index": 38
      }
     ]
    },
    "bafd596f9f254b4a8652bbf8e7bdc096": {
     "views": [
      {
       "cell_index": 41
      }
     ]
    },
    "e687973fb1ff41949de8de5587ad6461": {
     "views": [
      {
       "cell_index": 38
      }
     ]
    }
   },
   "version": "1.2.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}