Esempio n. 1
0
def _func(i):

    wpu.print_blue("MESSAGE: loop " + str(i) + ": " + listOfDataFiles[i])

    img = dxchange.read_tiff(listOfDataFiles[i])

    darkMeanValue = np.mean(wpu.crop_matrix_at_indexes(img, idx4cropDark))

    #TODO xshi, need to add option of input one value

    img = img - darkMeanValue  # calculate and remove dark
    img = wpu.crop_matrix_at_indexes(img, idx4crop)

    pv = int(period_harm_Vert / (sourceDistanceV + zvec[i]) *
             (sourceDistanceV + np.min(zvec)))
    ph = int(period_harm_Horz / (sourceDistanceH + zvec[i]) *
             (sourceDistanceH + np.min(zvec)))

    if plotFourierImages:

        wgi.plot_harmonic_grid(img, [pv, ph], isFFT=False)

        plt.savefig('FFT_{:.0f}mm.png'.format(zvec[i] * 1e3))
        plt.show(block=False)
        plt.close()

        wgi.plot_harmonic_peak(img, [pv, ph], isFFT=False)

        plt.savefig('FFT_peaks_{:.0f}mm.png'.format(zvec[i] * 1e3))
        plt.show(block=False)
        plt.close()

    return wgi.visib_1st_harmonics(img, [pv, ph],
                                   searchRegion=searchRegion,
                                   unFilterSize=unFilterSize)
def _func(i):

    wpu.print_blue("MESSAGE: loop " + str(i) + ": " + \
                   listOfDataFiles[i])

    if idx == [0, -1, 0, -1]:
        img = dxchange.read_tiff(listOfDataFiles[i]) - dark_im
    else:
        img = wpu.crop_matrix_at_indexes(
            dxchange.read_tiff(listOfDataFiles[i]), idx) - dark_im

    pv, ph = period_harm_Vert, period_harm_Horz

    pv = int(period_harm_Vert / (sourceDistance + zvec[i] - zvec[0]) *
             sourceDistance)
    ph = int(period_harm_Horz / (sourceDistance + zvec[i] - zvec[0]) *
             sourceDistance)

    wgi.plot_harmonic_grid(img, [pv, ph], isFFT=False)

    plt.savefig('FFT_{:04.0f}_ms_'.format(tvec[i] * 1e3) +
                '{:04.0f}mm.png'.format(zvec[i] * 1e3))
    plt.show(block=False)
    plt.close()

    #    wgi.plot_harmonic_peak(img,
    #                           [pv, ph],
    #                           isFFT=False,
    #                           fname='FFT_peaks_{:04.0f}_ms_'.format(tvec[i]*1e3) +
    #                                   '{:04.0f}mm.png'.format(zvec[i]*1e3))
    #
    #
    #    plt.close()

    return wgi.visib_1st_harmonics(img, [pv, ph], searchRegion=10)
Esempio n. 3
0
def _intial_gui_setup(sys_argv):

    global inifname  # name of .ini file
    inifname = os.curdir + '/.' + os.path.basename(__file__).replace(
        '.py', '.ini')

    for i, argv in enumerate(sys_argv):
        print('arg {}: '.format(i) + argv)

    if len(sys_argv) == 1:

        default_ini = wpu.load_ini_file(inifname)
        foldername = default_ini['Files']['Folder Name']

        if easyqt.get_yes_or_no('Select new folder?\n' +
                                '[ESC load folder of previous run]'):

            foldername = easyqt.get_directory_name(title='Select Folder that' +
                                                   '\ncontains *csv files')

    elif len(sys_argv) == 2:

        foldername = sys_argv[1]

    else:

        print('ERROR: wrong number of inputs: {} \n'.format(len(argv) - 1) +
              'Usage: \n'
              '\n' + os.path.basename(__file__) +
              ' : (no inputs) load dialogs \n'
              '\n' + os.path.basename(__file__) + ' [args] \n'
              '\n'
              'arg1: folder that contains the *csv files\n'
              '\n')

        exit(-1)

    wpu.set_at_ini_file(inifname, 'Files', 'Folder Name', foldername)

    list_of_files = sorted(glob.glob(foldername + '/*csv'))

    nfiles = len(list_of_files)

    data, header_list = wpu.load_csv_file(list_of_files[0])

    wpu.print_blue('MESSAGE: Header of data files:')
    wpu.print_blue(header_list)

    ncurves = data.shape[1] - 1

    label_list = [
        fname.rsplit('_', 1)[1].split('.')[0] for fname in list_of_files
    ]

    #[fname.rsplit('/', 1)[1].split('_Y_integrated')[0]
    #                  for fname in list_of_files]

    return list_of_files, nfiles, ncurves, label_list, header_list
def fit_peaks_talbot2gauss(zvec, contrast, wavelength,
                           patternPeriod, sourceDist,
                           cohLength,
                           fname4graphs, title4graph='Title'):

    def _func_4_fit(z, Amp, Amp2, sigma1, sigma2):
        return Amp*np.exp(-z**2/2/sigma1**2) + Amp2*np.exp(-z**2/2/sigma2**2)

    cohL_o = cohLength/wavelength*patternPeriod
    p0 = [1.0, .5, cohL_o, cohL_o*.15]
    bounds = ([.01, .01, cohL_o*0.5, cohL_o*0.01],
              [2.0,  2.0, cohL_o*1.5, cohL_o*1.0])

    popt, pcov = curve_fit(_func_4_fit, zvec, contrast, p0=p0,
                           bounds=bounds)

    print("Fit 1D")
    print("Amp, z_period, sigma, phase")
    print(popt)

    cohLength1 = np.abs(popt[2])*wavelength/patternPeriod
    cohLength2 = np.abs(popt[3])*wavelength/patternPeriod

    print('Coherent length: {:.4g} um'.format(cohLength1*1e6))
    print('Coherent length: {:.4g} um'.format(cohLength2*1e6))

    plt.figure(figsize=(12, 9))
    plt.plot(zvec*1e3, 100*contrast, 'ok', ms=7, label='data')

    fitted_values = _func_4_fit(zvec, popt[0], popt[1],
                                popt[2], popt[3])
    chi2 = _chi2(contrast, fitted_values)
    wpu.print_blue('chi2 Fit = {:.3f}'.format(chi2))

    zvec_4_fit = np.linspace(zvec[0], zvec[-1], zvec.size*5)
    plt.plot(zvec_4_fit*1e3,
             100*_func_4_fit(zvec_4_fit, popt[0], popt[1], popt[2], popt[3]),
             '-r', lw=3, label='Fit')

    max_cont, min_cont, mean_cont = max_min_mean_4plot(zvec, contrast)
    plt.plot(np.unique(zvec)*1e3, 100*max_cont, '--c', lw=2, label='Max')
    plt.plot(np.unique(zvec)*1e3, 100*min_cont, '--c', lw=2, label='Min')
    plt.plot(np.unique(zvec)*1e3, 100*mean_cont, '--m', lw=2, label='Mean')

    title4graph += r', $l_{coh}$ =' + ' {:.3f} um'.format(cohLength1*1e6)
    title4graph += r', $l_{coh}$ =' + ' {:.3f} um'.format(cohLength2*1e6)
    title4graph += r', $\chi^2$ = {:.3f}'.format(chi2)

    plt.xlabel('Distance [mm]', fontsize=27)
    plt.ylabel(r'Visibility $\times$ 100 [%]', fontsize=27)
    plt.title(title4graph, fontsize=27, weight='bold')
    plt.legend(fontsize=22)
    plt.grid()
    wpu.save_figs_with_idx(fname4graphs)
    plt.show(block=True)

    return cohLength1, cohLength2, popt  # zperiod
def gui_list_data_phase_stepping(directory=''):
    '''
        TODO: Write Docstring
    '''

    originalDir = os.getcwd()

    if directory != '':

        if os.path.isdir(directory):
            os.chdir(directory)
        else:
            wpu.print_red("WARNING: Directory " + directory +
                          " doesn't exist.")
            wpu.print_blue("MESSAGE: Using current working directory " +
                           originalDir)

    samplef1 = easyqt.get_file_names("Choose one of the scan " +
                                     "files with sample")

    if len(samplef1) == 3:
        [samplef1, samplef2, samplef3] = samplef1

    else:

        samplef1 = samplef1[0]
        os.chdir(samplef1.rsplit('/', 1)[0])

        samplef2 = easyqt.get_file_names("File name with Reference")[0]
        samplef3 = easyqt.get_file_names("File name with Dark Image")

        if len(samplef3) == 1:
            samplef3 = samplef3[0]
        else:
            samplef3 = ''
            wpu.print_red('MESSAGE: You choosed to not use dark images')

    wpu.print_blue('MESSAGE: Sample files directory: ' +
                   samplef1.rsplit('/', 1)[0])

    samplef1.rsplit('/', 1)[0]

    listf1 = load_files_scan(samplef1)
    listf2 = load_files_scan(samplef2)
    listf3 = load_files_scan(samplef3)

    listf1.sort()
    listf2.sort()
    listf3.sort()

    return listf1, listf2, listf3
