Speckle Analyses

The analyses of the speckle tracking data is split in three steps:

  • Pre-processing:
    Consist of loading and cropping the raw image(s) and doing basic operations like normalization, filtering and subtraction of background.
  • Data analyses per se:
    Here the physics of the method is used to convert the pre processed data to some meaninfull physical information. It will likely require experimental information like pixel size, photon energy and distance sample to detector. It should not require any information about the sample.
  • Post Processing:
    Perform additional steps to the physical data, like integration, mask, filtering and unwrap. At this point some information about the sample may be required. It must produce graphics and results to be presented to others.

The two files below present examples of speckle tracking data analyses. The first is speckleAnalyses.py and it perfrom basic pre processing (interactive crop), data analyses, and save the result in hdf5 format.

Then speckleAnalyses_postProcessing.py loads the results obtained with speckleAnalyses.py, and perform operations like undersampling, mask, integration and extra calculations to obtain the final desired result, in this case thisckness of the sample. It also plot the results in a meaninful manner.

Code

Speckle Tracking Analyses

This section contains the speckleAnalyses script.

Download file: speckleAnalyses.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2015, UChicago Argonne, LLC. All rights reserved.         #
#                                                                         #
# Copyright 2015. UChicago Argonne, LLC. This software was produced       #
# under U.S. Government contract DE-AC02-06CH11357 for Argonne National   #
# Laboratory (ANL), which is operated by UChicago Argonne, LLC for the    #
# U.S. Department of Energy. The U.S. Government has rights to use,       #
# reproduce, and distribute this software.  NEITHER THE GOVERNMENT NOR    #
# UChicago Argonne, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR        #
# ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE.  If software is     #
# modified to produce derivative works, such modified software should     #
# be clearly marked, so as not to confuse it with the version available   #
# from ANL.                                                               #
#                                                                         #
# Additionally, redistribution and use in source and binary forms, with   #
# or without modification, are permitted provided that the following      #
# conditions are met:                                                     #
#                                                                         #
#     * Redistributions of source code must retain the above copyright    #
#       notice, this list of conditions and the following disclaimer.     #
#                                                                         #
#     * Redistributions in binary form must reproduce the above copyright #
#       notice, this list of conditions and the following disclaimer in   #
#       the documentation and/or other materials provided with the        #
#       distribution.                                                     #
#                                                                         #
#     * Neither the name of UChicago Argonne, LLC, Argonne National       #
#       Laboratory, ANL, the U.S. Government, nor the names of its        #
#       contributors may be used to endorse or promote products derived   #
#       from this software without specific prior written permission.     #
#                                                                         #
# THIS SOFTWARE IS PROVIDED BY UChicago Argonne, LLC AND CONTRIBUTORS     #
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT       #
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS       #
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UChicago     #
# Argonne, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,        #
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,    #
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;        #
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER        #
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT      #
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN       #
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE         #
# POSSIBILITY OF SUCH DAMAGE.                                             #
# #########################################################################


"""
Example of speckle tracking data analyses
"""

import numpy as np
from scipy import constants
import dxchange
import h5py as h5

import wavepy.utils as wpu
import wavepy.speckletracking as wps


__authors__ = "Walan Grizolli"
__copyright__ = "Copyright (c) 2016, Affiliation"
__version__ = "0.1.0"


# =============================================================================
# %% preamble. Load parameters from ini file
# =============================================================================


inifname = '.speckleAnalyses.ini'

config, ini_pars, ini_file_list = wpu.load_ini_file_terminal_dialog(inifname)

fname = ini_file_list.get('image_filename')
image = dxchange.read_tiff(fname)
image_ref = dxchange.read_tiff(ini_file_list.get('ref_filename'))

