コード例 #1
0
def save_profile_from_sdf(fname, nprofiles=3, direction='V', savecsv=True):

    data, pixelsize, headerdic = wpu.load_sdf_file(fname)

    saveFileSuf = fname.replace('.sdf', '')


    if 'V' in direction:

        xvec = wpu.realcoordvec(data.shape[0], pixelsize[0])[np.newaxis]
        data2save = np.c_[xvec.T]

        for j in np.linspace(0, np.shape(data)[1] - 1, nprofiles + 2, dtype=int):
            data2save = np.c_[data2save, data[:, j]]
    else:

        xvec = wpu.realcoordvec(data.shape[1], pixelsize[1])[np.newaxis]
        data2save = np.c_[xvec.T]

        for i in np.linspace(0, np.shape(data)[0] - 1, nprofiles + 2, dtype=int):
            data2save = np.c_[data2save, data[i, :]]


    if savecsv:

        wpu.save_csv_file(data2save,
                          wpu.get_unique_filename(saveFileSuf +
                                                  '_profiles_V', 'csv'),
                                                  headerList='bla')

    return data2save, headerdic
コード例 #2
0
    temp_Data[:, profilenumber] = target_original - fitted_target
    plt.figure(12)
    plt.subplot(121)
    plt.plot(temp_Data[:, 0], target_original, '-r', temp_Data[:, 0],
             fitted_target, '*k')
    plt.legend(['original', 'spherical fitting'])
    plt.title('target wavefront spherical fitting')
    plt.ylabel('rad')
    plt.xlabel('position')
    plt.subplot(122)
    plt.plot(temp_Data[:, 0], temp_Data[:, profilenumber], '-r')
    plt.title('residual')
    plt.ylabel('rad')
    plt.xlabel('position')

    figname = wpu.get_unique_filename(dirName + '/respons_func', 'png')
    plt.savefig(figname)
    plt.show()

# %%

npoints_interp = 200

xnew = np.linspace(-lim_xnew, lim_xnew, npoints_interp)

# %%

#exit()

# %% to filter the data to make it smooth for the analyze
コード例 #3
0
import wavepy.utils as wpu
import dxchange

# %% Load
img1fname, img2fname = wpu.gui_load_data_dark_filenames()

img1 = dxchange.read_tiff(img1fname)
img2 = dxchange.read_tiff(img2fname)


# %% alignment 1
img1_aligned, img2_aligned, pixel_shift = wpu.gui_align_two_images(img1, img2, option='pad')


# save files
outfname = wpu.get_unique_filename(img1fname.split('.')[0] + '_aligned',
                                   'tiff')
dxchange.write_tiff(img1_aligned, outfname)
wpu.print_blue('MESSAGE: file ' + outfname + ' saved.')

outfname = wpu.get_unique_filename(img2fname.split('.')[0] + '_aligned',
                                   'tiff')
dxchange.write_tiff(img2_aligned, outfname)
wpu.print_blue('MESSAGE: file ' + outfname + ' saved.')


# %%

plt.figure(figsize=(12, 12))
plt.imshow(img1_aligned[::5, ::5], cmap='viridis')
plt.title('img1')
wpu.save_figs_with_idx('aligned')
コード例 #4
0
contrastV = np.asarray([x[0] for x in res])
contrastH = np.asarray([x[1] for x in res])

p0 = np.asarray([x[2] for x in res])
pv = np.asarray([x[3] for x in res])
ph = np.asarray([x[4] for x in res])

pattern_period_Vert_z = pixelSize / (pv[:, 0] - p0[:, 0]) * img.shape[0]
pattern_period_Horz_z = pixelSize / (ph[:, 1] - p0[:, 1]) * img.shape[1]

# =============================================================================
# %% Save csv file
# =============================================================================

outputfname = wpu.get_unique_filename(fname2save, 'csv')

wpu.save_csv_file(np.c_[zvec.T, contrastV.T, contrastH.T,
                        pattern_period_Vert_z.T, pattern_period_Horz_z.T],
                  outputfname,
                  headerList=[
                      'z [m]', 'Vert Contrast', 'Horz Contrast',
                      'Vert Period [m]', 'Horz Period [m]'
                  ])

wpu.log_this('\nOutput file: ' + outputfname)

# =============================================================================
# %% Plot
# =============================================================================
コード例 #5
0
    label = fname.rsplit('/', 1)[1].split('.')[0]

    plt.plot(data[:, 0] * 1e6, data[:, 1], 'o', label=label)

    pfit = np.polyfit(data[:, 0], data[:, 1], 1)

    plt.plot(data[:, 0] * 1e6,
             pfit[0] * data[:, 0] + pfit[1],
             '--',
             label=label)

plt.ylabel('WF ' + headers[2])
plt.xlabel('[µm]')
plt.legend(loc='best', fontsize='x-small')

figname = wpu.get_unique_filename(dirName + '/respons_func', 'png')
plt.savefig(figname)
print('MESSAGE: Saving ' + figname)
plt.show(block=True)

# %%

plt.figure(figsize=(12, 8))

listOfDPC_removed = []

for data, fname in zip(listOfArrays, listOfFiles):

    label = fname.rsplit('/', 1)[1].split('.')[0]

    pfit = np.polyfit(data[:, 0], data[:, 1], 1)