Esempio n. 6
0
def fit_nominal_lens_2d(thickness,
                        pixelsize,
                        radius4fit,
                        p0=[20e-6, 1.005e-6, -.005e-6, -.005e-6],
                        bounds=([10e-6, -2.05e-6, -2.05e-6,
                                 -2.05e-6], [50e-6, 2.05e-6, 2.05e-6,
                                             2.05e-6]),
                        saveFigFlag=False,
                        str4title='',
                        kwargs4fit={}):

    #    thickness = center_CM_2darray(thickness)

    xmatrix, ymatrix = wpu.grid_coord(thickness, pixelSize)
    r2 = np.sqrt(xmatrix**2 + ymatrix**2)
    args4fit = np.where(r2.flatten() < radius4fit)

    mask = xmatrix * np.nan
    mask[np.where(r2 < radius4fit)] = 1.0

    data2fit = thickness.flatten()[args4fit]

    xxfit = xmatrix.flatten()[args4fit]
    yyfit = ymatrix.flatten()[args4fit]

    xyfit = [xxfit, yyfit]

    # FIT

    popt, pcov = curve_fit(_2Dparabol_4_fit,
                           xyfit,
                           data2fit,
                           p0=p0,
                           bounds=bounds,
                           method='trf',
                           **kwargs4fit)

    wpu.print_blue("Nominal Parabolic 2D Fit")
    wpu.print_blue("Curv Radius, xo, yo, offset")
    wpu.print_blue(popt)

    wpu.print_blue("Nominal Parabolic 2D Fit: Radius of 1 face  / nfaces, " +
                   "x direction: {:.4g} um".format(popt[0] * 1e6))

    lim_x = np.argwhere(xmatrix[0, :] <= -radius4fit * 1.01)[-1, 0]
    lim_y = np.argwhere(ymatrix[:, 0] <= -radius4fit * 1.01)[-1, 0]

    fitted = _2Dparabol_4_fit([xmatrix, ymatrix], popt[0], popt[1], popt[2],
                              popt[3])

    if (lim_x <= 1 or lim_y <= 1):
        thickness_cropped = thickness * mask
        fitted_cropped = fitted * mask
    else:
        thickness_cropped = (thickness[lim_y:-lim_y + 1, lim_x:-lim_x + 1] *
                             mask[lim_y:-lim_y + 1, lim_x:-lim_x + 1])
        fitted_cropped = (fitted[lim_y:-lim_y + 1, lim_x:-lim_x + 1] *
                          mask[lim_y:-lim_y + 1, lim_x:-lim_x + 1])

    return (thickness_cropped, fitted_cropped, popt)
def fit_peaks_talbot(zvec, contrast, wavelength,
                     patternPeriod, sourceDist,
                     fname4graphs, title4graph='Title'):

    def _func_4_fit(z, Amp, sigma):
        return (Amp*np.exp(-z**2/2/sigma**2))

    p0 = [1.0, np.sqrt(np.sum(contrast*zvec**2)/np.sum(contrastV))]
    # bounds = ([1e-3, 0.1, .01, -1., .001],
    #          [2.0,   1.0, 100 , 1., .1])

    popt, pcov = curve_fit(_func_4_fit, zvec, contrast, p0=p0)

    print("Fit 1D")
    print("Amp, sigma")
    print(popt)

    cohLength = np.abs(popt[1])*wavelength/patternPeriod

    print('Coherent length: {:.4g} um'.format(cohLength*1e6))

    plt.figure(figsize=(12, 9))
    plt.plot(zvec*1e3, 100*contrast, 'ok', ms=7, label='data')

    fitted_values = _func_4_fit(zvec, popt[0], popt[1])
    chi2 = _chi2(contrast, fitted_values)
    wpu.print_blue('chi2 Fit = {:.3f}'.format(chi2))

    zvec_4_fit = np.linspace(zvec[0], zvec[-1], zvec.size*5)
    plt.plot(zvec_4_fit*1e3,
             100*_func_4_fit(zvec_4_fit, popt[0], popt[1]),
             '-r', lw=3, label='Fit')

    max_cont, min_cont, mean_cont = max_min_mean_4plot(zvec, contrast)
    plt.plot(np.unique(zvec)*1e3, 100*max_cont, '--c', lw=2, label='Max')
    plt.plot(np.unique(zvec)*1e3, 100*min_cont, '--c', lw=2, label='Min')
    plt.plot(np.unique(zvec)*1e3, 100*mean_cont, '--m', lw=2, label='Mean')

    title4graph += r', $l_{coh}$ =' + ' {:.3f} um'.format(cohLength*1e6)
    title4graph += r', $\chi^2$ = {:.3f}'.format(chi2)

    plt.xlabel('Distance [mm]', fontsize=27)
    plt.ylabel(r'Visibility $\times$ 100 [%]', fontsize=27)
    plt.title(title4graph, fontsize=27, weight='bold')
    plt.legend(fontsize=22)
    plt.grid()
    wpu.save_figs_with_idx(fname4graphs)
    plt.show(block=True)

    return cohLength, popt  # zperiod
def _func(i):

    wpu.print_blue("MESSAGE: loop " + str(i) + ": " + \
                   listOfDataFiles[i])

    if idx == [0, -1, 0, -1]:
        img = dxchange.read_tiff(listOfDataFiles[i]) - dark_im
    else:
        img = wpu.crop_matrix_at_indexes(dxchange.read_tiff(listOfDataFiles[i]), idx) - dark_im


    pv, ph = period_harm_Vert, period_harm_Horz

    pv = int(period_harm_Vert/(sourceDistance + zvec[i]-zvec[0])*sourceDistance)
    ph = int(period_harm_Horz/(sourceDistance + zvec[i]-zvec[0])*sourceDistance)


    return wgi.visib_1st_harmonics(img, [pv, ph], searchRegion=10)
Esempio n. 9
0
def intial_setup():

    [list_sample_files, list_ref_files,
     list_dark_files] = wpu.gui_list_data_phase_stepping()

    for fname in list_sample_files + list_ref_files + list_dark_files:
        wpu.print_blue('MESSAGE: Loading ' + fname.rsplit('/')[-1])

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

    stepSize = easyqt.get_float("Enter scan step size [um]",
                                title='Experimental Values',
                                default_value=.2) * 1e-6

    return (list_sample_files, list_ref_files, list_dark_files, pixelSize,
            stepSize)
def intial_setup():

    [list_sample_files,
     list_ref_files,
     list_dark_files] = wpu.gui_list_data_phase_stepping()

    for fname in list_sample_files + list_ref_files + list_dark_files:
        wpu.print_blue('MESSAGE: Loading ' + fname.rsplit('/')[-1])

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

    stepSize = easyqt.get_float("Enter scan step size [um]",
                                title='Experimental Values',
                                default_value=.2)*1e-6

    return (list_sample_files, list_ref_files, list_dark_files,
            pixelSize, stepSize)
Esempio n. 11
0
def exp_harm_period(img,
                    harmonicPeriod,
                    harmonic_ij='00',
                    searchRegion=10,
                    isFFT=False,
                    verbose=True):
    """
    Function to obtain the position (in pixels) in the reciprocal space
    of the first harmonic ().
    """

    (nRows, nColumns) = img.shape

    harV = int(harmonic_ij[0])
    harH = int(harmonic_ij[1])

    periodVert = harmonicPeriod[0]
    periodHor = harmonicPeriod[1]

    # adjusts for 1D grating
    if periodVert <= 0 or periodVert is None:
        periodVert = nRows
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Horizontal 1D Grating")

    if periodHor <= 0 or periodHor is None:
        periodHor = nColumns
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Vertical 1D Grating")

    #    _check_harmonic_inside_image(harV, harH, nRows, nColumns,
    #                                 periodVert, periodHor)

    if isFFT:
        imgFFT = img
    else:
        imgFFT = np.fft.fftshift(fft2(img, norm='ortho'))

    del_i, del_j = _error_harmonic_peak(imgFFT, harV, harH, periodVert,
                                        periodHor, searchRegion)

    if verbose:
        wpu.print_blue("MESSAGE: error experimental harmonics " +
                       "vertical: {:d}".format(del_i))
        wpu.print_blue("MESSAGE: error experimental harmonics " +
                       "horizontal: {:d}".format(del_j))

    return periodVert + del_i, periodHor + del_j
Esempio n. 12
0
def exp_harm_period(img, harmonicPeriod,
                    harmonic_ij='00', searchRegion=10,
                    isFFT=False, verbose=True):
    """
    Function to obtain the position (in pixels) in the reciprocal space
    of the first harmonic ().
    """

    (nRows, nColumns) = img.shape

    harV = int(harmonic_ij[0])
    harH = int(harmonic_ij[1])

    periodVert = harmonicPeriod[0]
    periodHor = harmonicPeriod[1]

    # adjusts for 1D grating
    if periodVert <= 0 or periodVert is None:
        periodVert = nRows
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Horizontal 1D Grating")

    if periodHor <= 0 or periodHor is None:
        periodHor = nColumns
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Vertical 1D Grating")

    #    _check_harmonic_inside_image(harV, harH, nRows, nColumns,
    #                                 periodVert, periodHor)

    if isFFT:
        imgFFT = img
    else:
        imgFFT = np.fft.fftshift(fft2(img, norm='ortho'))

    del_i, del_j = _error_harmonic_peak(imgFFT, harV, harH,
                                        periodVert, periodHor,
                                        searchRegion)

    if verbose:
        wpu.print_blue("MESSAGE: error experimental harmonics " +
                       "vertical: {:d}".format(del_i))
        wpu.print_blue("MESSAGE: error experimental harmonics " +
                       "horizontal: {:d}".format(del_j))

    return periodVert + del_i, periodHor + del_j