idx = list(map(int, ini_pars.get('crop').split(',')))
pixelsize = float(ini_pars.get('pixel size'))
phenergy = float(ini_pars.get('photon energy'))
distDet2sample = float(ini_pars.get('distance detector to sample'))
halfsubwidth = int(ini_pars.get('halfsubwidth'))
halfTemplateSize = int(ini_pars.get('halfTemplateSize'))
subpixelResolution = int(ini_pars.get('subpixelResolution'))
npointsmax = int(ini_pars.get('npointsmax'))
ncores = float(ini_pars.get('ncores')) / float(ini_pars.get('ncores of machine'))
saveH5 = ini_pars.get('save hdf5 files')

if subpixelResolution < 1: subpixelResolution = None
if halfTemplateSize < 1: halfTemplateSize = None



# %%
#
#dummy = wpu.dummy_images('Shapes',  shape=(110, 110), noise = 1)
#fname = 'dummy.tif'
#image = dummy[5:-5,5:-5]
#image_ref = dummy[7:-3,4:-6]

# =============================================================================
# %% parameters
# =============================================================================

rad2deg = np.rad2deg(1)
deg2rad = np.deg2rad(1)
NAN = float('Nan')  # not a number alias

hc = constants.value('inverse meter-electron volt relationship')  # hc

wavelength = hc/phenergy
kwave = 2*np.pi/wavelength


# =============================================================================
# %% Crop
# =============================================================================


#image = np.rot90(image)  # rotate images, good for sanity checks
#image_ref = np.rot90(image_ref)


kb_input = input('\nGraphic Crop? [N/y] : ')
if kb_input.lower() == 'y':
    # Graphical Crop

    idx = wpu.graphical_roi_idx(image, verbose=True)

    print('New idx:')
    print(idx)

    ini_pars['crop'] = str('{0}, {1}, {2}, {3}'.format(idx[0], idx[1], idx[2], idx[3]))
    with open(inifname, 'w') as configfile:  # update values in the ini file
        config.write(configfile)




image = wpu.crop_matrix_at_indexes(image, idx)
image_ref = wpu.crop_matrix_at_indexes(image_ref, idx)


# %%
# =============================================================================
# Displacement
# =============================================================================

sx, sy, \
error, step = wps.speckleDisplacement(image, image_ref,
                                      halfsubwidth=halfsubwidth,
                                      halfTemplateSize=halfTemplateSize,
                                      subpixelResolution=subpixelResolution,
                                      npointsmax=npointsmax,
                                      ncores=ncores, taskPerCore=15,
                                      verbose=True)




totalS = np.sqrt(sx**2 + sy**2)

xVec2 = wpu.realcoordvec(sx.shape[1], pixelsize*step)
yVec2 = wpu.realcoordvec(sx.shape[0], pixelsize*step)


# %%
# =============================================================================
# Save data in hdf5 format
# =============================================================================

fname_output = fname[:-4] + '_' + wpu.datetime_now_str() + ".h5"
f = h5.File(fname_output, "w")


h5rawdata = f.create_group('raw')
f.create_dataset("raw/image_sample", data=image)
f.create_dataset("raw/image_ref", data=image_ref)
h5rawdata.attrs['Pixel Size Detector [m]'] = pixelsize
h5rawdata.attrs['Distance Detector to Sample [m]'] = distDet2sample
h5rawdata.attrs['Photon Energy [eV]'] = phenergy

h5displacement = f.create_group('displacement')
f.create_dataset("displacement/displacement_x", data=sx)
f.create_dataset("displacement/displacement_y", data=sy)
f.create_dataset("displacement/error", data=error)
f.create_dataset("displacement/xvec", data=xVec2)
f.create_dataset("displacement/yvec", data=yVec2)



h5displacement.attrs['Comments'] = 'Created by Walan Grizolli at ' + wpu.datetime_now_str()
h5displacement.attrs['Pixel Size Processed images [m]'] = pixelsize*step
h5displacement.attrs['Distance Detector to Sample [m]'] = distDet2sample
h5displacement.attrs['Photon Energy [eV]'] = phenergy
h5displacement.attrs['ini file'] = '\n' + open(inifname, 'r').read()


f.flush()
f.close()