コード例 #6
0
def plot_residual_parabolic_lens_2d(thickness,
                                    pixelsize,
                                    fitted,
                                    fitParameters,
                                    saveFigFlag=False,
                                    savePickle=False,
                                    str4title='',
                                    saveSdfData=False,
                                    vlimErrSigma=1,
                                    plotProfileFlag=True,
                                    plot3dFlag=True,
                                    makeAnimation=False):

    xmatrix, ymatrix = wpu.grid_coord(thickness, pixelsize)

    errorThickness = thickness - fitted
    argNotNAN = np.isfinite(errorThickness)

    factorx, unitx = wpu.choose_unit(xmatrix)
    factory, unity = wpu.choose_unit(ymatrix)
    factorz, unitz = wpu.choose_unit(errorThickness[argNotNAN])

    ptp = np.ptp(errorThickness[argNotNAN].flatten() * factorz)
    wpu.print_red('PV: {0:4.3g} '.format(ptp) + unitz[-1] + 'm')

    sigmaError = np.std(errorThickness[argNotNAN].flatten() * factorz)
    wpu.print_red('SDV: {0:4.3g} '.format(sigmaError) + unitz[-1] + 'm')

    str4title += r'Residual, ' + \
                 r'R $= {:.4g} \mu m$,'.format(fitParameters[0]*1e6) + '\n' + \
                 r'PV $= {0:.2f}$ '.format(ptp) + '$' + unitz + '  m$, '\
                 'SDV $= {0:.2f}$ '.format(sigmaError) + '$' + unitz + '  m$'

    # Plot Histogram

    plt.figure(figsize=(7, 8))
    plt.hist(errorThickness[argNotNAN] * factorz,
             100,
             color='r',
             histtype='step')
    plt.xlabel(r'Residual [$' + unitz + '  m$ ]')
    plt.title(str4title)

    if saveFigFlag:
        wpu.save_figs_with_idx(fname2save, extension='png')

    plt.show(block=False)

    # Plot Profiles

    vlimErr = wpu.mean_plus_n_sigma(errorThickness[argNotNAN] * factorz,
                                    vlimErrSigma / 2)
    cmap4graph = plt.cm.Spectral_r
    cmap4graph.set_over('m')
    cmap4graph.set_under('c')

    if plotProfileFlag:

        wpu.plot_profile(xmatrix * factorx,
                         ymatrix * factory,
                         errorThickness * factorz,
                         title=str4title,
                         xlabel=r'[$' + unitx + '  m$ ]',
                         ylabel=r'[$' + unity + '  m$ ]',
                         zlabel=r'[$' + unitz + '  m$ ]',
                         arg4main={
                             'cmap': 'Spectral_r',
                             'vmin': -vlimErr,
                             'vmax': vlimErr,
                             'extend': 'both'
                         })

    if savePickle or saveFigFlag:
        fig = plt.figure(figsize=(10, 7))

        cf = plt.contourf(xmatrix * factorx,
                          ymatrix * factory,
                          errorThickness * factorz,
                          256,
                          cmap=cmap4graph,
                          extend='both')

        plt.clim(-vlimErr, vlimErr)
        plt.contour(cf, levels=cf.levels[::32], colors='gray')

        plt.xlabel(r'[$' + unitx + '  m$ ]', fontsize=22)
        plt.ylabel(r'[$' + unity + '  m$ ]', fontsize=22)
        plt.title(str4title, fontsize=22)
        cbar = plt.colorbar(cf, shrink=.8, aspect=20)
        #        cbar.set_clim(-vlimErr, vlimErr)
        cbar.ax.set_title(r'[$' + unitz + '  m$ ]', y=1.01)

        plt.gca().set_aspect('equal', adjustable='box')
        plt.grid(color='grey')

        if saveFigFlag:
            wpu.save_figs_with_idx(fname2save, extension='png')

        if savePickle:
            wpu.save_figs_with_idx_pickle(fig, fname2save)

        plt.show(block=True)

    # Plot 3D

    if plot3dFlag:

        wpu.print_red('MESSAGE: Ploting 3d in the background')

        fig = plt.figure(figsize=(10, 7), facecolor="white")
        ax = fig.gca(projection='3d')
        plt.tight_layout(pad=2.5)

        surf = ax.plot_trisurf(xmatrix[argNotNAN].flatten() * factorx,
                               ymatrix[argNotNAN].flatten() * factory,
                               errorThickness[argNotNAN].flatten() * factorz,
                               vmin=-vlimErr,
                               vmax=vlimErr,
                               cmap=cmap4graph,
                               linewidth=0.1,
                               shade=False)

        ax.view_init(azim=-120, elev=40)

        plt.xlabel(r'$x$ [$' + unitx + '  m$ ]')
        plt.ylabel(r'$y$ [$' + unity + '  m$ ]')

        plt.title(str4title)

        cbar = plt.colorbar(surf, shrink=.8, aspect=20, extend='both')
        cbar.ax.set_title(r'[$' + unitz + '  m$ ]', y=1.01)

        plt.tight_layout()

        if saveFigFlag:
            wpu.save_figs_with_idx(fname2save, extension='png')

            ax.view_init(azim=690, elev=40)

            wpu.save_figs_with_idx(fname2save, extension='png')

        if makeAnimation:
            #            plt.show(block=False)
            plt.pause(1.0)
            wpu.rocking_3d_figure(ax,
                                  wpu.get_unique_filename(fname2save, 'gif'),
                                  elevOffset=45,
                                  azimOffset=60,
                                  elevAmp=0,
                                  azimAmpl=-1,
                                  dpi=80,
                                  npoints=5)

        plt.pause(1.0)
        plt.close('all')
        #    plt.show(block=True)

    if saveSdfData:
        mask_for_sdf = errorThickness * 0.0
        mask_for_sdf[~argNotNAN] = 1.0
        errorThickness[~argNotNAN] = 00000000
        wpu.save_sdf_file(
            errorThickness, pixelsize,
            wpu.get_unique_filename(fname2save + '_residual', 'sdf'))
        wpu.save_sdf_file(
            mask_for_sdf, pixelsize,
            wpu.get_unique_filename(fname2save + '_residual_mask', 'sdf'))

    return sigmaError / factorz, ptp / factorz
コード例 #7
0
def plot_residual_1d(xvec,
                     data,
                     fitted,
                     str4title='',
                     saveFigFlag=False,
                     saveAsciiFlag=False):

    # Plot Horizontal profile

    errorThickness = -data + fitted
    argNotNAN = np.isfinite(errorThickness)

    factorx, unitx = wpu.choose_unit(xvec)
    factory1, unity1 = wpu.choose_unit(data)
    factory2, unity2 = wpu.choose_unit(errorThickness)

    ptp = np.ptp(errorThickness[argNotNAN].flatten() * factory2)
    wpu.print_red('PV: {0:4.3g} '.format(ptp) + unity2[-1] + 'm')

    sigmaError = np.std(errorThickness[argNotNAN].flatten() * factory2)
    wpu.print_red('SDV: {0:4.3g} '.format(sigmaError) + unity2[-1] + 'm')

    str4title += '\n' + \
                 r'PV $= {0:.2f}$ '.format(ptp) + '$' + unity2 + '  m$, '\
                 'SDV $= {0:.2f}$ '.format(sigmaError) + '$' + unity2 + '  m$'

    plt.figure(figsize=(10, 7))
    ax1 = plt.gca()
    ax1.plot(xvec[argNotNAN] * factorx,
             data[argNotNAN] * factory1,
             '-ko',
             markersize=5,
             label='1D data')

    ax1.plot(xvec[argNotNAN] * factorx,
             fitted[argNotNAN] * factory1,
             '-+r',
             label='Fit parabolic')

    ax2 = ax1.twinx()

    # trick to add both axes to legend
    ax2.plot(np.nan, '-ko', label='1D data')
    ax2.plot(np.nan, '-+r', label='Fit parabolic')

    ax2.plot(xvec[argNotNAN] * factorx,
             errorThickness[argNotNAN] * factory2,
             '-+',
             markersize=5,
             label='fit residual')

    plt.title(str4title)

    for tl in ax2.get_yticklabels():
        tl.set_color('b')

    ax2.legend(loc=1, fontsize='small')
    # trick to add both axes to legend

    ax1.grid(color='gray')

    ax1.set_xlabel(r'[$' + unitx + ' m$]')
    ax1.set_ylabel(r'Thickness ' + r'[$' + unity1 + ' m$]')

    #    ax2.set_ylim([-20, 20])

    ax2.set_ylim(-1.1 * np.max(np.abs(errorThickness[argNotNAN]) * factory2),
                 1.1 * np.max(np.abs(errorThickness[argNotNAN]) * factory2))
    ax2.set_ylabel(r'Residual' + r'[$' + unity2 + ' m$]')
    ax2.grid(b='off')
    plt.xlim(-1.1 * np.max(xvec * factorx), 1.1 * np.max(xvec * factorx))

    plt.tight_layout(rect=(0, 0, 1, .98))

    if saveFigFlag:
        wpu.save_figs_with_idx(fname2save, extension='png')

    if saveAsciiFlag:
        csv_fname = wpu.get_unique_filename(fname2save, 'csv')
        np.savetxt(csv_fname,
                   np.transpose([xvec, data, fitted, fitted - data]),
                   delimiter=',\t',
                   header="xvec, data, fitted, residual, " + str4title,
                   fmt='%.6g')
    plt.show(block=False)
