예제 #1
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
예제 #2
0
# %%

if len(sys.argv) == 1:
    dirName = easyqt.get_directory_name('Directory to the data:')
else:
    dirName = sys.argv[1]

# here the response function initialization file
inifname = '.Revise_response_func.ini'
defaults = wpu.load_ini_file(inifname)

if dirName == '':
    dirName = defaults['Files'].get('Folder with csv files')

else:
    wpu.set_at_ini_file(inifname, 'Files', 'Folder with csv files', dirName)

print(dirName)
'''
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 = []
    what2do = wpu.get_from_ini_file(inifname, 'Parameters', 'what2do')

    if 'DPC' in what2do:
        choices = [
            'DPC response function',
            'Curvature response function from diff data'
        ]
    else:
        choices = [
            'Curvature response function from diff data',
            'DPC response function'
        ]

    what2do = easyqt.get_choice('Pick one', choices=choices)

wpu.set_at_ini_file(inifname, 'Parameters', 'what2do', what2do)

# %%

listInterpFunc = []

npoints_interp = 460
xnew = np.linspace(listOfArrays[0][0, 0], listOfArrays[0][-1, 0],
                   npoints_interp)

# %%

from scipy.ndimage import gaussian_filter1d

if 'Curvature' in what2do:
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)
예제 #5
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)
def main_single_gr_Talbot(img, imgRef,
                          phenergy, pixelsize, distDet2sample,
                          period_harm, saveFileSuf,
                          unwrapFlag=True,
                          plotFlag=True,
                          saveFigFlag=False):

    global inifname  # name of .ini file

    [period_harm_Vert, period_harm_Hor] = period_harm


    #    img, imgRef = wpu.align_two_images(img, imgRef)

    # Crop

    img_size_o = np.shape(img)

    # take index from ini file
    idx4crop = list(map(int, (wpu.get_from_ini_file(inifname, 'Parameters',
                                                    'Crop').split(','))))

    # Plot Real Image wiht default crop

    tmpImage = wpu.crop_matrix_at_indexes(img, idx4crop)

    plt.figure()
    plt.imshow(tmpImage,
               cmap='viridis',
               extent=wpu.extent_func(tmpImage, pixelsize)*1e6)
    plt.xlabel(r'$[\mu m]$')
    plt.ylabel(r'$[\mu m]$')
    plt.colorbar()

    plt.title('Raw Image with initial Crop', fontsize=18, weight='bold')

    plt.pause(.1)
    # ask if the crop need to be changed
    newCrop = easyqt.get_yes_or_no('New Crop?')

    if saveFigFlag and not newCrop:
        wpu.save_figs_with_idx(saveFileSuf + '_Talbot_image')
    plt.close(plt.gcf())

    if newCrop:

        [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.set_at_ini_file(inifname, 'Parameters', 'Crop',
                            '{}, {}, {}, {}'.format(idx4crop[0], idx4crop[1],
                                                    idx4crop[2], idx4crop[3]))

        img = wpu.crop_matrix_at_indexes(img, idx4crop)

        # Plot Real Image AFTER crop

        plt.imshow(img, cmap='viridis',
                   extent=wpu.extent_func(img, pixelsize)*1e6)
        plt.xlabel(r'$[\mu m]$')
        plt.ylabel(r'$[\mu m]$')
        plt.colorbar()
        plt.title('Raw Image with New Crop', fontsize=18, weight='bold')

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Talbot_image')
        plt.show(block=True)

    else:
        img = tmpImage

    imgRef = wpu.crop_matrix_at_indexes(imgRef, idx4crop)

    # calculate harmonic position after crop

    period_harm_Vert = int(period_harm_Vert*(idx4crop[1] - idx4crop[0]) /
                           img_size_o[0])
    period_harm_Hor = int(period_harm_Hor*(idx4crop[3] - idx4crop[2]) /
                          img_size_o[1])

    # Obtain harmonic periods from images

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

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

    # Calculate everything

    harmPeriod = [period_harm_Vert, period_harm_Hor]

    [int00, int01, int10,
     darkField01, darkField10,
     phaseFFT_01,
     phaseFFT_10] = wgi.single_2Dgrating_analyses(img, imgRef,
                                                  harmonicPeriod=harmPeriod,
                                                  plotFlag=plotFlag,
                                                  unwrapFlag=unwrapFlag,
                                                  verbose=True)

    virtual_pixelsize = [0, 0]
    virtual_pixelsize[0] = pixelsize[0]*img.shape[0]/int00.shape[0]
    virtual_pixelsize[1] = pixelsize[1]*img.shape[1]/int00.shape[1]

    diffPhase01 = phaseFFT_01*virtual_pixelsize[1]/distDet2sample/hc*phenergy
    diffPhase10 = phaseFFT_10*virtual_pixelsize[0]/distDet2sample/hc*phenergy

    return [int00, int01, int10,
            darkField01, darkField10,
            diffPhase01, diffPhase10,
            virtual_pixelsize]
    else:

        idx4crop = list(map(int,
                            (wpu.get_from_ini_file(inifname,
                                                   'Parameters',
                                                   'crop integration').split(','))))
    phase, idx4crop = wgi.dpc_integration(diffPhase01, diffPhase10,
                                          virtual_pixelsize,
                                          idx4crop=idx4crop,
                                          saveFileSuf=saveFileSuf,
                                          plotErrorIntegration=True,
                                          shifthalfpixel=True)

    wpu.set_at_ini_file(inifname, 'Parameters', 'crop integration',
                        '{}, {}, {}, {}'.format(idx4crop[0], idx4crop[1],
                                                idx4crop[2], idx4crop[3]))

    phase -= np.mean(phase)  # apply here your favorite offset


    # %%
    ax = wgi.plot_integration(1/2/np.pi*phase, virtual_pixelsize,
                              titleStr=r'WF $[\lambda$ units $]$',
                              saveFigFlag=True, saveFileSuf=saveFileSuf)

    plt.pause(.2)



    # ==========================================================================
예제 #8
0
    map(int,
        (wpu.get_from_ini_file(inifname, 'Parameters', 'Crop').split(','))))
defaults = wpu.load_ini_file(inifname)
deafaultfileName = defaults['Files'].get('Reference')

# %% Load

if len(sys.argv) == 1:
    samplefileName = easyqt.get_file_names("Choose the reference file " +
                                           "for alignment")

    if samplefileName == []:
        samplefileName = deafaultfileName
    else:
        samplefileName = samplefileName[0]
        wpu.set_at_ini_file(inifname, 'Files', 'reference', samplefileName)

    optionRef = easyqt.get_choice(
        'Align images to reference ot to previous image?',
        title='Title',
        choices=['Reference', 'Previous', 'Manual'])

    fixRef = (optionRef == 'Reference')

    if optionRef != 'Manual':
        option = easyqt.get_choice('Crop or Pad?',
                                   title='Title',
                                   choices=['Pad', 'Crop'])
else:
    samplefileName = sys.argv[1]
    option = sys.argv[2]