Esempio n. 13
0
def fit_parabolic_lens_2d(thickness, pixelsize, radius4fit, mode='2D'):

    # FIT
    xx, yy = wpu.grid_coord(thickness, pixelSize)
    mask = xx * np.nan

    lim_x = np.argwhere(xx[0, :] <= -radius4fit * 1.01)[-1, 0]
    lim_y = np.argwhere(yy[:, 0] <= -radius4fit * 1.01)[-1, 0]

    if '2D' in mode:

        r2 = np.sqrt(xx**2 + yy**2)
        mask[np.where(r2 < radius4fit)] = 1.0

    elif '1Dx' in mode:
        mask[np.where(xx**2 < radius4fit)] = 1.0
        lim_y = 2

    elif '1Dy' in mode:
        mask[np.where(yy**2 < radius4fit)] = 1.0
        lim_x = 2

    fitted, popt = _lsq_fit_parabola(thickness * mask, pixelSize, mode=mode)

    wpu.print_blue("Parabolic 2D Fit")
    wpu.print_blue("Curv Radius, xo, yo, offset")
    wpu.print_blue(popt)

    wpu.print_blue("Parabolic 2D Fit: Radius of 1 face  / nfaces, " +
                   "x direction: {:.4g} um".format(popt[0] * 1e6))

    if (lim_x <= 1 or lim_y <= 1):
        thickness_cropped = thickness * mask
        fitted_cropped = fitted * mask
    else:
        thickness_cropped = (thickness[lim_y:-lim_y + 1, lim_x:-lim_x + 1] *
                             mask[lim_y:-lim_y + 1, lim_x:-lim_x + 1])
        fitted_cropped = (fitted[lim_y:-lim_y + 1, lim_x:-lim_x + 1] *
                          mask[lim_y:-lim_y + 1, lim_x:-lim_x + 1])

    return (thickness_cropped, fitted_cropped, popt)
Esempio n. 14
0
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))
def _intial_gui_setup(argvzero):

    global inifname  # name of .ini file
    pwd, inifname = argvzero.rsplit('/', 1)
    inifname = pwd + '/.' + inifname.replace('.py', '.ini')

    defaults = wpu.load_ini_file(inifname)

    if defaults is None:
        p1, p2, p3, p4, p5, p6 = [0, 0, 0, 0, 0, 0]

    else:

        p1 = float(defaults['Parameters'].get('Pixel Size'))
        p2 = float(defaults['Parameters'].get('Chekerboard Grating Period'))
        p3 = defaults['Parameters'].get('Pattern')
        p4 = float(defaults['Parameters'].get('Distance Detector to Gr'))
        p5 = float(defaults['Parameters'].get('Photon Energy'))
        p6 = float(defaults['Parameters'].get('Source Distance'))

    title = 'Select Sample, Reference and Dark Images. '
    title += 'Press ESC to repeat last run.'
    fname1, fname2, fname3 = wpu.gui_load_data_ref_dark_filenames(title=title)

    if fname1 is None:
        fname1 = defaults['Files'].get('Sample')
        fname2 = defaults['Files'].get('Reference')
        fname3 = defaults['Files'].get('Blank')

    else:
        defaults['Files']['Sample'] = fname1
        defaults['Files']['Reference'] = fname2
        defaults['Files']['Blank'] = fname3

    wpu.print_blue('MESSAGE: loading dark: ' + fname3)
    wpu.print_blue('MESSAGE: loading Reference: ' + fname2)
    wpu.print_blue('MESSAGE: loading Image: ' + fname1)

    pixelsize = easyqt.get_float("Enter Pixel Size [um]",
                                 title='Experimental Values',
                                 default_value=p1*1e6)*1e-6

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

    if p3 == 'Diagonal half pi':
        choices = ['Diagonal half pi', 'Edge pi']
    else:
        choices = ['Edge pi', 'Diagonal half pi']

    pattern = easyqt.get_choice(message='Select CB Grating Pattern',
                                title='Title',
                                choices=choices)

    distDet2sample = easyqt.get_float("Enter Distance Sample - Detector [mm]",
                                      title='Experimental Values',
                                      default_value=p4*1e3)*1e-3

    phenergy = easyqt.get_float("Enter Photon Energy [KeV]",
                                title='Experimental Values',
                                default_value=p5*1e-3)*1e3

    sourceDistance = easyqt.get_float("Enter Distance to Source [m]",
                                      title='Experimental Values',
                                      default_value=p6)

    defaults['Parameters']['Pixel Size'] = str(pixelsize)
    defaults['Parameters']['Chekerboard Grating Period'] = str(gratingPeriod)
    defaults['Parameters']['Pattern'] = pattern
    defaults['Parameters']['Distance Detector to Gr'] = str(distDet2sample)
    defaults['Parameters']['Photon Energy'] = str(phenergy)
    defaults['Parameters']['Source Distance'] = str(sourceDistance)

    with open(inifname, 'w') as configfile:
            defaults.write(configfile)

    return (fname1, fname2, fname3,
            pixelsize, gratingPeriod, pattern, distDet2sample,
            phenergy, sourceDistance)
Esempio n. 16
0
def _intial_gui_setup():

    #    global inifname  # name of .ini file
    #    pwd, inifname = argvzero.rsplit('/', 1)
    #    inifname = pwd + '/.' + inifname.replace('.py', '.ini')

    defaults = wpu.load_ini_file(inifname)

    fname = easyqt.get_file_names("File to Plot (Pickle or sdf)")

    if fname == []:
        fname = defaults['Files'].get('file with thickness')

    else:
        fname = fname[0]
        defaults['Files']['file with thickness'] = fname

    wpu.print_blue('MESSAGE: Loading File: ' + fname)

    with open(inifname, 'w') as configfile:
        defaults.write(configfile)

    if defaults is None:
        p1 = ''
        p2 = 100e-6

    else:
        p1 = defaults['Parameters'].get('String for Titles')
        p2 = float(defaults['Parameters'].get('Nominal Radius For Fitting'))
        p3 = defaults['Parameters']['Diameter of active area for fitting']
        p4 = defaults['Parameters']['Lens Geometry']

    str4title = easyqt.get_string('String for Titles', 'Enter String', p1)

    if str4title != '':
        defaults['Parameters']['String for Titles'] = str4title

    wpu.print_blue('MESSAGE: Loading Pickle: ' + fname)

    if p4 == '2D Lens Stigmatic Lens':
        menu_choices4lensmode = [
            '2D Lens Stigmatic Lens', '1Dx Horizontal focusing',
            '1Dy Vertical focusing'
        ]
    elif p4 == '1Dx Horizontal focusing':
        menu_choices4lensmode = [
            '1Dx Horizontal focusing', '1Dy Vertical focusing',
            '2D Lens Stigmatic Lens'
        ]
    elif p4 == '1Dy Vertical focusing':
        menu_choices4lensmode = [
            '1Dy Vertical focusing', '1Dx Horizontal focusing',
            '2D Lens Stigmatic Lens'
        ]

    lensGeometry = easyqt.get_choice(message='Lens Geometry',
                                     title='Input Parameter',
                                     choices=menu_choices4lensmode)

    nominalRadius = easyqt.get_float(
        'Nominal Curvature Radius' + ' for Fitting [um]',
        title='Input Parameter',
        default_value=p2 * 1e6) * 1e-6

    diameter4fit_str = easyqt.get_string(
        'Diameter of active area for fitting [um]',
        title='Input Parameter',
        default_response=p3)

    diameter4fit_list = [float(a) * 1e-6 for a in diameter4fit_str.split(',')]

    defaults['Parameters']['Nominal Radius For Fitting'] = str(nominalRadius)
    defaults['Parameters'][
        'Diameter of active area for fitting'] = diameter4fit_str
    defaults['Parameters']['Lens Geometry'] = lensGeometry

    with open(inifname, 'w') as configfile:
        defaults.write(configfile)

    return fname, str4title, nominalRadius, diameter4fit_list, lensGeometry
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)
Esempio n. 18
0
# %% 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')
plt.show(block=False)
                                   unwrapFlag=True,
                                   plotFlag=False,
                                   saveFigFlag=True)

    [int00, int01, int10,
     darkField01, darkField10,
     diffPhase01, diffPhase10,
     virtual_pixelsize] = result

    # due to beam divergence, the image will expand when propagating.
    # The script uses the increase of the pattern period compared to
    # the theoretical period, and apply the same factor to the pixel size.
    # Note that, since the hor and vert divergences can be different, the
    # virtual pixel size can also be different for hor and vert directions
    wpu.print_blue('VALUES: virtual pixelsize i, j: ' +
                   '{:.4f}um, {:.4f}um'.format(virtual_pixelsize[0]*1e6,
                                               virtual_pixelsize[1]*1e6))

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

    #    # %% plot Intensities
    #
    #    wgi.plot_intensities_harms(int00, int01, int10,
    #                               virtual_pixelsize, saveFigFlag=False,
    #                               saveFileSuf=saveFileSuf)
    #
    #    # %% plot dark field
    #
Esempio n. 20
0
                                               "for alignment")[0]

    else:
        samplefileName = sys.argv[1]


    if '/' in samplefileName:
        data_dir = samplefileName.rsplit('/', 1)[0]
        os.chdir(data_dir)
    else:
        data_dir = os.getcwd()


    os.makedirs('png_figs', exist_ok=True)

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

    listOfDataFiles = glob.glob(data_dir + '/*.tif')
    listOfDataFiles.sort()


    # %% Loop over the files in the folder

    for i, imgfname in enumerate(listOfDataFiles):
        if i == 0:

            img_0 = dxchange.read_tiff(imgfname)
            all_img = np.zeros((len(listOfDataFiles),
                                img_0.shape[0], img_0.shape[1]), dtype=int)

        all_img[i,:,:] = dxchange.read_tiff(imgfname)