コード例 #8
0
def curv_from_height(height,
                     virtual_pixelsize,
                     grazing_angle=0.0,
                     projectionFromDiv=1.0,
                     labels=[],
                     xlabel='x',
                     ylabel='Curvature',
                     titleStr='',
                     saveFileSuf=''):

    ls_cycle, lc_cycle = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                              ncurves=height.shape[1] - 1,
                                              cmap_str='gist_rainbow_r')

    if grazing_angle // .00001 > 0:
        projection = 1 / np.sin(grazing_angle) * projectionFromDiv
    else:
        projection = projectionFromDiv

    projected_pixel = virtual_pixelsize * projection
    xvec = wpu.realcoordvec(height.shape[0] - 2, projected_pixel)

    print('projected_pixel')
    print(projected_pixel)

    plt.figure(figsize=(12, 12 * 9 / 16))
    list_curv = [xvec]

    header = [xlabel + ' [m]']

    for j_line in range(1, height.shape[1]):

        curv = np.diff(np.diff(height[:, j_line])) / projected_pixel**2

        if j_line == 1:
            factor_x, unit_x = wpu.choose_unit(xvec)

            #factor_y, unit_y = wpu.choose_unit(curv)

        list_curv.append(curv)
        header.append(labels[j_line - 1])

        plt.plot(xvec * factor_x,
                 curv,
                 next(ls_cycle),
                 c=next(lc_cycle),
                 label=labels[j_line - 1])

    marginx = 0.1 * np.ptp(xvec * factor_x)
    plt.xlim(
        [np.min(xvec * factor_x) - marginx,
         np.max(xvec * factor_x) + marginx])
    plt.xlabel(xlabel + r' [$' + unit_x + ' m$]')
    plt.ylabel(ylabel + r'[$m^{-1}$]')
    plt.legend(loc=0, fontsize=12)

    if grazing_angle // .00001 > 0:

        plt.title(titleStr + 'Mirror Curvature,\n' +
                  'grazing angle {:.2f} mrad,\n'.format(grazing_angle * 1e3) +
                  'projection due divergence = ' +
                  r'$ \times $ {:.2f}'.format(projectionFromDiv))
    else:
        plt.title(titleStr + 'Curvature')

    plt.tight_layout()
    wpu.save_figs_with_idx(saveFileSuf)
    plt.show()

    data2saveV = np.asarray(list_curv).T

    header.append(ylabel + ' [1/m]')

    if grazing_angle // .00001 > 0:
        header.append(', grazing_angle = {:.4g}'.format(grazing_angle))

    if projectionFromDiv // 1 != 1:
        header.append('projection due divergence = ' +
                      '{:.2f}x'.format(projectionFromDiv))

    wpu.save_csv_file(data2saveV,
                      wpu.get_unique_filename(saveFileSuf + '_curv_' + xlabel,
                                              'csv'),
                      headerList=header)

    return np.asarray(list_curv).T