with open(fname_output[:-3] + '.log', 'w') as logfile:  # save ini files as log
    config.write(logfile)

wpu.print_blue("File saved at:\n{0}".format(fname_output))

Speckle Analyses Post Processing

This section contains the speckleAnalyses_postProcessing script.

Download file: speckleAnalyses_postProcessing.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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
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
485
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
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 13 16:00:19 2016

@author: wcgrizolli
"""

#==============================================================================
# %%
#==============================================================================
import numpy as np

from numpy.fft import fft2, ifft2, fftfreq
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt


import h5py as h5


import wavepy.utils as wpu
import wavepy.surface_from_grad as wpsg

import itertools



#==============================================================================
# %% preamble
#==============================================================================


# Flags
saveFigFlag = True

# useful constants
rad2deg = np.rad2deg(1)
deg2rad = np.deg2rad(1)
NAN = float('Nan')  # not a number alias

from scipy import constants
hc = constants.value('inverse meter-electron volt relationship') # hc

figCount = itertools.count()  # itera
next(figCount)


def mpl_settings_4_nice_graphs():
    '''
    Settings for latex fonts in the graphs
    ATTENTION: This will make the program slow because it will compile all
    latex text. This means that you also need latex and any latex package
    you want to use. I suggest to only use this when you want produce final
    graphs to publish or to make public. The latex dependecies are not taken
    care  by the installation scripts. You are by your own to solve these
    dependencies.
    '''

    plt.style.use('default')
    #Direct input
    plt.rcParams['text.latex.preamble']=[r"\usepackage[utopia]{mathdesign}"]
    ##Options
    params = {'text.usetex' : True,
              'font.size' : 16,
              'font.family' : 'utopia',
              'text.latex.unicode': True,
              'figure.facecolor' : 'white'
              }
    plt.rcParams.update(params)

# mpl_settings_4_nice_graphs()


#==============================================================================
# %% Some definitions
#==============================================================================


def mySimplePlot(array, title=''):

    plt.figure()
    plt.imshow(array, cmap='spectral', interpolation='none')
    plt.title(title)
    plt.colorbar()
    if saveFigFlag: wpu.save_figs_with_idx(foutname)
    plt.show(block=True)

#==============================================================================
# %% Load files
#==============================================================================

fname = wpu.select_file('**/*.h5')

foutname = fname.rsplit('.')[0]

f = h5.File(fname,'r')

#print(wpu.h5ListOfGroups(f))

#==============================================================================
# %% parameters
#==============================================================================

delta = 5.3265E-06
# real part refractive index Be at 8KeV from http://henke.lbl.gov/


pixelsizeDetector = f['raw'].attrs['Pixel Size Detector [m]']

pixelsizeImg = f['displacement'].attrs['Pixel Size Processed images [m]']
distDet2sample = f['displacement'].attrs['Distance Detector to Sample [m]']
phenergy = f['displacement'].attrs['Photon Energy [eV]']

wavelength = hc/phenergy
kwave = 2*np.pi/wavelength

print('MESSAGE: Comments from hdf5 files')
print('MESSAGE: '+ f['displacement'].attrs['Comments'])


# %%

sx_raw = np.array(f['displacement/displacement_x'])
sy_raw = np.array(f['displacement/displacement_y'])
error_raw = np.array(f['displacement/error'])

xVec_raw =  np.array(f['displacement/xvec'])
yVec_raw =  np.array(f['displacement/yvec'])

#==============================================================================
# %% Crop
#==============================================================================

idx4crop = wpu.graphical_roi_idx(np.sqrt(sx_raw**2 + sy_raw**2), verbose=True)



sx = wpu.crop_matrix_at_indexes(sx_raw, idx4crop)
sy = wpu.crop_matrix_at_indexes(sy_raw, idx4crop)
error = wpu.crop_matrix_at_indexes(error_raw, idx4crop)


xVec = wpu.realcoordvec(sx.shape[1], pixelsizeImg)
yVec = wpu.realcoordvec(sx.shape[0], pixelsizeImg)

xmatrix, ymatrix = np.meshgrid(xVec, yVec)




#==============================================================================
# %% Calculations of physical quantities
#==============================================================================


totalS = np.sqrt(sx**2 + sy**2)


# Differenctial Phase
dpx = kwave*np.arctan2(sx*pixelsizeDetector, distDet2sample)
dpy = kwave*np.arctan2(sy*pixelsizeDetector, distDet2sample)


# Differenctial Thickness
dTx = 1.0/delta*np.arctan2(sx*pixelsizeDetector, distDet2sample)
dTy = 1.0/delta*np.arctan2(sy*pixelsizeDetector, distDet2sample)


#==============================================================================
# %% quiver
#==============================================================================

#
#
#
#from skimage.io import imread, imsave
#
#tempImage = imread('/home/grizolli/workspace/pythonWorkspace/data/Be1x50um/set1/very_small_sample.jpg')
#
#
#fig = plt.figure(figsize=(10, 7.5))
#stride = 1
#plt.contourf(xmatrix*1e6,
#             ymatrix*1e6,
#             wpu.crop_matrix_at_indexes(tempImage, idx4crop),
#             1001, cmap='Greys_r')
#
#plt.xlabel('[um]')
#plt.ylabel('[um]')
#
#plt.show()
#wpu.save_figs_with_idx(foutname)
#
#
#
##
#
#fig = plt.figure(figsize=(10, 7.5))
#stride = 1
#plt.contourf(xmatrix*1e6,
#             ymatrix*1e6,
#             wpu.crop_matrix_at_indexes(tempImage, idx4crop),
#             1001, cmap='Greys_r')
#
#stride = 12
#plt.quiver(xmatrix[::stride, ::stride]*1e6,
#           ymatrix[::stride, ::stride]*1e6,
#           sx[::stride, ::stride], sy[::stride, ::stride],
#           angles='xy', minlength=2.2, color='c', lw=.5, width=0.005)
#
#plt.xlabel('[um]')
#plt.ylabel('[um]')
#
#plt.show()
#wpu.save_figs_with_idx(foutname)
#



#==============================================================================
# %% integration frankotchellappa
#==============================================================================


#integration_res = frankotchellappa(dTx,dTy)
integration_res = wpsg.frankotchellappa(dTx*pixelsizeImg, dTy*pixelsizeImg)

thickness = np.real(integration_res)

thickness = thickness - np.min(thickness)

# %%

wpsg.error_integration(dTx*pixelsizeImg, dTy*pixelsizeImg, thickness,
                       [pixelsizeImg, pixelsizeImg], shifthalfpixel=True, plot_flag=True)

#==============================================================================
# %% Thickness
#==============================================================================


stride = 1

wpu.plot_profile(xmatrix[::stride, ::stride]*1e6,
                 ymatrix[::stride, ::stride]*1e6,
                 thickness[::stride, ::stride]*1e6,
                 title='Thickness', xlabel='[um]', ylabel='[um]',
                 arg4main={'cmap':'spectral'}) #, xo=0.0, yo=0.0)_1Dparabol_4_fit
plt.show(block=True)

#==============================================================================
# %% Plot
#==============================================================================





def plotsidebyside(array1, array2, title1='', title2='', maintitle=''):

    fig = plt.figure(figsize=(14, 5))
    fig.suptitle(maintitle, fontsize=14)

    vmax = np.max([array1, array2])
    vmin = np.min([array1, array2])

    ax1 = plt.subplot(121)
    ax2 = plt.subplot(122, sharex=ax1, sharey=ax1)

    im1 = ax1.imshow(array1, cmap='RdGy',
                     interpolation='none',
                     vmin=vmin, vmax=vmax)
    ax1.set_title(title1, fontsize=22)
    ax1.set_adjustable('box-forced')
    fig.colorbar(im1, ax=ax1, shrink=.8, aspect=20)

    im2 = ax2.imshow(array2, cmap='RdGy',
                     interpolation='none',
                     vmin=vmin, vmax=vmax)
    ax2.set_title(title2, fontsize=22)
    ax2.set_adjustable('box-forced')
    fig.colorbar(im2, ax=ax2, shrink=.8, aspect=20)


    if saveFigFlag: wpu.save_figs_with_idx(foutname)
    plt.show(block=True)

#==============================================================================
# %% Plot dpx and dpy and fit Curvature Radius of WF
#==============================================================================


fig = plt.figure(figsize=(14, 5))
fig.suptitle('Phase [rad]', fontsize=14)


ax1 = plt.subplot(121)
ax2 = plt.subplot(122, sharex=ax1, sharey=ax1)



ax1.plot(xVec*1e6, dpx[dpx.shape[1]//4,:],'-ob')
ax1.plot(xVec*1e6, dpx[dpx.shape[1]//2,:],'-or')
ax1.plot(xVec*1e6, dpx[dpx.shape[1]//4*3,:],'-og')
ax1.ticklabel_format(style='sci', axis='y', scilimits=(0, 1))
ax1.set_xlabel('[um]')
ax1.set_ylabel('dpx [radians]')

lin_fitx = np.polyfit(xVec, dpx[dpx.shape[1]//2,:], 1)
lin_funcx = np.poly1d(lin_fitx)
ax1.plot(xVec*1e6, lin_funcx(xVec),'--c',lw=2)
curvrad_x = kwave/(lin_fitx[0])

ax1.set_title('Curvature Radius of WF {:.3g} m'.format(curvrad_x), fontsize=18)
ax1.set_adjustable('box-forced')


ax2.plot(yVec*1e6, dpy[:,dpy.shape[0]//4],'-ob')
ax2.plot(yVec*1e6, dpy[:,dpy.shape[0]//2],'-or')
ax2.plot(yVec*1e6, dpy[:,dpy.shape[0]//4*3],'-og')
ax2.ticklabel_format(style='sci', axis='y', scilimits=(0, 1))
ax2.set_xlabel('[um]')
ax2.set_ylabel('dpy [radians]')

lin_fity = np.polyfit(yVec, dpy[:,dpy.shape[0]//2], 1)
lin_funcy = np.poly1d(lin_fity)
ax2.plot(yVec*1e6, lin_funcy(yVec),'--c',lw=2)
curvrad_y = kwave/(lin_fity[0])

ax2.set_title('Curvature Radius of WF {:.3g} m'.format(curvrad_y), fontsize=18)
ax2.set_adjustable('box-forced')



if saveFigFlag: wpu.save_figs_with_idx(foutname)
plt.show(block=True)



# %%

plotsidebyside(sx, sy, r'Displacement $S_x$ [pixels]',
                         r'Displacement $S_y$ [pixels]')

# %%
mySimplePlot(totalS, title=r'Displacement Module $|\vec{S}|$ [pixels]')

# %%


fig = plt.figure(figsize=(14, 5))

ax1 = plt.subplot(121)
ax2 = plt.subplot(122, sharex=ax1, sharey=ax1)

ax1.plot(sx.flatten(),error.flatten(),'.')
ax1.set_xlabel('Sy [pixel]')
ax1.set_title('Error vs Sx', fontsize=22)
ax1.set_adjustable('box-forced')


ax2.plot(sy.flatten(),error.flatten(),'.')
ax2.set_xlabel('Sy [pixel]')
ax2.set_title('Error vs Sy', fontsize=22)
ax2.set_adjustable('box-forced')


if saveFigFlag: wpu.save_figs_with_idx(foutname)
plt.show(block=True)


#==============================================================================
# %% Histograms to evaluate data quality
#==============================================================================


fig = plt.figure(figsize=(14, 5))
fig.suptitle('Histograms to evaluate data quality', fontsize=16)

ax1 = plt.subplot(121)
ax1 = plt.hist(sx.flatten(), 51)
ax1 = plt.title(r'$S_x$ [pixels]', fontsize=16)

ax1 = plt.subplot(122)
ax2 = plt.hist(sy.flatten(), 51)
ax2 = plt.title(r'$S_y$ [pixels]', fontsize=16)


if saveFigFlag: wpu.save_figs_with_idx(foutname)
plt.show(block=True)

##==============================================================================
## %% Total displacement
##==============================================================================
#
#plt.figure()
#plt.hist(totalS.flatten(), 51)[0]
#plt.title(r'Total displacement $|\vec{S}|$ [pixels]', fontsize=16)
#if saveFigFlag: wpu.save_figs_with_idx(foutname)
#plt.show(block=True)


#==============================================================================
# %% Integration Real and Imgainary part
#==============================================================================


fig = plt.figure(figsize=(14, 5))
fig.suptitle('Histograms to evaluate data quality', fontsize=16)

ax1 = plt.subplot(121)
ax1 = plt.hist(np.real(integration_res).flatten()*1e6, 51)
ax1 = plt.title(r'Integration Real part', fontsize=16)

ax1 = plt.subplot(122)
ax2 = plt.hist(np.imag(integration_res).flatten()*1e6, 51)
ax2 = plt.title(r'Integration Imag part', fontsize=16)

if saveFigFlag: wpu.save_figs_with_idx(foutname)
plt.show(block=True)

# %% Crop Result and plot surface



(xVec_croped1, yVec_croped1,
 thickness_croped, _) = wpu.crop_graphic(xVec, yVec,
                                         thickness*1e6, verbose=True)

thickness_croped *= 1e-6
thickness_croped -= np.max(thickness_croped)

xmatrix_croped1, ymatrix_croped1 = wpu.realcoordmatrix_fromvec(xVec_croped1,
                                                               yVec_croped1)


# %% center fig

def center_max_2darray(array):
    '''
    crop the array in order to have the max at the center of the array
    '''
    center_i, center_j = np.unravel_index(array.argmax(), array.shape)

    if 2*center_i  > array.shape[0]:
        array = array[2*center_i-array.shape[0]:-1,:]
    else:
        array = array[0:2*center_i,:]

    if 2*center_j  > array.shape[1]:
        array = array[:, 2*center_j-array.shape[1]:-1]
    else:
        array = array[:,0:2*center_j]

    return array


# %%

thickness_croped = center_max_2darray(thickness_croped)


xVec_croped1 = wpu.realcoordvec(thickness_croped.shape[1], pixelsizeImg)
yVec_croped1 = wpu.realcoordvec(thickness_croped.shape[0], pixelsizeImg)

xmatrix_croped1, ymatrix_croped1 = np.meshgrid(xVec_croped1, yVec_croped1)



# %%

lim = 1

wpu.plot_profile(xmatrix_croped1[lim:-lim,lim:-lim]*1e6,
                 ymatrix_croped1[lim:-lim,lim:-lim]*1e6,
                 thickness_croped[lim:-lim,lim:-lim]*1e6,
                 title='Thickness centered [um]', xlabel='[um]', ylabel='[um]',
                 arg4main={'cmap':'spectral'}) #, xo=0.0, yo=0.0)




plt.show(block=True)

# %%

#



fig = plt.figure(figsize=(10, 7))
ax = fig.add_subplot(111, projection='3d')

stride = thickness_croped.shape[0] // 100
if stride == 0: stride = 1


surf = ax.plot_surface(xmatrix_croped1*1e6,
                       ymatrix_croped1*1e6,
                       thickness_croped*1e6,
                        rstride=stride, cstride=stride,
                        #vmin=-120, vmax=0,
                       cmap='spectral', linewidth=0.1)

plt.xlabel('[um]')
plt.ylabel('[um]')

plt.title('Thickness [um]', fontsize=18, weight='bold')
plt.colorbar(surf, shrink=.8, aspect=20)

plt.tight_layout()
if saveFigFlag: wpu.save_figs_with_idx(foutname)
plt.show(block=False)