for i in range(nfiles):

    zvec[i] = float(listOfDataFiles[i].rsplit('mm')[0].split('_')[-1]) * 1e-3
    tvec[i] = tvec_labels[int(listOfDataFiles[i].rsplit('.')[0].split('_')[-1])
                          - 1]

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

idx = [200, -200, 0, 2160]

img = wpu.crop_matrix_at_indexes(img, idx)

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

if idx != [0, -1, 0, -1]:
    dark_im = wpu.crop_matrix_at_indexes(dark_im, idx)

    idx[1] = idx[0] + np.max([idx[1] - idx[0], idx[3] - idx[2]])

    idx[3] = idx[2] + np.max([idx[1] - idx[0], idx[3] - idx[2]])

# =============================================================================
# %% Plot Real Image
# =============================================================================
#
plt.imshow(img, cmap='Greys')
plt.colorbar()
    try:
        os.chdir('~/workspace/pythonWorkspace/data')
    except:
        pass



samplefileName =  easyqt.get_file_names("Choose one of the scan files")[0]
listOfDataFiles = glob.glob(samplefileName.rsplit('_' ,1)[0] + '*.tif')

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

listOfDataFiles.sort()

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

#fname_dark =  easyqt.get_file_names("Dark File")[0]

os.chdir(originalDir)


strideFile = easyqt.get_int('Stride', default_value=1)


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

step_z_scan = strideFile*easyqt.get_float('Step size scan [mm]',
                                        default_value=2)*1e-3