コード例 #9
0
def _n_profiles_H_V(arrayH,
                    arrayV,
                    virtual_pixelsize,
                    zlabel=r'z',
                    titleH='Horiz',
                    titleV='Vert',
                    nprofiles=5,
                    filter_width=0,
                    remove2ndOrder=False,
                    saveFileSuf='',
                    saveFigFlag=True):

    xxGrid, yyGrid = wpu.grid_coord(arrayH, virtual_pixelsize)

    fit_coefs = [[], []]
    data2saveH = None
    data2saveV = None
    labels_H = None
    labels_V = None

    plt.rcParams['lines.markersize'] = 4
    plt.rcParams['lines.linewidth'] = 2

    # Horizontal
    if np.all(np.isfinite(arrayH)):

        plt.figure(figsize=(12, 12 * 9 / 16))

        xvec = xxGrid[0, :]
        data2saveH = np.c_[xvec]
        header = ['x [m]']

        ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                                ncurves=nprofiles,
                                                cmap_str='gist_rainbow_r')

        lc = []
        labels_H = []
        for i, row in enumerate(
                np.linspace(filter_width // 2,
                            np.shape(arrayV)[0] - filter_width // 2 - 1,
                            nprofiles + 2,
                            dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            if filter_width != 0:
                yvec = arrayH[row - filter_width:row + filter_width, :]
                yvec = np.sum(yvec, 0) / filter_width / 2
            else:
                yvec = arrayH[row, :]

            lc.append(next(lc_jet))
            p01 = np.polyfit(xvec, yvec, 1)
            fit_coefs[0].append(p01)

            if remove2ndOrder:
                yvec -= p01[0] * xvec + p01[1]

            plt.plot(xvec * 1e6,
                     yvec,
                     next(ls_cycle),
                     color=lc[i - 1],
                     label=str(row))

            if not remove2ndOrder:
                plt.plot(xvec * 1e6,
                         p01[0] * xvec + p01[1],
                         '--',
                         color=lc[i - 1],
                         lw=3)

            data2saveH = np.c_[data2saveH, yvec]
            header.append(str(row))
            labels_H.append(str(row))

        if remove2ndOrder:
            titleH = titleH + ', 2nd order removed'
        plt.legend(title='Pixel Y', loc=0, fontsize=12)

        plt.xlabel(r'x [$\mu m$]', fontsize=18)
        plt.ylabel(zlabel, fontsize=18)
        plt.title(titleH + ', Filter Width = {:d} pixels'.format(filter_width),
                  fontsize=20)

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_H')

        plt.show(block=False)

        header.append(zlabel +
                      ', Filter Width = {:d} pixels'.format(filter_width))

        wpu.save_csv_file(data2saveH,
                          wpu.get_unique_filename(
                              saveFileSuf + '_WF_profiles_H', 'csv'),
                          headerList=header)

        plt.figure(figsize=(12, 12 * 9 / 16))
        plt.imshow(arrayH,
                   cmap='RdGy',
                   vmin=wpu.mean_plus_n_sigma(arrayH, -3),
                   vmax=wpu.mean_plus_n_sigma(arrayH, 3))
        plt.xlabel('Pixel')
        plt.ylabel('Pixel')
        plt.title(titleH + ', Profiles Position')

        currentAxis = plt.gca()

        _, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                         ncurves=nprofiles,
                                         cmap_str='gist_rainbow_r')

        for i, row in enumerate(
                np.linspace(filter_width // 2,
                            np.shape(arrayV)[0] - filter_width // 2 - 1,
                            nprofiles + 2,
                            dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            currentAxis.add_patch(
                Rectangle((-.5, row - filter_width // 2 - .5),
                          np.shape(arrayH)[1],
                          filter_width,
                          facecolor=lc[i - 1],
                          alpha=.5))
            plt.axhline(row, color=lc[i - 1])

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_H')

        plt.show(block=True)

    # Vertical
    if np.all(np.isfinite(arrayV)):

        plt.figure(figsize=(12, 12 * 9 / 16))

        xvec = yyGrid[:, 0]
        data2saveV = np.c_[xvec]
        header = ['y [m]']

        ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                                ncurves=nprofiles,
                                                cmap_str='gist_rainbow_r')

        lc = []
        labels_V = []
        for i, col in enumerate(
                np.linspace(filter_width // 2,
                            np.shape(arrayH)[1] - filter_width // 2 - 1,
                            nprofiles + 2,
                            dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            if filter_width != 0:
                yvec = arrayV[:, col - filter_width:col + filter_width]
                yvec = np.sum(yvec, 1) / filter_width / 2
            else:
                yvec = arrayV[:, col]

            lc.append(next(lc_jet))
            p10 = np.polyfit(xvec, yvec, 1)
            fit_coefs[1].append(p10)

            if remove2ndOrder:
                yvec -= p10[0] * xvec + p10[1]

            plt.plot(xvec * 1e6,
                     yvec,
                     next(ls_cycle),
                     color=lc[i - 1],
                     label=str(col))

            if not remove2ndOrder:
                plt.plot(xvec * 1e6,
                         p10[0] * xvec + p10[1],
                         '--',
                         color=lc[i - 1],
                         lw=3)

            data2saveV = np.c_[data2saveV, yvec]
            header.append(str(col))
            labels_V.append(str(col))

        if remove2ndOrder:
            titleV = titleV + ', 2nd order removed'

        plt.legend(title='Pixel X', loc=0, fontsize=12)

        plt.xlabel(r'y [$\mu m$]', fontsize=18)
        plt.ylabel(zlabel, fontsize=18)

        plt.title(titleV + ', Filter Width = {:d} pixels'.format(filter_width),
                  fontsize=20)
        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Y')
        plt.show(block=False)

        header.append(zlabel +
                      ', Filter Width = {:d} pixels'.format(filter_width))

        wpu.save_csv_file(data2saveV,
                          wpu.get_unique_filename(
                              saveFileSuf + '_WF_profiles_V', 'csv'),
                          headerList=header)

        plt.figure(figsize=(12, 12 * 9 / 16))
        plt.imshow(arrayV,
                   cmap='RdGy',
                   vmin=wpu.mean_plus_n_sigma(arrayV, -3),
                   vmax=wpu.mean_plus_n_sigma(arrayV, 3))
        plt.xlabel('Pixel')
        plt.ylabel('Pixel')
        plt.title(titleV + ', Profiles Position')

        currentAxis = plt.gca()

        for i, col in enumerate(
                np.linspace(filter_width // 2,
                            np.shape(arrayH)[1] - filter_width // 2 - 1,
                            nprofiles + 2,
                            dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            currentAxis.add_patch(
                Rectangle((col - filter_width // 2 - .5, -.5),
                          filter_width,
                          np.shape(arrayV)[0],
                          facecolor=lc[i - 1],
                          alpha=.5))
            plt.axvline(col, color=lc[i - 1])

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Y')

        plt.show(block=True)

    return data2saveH, data2saveV, labels_H, labels_V, fit_coefs
コード例 #10
0
def integrate_DPC_cumsum(data_DPC,
                         wavelength,
                         grazing_angle=0.0,
                         projectionFromDiv=1.0,
                         labels=[],
                         xlabel='x',
                         ylabel='Height',
                         titleStr='',
                         saveFileSuf=''):

    ls_cycle, lc_cycle = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                              ncurves=data_DPC.shape[1] - 1,
                                              cmap_str='gist_rainbow_r')

    if grazing_angle // .00001 > 0:
        projection = 1 / np.sin(grazing_angle) * projectionFromDiv
    else:
        projection = projectionFromDiv

    xvec = data_DPC[:, 0] * projection

    plt.figure(figsize=(12, 12 * 9 / 16))
    list_integrated = [xvec]

    header = [xlabel + ' [m]']

    for j_line in range(1, data_DPC.shape[1]):

        integrated = (
            np.cumsum(data_DPC[:, j_line] - np.mean(data_DPC[:, j_line])) *
            (xvec[1] - xvec[0]))

        integrated *= -1 / 2 / np.pi * wavelength * np.abs(projection)

        # TODO: check here!!

        if j_line == 1:
            factor_x, unit_x = wpu.choose_unit(xvec)
            factor_y, unit_y = wpu.choose_unit(integrated)

        list_integrated.append(integrated)
        header.append(labels[j_line - 1])

        plt.plot(xvec * factor_x,
                 integrated * factor_y,
                 next(ls_cycle),
                 c=next(lc_cycle),
                 label=labels[j_line - 1])

    marginx = 0.1 * np.ptp(xvec * factor_x)
    plt.xlim(
        [np.min(xvec * factor_x) - marginx,
         np.max(xvec * factor_x) + marginx])
    plt.xlabel(xlabel + r' [$' + unit_x + ' m$]')
    plt.ylabel(ylabel + r' [$' + unit_y + ' m$]')
    plt.legend(loc=0, fontsize=12)

    if grazing_angle // .00001 > 0:

        plt.title(titleStr + 'Mirror Height,\n' +
                  'grazing angle {:.2f} mrad,\n'.format(grazing_angle * 1e3) +
                  'projection due divergence = ' +
                  r'$ \times $ {:.2f}'.format(projectionFromDiv))
    else:
        plt.title(titleStr + 'Integration Cumulative Sum')

    plt.tight_layout()
    wpu.save_figs_with_idx(saveFileSuf)
    plt.show()

    data2saveV = np.asarray(list_integrated).T

    header.append(ylabel + ' [m]')

    if grazing_angle // .00001 > 0:
        header.append('grazing_angle = {:.4g}'.format(grazing_angle))

    if projectionFromDiv // 1 != 1:
        header.append('projection due divergence = ' +
                      '{:.2f}x'.format(projectionFromDiv))

    wpu.save_csv_file(data2saveV,
                      wpu.get_unique_filename(
                          saveFileSuf + '_integrated_' + xlabel, 'csv'),
                      headerList=header)

    return np.asarray(list_integrated).T
コード例 #11
0
def _n_profiles_H_V(arrayH, arrayV, virtual_pixelsize,
                    zlabel=r'z',
                    titleH='Horiz', titleV='Vert',
                    nprofiles=5, filter_width=0,
                    remove1stOrderDPC=False,
                    saveFileSuf='',
                    saveFigFlag=True):

    xxGrid, yyGrid = wpu.grid_coord(arrayH, virtual_pixelsize)

    fit_coefs = [[], []]
    data2saveH = None
    data2saveV = None
    labels_H = None
    labels_V = None

    plt.rcParams['lines.markersize'] = 4
    plt.rcParams['lines.linewidth'] = 2

    # Horizontal
    if np.all(np.isfinite(arrayH)):

        plt.figure(figsize=(12, 12*9/16))

        xvec = xxGrid[0, :]
        data2saveH = np.c_[xvec]
        header = ['x [m]']

        if filter_width != 0:
            arrayH_filtered = uniform_filter1d(arrayH, filter_width, 0)
        else:
            arrayH_filtered = arrayH

        ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                                ncurves=nprofiles,
                                                cmap_str='gist_rainbow_r')

        lc = []
        labels_H = []
        for i, row in enumerate(np.linspace(filter_width//2,
                                            np.shape(arrayV)[0]-filter_width//2-1,
                                            nprofiles + 2, dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            yvec = arrayH_filtered[row, :]

            lc.append(next(lc_jet))
            p01 = np.polyfit(xvec, yvec, 1)
            fit_coefs[0].append(p01)

            if remove1stOrderDPC:
                yvec -= p01[0]*xvec + p01[1]

            plt.plot(xvec*1e6, yvec, next(ls_cycle), color=lc[i-1],
                     label=str(row))

            if not remove1stOrderDPC:
                plt.plot(xvec*1e6, p01[0]*xvec + p01[1], '--',
                         color=lc[i-1], lw=3)

            data2saveH = np.c_[data2saveH, yvec]
            header.append(str(row))
            labels_H.append(str(row))

        if remove1stOrderDPC:
            titleH = titleH + ', 2nd order removed'
        plt.legend(title='Pixel Y', loc=0, fontsize=12)

        plt.xlabel(r'x [$\mu m$]', fontsize=18)
        plt.ylabel(zlabel, fontsize=18)
        plt.title(titleH + ', Filter Width = {:d} pixels'.format(filter_width),
                  fontsize=20)

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_H')

        plt.show(block=False)

        header.append(zlabel + ', Filter Width = {:d} pixels'.format(filter_width))

        wpu.save_csv_file(data2saveH,
                          wpu.get_unique_filename(saveFileSuf +
                                                  '_WF_profiles_H', 'csv'),
                          headerList=header)

        plt.figure(figsize=(12, 12*9/16))
        plt.imshow(arrayH, cmap='RdGy',
                   vmin=wpu.mean_plus_n_sigma(arrayH, -3),
                   vmax=wpu.mean_plus_n_sigma(arrayH, 3))
        plt.xlabel('Pixel')
        plt.ylabel('Pixel')
        plt.title(titleH + ', Profiles Position')

        currentAxis = plt.gca()

        _, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                         ncurves=nprofiles,
                                         cmap_str='gist_rainbow_r')

        for i, row in enumerate(np.linspace(filter_width//2,
                                            np.shape(arrayV)[0]-filter_width//2-1,
                                            nprofiles + 2, dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            currentAxis.add_patch(Rectangle((-.5, row - filter_width//2 - .5),
                                            np.shape(arrayH)[1], filter_width,
                                            facecolor=lc[i-1], alpha=.5))
            plt.axhline(row, color=lc[i-1])

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_H')

        plt.show(block=True)

    # Vertical
    if np.all(np.isfinite(arrayV)):

        plt.figure(figsize=(12, 12*9/16))

        xvec = yyGrid[:, 0]
        data2saveV = np.c_[xvec]
        header = ['y [m]']

        if filter_width != 0:
            arrayV_filtered = uniform_filter1d(arrayV, filter_width, 1)
        else:
            arrayV_filtered = arrayV

        ls_cycle, lc_jet = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                                ncurves=nprofiles,
                                                cmap_str='gist_rainbow_r')

        lc = []
        labels_V = []
        for i, col in enumerate(np.linspace(filter_width//2,
                                            np.shape(arrayH)[1]-filter_width//2-1,
                                            nprofiles + 2, dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue

            yvec = arrayV_filtered[:, col]

            lc.append(next(lc_jet))
            p10 = np.polyfit(xvec, yvec, 1)
            fit_coefs[1].append(p10)

            if remove1stOrderDPC:
                yvec -= p10[0]*xvec + p10[1]

            plt.plot(xvec*1e6, yvec, next(ls_cycle), color=lc[i-1],
                     label=str(col))

            if not remove1stOrderDPC:
                plt.plot(xvec*1e6, p10[0]*xvec + p10[1], '--',
                         color=lc[i-1], lw=3)

            data2saveV = np.c_[data2saveV, yvec]
            header.append(str(col))
            labels_V.append(str(col))

        if remove1stOrderDPC:
            titleV = titleV + ', 2nd order removed'

        plt.legend(title='Pixel X', loc=0, fontsize=12)

        plt.xlabel(r'y [$\mu m$]', fontsize=18)
        plt.ylabel(zlabel, fontsize=18)

        plt.title(titleV + ', Filter Width = {:d} pixels'.format(filter_width),
                  fontsize=20)
        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Y')
        plt.show(block=False)

        header.append(zlabel + ', Filter Width = {:d} pixels'.format(filter_width))

        wpu.save_csv_file(data2saveV,
                          wpu.get_unique_filename(saveFileSuf +
                                                  '_WF_profiles_V', 'csv'),
                          headerList=header)

        plt.figure(figsize=(12, 12*9/16))
        plt.imshow(arrayV, cmap='RdGy',
                   vmin=wpu.mean_plus_n_sigma(arrayV, -3),
                   vmax=wpu.mean_plus_n_sigma(arrayV, 3))
        plt.xlabel('Pixel')
        plt.ylabel('Pixel')
        plt.title(titleV + ', Profiles Position')

        currentAxis = plt.gca()

        for i, col in enumerate(np.linspace(filter_width//2,
                                            np.shape(arrayH)[1]-filter_width//2-1,
                                            nprofiles + 2, dtype=int)):

            if i == 0 or i == nprofiles + 1:
                continue


            currentAxis.add_patch(Rectangle((col - filter_width//2 - .5, -.5),
                                            filter_width, np.shape(arrayV)[0],
                                            facecolor=lc[i-1], alpha=.5))
            plt.axvline(col, color=lc[i-1])

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Y')

        plt.show(block=True)

    return data2saveH, data2saveV, labels_H, labels_V, fit_coefs
コード例 #12
0
def curv_from_height(height, virtual_pixelsize,
                     grazing_angle=0.0, projectionFromDiv=1.0,
                     labels=[],
                     xlabel='x', ylabel='Curvature',
                     titleStr='', saveFileSuf=''):

    ls_cycle, lc_cycle = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                              ncurves=height.shape[1] - 1,
                                              cmap_str='gist_rainbow_r')

    if grazing_angle//.00001 > 0:
        projection = 1/np.sin(grazing_angle)*projectionFromDiv
    else:
        projection = projectionFromDiv

    projected_pixel = virtual_pixelsize*projection
    xvec = wpu.realcoordvec(height.shape[0]-2, projected_pixel)

    print('projected_pixel')
    print(projected_pixel)

    plt.figure(figsize=(12, 12*9/16))
    list_curv = [xvec]

    header = [xlabel + ' [m]']

    for j_line in range(1, height.shape[1]):

        curv = np.diff(np.diff(height[:, j_line]))/projected_pixel**2

        if j_line == 1:
            factor_x, unit_x = wpu.choose_unit(xvec)

            #factor_y, unit_y = wpu.choose_unit(curv)

        list_curv.append(curv)
        header.append(labels[j_line - 1])

        plt.plot(xvec*factor_x, curv,
                 next(ls_cycle), c=next(lc_cycle),
                 label=labels[j_line - 1])

    marginx = 0.1*np.ptp(xvec*factor_x)
    plt.xlim([np.min(xvec*factor_x)-marginx,
              np.max(xvec*factor_x)+marginx])
    plt.xlabel(xlabel + r' [$' + unit_x + ' m$]')
    plt.ylabel(ylabel + r'[$m^{-1}$]')
    plt.legend(loc=0, fontsize=12)

    if grazing_angle//.00001 > 0:

        plt.title(titleStr + 'Mirror Curvature,\n' +
                  'grazing angle {:.2f} mrad,\n'.format(grazing_angle*1e3) +
                  'projection due divergence = ' +
                  r'$ \times $ {:.2f}'.format(projectionFromDiv))
    else:
        plt.title(titleStr + 'Curvature')

    plt.tight_layout()
    wpu.save_figs_with_idx(saveFileSuf)
    plt.show()

    data2saveV = np.asarray(list_curv).T

    header.append(ylabel + ' [1/m]')

    if grazing_angle//.00001 > 0:
        header.append(', grazing_angle = {:.4g}'.format(grazing_angle))

    if projectionFromDiv//1 != 1:
        header.append('projection due divergence = ' +
                      '{:.2f}x'.format(projectionFromDiv))

    wpu.save_csv_file(data2saveV,
                      wpu.get_unique_filename(saveFileSuf +
                                              '_curv_' + xlabel, 'csv'),
                      headerList=header)

    return np.asarray(list_curv).T
コード例 #13
0
def integrate_DPC_cumsum(data_DPC, wavelength,
                         grazing_angle=0.0, projectionFromDiv=1.0,
                         remove2ndOrder=False,
                         labels=[],
                         xlabel='x', ylabel='Height',
                         titleStr='', saveFileSuf=''):

    ls_cycle, lc_cycle = wpu.line_style_cycle(['-'], ['o', 's', 'd', '^'],
                                              ncurves=data_DPC.shape[1] - 1,
                                              cmap_str='gist_rainbow_r')

    if grazing_angle//.00001 > 0:
        projection = 1/np.sin(grazing_angle)*projectionFromDiv
    else:
        projection = projectionFromDiv

    xvec = data_DPC[:, 0]*projection

    plt.figure(figsize=(12, 12*9/16))
    list_integrated = [xvec]

    header = [xlabel + ' [m]']

    for j_line in range(1, data_DPC.shape[1]):

        integrated = (np.cumsum(data_DPC[:, j_line] - np.mean(data_DPC[:, j_line]))
                      * (xvec[1]-xvec[0])) # TODO: removed mean 20181020

        #        integrated = (np.cumsum(data_DPC[:, j_line])) * (xvec[1]-xvec[0])

        integrated *= -1/2/np.pi*wavelength*np.abs(projection)

        p02 = np.polyfit(xvec, integrated, 2)
        fitted_pol2 = p02[0]*xvec**2 + p02[1]*xvec + p02[2]

        if remove2ndOrder:

            integrated -= fitted_pol2
            titleStr += 'Removed 2nd order, '

        # TODO: check here!!

        if j_line == 1:
            factor_x, unit_x = wpu.choose_unit(xvec)
            factor_y, unit_y = wpu.choose_unit(integrated)

        list_integrated.append(integrated)
        header.append(labels[j_line - 1])

        lc = next(lc_cycle)
        plt.plot(xvec*factor_x,
                 integrated*factor_y,
                 next(ls_cycle), c=lc,
                 label=labels[j_line - 1])

        if not remove2ndOrder:
            plt.plot(xvec*1e6, (fitted_pol2)*factor_y,
                     '--', color=lc, lw=3)

    marginx = 0.1*np.ptp(xvec*factor_x)
    plt.xlim([np.min(xvec*factor_x)-marginx,
              np.max(xvec*factor_x)+marginx])
    plt.xlabel(xlabel + r' [$' + unit_x + ' m$]')
    plt.ylabel(ylabel + r' [$' + unit_y + ' m$]')
    plt.legend(loc=0, fontsize=12)

    if grazing_angle//.00001 > 0:

        plt.title(titleStr + 'Mirror Height,\n' +
                  'grazing angle {:.2f} mrad,\n'.format(grazing_angle*1e3) +
                  'projection due divergence = ' +
                  r'$ \times $ {:.2f}'.format(projectionFromDiv))
    else:
        plt.title(titleStr + 'Integration Cumulative Sum')

    plt.tight_layout()
    wpu.save_figs_with_idx(saveFileSuf)
    plt.show()

    data2saveV = np.asarray(list_integrated).T

    header.append(ylabel + ' [m]')

    if grazing_angle//.00001 > 0:
        header.append('grazing_angle = {:.4g}'.format(grazing_angle))

    if projectionFromDiv//1 != 1:
        header.append('projection due divergence = ' +
                      '{:.2f}x'.format(projectionFromDiv))

    wpu.save_csv_file(data2saveV,
                      wpu.get_unique_filename(saveFileSuf +
                                              '_integrated_' + xlabel, 'csv'),
                      headerList=header)

    return np.asarray(list_integrated).T
コード例 #14
0
def main_terminal(data_dir,
                  zvec_from,
                  startDist,
                  step_z_scan,
                  image_per_point,
                  strideFile,
                  pixelSize=0.65e-6,
                  gratingPeriod=4.8e-6,
                  pattern='Diagonal',
                  sourceDistanceV=-1,
                  sourceDistanceH=32,
                  unFilterSize=1,
                  searchRegion=20,
                  idx4crop=[0, -1, 0, -1],
                  darkRegionSelctionFlag=True):
    '''
        *** all unit in [m]
        data_dir:       data folder path
        zvec_from:      distance type:
                        'Calculated'
                        'Tabled'
        startDist:      started distance postion
        step_z_scan:    step size
        image_per_point:    images number for every distance
        strideFile:     Stride (Use only every XX files)

        pixelSize:       Pixel Size
        gratingPeriod:   CB Grating Period
        pattern:         grating pattern
                        'Diagonal' or 'Edge']
        sourceDistanceV:    Distance to Source
                             in the VERTICAL [m]
        sourceDistanceH:    Distance to Source
                            in the Horizontal [m]
        unFilterSize:   Size for Uniform Filter [Pixels]
                        default_value  1
        searchRegion:   Size of Region for Searching
                        the Peak [in Pixels]
                        default_value=20
        idx4crop:       crop area
                        [low_y, high_y, low_x, high_x ]
        darkRegionSelctionFlag:     use dark region [0, 20, 0, 20]?

    '''
    wpu._mpl_settings_4_nice_graphs()

    # =============================================================================
    # %% Load Image
    # =============================================================================

    originalDir = os.getcwd()

    # samplefileName = easyqt.get_file_names("Choose one of the scan files")[0]

    # data_dir = samplefileName.rsplit('/', 1)[0]
    os.chdir(data_dir)

    try:
        os.mkdir(data_dir + '/output/')
    except:
        pass

    fname2save = data_dir + '/output/' + 'zscan'

    # wpu.print_blue('MESSAGE: Loading files ' +
    #                samplefileName.rsplit('_', 1)[0] + '*.tif')
    wpu.print_blue('MESSAGE: Loading files ' + data_dir + '/*.tif')

    # listOfDataFiles = glob.glob(samplefileName.rsplit('_', 2)[0] + '*.tif')
    listOfDataFiles = glob.glob(os.path.join(data_dir, '*.tif'))
    listOfDataFiles.sort()
    nfiles = len(listOfDataFiles)

    # zvec_from = easyqt.get_choice(message='z distances is calculated or from table?',
    #                               title='Title',
    #                               choices=['Calculated', 'Tabled'])

    # %%

    if zvec_from == 'Calculated':

        # startDist = easyqt.get_float('Starting distance scan [mm]',
        #                              title='Title',
        #                              default_value=20)*1e-3

        # step_z_scan = easyqt.get_float('Step size scan [mm]',
        #                                title='Title',
        #                                default_value=5)*1e-3

        # image_per_point = easyqt.get_int('Number of images by step',
        #                                  title='Title',
        #                                  default_value=1)

        zvec = np.linspace(
            startDist,
            startDist + step_z_scan * (nfiles / image_per_point - 1),
            int(nfiles / image_per_point))
        zvec = zvec.repeat(image_per_point)

        # strideFile = easyqt.get_int('Stride (Use only every XX files)',
        #                             title='Title',
        #                             default_value=1)
        listOfDataFiles = listOfDataFiles[0::strideFile]
        zvec = zvec[0::strideFile]
        print(zvec)
    elif zvec_from == 'Tabled':

        zvec = np.loadtxt(
            easyqt.get_file_names("Table with the z distance values in mm")
            [0]) * 1e-3
        step_z_scan = np.mean(np.diff(zvec))

    if step_z_scan > 0:
        pass
    else:
        listOfDataFiles = listOfDataFiles[::-1]
        zvec = zvec[::-1]

    img = dxchange.read_tiff(listOfDataFiles[0])

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

    # pixelSize = easyqt.get_float("Enter Pixel Size [um]",
    #                              title='Experimental Values',
    #                              default_value=.6500, decimals=5)*1e-6

    # gratingPeriod = easyqt.get_float("Enter CB Grating Period [um]",
    #                                  title='Experimental Values',
    #                                  default_value=4.8)*1e-6

    # pattern = easyqt.get_choice(message='Select CB Grating Pattern',
    #                             title='Title',
    #                             choices=['Diagonal', 'Edge'])
    # #                            choices=['Edge', 'Diagonal'])

    # sourceDistanceV = easyqt.get_float("Enter Distance to Source\n in the VERTICAL [m]",
    #                                    title='Experimental Values',
    #                                    default_value=-0.73)

    # sourceDistanceH = easyqt.get_float("Enter Distance to Source\n in the Horizontal [m]",
    #                                    title='Experimental Values',
    #                                    default_value=34.0)

    # unFilterSize = easyqt.get_int("Enter Size for Uniform Filter [Pixels]\n" +
    #                               "    (Enter 1 to NOT use the filter)",
    #                               title='Experimental Values',
    #                               default_value=1)

    # searchRegion = easyqt.get_int("Enter Size of Region for Searching\n the Peak [in Pixels]",
    #                               title='Experimental Values',
    #                               default_value=20)

    os.chdir(originalDir)

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

    idx4crop = [0, -1, 0, -1]

    # [colorlimit,
    #  cmap] = wpu.plot_slide_colorbar(img,
    #                                  title='SELECT COLOR SCALE,\n' +
    #                                  'Raw Image, No Crop',
    #                                  xlabel=r'x [$\mu m$ ]',
    #                                  ylabel=r'y [$\mu m$ ]',
    #                                  extent=wpu.extent_func(img,
    #                                                         pixelSize)*1e6)

    # idx4crop = wpu.graphical_roi_idx(img, verbose=True,
    #                                  kargs4graph={'cmap': cmap,
    #                                               'vmin': colorlimit[0],
    #                                               'vmax': colorlimit[1]})

    wpu.print_blue("MESSAGE: idx for cropping")
    wpu.print_blue(idx4crop)

    # =============================================================================
    # %% Dark indexes
    # =============================================================================

    # darkRegionSelctionFlag = easyqt.get_yes_or_no('Do you want to select ' +
    #                                               'region for dark calculation?\n' +
    #                                               'Press ESC to use [0, 20, 0, 20]')
    print(darkRegionSelctionFlag)
    if darkRegionSelctionFlag:

        idx4cropDark = wpu.graphical_roi_idx(img,
                                             verbose=True,
                                             kargs4graph={
                                                 'cmap': cmap,
                                                 'vmin': colorlimit[0],
                                                 'vmax': colorlimit[1]
                                             })
    else:
        idx4cropDark = [0, 20, 0, 20]

    # dark_im = dxchange.read_tiff(listOfDataFiles[0])*0.0 + avgDark

    img = wpu.crop_matrix_at_indexes(img, idx4crop)

    # ==============================================================================
    # %% Harmonic Periods
    # ==============================================================================

    if pattern == 'Diagonal':
        period_harm_Vert = np.int(
            np.sqrt(2) * pixelSize / gratingPeriod * img.shape[0])
        period_harm_Horz = np.int(
            np.sqrt(2) * pixelSize / gratingPeriod * img.shape[1])
    elif pattern == 'Edge':
        period_harm_Vert = np.int(2 * pixelSize / gratingPeriod * img.shape[0])
        period_harm_Horz = np.int(2 * pixelSize / gratingPeriod * img.shape[1])

    # Obtain harmonic periods from images

    (period_harm_Vert,
     _) = wgi.exp_harm_period(img, [period_harm_Vert, period_harm_Horz],
                              harmonic_ij=['1', '0'],
                              searchRegion=40,
                              isFFT=False,
                              verbose=True)

    (_, period_harm_Horz) = wgi.exp_harm_period(
        img, [period_harm_Vert, period_harm_Horz],
        harmonic_ij=['0', '1'],
        searchRegion=40,
        isFFT=False,
        verbose=True)

    wpu.log_this('Input folder: ' + data_dir, preffname=fname2save)
    wpu.log_this('\nNumber of files : ' + str(nfiles))
    wpu.log_this('Stride : ' + str(strideFile))
    print(zvec_from)
    wpu.log_this('Z distances is ' + zvec_from)

    if zvec_from == 'Calculated':
        wpu.log_this('Step zscan [mm] : {:.4g}'.format(step_z_scan * 1e3))
        wpu.log_this('Start point zscan [mm] : {:.4g}'.format(startDist * 1e3))

    wpu.log_this('Pixel Size [um] : {:.4g}'.format(pixelSize * 1e6))
    wpu.log_this('Grating Period [um] : {:.4g}'.format(gratingPeriod * 1e6))
    wpu.log_this('Grating Pattern : ' + pattern)
    wpu.log_this('Crop idxs : ' + str(idx4crop))
    wpu.log_this('Dark idxs : ' + str(idx4cropDark))

    wpu.log_this('Vertical Source Distance: ' + str(sourceDistanceV))
    wpu.log_this('Horizontal Source Distance: ' + str(sourceDistanceH))

    wpu.log_this('Uniform Filter Size : {:d}'.format(unFilterSize))

    wpu.log_this('Search Region : {:d}'.format(searchRegion))

    # =============================================================================
    # %% Calculate everything
    # =============================================================================

    # =============================================================================
    # %% multiprocessing
    # =============================================================================

    ncpus = cpu_count()

    wpu.print_blue("MESSAGE: %d cpu's available" % ncpus)

    tzero = time.time()

    p = Pool(ncpus - 2)

    indexes = range(len(listOfDataFiles))
    parameters = []

    for i in indexes:
        parameters.append([
            i, listOfDataFiles, zvec, idx4cropDark, idx4crop, period_harm_Vert,
            sourceDistanceV, period_harm_Horz, sourceDistanceH, searchRegion,
            unFilterSize
        ])

    res = p.map(_func, parameters)
    p.close()

    wpu.print_blue('MESSAGE: Time spent: {0:.3f} s'.format(time.time() -
                                                           tzero))
    '''
    res = []
    for i in range(len(listOfDataFiles)):
        res.append(_func(i))
    print(res)
    '''
    # =============================================================================
    # %% Sorting the data
    # =============================================================================

    contrastV = np.asarray([x[0] for x in res])
    contrastH = np.asarray([x[1] for x in res])

    p0 = np.asarray([x[2] for x in res])
    pv = np.asarray([x[3] for x in res])
    ph = np.asarray([x[4] for x in res])

    pattern_period_Vert_z = pixelSize / (pv[:, 0] - p0[:, 0]) * img.shape[0]
    pattern_period_Horz_z = pixelSize / (ph[:, 1] - p0[:, 1]) * img.shape[1]

    # =============================================================================
    # %% Save csv file
    # =============================================================================

    outputfname = wpu.get_unique_filename(fname2save, 'csv')

    wpu.save_csv_file(np.c_[zvec.T, contrastV.T, contrastH.T,
                            pattern_period_Vert_z.T, pattern_period_Horz_z.T],
                      outputfname,
                      headerList=[
                          'z [m]', 'Vert Contrast', 'Horz Contrast',
                          'Vert Period [m]', 'Horz Period [m]'
                      ])

    wpu.log_this('\nOutput file: ' + outputfname)

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

    # contrast vs z
    fig = plt.figure(figsize=(10, 7))
    plt.plot(zvec * 1e3, contrastV * 100, '-ko', label='Vert')
    plt.plot(zvec * 1e3, contrastH * 100, '-ro', label='Hor')
    plt.xlabel(r'Distance $z$  [mm]', fontsize=14)

    plt.ylabel(r'Visibility $\times$ 100 [%]', fontsize=14)
    plt.title('Visibility vs detector distance', fontsize=14, weight='bold')

    plt.legend(fontsize=14, loc=0)

    wpu.save_figs_with_idx(fname2save)
    plt.show(block=False)

    # =============================================================================
    # %% Plot Harmonic position and calculate source distance
    # =============================================================================
    from wavepytools.diag.coherence.fit_singleGratingCoherence_z_scan import fit_period_vs_z
    #xshi 20190719
    #from fit_singleGratingCoherence_z_scan import fit_period_vs_z
    (sourceDistance_from_fit_V,
     patternPeriodFromData_V) = fit_period_vs_z(zvec,
                                                pattern_period_Vert_z,
                                                contrastV,
                                                direction='Vertical',
                                                threshold=.002,
                                                fname4graphs=fname2save)

    (sourceDistance_from_fit_H,
     patternPeriodFromData_H) = fit_period_vs_z(zvec,
                                                pattern_period_Horz_z,
                                                contrastH,
                                                direction='Horizontal',
                                                threshold=0.0005,
                                                fname4graphs=fname2save)