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
def gui_load_data_finename(directory='', title="File name with Data"): 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) fname1 = easyqt.get_file_names(title) if len(fname1) == 0: fname_last = None else: fname_last = fname1[0] os.chdir(originalDir) return fname_last
unFilterSize=unFilterSize) # ============================================================================= # %% Script starts # ============================================================================= 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/' + samplefileName.rsplit('_', 1)[0].rsplit( '/', 1)[1] wpu.print_blue('MESSAGE: Loading files ' + samplefileName.rsplit('_', 1)[0] + '*.tif')
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
return data2save, headerdic # %% if __name__ == '__main__': argv = sys.argv if len(argv) == 4: data, headerdic = save_profile_from_sdf(argv[1], nprofiles=int(argv[2]), direction=argv[3]) else: data, headerdic = save_profile_from_sdf(easyqt.get_file_names()[0], nprofiles=easyqt.get_int('Number of profiles'), direction=easyqt.get_choice(choices=['Vertical', 'Horizontal'])) # %% plt.figure() for i in range(1, data.shape[1]): plt.plot(data[:,0], data[:,i]+1e-9) plt.show()
] what2do = easyqt.get_choice('Pick one', choices=choices) wpu.set_at_ini_file(inifname, 'Parameters', 'what2do', what2do) # %% Target # Target file is the shape wanted for the correction. if len(sys.argv) > 2 or easyqt.get_yes_or_no( 'Do you want to load a target file?'): if len(sys.argv) > 2: targetName = sys.argv[2] else: targetName = easyqt.get_file_names('the target file directory:') if targetName == []: targetName = defaults['Files'].get('target file') else: wpu.set_at_ini_file(inifname, 'Files', 'target file', targetName[0]) temp_Data = wpu.load_csv_file(targetName[0])[0] lim_xnew = np.min( (np.abs(listOfArrays[0][0, 0]), np.abs(listOfArrays[0][-1, 0]), np.abs(temp_Data[0, 0]), np.abs(temp_Data[-1, 0]))) else: temp_Data = None lim_xnew = np.min( (np.abs(listOfArrays[0][0, 0]), np.abs(listOfArrays[0][-1, 0])))
import os import sys import matplotlib.pyplot as plt from skimage.restoration import unwrap_phase import numpy as np from mpl_toolkits.mplot3d import Axes3D if len(sys.argv) != 1: os.chdir(sys.argv[1]) os.chdir('/home/grizolli/work/spectra/tempresults/') data = np.loadtxt(open(easyqt.get_file_names("Data File to Plot")[0], 'rb'), skiprows=11) # %% nx = len(set(data[:, 0])) ny = len(set(data[:, 1])) xxGrid = np.reshape(data[:, 0]*1e-3, (nx, ny)) yyGrid = np.reshape(data[:, 1]*1e-3, (nx, ny)) field_x = np.reshape(data[:, 2] + 1j*data[:, 3], (nx, ny)) field_y = np.reshape(data[:, 4] + 1j*data[:, 5], (nx, ny)) phase_x = -unwrap_phase(np.angle(field_x))
] what2do = easyqt.get_choice('Pick one', choices=choices) wpu.set_at_ini_file(inifname, 'Parameters', 'what2do', what2do) # %% Target # Target file is the shape wanted for the correction. if len(sys.argv) > 2 or easyqt.get_yes_or_no( 'Do you want to load a target file?'): if len(sys.argv) > 2: targetName = sys.argv[2] else: targetName = easyqt.get_file_names('the target file directory:') # use one image as the current state if easyqt.get_yes_or_no( 'Do you want to load the refence file for target?'): ref_name = easyqt.get_file_names('the reference file directory:') else: ref_name = [] if targetName == []: targetName = defaults['Files'].get('target file') else: wpu.set_at_ini_file(inifname, 'Files', 'target file', targetName[0]) if use_cap: if ref_name == []:
# ============================================================================= originalDir = os.getcwd() try: os.chdir('/data/share/BeamtimeData/') except FileNotFoundError: 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)
curves.append(np.asarray(fig.axes[0].lines[i].get_data())) return curves # %% if __name__ == '__main__': # if len(sys.argv) != 1: # os.chdir(sys.argv[1]) if len(sys.argv) == 1: flist = easyqt.get_file_names("Pickle File to Plot") fname = flist[0] else: fname = sys.argv[1] results = _load_data_from_pickle(fname) # %% zvec = results[0][0] * 1e-3 contrastV = results[0][1] * 1e-2 contrastH = results[1][1] * 1e-2 if zvec[-1] - zvec[0] < 0:
""" from wavepy.utils import easyqt import dxchange import sys import numpy as np import wavepy.utils as wpu if len(sys.argv) != 1: fname = sys.argv[1] else: fname = easyqt.get_file_names("Data File to Plot")[0] data = dxchange.read_tiff(fname) data = wpu.crop_graphic_image(data, kargs4graph={'cmap': 'rainbow'})[0] # %% nx, ny = np.shape(data) stride = 1 if nx > 200 or ny > 200: stride = easyqt.get_int( 'Number of points: {} x {}.'.format(nx, ny) + ' Enter value for stride:', 'Enter Value', 2, 1, 101)
@author: Walan Grizolli Hint: make the file executable and add to a directory in the PATH to make executable in linux: >>> chmod +x FILENAME """ import pickle from wavepy.utils import easyqt import matplotlib.pyplot as plt figx = pickle.load(open(easyqt.get_file_names("Pickle File to Plot")[0],'rb')) plt.show(block=False) # this lines keep the script alive to see the plot figx2 = pickle.load(open(easyqt.get_file_names("Pickle File to Plot")[0],'rb')) plt.show(block=True) # this lines keep the script alive to see the plot # %% Example of how to get the data from a graph import numpy as np
# %% inifname = '.align_many_imgs_and_save.ini' # %% idx4crop = list( 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':
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)
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) # %% Target if len(sys.argv) > 2 or easyqt.get_yes_or_no('Do you want to load a target file?'): if len(sys.argv) > 2: targetName = sys.argv[2] else: targetName = easyqt.get_file_names(title='select target CSV') if targetName == []: targetName = defaults['Files'].get('target file') else: wpu.set_at_ini_file(inifname, 'Files', 'target file', targetName[0]) #temp_Data = wpu.load_csv_file(targetName[0])[0] temp_Data = load_csv_new(targetName[0])[0] lim_xnew = np.min((np.abs(listOfArrays[0][0, 0]), np.abs(listOfArrays[0][-1, 0]), np.abs(temp_Data[0, 0]), np.abs(temp_Data[-1, 0]))) else:
Hint: make the file executable and add to a directory in the PATH to make executable in linux: >>> chmod +x FILENAME """ import pickle from wavepy.utils import easyqt import os import sys import matplotlib.pyplot as plt fname = easyqt.get_file_names("Pickle File to Plot")[0] figx = pickle.load(open(fname, 'rb')) plt.show(block=False) # this lines keep the script alive to see the plot label1 = fname.rsplit('.')[0].rsplit('/')[-1] fname = easyqt.get_file_names("Pickle File to Plot")[0] figx2 = pickle.load(open(fname, 'rb')) plt.show(block=False) # this lines keep the script alive to see the plot label2 = fname.rsplit('.')[0].rsplit('/')[-1] fname = easyqt.get_file_names("Pickle File to Plot")[0] figx3 = pickle.load(open(fname, 'rb')) plt.show(block=False) # this lines keep the script alive to see the plot label3 = fname.rsplit('.')[0].rsplit('/')[-1] fname = easyqt.get_file_names("Pickle File to Plot")[0]
@author: grizolli """ # %% import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import wavepy.utils as wpu from wavepy.utils import easyqt import h5py # %% fname_dpc_h5 = easyqt.get_file_names("DPC Files")[0] fh5 = h5py.File(fname_dpc_h5) # %% dpc_x = np.array(fh5['dpcHorizontal']) dpc_y = np.array(fh5['dpcVertical']) phase = np.array(fh5['phase'])
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)
import sys from wavepy.utils import _fwhm_xy plt.rc('axes', prop_cycle=(cycler('linestyle', ['-', '--', '-.', ':']) * cycler('color', ['k', 'r', 'g', 'b', 'm', 'c']))) # %% Select data File if len(sys.argv) != 1: listFiles = sys.argv[1:] else: listFiles = easyqt.get_file_names("File name with Data") figname = listFiles[0].rsplit('/', 1)[1].rsplit('.', 1)[0] f = open(listFiles[0], 'r') text = f.readlines()[0:11] f.close() print('### FILE HEADER') for item in text: print('###' + item[:-1]) # %% Select which collum to plot quantity = text[8].split()
zmin = np.nanmin(z) zmax = np.nanmax(z) colorIndex = np.rint(inverse * ((z - zmin) / (zmax - zmin))**power * (nColours - 1)).astype(int) colorIndex[np.isnan(z)] = 1 colorMap = jet_vals[colorIndex[:, :]] return colorMap if __name__ == '__main__': # %% dataFilename = easyqt.get_file_names() if len(dataFilename) == 1: dataFilename = dataFilename[0] dataZ, pixelSize, headerdic = wpu.load_sdf_file(dataFilename) else: y, x = np.mgrid[-1:1:100j, -1:1:100j] dataZ = np.sinc(10 * x**2) * np.exp(-y**2 / .5**2) pixelSize = [1 / 2, 1] # %% plot_surf_fast(dataZ, pixelSize,