Esempio n. 23
0
def extract_harmonic(img,
                     harmonicPeriod,
                     harmonic_ij='00',
                     searchRegion=10,
                     isFFT=False,
                     plotFlag=False,
                     verbose=True):
    """
    Function to extract one harmonic image of the FFT of single grating
    Talbot imaging.


    The function use the provided value of period to search for the harmonics
    peak. The search is done in a rectangle of size
    ``periodVert*periodHor/searchRegion**2``. The final result is a rectagle of
    size ``periodVert x periodHor`` centered at
    ``(harmonic_Vertical*periodVert x harmonic_Horizontal*periodHor)``


    Parameters
    ----------

    img : 	ndarray – Data (data_exchange format)
        Experimental image, whith proper blank image, crop and rotation already
        applied.

    harmonicPeriod : list of integers in the format [periodVert, periodHor]
        ``periodVert`` and ``periodVert`` are the period of the harmonics in
        the reciprocal space in pixels. For the checked board grating,
        periodVert = sqrt(2) * pixel Size / grating Period * number of
        rows in the image. For 1D grating, set one of the values to negative or
        zero (it will set the period to number of rows or colunms).

    harmonic_ij : string or list of string
        string with the harmonic to extract, for instance '00', '01', '10'
        or '11'. In this notation negative harmonics are not allowed.

        Alternativelly, it accepts a list of string
        ``harmonic_ij=[harmonic_Vertical, harmonic_Horizontal]``, for instance
        ``harmonic_ij=['0', '-1']``

        Note that since the original image contain only real numbers (not
        complex), then negative and positive harmonics are symetric
        related to zero.
    isFFT : Boolean
        Flag that tells if the input image ``img`` is in the reciprocal
        (``isFFT=True``) or in the real space (``isFFT=False``)

    searchRegion: int
        search for the peak will be in a region of harmonicPeriod/searchRegion
        around the theoretical peak position

    plotFlag: Boolean
        Flag to plot the image in the reciprocal space and to show the position
        of the found peaked and the limits of the harmonic image

    verbose: Boolean
        verbose flag.


    Returns
    -------
    2D ndarray
        Copped Images of the harmonics ij


    This functions crops a rectagle of size ``periodVert x periodHor`` centered
    at ``(harmonic_Vertical*periodVert x harmonic_Horizontal*periodHor)`` from
    the provided FFT image.


    Note
    ----
        * Note that it is the FFT of the image that is required.
        * The search for the peak is only used to print warning messages.

    **Q: Why not the real image??**

    **A:** Because FFT can be time consuming. If we use the real image, it will
    be necessary to run FFT for each harmonic. It is encourage to wrap this
    function within a function that do the FFT, extract the harmonics, and
    return the real space harmonic image.


    See Also
    --------
    :py:func:`wavepy.grating_interferometry.plot_harmonic_grid`

    """

    (nRows, nColumns) = img.shape

    harV = int(harmonic_ij[0])
    harH = int(harmonic_ij[1])

    periodVert = harmonicPeriod[0]
    periodHor = harmonicPeriod[1]

    if verbose:
        wpu.print_blue("MESSAGE: Extracting harmonic " + harmonic_ij[0] +
                       harmonic_ij[1])
        wpu.print_blue("MESSAGE: Harmonic period " +
                       "Horizontal: {:d} pixels".format(periodHor))
        wpu.print_blue("MESSAGE: Harmonic period " +
                       "Vertical: {:d} pixels".format(periodVert))

    # adjusts for 1D grating
    if periodVert <= 0 or periodVert is None:
        periodVert = nRows
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Horizontal 1D Grating")

    if periodHor <= 0 or periodHor is None:
        periodHor = nColumns
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Vertical 1D Grating")

    try:
        _check_harmonic_inside_image(harV, harH, nRows, nColumns, periodVert,
                                     periodHor)
    except ValueError:
        raise SystemExit

    if isFFT:
        imgFFT = img
    else:
        imgFFT = np.fft.fftshift(fft2(img, norm='ortho'))

    intensity = (np.abs(imgFFT))

    #  Estimate harmonic positions
    idxPeak_ij = _idxPeak_ij(harV, harH, nRows, nColumns, periodVert,
                             periodHor)

    del_i, del_j = _error_harmonic_peak(imgFFT, harV, harH, periodVert,
                                        periodHor, searchRegion)

    if verbose:
        print("MESSAGE: extract_harmonic:" + " harmonic peak " +
              harmonic_ij[0] + harmonic_ij[1] + " is misplaced by:")
        print("MESSAGE: {:d} pixels in vertical, {:d} pixels in hor".format(
            del_i, del_j))

        print("MESSAGE: Theoretical peak index: {:d},{:d} [VxH]".format(
            idxPeak_ij[0], idxPeak_ij[1]))

    if ((np.abs(del_i) > searchRegion // 2)
            or (np.abs(del_j) > searchRegion // 2)):

        wpu.print_red("ATTENTION: Harmonic Peak " + harmonic_ij[0] +
                      harmonic_ij[1] + " is too far from theoretical value.")
        wpu.print_red("ATTENTION: {:d} pixels in vertical,".format(del_i) +
                      "{:d} pixels in hor".format(del_j))

    if plotFlag:

        from matplotlib.patches import Rectangle
        plt.figure(figsize=(8, 7))
        plt.imshow(np.log10(intensity),
                   cmap='inferno',
                   extent=wpu.extent_func(intensity))

        plt.xlabel('Pixels')
        plt.ylabel('Pixels')

        xo = idxPeak_ij[1] - nColumns // 2 - periodHor // 2
        yo = nRows // 2 - idxPeak_ij[0] - periodVert // 2
        # xo yo are the lower left position of the reangle

        plt.gca().add_patch(
            Rectangle((xo, yo),
                      periodHor,
                      periodVert,
                      lw=2,
                      ls='--',
                      color='red',
                      fill=None,
                      alpha=1))

        plt.title('Selected Region ' + harmonic_ij[0] + harmonic_ij[1],
                  fontsize=18,
                  weight='bold')
        plt.show(block=False)

    return imgFFT[idxPeak_ij[0] - periodVert // 2:idxPeak_ij[0] +
                  periodVert // 2, idxPeak_ij[1] -
                  periodHor // 2:idxPeak_ij[1] + periodHor // 2]
Esempio n. 24
0
# %% crop

img, idx4crop = wpu.crop_graphic_image(img)
imgRef = wpu.crop_matrix_at_indexes(imgRef, idx4crop)

# %% Find harmonic in the Fourier images

# calculate the theoretical position of the hamonics
period_harm_Vert_o = np.int(pixelsize[0] / patternPeriod * img.shape[0] /
                            (sourceDistance + distDet2sample) * sourceDistance)
period_harm_Hor_o = np.int(pixelsize[1] / patternPeriod * img.shape[1] /
                           (sourceDistance + distDet2sample) * sourceDistance)

# Obtain harmonic periods from images

wpu.print_blue('MESSAGE: Obtain harmonic 01 exprimentally')

(_, period_harm_Hor) = wgi.exp_harm_period(
    imgRef, [period_harm_Vert_o, period_harm_Hor_o], harmonic_ij=['0', '1'])

wpu.print_blue('MESSAGE: Obtain harmonic 10 exprimentally')

(period_harm_Vert,
 _) = wgi.exp_harm_period(imgRef, [period_harm_Vert_o, period_harm_Hor_o],
                          harmonic_ij=['1', '0'])

harmPeriod = [period_harm_Vert, period_harm_Hor]

# %% Obtain DPC and Dark Field image

[int00, int01, int10, darkField01, darkField10, alpha_x,
Esempio n. 25
0
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))
def correct_zero_DPC(dpc01, dpc10,
                     pixelsize, distDet2sample, phenergy, saveFileSuf):

    title = ['Angle displacement of fringes 01',
             'Angle displacement of fringes 10']

    factor = distDet2sample*hc/phenergy

    angle = [dpc01/pixelsize[1]*factor, dpc10/pixelsize[0]*factor]
    dpc = [dpc01, dpc10]

    pi_jump = [0, 0]

    iamhappy = False
    while not iamhappy:

        pi_jump[0] = int(np.round(np.mean(angle[0])/np.pi))
        pi_jump[1] = int(np.round(np.mean(angle[1])/np.pi))

        plt.figure()
        plt.hist(angle[0].flatten()/np.pi, 201,
                 histtype='step')
        plt.hist(angle[1].flatten()/np.pi, 201,
                 histtype='step')

        plt.xlabel(r'Angle [$\pi$rad]')

        plt.title('Correct DPC\n' +
                  r'Angle displacement of fringes $[\pi$ rad]' +
                  '\n' + r'Calculated jumps $x$ and $y$ : ' +
                  '{:d}, {:d} $\pi$'.format(pi_jump[0], pi_jump[1]))

        plt.legend(('DPC x', 'DPC y'))
        plt.show(block=False)
        plt.pause(.5)

        if pi_jump == [0, 0]:
            break

        if easyqt.get_yes_or_no('Subtract pi jump of DPC?'):
            plt.close('all')

            angle[0] -= pi_jump[0]*np.pi
            angle[1] -= pi_jump[1]*np.pi

            dpc01 = angle[0]*pixelsize[0]/factor
            dpc10 = angle[1]*pixelsize[1]/factor
            dpc = [dpc01, dpc10]

            wgi.plot_DPC(dpc01, dpc10,
                         virtual_pixelsize, saveFigFlag=True,
                         saveFileSuf=saveFileSuf)
        else:
            plt.close('all')
            iamhappy = True


    wpu.print_blue('MESSAGE: mean angle/pi ' +
                               '0: {:} pi'.format(np.mean(angle[0]/np.pi)))
    wpu.print_blue('MESSAGE: mean angle/pi ' +
                               '1: {:} pi'.format(np.mean(angle[1]/np.pi)))

    if easyqt.get_yes_or_no('Subtract mean of DPC?'):
        plt.close('all')

        angle[0] -= np.mean(angle[0])
        angle[1] -= np.mean(angle[1])

        dpc01 = angle[0]*pixelsize[0]/factor
        dpc10 = angle[1]*pixelsize[1]/factor
        dpc = [dpc01, dpc10]

        wgi.plot_DPC(dpc01, dpc10,
                     virtual_pixelsize, saveFigFlag=True,
                     saveFileSuf=saveFileSuf)
        plt.pause(.1)
    else:
        pass

    if easyqt.get_yes_or_no('Correct DPC center?'):
        plt.close('all')

        for i in [0, 1]:

            iamhappy = False
            while not iamhappy:

                angle[i], pi_jump[i] = correct_zero_from_unwrap(angle[i])

                wpu.print_blue('MESSAGE: pi jump ' +
                               '{:}: {:} pi'.format(i, pi_jump[i]))
                wpu.print_blue('MESSAGE: mean angle/pi ' +
                               '{:}: {:} pi'.format(i, np.mean(angle[i]/np.pi)))
                plt.figure()
                plt.hist(angle[i].flatten() / np.pi, 101)
                plt.title(r'Angle displacement of fringes $[\pi$ rad]')
                plt.show()

                plt.figure()

                vlim = np.max((np.abs(wpu.mean_plus_n_sigma(angle[i]/np.pi,
                                                            -5)),
                               np.abs(wpu.mean_plus_n_sigma(angle[i]/np.pi,
                                                            5))))

                plt.imshow(angle[i] / np.pi,
                           cmap='RdGy',
                           vmin=-vlim, vmax=vlim)

                plt.colorbar()
                plt.title(title[i] + r' [$\pi$ rad],')
                plt.xlabel('Pixels')
                plt.ylabel('Pixels')

                plt.pause(.1)

                iamhappy = easyqt.get_yes_or_no('Happy?')
                plt.close('all')

            dpc[i] = angle[i]*pixelsize[i]/factor

    plt.close('all')

    return dpc
Esempio n. 27
0
def dpc_profile_analysis(fnameH, fnameV,
                         phenergy,
                         grazing_angle=0.0, projectionFromDiv=1.0,
                         nprofiles=1,
                         remove1stOrderDPC=False,
                         remove2ndOrder=False,
                         filter_width=0):

    wavelength = wpu.hc/phenergy

    if fnameH is not None:
        diffPhaseH, virtual_pixelsize, _ = wpu.load_sdf_file(fnameH)

    if fnameV is not None:
        diffPhaseV, virtual_pixelsize, _ = wpu.load_sdf_file(fnameV)

    if fnameH is None:
        diffPhaseH = diffPhaseV*np.nan

    if fnameV is None:
        diffPhaseV = diffPhaseH*np.nan
        saveFileSuf = fnameH.rsplit('/', 1)[0] + '/profiles/' +\
                      fnameH.rsplit('/', 1)[1]
        saveFileSuf = saveFileSuf.rsplit('_X')[0] + '_profiles'
    else:
        saveFileSuf = fnameV.rsplit('/', 1)[0] + '/profiles/' +\
                      fnameV.rsplit('/', 1)[1]
        saveFileSuf = saveFileSuf.rsplit('_Y')[0] + '_profiles'

    if not os.path.exists(saveFileSuf.rsplit('/', 1)[0]):
        os.makedirs(saveFileSuf.rsplit('/', 1)[0])

    (dataH, dataV,
     labels_H, labels_V,
     fit_coefs) = _n_profiles_H_V(diffPhaseH,
                                  diffPhaseV,
                                  virtual_pixelsize,
                                  'DPC [rad/m]',
                                  titleH='WF DPC Horz',
                                  titleV='WF DPC Vert',
                                  saveFileSuf=saveFileSuf,
                                  nprofiles=nprofiles,
                                  remove1stOrderDPC=remove1stOrderDPC,
                                  filter_width=filter_width)

    fit_coefsH = np.array(fit_coefs[0])
    fit_coefsV = np.array(fit_coefs[1])

    print(fit_coefsH)
    print(fit_coefsV)

    if __name__ == '__main__':
        wpu.log_this(preffname=saveFileSuf, inifname=inifname)

    if fnameH is not None:

        radii_fit_H = (2*np.pi/wavelength/fit_coefsH[:][0])

        wpu.print_blue('MESSAGE: Radius H from fit profiles: ')
        print(radii_fit_H)
        wpu.log_this('radius fit Hor = ' + str(radii_fit_H))

        integratedH = integrate_DPC_cumsum(dataH, wavelength,
                                           #grazing_angle=grazing_angle,
                                           remove2ndOrder=remove2ndOrder,
                                           xlabel='x',
                                           labels=labels_H,
                                           titleStr='Horizontal, ',
                                           saveFileSuf=saveFileSuf + '_X')

        curv_H = curv_from_height(integratedH, virtual_pixelsize[0],
                                  #grazing_angle=grazing_angle,
                                  #projectionFromDiv=projectionFromDiv,
                                  xlabel='x',
                                  labels=labels_H,
                                  titleStr='Horizontal, ',
                                  saveFileSuf=saveFileSuf + '_X')

    if fnameV is not None:

        radii_fit_V = (2*np.pi/wavelength/fit_coefsV[:][0])

        wpu.print_blue('MESSAGE: Radius V from fit profiles: ')
        print(radii_fit_V)
        wpu.log_this('radius fit Vert = ' + str(radii_fit_V))

        integratedV = integrate_DPC_cumsum(dataV, wavelength,
                                           grazing_angle=grazing_angle,
                                           projectionFromDiv=projectionFromDiv,
                                           remove2ndOrder=remove2ndOrder,
                                           xlabel='y',
                                           labels=labels_V,
                                           titleStr='Vertical, ',
                                           saveFileSuf=saveFileSuf + '_Y')

        curv_V = curv_from_height(integratedV, virtual_pixelsize[1],
                                  grazing_angle=grazing_angle,
                                  projectionFromDiv=projectionFromDiv,
                                  xlabel='y',
                                  labels=labels_V,
                                  titleStr='Vertical, ',
                                  saveFileSuf=saveFileSuf + '_Y')
Esempio n. 28
0
def _intial_gui_setup(sys_argv):

    global inifname  # name of .ini file
    pwd, inifname = sys_argv[0].rsplit('/', 1)
    inifname = pwd + '/.' + inifname.replace('.py', '.ini')

    for i, argv in enumerate(sys_argv):
        print('arg {}: '.format(i) + argv)

    if len(sys_argv) == 1:

        default_ini = wpu.load_ini_file(inifname)
        p0 = float(default_ini['Parameters']['Photon Energy [eV]'])
        p1 = float(default_ini['Parameters']['grazing angle [mrad]'])
        p2 = int(default_ini['Parameters']['n profiles'])
        p3 = int(default_ini['Parameters']['filter width'])
        p4 = float(default_ini['Parameters']['projection From Divergence'])

        if easyqt.get_yes_or_no('Load new files?\n' +
                                '[ESC load file(s) of previous run]'):

            fnameH = easyqt.get_file_names(title='Select DPC Horizontal\n' +
                                           '(and Vertical if you want)')
            fnameV = None

            if len(fnameH) == 1:
                fnameH = fnameH[0]
                wpu.print_blue('MESSAGE: Horiz DPC: Loading ' + fnameH)
            elif len(fnameH) == 0:
                fnameH = None
            elif len(fnameH) == 2:
                [fnameH, fnameV] = fnameH
                wpu.print_blue('MESSAGE: Horiz DPC: Loading ' + fnameH)
                wpu.print_blue('MESSAGE: Vert DPC: Loading ' + fnameV)

            if fnameV is None:
                fnameV = easyqt.get_file_names(title='Select DPC Vertical')

                if len(fnameV) == 1:
                    fnameV = fnameV[0]
                    wpu.print_blue('MESSAGE: Vert DPC: Loading ' + fnameV)

                elif len(fnameV) == 0:
                    fnameV = None

        else:
            fnameH = default_ini['Files']['dpc H']
            fnameV = default_ini['Files']['dpc V']

            wpu.print_blue('MESSAGE: Horiz DPC: Loading ' + fnameH)
            wpu.print_blue('MESSAGE: Vert DPC: Loading ' + fnameV)

            if fnameH == 'None':
                fnameH = None
            if fnameV == 'None':
                fnameV = None

        phenergy = easyqt.get_float("Enter Photon Energy [KeV]",
                                    title='Experimental Values',
                                    default_value=p0*1e-3)*1e3

        grazing_angle = easyqt.get_float('Grazing angle [mrad]\n' +
                                         '[0.0 to ignore projection]',
                                         title='Experimental Values',
                                         default_value=p1)*1e-3

        projectionFromDiv = easyqt.get_float('projection From Divergence\n' +
                                             '[Multiplication factor]',
                                             title='Experimental Values',
                                             default_value=p4)

        nprofiles = easyqt.get_int("Number of profiles to plot",
                                   title='Experimental Values',
                                   default_value=p2)

        filter_width = easyqt.get_int("Width fo uniform filter [pixels]",
                                      title='Experimental Values',
                                      default_value=p3, max_=1e6)


        remove1stOrderDPC = easyqt.get_yes_or_no("Remove 1st Order DPC?",
                                                 title='Experimental Values')

        remove2ndOrder = easyqt.get_yes_or_no("Remove 2nd Order?",
                                              title='Experimental Values')

    elif len(sys_argv) == 10:

        if 'none' in sys_argv[1].lower():
            fnameH = None
        else:
            fnameH = sys_argv[1]

        if 'none' in sys_argv[2].lower():
            fnameV = None
        else:
            fnameV = sys_argv[2]

        phenergy = float(sys_argv[3])*1e3
        nprofiles = int(sys_argv[4])
        filter_width = int(sys_argv[5])
        grazing_angle = float(sys_argv[6])*1e-3
        projectionFromDiv = float(sys_argv[7])
        remove1stOrderDPC = bool(int(argv[8]))
        remove2ndOrder = bool(int(argv[9]))

    else:

        print('ERROR: wrong number of inputs: {} \n'.format(len(argv)-1) +
              'Usage: \n'
              '\n' +
              sys_argv[0].rsplit('/')[-1] + ' : (no inputs) load dialogs \n'
              '\n' +
              sys_argv[0].rsplit('/')[-1] + ' [args] \n'
              '\n'
              'arg1: file name DPC Horiz (type "None" '
              '      to ignore it)\n'
              'arg2: file name DPC Vert (type "None" '
              '      to ignore it)\n'
              'arg3: Photon Energy [KeV]\n'
              'arg4: Number of profiles to plot\n'
              'arg5: Width  of uniform filter [pixels]\n'
              'arg6: Grazing angle to project coordinates to mirror [mrad], use zero to ignore\n'
              'arg7: Projection From Divergence, use 1 to ignore'
              '\n')

        exit(-1)

    wpu.set_at_ini_file(inifname, 'Files', 'DPC H', fnameH)
    wpu.set_at_ini_file(inifname, 'Files', 'DPC V', fnameV)
    wpu.set_at_ini_file(inifname, 'Parameters', 'Photon Energy [eV]', phenergy)
    wpu.set_at_ini_file(inifname, 'Parameters',
                        'grazing angle [mrad]', grazing_angle*1e3)
    wpu.set_at_ini_file(inifname, 'Parameters',
                        'projection From Divergence', projectionFromDiv)
    wpu.set_at_ini_file(inifname, 'Parameters', 'n profiles', nprofiles)
    wpu.set_at_ini_file(inifname, 'Parameters', 'filter width', filter_width)

    wpu.set_at_ini_file(inifname, 'Parameters', 'Remove 1st Order DPC', remove1stOrderDPC)
    wpu.set_at_ini_file(inifname, 'Parameters', 'Remove 2nd Order', remove2ndOrder)

    return (fnameH, fnameV,
            phenergy, grazing_angle, projectionFromDiv,
            nprofiles, remove1stOrderDPC, remove2ndOrder, filter_width)
Esempio n. 29
0
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/' + samplefileName.rsplit('_', 1)[0].rsplit(
    '/', 1)[1]

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

listOfDataFiles = glob.glob(samplefileName.rsplit('_', 2)[0] + '*.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(
def dpc_profile_analysis(fnameH,
                         fnameV,
                         phenergy,
                         grazing_angle=0.0,
                         projectionFromDiv=1.0,
                         nprofiles=1,
                         remove2ndOrder=False,
                         filter_width=0):

    wavelength = wpu.hc / phenergy

    if fnameH is not None:
        diffPhaseH, virtual_pixelsize, _ = wpu.load_sdf_file(fnameH)

    if fnameV is not None:
        diffPhaseV, virtual_pixelsize, _ = wpu.load_sdf_file(fnameV)

    if fnameH is None:
        diffPhaseH = diffPhaseV * np.nan

    if fnameV is None:
        diffPhaseV = diffPhaseH * np.nan
        saveFileSuf = fnameH.rsplit('/', 1)[0] + '/profiles/' +\
                      fnameH.rsplit('/', 1)[1]
        saveFileSuf = saveFileSuf.rsplit('_X')[0] + '_profiles'
    else:
        saveFileSuf = fnameV.rsplit('/', 1)[0] + '/profiles/' +\
                      fnameV.rsplit('/', 1)[1]
        saveFileSuf = saveFileSuf.rsplit('_Y')[0] + '_profiles'

    if not os.path.exists(saveFileSuf.rsplit('/', 1)[0]):
        os.makedirs(saveFileSuf.rsplit('/', 1)[0])

    (dataH, dataV, labels_H, labels_V,
     fit_coefs) = _n_profiles_H_V(diffPhaseH,
                                  diffPhaseV,
                                  virtual_pixelsize,
                                  'DPC [rad/m]',
                                  titleH='WF DPC Horz',
                                  titleV='WF DPC Vert',
                                  saveFileSuf=saveFileSuf,
                                  nprofiles=nprofiles,
                                  remove2ndOrder=remove2ndOrder,
                                  filter_width=filter_width)

    fit_coefsH = np.array(fit_coefs[0])
    fit_coefsV = np.array(fit_coefs[1])

    print(fit_coefsH)
    print(fit_coefsV)

    if __name__ == '__main__':
        wpu.log_this(preffname=saveFileSuf, inifname=inifname)

    if fnameH is not None:

        radii_fit_H = (2 * np.pi / wavelength / fit_coefsH[:][0])

        wpu.print_blue('MESSAGE: Radius H from fit profiles: ')
        print(radii_fit_H)
        wpu.log_this('radius fit Hor = ' + str(radii_fit_H))

        integratedH = integrate_DPC_cumsum(
            dataH,
            wavelength,
            #grazing_angle=grazing_angle,
            xlabel='x',
            labels=labels_H,
            titleStr='Horizontal, ',
            saveFileSuf=saveFileSuf + '_X')

        curv_H = curv_from_height(
            integratedH,
            virtual_pixelsize[0],
            #grazing_angle=grazing_angle,
            #projectionFromDiv=projectionFromDiv,
            xlabel='x',
            labels=labels_H,
            titleStr='Horizontal, ',
            saveFileSuf=saveFileSuf + '_X')

    if fnameV is not None:

        radii_fit_V = (2 * np.pi / wavelength / fit_coefsV[:][0])

        wpu.print_blue('MESSAGE: Radius V from fit profiles: ')
        print(radii_fit_V)
        wpu.log_this('radius fit Vert = ' + str(radii_fit_V))

        integratedV = integrate_DPC_cumsum(dataV,
                                           wavelength,
                                           grazing_angle=grazing_angle,
                                           projectionFromDiv=projectionFromDiv,
                                           xlabel='y',
                                           labels=labels_V,
                                           titleStr='Vertical, ',
                                           saveFileSuf=saveFileSuf + '_Y')

        curv_V = curv_from_height(integratedV,
                                  virtual_pixelsize[1],
                                  grazing_angle=grazing_angle,
                                  projectionFromDiv=projectionFromDiv,
                                  xlabel='y',
                                  labels=labels_V,
                                  titleStr='Vertical, ',
                                  saveFileSuf=saveFileSuf + '_Y')
img, idx4crop = wpu.crop_graphic_image(img)
imgRef = wpu.crop_matrix_at_indexes(imgRef, idx4crop)

# %% Find harmonic in the Fourier images

# calculate the theoretical position of the hamonics
period_harm_Vert_o = np.int(pixelsize[0]/patternPeriod*img.shape[0] /
                            (sourceDistance + distDet2sample)*sourceDistance)
period_harm_Hor_o = np.int(pixelsize[1]/patternPeriod*img.shape[1] /
                           (sourceDistance + distDet2sample)*sourceDistance)


# Obtain harmonic periods from images

wpu.print_blue('MESSAGE: Obtain harmonic 01 exprimentally')

(_,
 period_harm_Hor) = wgi.exp_harm_period(imgRef, [period_harm_Vert_o,
                                        period_harm_Hor_o],
                                        harmonic_ij=['0', '1'])

wpu.print_blue('MESSAGE: Obtain harmonic 10 exprimentally')

(period_harm_Vert,
 _) = wgi.exp_harm_period(imgRef, [period_harm_Vert_o,
                          period_harm_Hor_o],
                          harmonic_ij=['1', '0'])

harmPeriod = [period_harm_Vert, period_harm_Hor]
Esempio n. 32
0
            (dpy, _, _) = wpu.load_sdf_file(dpcFiles[1])

            fit_radius_dpc(
                dpx,
                dpy,
                pixelsize_dpc,
                radius4fit=np.min(
                    (-xx[0, 0], xx[-1, -1], -yy[0, 0], yy[-1, -1])) * .9,
                kwave=2 * np.pi / 1.5498025e-10,
                saveFigFlag=True,
                str4title='')

    # %% Fit

    #    nominalRadius = 23.00e-6
    wpu.print_blue('MESSAGE: Start Fit')

    if nominalRadius > 0:
        opt = [1, 2]
    else:
        opt = [1]

    for diameter4fit, i in itertools.product(diameter4fit_list, opt):

        radius4fit = _biggest_radius(thickness, pixelSize, diameter4fit / 2)

        wpu.log_this('Radius of the area for fit = ' +
                     '{:.2f} um'.format(radius4fit * 1e6),
                     preffname=fname2save)

        if i == 1:
Esempio n. 33
0
def extract_harmonic(img, harmonicPeriod,
                     harmonic_ij='00', searchRegion=10, isFFT=False,
                     plotFlag=False, verbose=True):

    """
    Function to extract one harmonic image of the FFT of single grating
    Talbot imaging.


    The function use the provided value of period to search for the harmonics
    peak. The search is done in a rectangle of size
    ``periodVert*periodHor/searchRegion**2``. The final result is a rectagle of
    size ``periodVert x periodHor`` centered at
    ``(harmonic_Vertical*periodVert x harmonic_Horizontal*periodHor)``


    Parameters
    ----------

    img : 	ndarray – Data (data_exchange format)
        Experimental image, whith proper blank image, crop and rotation already
        applied.

    harmonicPeriod : list of integers in the format [periodVert, periodHor]
        ``periodVert`` and ``periodVert`` are the period of the harmonics in
        the reciprocal space in pixels. For the checked board grating,
        periodVert = sqrt(2) * pixel Size / grating Period * number of
        rows in the image. For 1D grating, set one of the values to negative or
        zero (it will set the period to number of rows or colunms).

    harmonic_ij : string or list of string
        string with the harmonic to extract, for instance '00', '01', '10'
        or '11'. In this notation negative harmonics are not allowed.

        Alternativelly, it accepts a list of string
        ``harmonic_ij=[harmonic_Vertical, harmonic_Horizontal]``, for instance
        ``harmonic_ij=['0', '-1']``

        Note that since the original image contain only real numbers (not
        complex), then negative and positive harmonics are symetric
        related to zero.
    isFFT : Boolean
        Flag that tells if the input image ``img`` is in the reciprocal
        (``isFFT=True``) or in the real space (``isFFT=False``)

    searchRegion: int
        search for the peak will be in a region of harmonicPeriod/searchRegion
        around the theoretical peak position

    plotFlag: Boolean
        Flag to plot the image in the reciprocal space and to show the position
        of the found peaked and the limits of the harmonic image

    verbose: Boolean
        verbose flag.


    Returns
    -------
    2D ndarray
        Copped Images of the harmonics ij


    This functions crops a rectagle of size ``periodVert x periodHor`` centered
    at ``(harmonic_Vertical*periodVert x harmonic_Horizontal*periodHor)`` from
    the provided FFT image.


    Note
    ----
        * Note that it is the FFT of the image that is required.
        * The search for the peak is only used to print warning messages.

    **Q: Why not the real image??**

    **A:** Because FFT can be time consuming. If we use the real image, it will
    be necessary to run FFT for each harmonic. It is encourage to wrap this
    function within a function that do the FFT, extract the harmonics, and
    return the real space harmonic image.


    See Also
    --------
    :py:func:`wavepy.grating_interferometry.plot_harmonic_grid`

    """

    (nRows, nColumns) = img.shape

    harV = int(harmonic_ij[0])
    harH = int(harmonic_ij[1])

    periodVert = harmonicPeriod[0]
    periodHor = harmonicPeriod[1]

    if verbose:
            wpu.print_blue("MESSAGE: Extracting harmonic " +
                           harmonic_ij[0] + harmonic_ij[1])
            wpu.print_blue("MESSAGE: Harmonic period " +
                           "Horizontal: {:d} pixels".format(periodHor))
            wpu.print_blue("MESSAGE: Harmonic period " +
                           "Vertical: {:d} pixels".format(periodVert))

    # adjusts for 1D grating
    if periodVert <= 0 or periodVert is None:
        periodVert = nRows
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Horizontal 1D Grating")

    if periodHor <= 0 or periodHor is None:
        periodHor = nColumns
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Vertical 1D Grating")

    try:
        _check_harmonic_inside_image(harV, harH, nRows, nColumns,
                                     periodVert, periodHor)
    except ValueError:
        raise SystemExit

    if isFFT:
        imgFFT = img
    else:
        imgFFT = np.fft.fftshift(fft2(img, norm='ortho'))

    intensity = (np.abs(imgFFT))

    #  Estimate harmonic positions
    idxPeak_ij = _idxPeak_ij(harV, harH, nRows, nColumns,
                             periodVert, periodHor)

    del_i, del_j = _error_harmonic_peak(imgFFT, harV, harH,
                                        periodVert, periodHor,
                                        searchRegion)

    if verbose:
        print("MESSAGE: extract_harmonic:" +
              " harmonic peak " + harmonic_ij[0] + harmonic_ij[1] +
              " is misplaced by:")
        print("MESSAGE: {:d} pixels in vertical, {:d} pixels in hor".format(
               del_i, del_j))

        print("MESSAGE: Theoretical peak index: {:d},{:d} [VxH]".format(
              idxPeak_ij[0], idxPeak_ij[1]))

    if ((np.abs(del_i) > searchRegion // 2) or
       (np.abs(del_j) > searchRegion // 2)):

        wpu.print_red("ATTENTION: Harmonic Peak " + harmonic_ij[0] +
                      harmonic_ij[1] + " is too far from theoretical value.")
        wpu.print_red("ATTENTION: {:d} pixels in vertical,".format(del_i) +
                      "{:d} pixels in hor".format(del_j))

    if plotFlag:

        from matplotlib.patches import Rectangle
        plt.figure(figsize=(8, 7))
        plt.imshow(np.log10(intensity), cmap='inferno', extent=wpu.extent_func(intensity))

        plt.xlabel('Pixels')
        plt.ylabel('Pixels')

        xo = idxPeak_ij[1] - nColumns//2 - periodHor//2
        yo = nRows//2 - idxPeak_ij[0] - periodVert//2
        # xo yo are the lower left position of the reangle

        plt.gca().add_patch(Rectangle((xo, yo),
                                      periodHor, periodVert,
                                      lw=2, ls='--', color='red',
                                      fill=None, alpha=1))

        plt.title('Selected Region ' + harmonic_ij[0] + harmonic_ij[1],
                  fontsize=18, weight='bold')
        plt.show(block=False)

    return imgFFT[idxPeak_ij[0] - periodVert//2:
                  idxPeak_ij[0] + periodVert//2,
                  idxPeak_ij[1] - periodHor//2:
                  idxPeak_ij[1] + periodHor//2]
Esempio n. 34
0
def fit_radius_dpc(dpx,
                   dpy,
                   pixelsize,
                   radius4fit,
                   kwave,
                   saveFigFlag=False,
                   str4title=''):

    xVec = wpu.realcoordvec(dpx.shape[1], pixelsize[1])
    yVec = wpu.realcoordvec(dpx.shape[0], pixelsize[0])

    lim_x = np.argwhere(xVec >= -radius4fit * 1.01)[0, 0]
    lim_y = np.argwhere(yVec >= -radius4fit * 1.01)[0, 0]

    xmatrix, ymatrix = np.meshgrid(xVec[lim_x:-lim_x + 1],
                                   yVec[lim_y:-lim_y + 1])

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

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

    ax1.plot(xVec[lim_x:-lim_x + 1] * 1e6,
             dpx[dpx.shape[1] // 4, lim_x:-lim_x + 1],
             '-ob',
             label='1/4')
    ax1.plot(xVec[lim_x:-lim_x + 1] * 1e6,
             dpx[dpx.shape[1] // 2, lim_x:-lim_x + 1],
             '-or',
             label='1/2')
    ax1.plot(xVec[lim_x:-lim_x + 1] * 1e6,
             dpx[dpx.shape[1] // 4 * 3, lim_x:-lim_x + 1],
             '-og',
             label='3/4')

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

    wpu.print_blue('lin_fitx[0] x: {:.3g} m'.format(lin_fitx[0]))
    wpu.print_blue('lin_fitx[1] x: {:.3g} m'.format(lin_fitx[1]))

    wpu.print_blue('Curvature Radius of WF x: {:.3g} m'.format(curvrad_x))

    ax1.ticklabel_format(style='sci', axis='y', scilimits=(0, 1))
    ax1.set_xlabel(r'[$\mu m$]')
    ax1.set_ylabel('dpx [radians]')
    ax1.legend(loc=0, fontsize='small')
    ax1.set_title('Curvature Radius of WF {:.3g} m'.format(curvrad_x),
                  fontsize=16)
    ax1.set_adjustable('box-forced')

    ax2.plot(yVec[lim_y:-lim_y + 1] * 1e6,
             dpy[lim_y:-lim_y + 1, dpy.shape[0] // 4],
             '-ob',
             label='1/4')
    ax2.plot(yVec[lim_y:-lim_y + 1] * 1e6,
             dpy[lim_y:-lim_y + 1, dpy.shape[0] // 2],
             '-or',
             label='1/2')
    ax2.plot(yVec[lim_y:-lim_y + 1] * 1e6,
             dpy[lim_y:-lim_y + 1, dpy.shape[0] // 4 * 3],
             '-og',
             label='3/4')

    lin_fity = np.polyfit(yVec[lim_y:-lim_y + 1], dpy[lim_y:-lim_y + 1,
                                                      dpy.shape[0] // 2], 1)
    lin_funcy = np.poly1d(lin_fity)
    ax2.plot(yVec[lim_y:-lim_y + 1] * 1e6,
             lin_funcy(yVec[lim_y:-lim_y + 1]),
             '--c',
             lw=2,
             label='Fit 1/2')
    curvrad_y = kwave / (lin_fity[0])
    wpu.print_blue('Curvature Radius of WF y: {:.3g} m'.format(curvrad_y))

    ax2.ticklabel_format(style='sci', axis='y', scilimits=(0, 1))
    ax2.set_xlabel(r'[$\mu m$]')
    ax2.set_ylabel('dpy [radians]')
    ax2.legend(loc=0, fontsize='small')
    ax2.set_title('Curvature Radius of WF {:.3g} m'.format(curvrad_y),
                  fontsize=16)
    ax2.set_adjustable('box-forced')

    if saveFigFlag:
        wpu.save_figs_with_idx(fname2save, extension='png')
    plt.show(block=False)
Esempio n. 35
0
'''
Here use the cap to wavesensor data transfer function to generate the same structure
data file with the wavefront measurement curve. The file is generated in the dir_name path
'''

listOfFiles = glob.glob(dirName + '/*.csv')
listOfFiles.sort()
n_files = len(listOfFiles)

# %% Load data

listOfArrays = []
listOfShapes = []

for fname in listOfFiles:
    wpu.print_blue('MESSAGE: Open File ' + fname)
    if use_cap:
        fileContent = load_cap_file(fname)
    else:
        fileContent = wpu.load_csv_file(fname)
    listOfArrays.append(fileContent[0])

    listOfShapes.append(np.shape(fileContent[0]))

headers = fileContent[1]

# %%
for data, fname in zip(listOfArrays, listOfFiles):
    label = fname.rsplit('/', 1)[1].split('.')[0]
    print(
        label +
Esempio n. 36
0
                           int10,
                           virtual_pixelsize,
                           saveFigFlag=saveFigFlag,
                           titleStr='Intensity',
                           saveFileSuf=saveFileSuf)

wgi.plot_dark_field(darkField01,
                    darkField10,
                    virtual_pixelsize,
                    saveFigFlag=saveFigFlag,
                    saveFileSuf=saveFileSuf)

wgi.plot_DPC(diffPhase01,
             diffPhase10,
             virtual_pixelsize,
             saveFigFlag=saveFigFlag,
             saveFileSuf=saveFileSuf)

plt.show(block=True)

# %%

wgi.plot_integration(-1 / 2 / np.pi * phase * wavelength * 1e9,
                     virtual_pixelsize,
                     titleStr=r'-WF $[nm]$',
                     plot3dFlag=True,
                     saveFigFlag=False,
                     saveFileSuf=saveFileSuf)

wpu.print_blue('DONE')
# %% Plots

saveFigFlag = True
saveFileSuf = 'results'

wgi.plot_intensities_harms(int00, int01, int10,
                           virtual_pixelsize, saveFigFlag=saveFigFlag,
                           titleStr='Intensity',
                           saveFileSuf=saveFileSuf)

wgi.plot_dark_field(darkField01, darkField10,
                    virtual_pixelsize, saveFigFlag=saveFigFlag,
                    saveFileSuf=saveFileSuf)

wgi.plot_DPC(diffPhase01, diffPhase10,
             virtual_pixelsize, saveFigFlag=saveFigFlag,
             saveFileSuf=saveFileSuf)

plt.show(block=True)

# %%

wgi.plot_integration(-1/2/np.pi*phase*wavelength*1e9,
                     virtual_pixelsize,
                     titleStr=r'-WF $[nm]$',
                     plot3dFlag=True,
                     saveFigFlag=False,
                     saveFileSuf=saveFileSuf)

wpu.print_blue('DONE')
def _intial_gui_setup(sys_argv):

    global inifname  # name of .ini file
    inifname = os.curdir + '/.' + os.path.basename(__file__).replace(
        '.py', '.ini')

    for i, argv in enumerate(sys_argv):
        print('arg {}: '.format(i) + argv)

    if len(sys_argv) == 1:

        default_ini = wpu.load_ini_file(inifname)
        p0 = float(default_ini['Parameters']['Photon Energy [eV]'])
        p1 = float(default_ini['Parameters']['grazing angle [mrad]'])
        p2 = int(default_ini['Parameters']['n profiles'])
        p3 = int(default_ini['Parameters']['filter width'])
        p4 = float(default_ini['Parameters']['projection From Divergence'])

        if easyqt.get_yes_or_no('Load new files?\n' +
                                '[ESC load file(s) of previous run]'):

            fnameH = easyqt.get_file_names(title='Select DPC Horizontal\n' +
                                           '(and Vertical if you want)')
            fnameV = None

            if len(fnameH) == 1:
                fnameH = fnameH[0]
                wpu.print_blue('MESSAGE: Horiz DPC: Loading ' + fnameH)
            elif len(fnameH) == 0:
                fnameH = None
            elif len(fnameH) == 2:
                [fnameH, fnameV] = fnameH
                wpu.print_blue('MESSAGE: Horiz DPC: Loading ' + fnameH)
                wpu.print_blue('MESSAGE: Vert DPC: Loading ' + fnameV)

            if fnameV is None:
                fnameV = easyqt.get_file_names(title='Select DPC Vertical')

                if len(fnameV) == 1:
                    fnameV = fnameV[0]
                    wpu.print_blue('MESSAGE: Vert DPC: Loading ' + fnameV)

                elif len(fnameV) == 0:
                    fnameV = None

        else:
            fnameH = default_ini['Files']['dpc H']
            fnameV = default_ini['Files']['dpc V']

            wpu.print_blue('MESSAGE: Horiz DPC: Loading ' + fnameH)
            wpu.print_blue('MESSAGE: Vert DPC: Loading ' + fnameV)

            if fnameH == 'None':
                fnameH = None
            if fnameV == 'None':
                fnameV = None

        phenergy = easyqt.get_float("Enter Photon Energy [KeV]",
                                    title='Experimental Values',
                                    default_value=p0 * 1e-3) * 1e3

        grazing_angle = easyqt.get_float(
            'Grazing angle [mrad]\n' + '[0.0 to ignore projection]',
            title='Experimental Values',
            default_value=p1) * 1e-3

        projectionFromDiv = easyqt.get_float('projection From Divergence\n' +
                                             '[Multiplication factor]',
                                             title='Experimental Values',
                                             default_value=p4)

        nprofiles = easyqt.get_int("Number of profiles to plot",
                                   title='Experimental Values',
                                   default_value=p2)

        filter_width = easyqt.get_int("Width fo uniform filter [pixels]",
                                      title='Experimental Values',
                                      default_value=p3)

        remove2ndOrder = easyqt.get_yes_or_no("Remove 2nd Order?",
                                              title='Experimental Values')

    elif len(sys_argv) == 8:

        if 'none' in sys_argv[1].lower():
            fnameH = None
        else:
            fnameH = sys_argv[1]

        if 'none' in sys_argv[2].lower():
            fnameV = None
        else:
            fnameV = sys_argv[2]

        phenergy = float(sys_argv[3]) * 1e3
        nprofiles = int(sys_argv[4])
        filter_width = int(sys_argv[5])
        grazing_angle = float(sys_argv[6]) * 1e-3
        projectionFromDiv = float(sys_argv[7])

    else:

        print(
            'ERROR: wrong number of inputs: {} \n'.format(len(argv) - 1) +
            'Usage: \n'
            '\n' + os.path.basename(__file__) +
            ' : (no inputs) load dialogs \n'
            '\n' + os.path.basename(__file__) + ' [args] \n'
            '\n'
            'arg1: file name DPC Horiz (type "None" '
            '      to ignore it)\n'
            'arg2: file name DPC Vert (type "None" '
            '      to ignore it)\n'
            'arg3: Photon Energy [KeV]\n'
            'arg4: Number of profiles to plot\n'
            'arg5: Width  of uniform filter [pixels]\n'
            'arg6: Grazing angle to project coordinates to mirror [mrad], use zero to ignore\n'
            'arg7: Projection From Divergence, use 1 to ignore'
            '\n')

        exit(-1)

    wpu.set_at_ini_file(inifname, 'Files', 'DPC H', fnameH)
    wpu.set_at_ini_file(inifname, 'Files', 'DPC V', fnameV)
    wpu.set_at_ini_file(inifname, 'Parameters', 'Photon Energy [eV]', phenergy)
    wpu.set_at_ini_file(inifname, 'Parameters', 'grazing angle [mrad]',
                        grazing_angle * 1e3)
    wpu.set_at_ini_file(inifname, 'Parameters', 'projection From Divergence',
                        projectionFromDiv)
    wpu.set_at_ini_file(inifname, 'Parameters', 'n profiles', nprofiles)
    wpu.set_at_ini_file(inifname, 'Parameters', 'filter width', filter_width)

    wpu.set_at_ini_file(inifname, 'Parameters', 'Remove 2nd Order',
                        remove2ndOrder)

    return (fnameH, fnameV, phenergy, grazing_angle, projectionFromDiv,
            nprofiles, remove2ndOrder, filter_width)