def run(): c = gwy.gwy_app_data_browser_get_current(gwy.APP_CONTAINER) filename = c['/filename'] dir_path,basename = os.path.split(filename) basename = basename[0:-4] #print dir_path,base_name d = gwy.gwy_app_data_browser_get_current(gwy.APP_DATA_FIELD) data_field_id = gwy.gwy_app_data_browser_get_current(gwy.APP_DATA_FIELD_ID) meta_field = '/' + str(data_field_id) + '/meta' title = '/' + str(data_field_id) + '/data/title' channel = c[title] #print channel gwy.gwy_app_data_browser_select_data_field(c,data_field_id) #meta = c[meta_field] #print meta.keys_by_name() #bias = meta['Bias'] #bias, bu = bias.split(' ') #current = meta['Z controller Setpoint'] #current, cu = current.split(' ') #current = float(current) * 1e12 #cu = 'pA' #current_bias = 'pm' #xd = d.get_xreal() * 1e9 #yd = d.get_yreal() * 1e9 #xyu = 'nm' output_path = dir_path output_name = basename + '.png' output = os.path.join(output_path,output_name) gwy.gwy_file_save(c, output, gwy.RUN_NONINTERACTIVE)
def savefilesasgwy(data, filename): # Turn rulers on s["/module/pixmap/xytype"] = 1 # Get directory path and filename (including extension to avoid overwriting .000 type Bruker files) directory, filename = os.path.split(filename) # Create a saving name format/directory savedir = os.path.join(directory) # If the folder Processed doest exist make it here if not os.path.exists(savedir): os.makedirs(savedir) # Save the data for the channels found above i.e. ZSensor/Height, as chosen_ids # Data is exported to a file of extension set in the main script # Data is exported with the string '_processed' added to the end of its filename gwy.gwy_app_data_browser_select_data_field(data, k) # change the colour map for all channels (k) in the image: palette = data.set_string_by_name("/" + str(k) + "/base/palette", "Nanoscope.txt") # Determine the title of each channel # title = data["/%d/data/title" % k] # if not title: # title = 'unknown' # Generate a filename to save to by removing the extension to the file, adding the suffix '_processed' # and an extension set in the main file savename = os.path.join(savedir, filename) + str(k) + '.gwy' # Save the file gwy.gwy_file_save(data, savename, gwy.RUN_NONINTERACTIVE)
def save_image_file(container, save_file): """Saves image file through Gwyddion, with optional file dialog. Args: container (gwy-container): Gwyddion container which will be exported. save_file (str): Filepath how the file will be saved. """ if config.export_image_dialog: gwy.gwy_file_save(container, save_file, gwy.RUN_INTERACTIVE) else: gwy.gwy_file_save(container, save_file, gwy.RUN_NONINTERACTIVE)
def save_dfield_to_png(container, datafield_name, filename, run_type): """ Save desired datafield given by name stored in container to file. @param container: gwy.Container which has datafield of given name @param datafield_name: datafield name in string representation (like '/0/data') @param filename: expected filename @param run_type: select of interactive (RUN_INTERACTIVE) or noninteractive mode (RUN_NONINTERACTIVE) """ gwy.gwy_app_data_browser_reset_visibility(container, gwy.VISIBILITY_RESET_SHOW_ALL) datafield_num = int(datafield_name.split('/')[1]) gwy.gwy_app_data_browser_select_data_field(container, datafield_num) gwy.gwy_file_save(container, filename, run_type)
def run(container, mode): container = gwy.gwy_app_data_browser_get_current(gwy.APP_CONTAINER) filename = container['/filename'] path, _ = os.path.splitext(filename) output_path = path + OUTPUT_SUFFIX if not os.path.exists(output_path): os.mkdir(output_path) for i, id_ in enumerate(gwy.gwy_app_data_browser_get_data_ids(container)): title = container['/{}/data/title'.format(id_)] gwy.gwy_app_data_browser_select_data_field(container, id_) output_filename = '{:03d}_{}.{}'.format(id_, title, OUTPUT_FILESUFFIX) output_filename = os.path.join(output_path, output_filename) mode = gwy.RUN_INTERACTIVE if i == 0 else gwy.RUN_NONINTERACTIVE print 'Exporting {} ...'.format(output_filename) gwy.gwy_file_save(container, output_filename, mode)
def save_topo_bwd_data(self, path): """Save backward topography data file. Args: path (str): File path where the file should be save. """ self.dat_topo_bwd = os.path.join( path, str(self.m_id) + "_bwd." + config.dat_type_out) gwy.gwy_file_save(self.container, self.dat_topo_bwd, gwy.RUN_NONINTERACTIVE) if config.dat_type_igor: self.file_igor = os.path.join(path, "g" + str(self.m_id) + "_ori.tb0") shutil.move(self.dat_topo_bwd, self.file_igor)
def savecroppedfiles(directory, data, filename, extension, orig_ids, crop_ids, minheightscale, maxheightscale): # Save the data for the cropped channels # Data is exported to a file of extension set in the main script # Data is exported with the string '_cropped' added to the end of its filename # Turn rulers off s["/module/pixmap/xytype"] = 0 # Get directory path and filename (including extension to avoid overwriting .000 type Bruker files) directory, filename = os.path.split(filename) # Create a saving name format/directory savedir = os.path.join(directory, 'Cropped') # If the folder Cropped doest exist make it here if not os.path.exists(savedir): os.makedirs(savedir) crop_directory = savedir # Otherwise set the existing Cropped directory as the directory to write to else: crop_directory = savedir # For each cropped file, save out the data with the suffix _Cropped_# for i in range(len(orig_ids), len(crop_ids), 1): # select each channel fo the file in turn gwy.gwy_app_data_browser_select_data_field(data, i) # change the colour map for all channels (k) in the image: palette = data.set_string_by_name("/" + str(i) + "/base/palette", "Nanoscope.txt") # Set the image display to fixed range and the colour scale for the images maximum_disp_value = data.set_int32_by_name( "/" + str(i) + "/base/range-type", int(1)) minimum_disp_value = data.set_double_by_name( "/" + str(i) + "/base/min", float(minheightscale)) maximum_disp_value = data.set_double_by_name( "/" + str(i) + "/base/max", float(maxheightscale)) # Generate a filename to save to by removing the extension to the file and a numerical identifier (the crop no) # The 'crop number' is the channel number minus the original number of channels, less one to avoid starting at 0 savenumber = i - (len(orig_ids) - 1) # adding the suffix '_cropped' and adding the extension set in the main file savename = os.path.join( crop_directory, filename) + '_cropped_' + str(savenumber) + str(extension) # Save the file gwy.gwy_file_save(data, savename, gwy.RUN_NONINTERACTIVE)
def savefiles(data, filename, extension): # Save file scale option: 1 - ruler, 2 - inset scale bar, 0 - none s["/module/pixmap/xytype"] = savefilesScale_option # Get directory path and filename (including extension to avoid overwriting .000 type Bruker files) directory, filename = os.path.split(filename) # Create a saving name format/directory savedir = os.path.join(directory, 'Processed') # If the folder Processed doest exist make it here if not os.path.exists(savedir): os.makedirs(savedir) # Save the data for the channels found above i.e. ZSensor/Height, as chosen_ids # Data is exported to a file of extension set in the main script # Data is exported with the string '_processed' added to the end of its filename gwy.gwy_app_data_browser_select_data_field(data, k) # change the colour map for all channels (k) in the image: palette = data.set_string_by_name("/%s/base/palette" % k, savefile_zscalecolour) # Determine the title of each channel title = data["/%d/data/title" % k] # Generate a filename to save to by removing the extension to the file, adding the suffix '_processed' # and an extension set in the main file savename = os.path.join( savedir, filename) + str(k) + '_' + str(title) + '_processed' + str(extension) # Save the file gwy.gwy_file_save(data, savename, gwy.RUN_NONINTERACTIVE) # Show the mask data['/%d/mask' % k] = mask # Add the sufix _masked to the previous filename savename = os.path.join(savedir, filename) + str(k) + '_' + str( title) + '_processed_masked' + str(extension) # Save the data gwy.gwy_file_save(data, savename, gwy.RUN_NONINTERACTIVE) gwy.gwy_app_file_close()
def save_all(containers, format="svg", palette="Gray", _id=0): """ Saves all open files to PNG image files in a folder in image directory. containers is a list of open containers... ...can be obtained by gwy.gwy_app_data_browser_get_containers() """ for c in containers: # set palette of datafield c.set_string_by_name("/{}/base/palette".format(_id), "Gray") # file name fname = gwy.gwy_file_get_filename_sys(c) fpath, image_name = os.path.split(fname) # save image_name_string = "{}.{}".format( os.path.splitext(image_name)[0], format) save_string = os.path.join(fpath, image_name_string) gwy.gwy_app_data_browser_select_data_field(c, _id) gwy.gwy_file_save(c, save_string, gwy.RUN_NONINTERACTIVE)
def gwybas(filename): #add the gwyddion folders to the path, making sure they can be found import sys sys.path.append('C:\Program Files (x86)\Gwyddion\\bin') sys.path.append('C:\Program Files (x86)\Gwyddion\share\gwyddion\pygwy') #import gwyddion import gwy import gwyutils #load the file and add to data browser c = gwy.gwy_file_load(filename, gwy.RUN_IMMEDIATE) gwy.gwy_app_data_browser_add(c) #Set the right settings for the align_rows command settings = gwy.gwy_app_settings_get() settings['/module/linematch/direction'] = int(gwy.ORIENTATION_HORIZONTAL) settings['/module/linematch/do_extract'] = False settings['/module/linematch/do_plot'] = False settings[ '/module/linematch/method'] = 0 # 0: poly, 1: median, 2: median of diff,3: modus,4: matching, 5: trimemd mean, 6: trimmed mean of diff settings['/module/linematch/masking'] = 2 settings['/module/linematch/max_degree'] = 3 #Order of polynominal settings['/module/linematch/trim_fraction'] = 0.05 #print the datafield ID's corresponding to the different channels of the AFM, such as height, phase and error, usually the first one (0) is the height # print gwy.gwy_app_data_browser_get_data_ids(c) #itterate over the different datafield ID's/AFM channels, and do processing on them for datafield_id in gwy.gwy_app_data_browser_get_data_ids(c): # datafield = c['/%d/data' % datafield_id] #set the color range to automatic with tials cut off (corresponding to number 2) c['/%d/base/range-type' % datafield_id] = 2 #select the datafield_ID/AFM channel to process gwy.gwy_app_data_browser_select_data_field(c, datafield_id) #level the plane gwy.gwy_process_func_run("level", c, gwy.RUN_IMMEDIATE) #align the rows, with settings chosen above line 19-25 gwy.gwy_process_func_run("align_rows", c, gwy.RUN_IMMEDIATE) #remove scars a couple of times (button bashing) gwy.gwy_process_func_run("scars_remove", c, gwy.RUN_IMMEDIATE) gwy.gwy_process_func_run("scars_remove", c, gwy.RUN_IMMEDIATE) gwy.gwy_process_func_run("scars_remove", c, gwy.RUN_IMMEDIATE) gwy.gwy_process_func_run("scars_remove", c, gwy.RUN_IMMEDIATE) gwy.gwy_process_func_run("scars_remove", c, gwy.RUN_IMMEDIATE) #fix lowest point to zero gwy.gwy_process_func_run('fix_zero', c, gwy.RUN_IMMEDIATE) #define new file names, I chose to simply add the wanted extention to the original filename newname = filename + '.gwy' newname2 = filename + '.jpg' #find the ID/Channel corresponding to the height, of this one a JPG will be created, .gwy will contain all channels ids = gwy.gwy_app_data_browser_find_data_by_title(c, 'Height') gwy.gwy_app_data_browser_select_data_field(c, ids[0]) gwy.gwy_file_save(c, newname, gwy.RUN_NONINTERACTIVE) gwy.gwy_file_save(c, newname2, gwy.RUN_NONINTERACTIVE) #remove the current container, makes room for the next file gwy.gwy_app_data_browser_remove(c)
if chunk: # filter out keep-alive new chunks f.write(chunk) #f.flush() commented by recommendation from J.F.Sebastian return local_filename # Main program ## Create output folder output_folder = "." try: os.makedirs("%s/" % (output_folder)) os.chdir(output_folder) except OSError as exc: pass ## Download file #rawFile = download_file("http://127.0.0.1:8080%s" % path) rawFile = path ## Gywddion load print("Gwyddion loading %s" % rawFile) import gwy container = gwy.gwy_file_load(rawFile, gwy.RUN_NONINTERACTIVE) ## Save to gwy gwy.gwy_file_save(container, "%s/data.gwy" % (output_folder), gwy.RUN_NONINTERACTIVE) print("%s/" % (output_folder)) sys.exit()
# from array import array # output_file = open("%s/channel/%02d/binary" % (output_folder,i), 'wb') # float_array = array('d', data) # float_array.tofile(output_file) # output_file.close() # Save into JSON ch_meta["data"] = data # Save pickle #file = open("%s/channel/%02d/image.p" % (output_folder,i), "w" ) #pickle.dump(data,file) #file.close() # Save binary data #data = data_field.get_data() # Save PNG thumbnail gwy.gwy_file_save(container, "%s/channel/%02d/image.png" % (output_folder,i), gwy.RUN_NONINTERACTIVE) # Save metadata file = open("%s/channel/%02d/channel.json" % (output_folder,i), "w" ) json.dump(ch_meta,file) file.close() gwy.gwy_app_data_browser_remove(container) print("%s" % (output_folder)) sys.exit()
meta = c[meta_field] print meta.keys_by_name() bias = meta['Bias'] bias, bu = bias.split(' ') current = meta['Z controller Setpoint'] current, cu = current.split(' ') current = float(current) * 1e12 cu = 'pA' current_bias = 'pm' xd = d.get_xreal() * 1e9 yd = d.get_yreal() * 1e9 xyu = 'nm' print xd print bias temp_name = basename+'_temp.png' gwy.gwy_file_save(c, temp_name, gwy.RUN_NONINTERACTIVE) # prepare to save w = d.get_xres() h = d.get_yres() io.use_plugin('freeimage') data_field = '/' + str(data_field_id) + '/data' img = Image.open(temp_name) I = np.asarray(img) print len(I.shape) if len(I.shape) > 2: new = np.zeros((w+40,h,3)) new[:,:,:] = 256 new[:w,:h,:] = I new = new.astype('int16') else:
# Stupid bloody /0/data/nonsense key = "/"+str(data_set)+"/data" data = datafields[key] # Plane level a, bx, by = data.fit_plane() data.plane_level(a, bx, by) # Median line correction data = line_correct_median(data) # Fix zero data.add(-1.0 * data.get_min()) # Set colour range base = "/"+str(data_set)+"/base" container.set_int32_by_name(base+"/range-type", 1) container.set_double_by_name(base+"/min", colour_min) container.set_double_by_name(base+"/max", colour_max) container.set_string_by_name(base+"/palette", palette) # Do silly things required to save gwy.gwy_app_data_browser_reset_visibility(container, gwy.VISIBILITY_RESET_SHOW_ALL) gwy.gwy_app_data_browser_select_data_field(container, data_set) if saved_once: gwy.gwy_file_save(container, out_file, gwy.RUN_NONINTERACTIVE) else: gwy.gwy_file_save(container, out_file, gwy.RUN_INTERACTIVE) saved_once = True gwy.gwy_app_data_browser_reset_visibility(container, gwy.VISIBILITY_RESET_HIDE_ALL)
### SAVING THE MODIFIED FILES AS TIFFS ### #Save all files as tiffs - this puts them all with the raw data annoyingly #Could put in some os commands to move everything around afterwards #Use blue and gold colour scheme with a sensible and consistent colour scale maximum_disp_value = gwy_rawdata.set_int32_by_name( "/" + str(i) + "/base/range-type", int(1)) minimum_disp_value = gwy_rawdata.set_double_by_name( "/" + str(i) + "/base/min", float(1e-9)) maximum_disp_value = gwy_rawdata.set_double_by_name( "/" + str(i) + "/base/max", float(20e-9)) palette = gwy_rawdata.set_string_by_name( "/" + str(i) + "/base/palette", "BlueandGold") if i == 4: #save trace and retrace seperately - presumably can do this more elegantly saved_filename = str(image[:-4] + '_trace.tiff') gwy.gwy_file_save(gwy_rawdata, saved_filename, gwy.RUN_NONINTERACTIVE) else: saved_filename = str(image[:-4] + '_retrace.tiff') gwy.gwy_file_save(gwy_rawdata, saved_filename, gwy.RUN_NONINTERACTIVE) gwy.gwy_app_data_browser_remove( gwy_rawdata) #close the file once we've finished with it
def runbatch(root, cwd, pdr, pngexp, ratio): # Export PNG with scalebar s = gwy.gwy_app_settings_get() s['/module/pixmap/title_type'] = 0 s['/module/pixmap/ztype'] = 0 s['/module/pixmap/xytype'] = 0 s['/module/pixmap/draw_maskkey'] = False # ... (*lots* of possible settings, see ~/.gwyddion/settings) Files_To_Open = [ f for f in listdir(cwd) if isfile(join(cwd,f)) ] try: mkdir(join(cwd,'Processed')) except Exception as sym: print ('Already Exist') Tobe_Saved = join(cwd, 'Processed') filename_save = cwd.split('/')[-1] print (Files_To_Open) #Load first file to use as Merged file for filename in Files_To_Open: print(filename) try: Temp = gwy.gwy_file_load(join(cwd,filename), RUN_NONINTERACTIVE) print(type(Temp)) if type(Temp) == gwy.Container : print('right type') Cont_Dest = Temp Files_To_Open.remove(filename) break Files_To_Open.remove(filename) print('loadedbutnot') except Exception as sym: print('except') print ("not proper file"+str(sym)+"\n") continue #Add into current browser and Make Visible on display gwy.gwy_app_data_browser_add(Cont_Dest) Cont_Dest.set_boolean_by_name('/0/data/visible', 1) print (Files_To_Open) #File Merge #First Container DataFields = gwyutils.get_data_fields_dir(Cont_Dest) for key in DataFields.keys(): title = Cont_Dest.get_string_by_name(key+"/title") if (title == 'Amplitude') : Cont_Dest.remove_by_prefix('/'+key.split('/')[1]+'/') Cont_Dest.set_string_by_name(key+'/title', title+'.'+Files_To_Open[0]) #Rest of Containers for filename in Files_To_Open : #print (orgfile, join(cwd,filename)) try: Temp_Source = gwy.gwy_file_load(join(cwd,filename), RUN_NONINTERACTIVE) if type(Temp_Source) == gwy.Container: Cont_Source = Temp_Source pass else: continue except Exception as sym: print ("not proper file"+sym+"\n") continue DataFields = gwyutils.get_data_fields_dir(Cont_Source) for key in DataFields.keys(): ID = key.split('/')[1] title = Cont_Source.get_string_by_name(key+"/title") if (title == 'Height') : Cont_Source.set_string_by_name(key+'/title', title+'.'+filename) gwy.gwy_app_data_browser_copy_channel(Cont_Source, int(ID), Cont_Dest) print (key, title) gwy_app_data_browser_remove(Cont_Source) del Cont_Source print (gc.collect()) #Change Palette, Flatten, Correct line, Remove Scars, Change Scale DataFields = gwyutils.get_data_fields_dir(Cont_Dest) for key in DataFields.keys(): ID = key.split('/')[1] title = Cont_Dest.get_string_by_name(key+"/title") print (title+'\n') # Subtract polynomial background coeffs = DataFields[key].fit_polynom(3, 3) DataFields[key].subtract_polynom(3, 3, coeffs) DataFields[key].data_changed() #Get X Y scale si = {'x' : 'um' , 'y' : 'um'} size_x = DataFields[key].get_xreal()*1000000 if (size_x < 1.0): size_x = size_x * 1000 si['x'] = 'nm' size_y = DataFields[key].get_yreal()*1000000 if (size_y < 1.0): size_y = size_y * 1000 si['y'] = 'nm' scale = str(size_x)+si['x']+'by'+str(size_y)+si['y'] title = title + '_'+ scale # Line and scar correction (run module functions) gwy.gwy_app_data_browser_select_data_field(Cont_Dest, int(ID)) gwy.gwy_process_func_run("line_correct_median", Cont_Dest, gwy.RUN_IMMEDIATE) gwy.gwy_process_func_run("scars_remove", Cont_Dest, gwy.RUN_IMMEDIATE) gwy.gwy_process_func_run("fix_zero", Cont_Dest, gwy.RUN_IMMEDIATE) #Get Color Type colorr = Cont_Dest.get_int32_by_name('/'+ID+'/base/range-type') #Change_Color Palette Cont_Dest.set_string_by_name('/'+ID+'/base/palette', 'Gold') #Get Height Distribution and get Percentile color set range #Get CDH histogram = gwy.DataLine(1, 1, False) DataFields[key].cdh(histogram, 512) data = histogram.get_data() #Get Percentile Range Data_Range = DataFields[key].get_min_max() Histogram_pct = [(float(index))/512 for index, value in enumerate(data) if (data[index] >= ratio[1] and data[index-1] <= ratio[1]) or (data[index] <= ratio[0] and data[index+1] >= ratio[0])] Range = Data_Range[1]-Data_Range[0] Color_Range = {'min': Data_Range[0]+Range*Histogram_pct[0], 'max':Data_Range[0]+Range*Histogram_pct[1]} Cont_Dest.set_int32_by_name('/0/base/range-type' , 1) Cont_Dest.set_double_by_name('/0/base/min', Color_Range['min']) Cont_Dest.set_double_by_name('/0/base/max', Color_Range['max']) #Change Color Range into (Full:0, Manual:1, Auto:2, Adaptive:3) Cont_Dest.set_int32_by_name('/'+ID+'/base/range-type', 2) print (title) gwy.gwy_file_save(Cont_Dest, Tobe_Saved+'/'+str(title)+'%d.png' % int(ID), gwy.RUN_NONINTERACTIVE) Cont_Dest.set_boolean_by_name('/'+ID+'/data/visible', 0) gwy.gwy_file_save(Cont_Dest,Tobe_Saved+'/'+filename_save+'.gwy', gwy.RUN_NONINTERACTIVE) gwy_app_data_browser_remove(Cont_Dest)
title = '/' + str(data_field_id) + '/data/title' channel = c[title] print channel gwy.gwy_app_data_browser_select_data_field(c,data_field_id) meta = c[meta_field] print meta.keys_by_name() bias = meta['Bias'] bias, bu = bias.split(' ') current = meta['Z controller Setpoint'] current, cu = current.split(' ') current = float(current) * 1e12 cu = 'pA' current_bias = 'pm' xd = d.get_xreal() * 1e9 yd = d.get_yreal() * 1e9 xyu = 'nm' print xd print bias count = 1 output_name = basename+'_'+str(xd)+xyu+'_'+str(yd)+xyu+'_'+bias+bu+'_'+str(current)+cu+'_'+str(count)+'.png' while os.path.exists(output_name): count = count + 1 output_name = basename+'_'+str(xd)+xyu+'_'+str(yd)+xyu+'_'+bias+bu+'_'+str(current)+cu+'_'+str(count)+'.png' output_path = os.path.join(dir_path,'temp') if not os.path.isdir(output_path): os.mkdir(output_path) output = os.path.join(output_path,output_name) print output #img.save(output) gwy.gwy_file_save(c, output, gwy.RUN_NONINTERACTIVE)
import gwy import gwyutils import sys filename = sys.argv[1] # '/Users/pabloherrero/sabat/stm_data/november19_experiments/QE1/2019-11-12-QE1_001.sxm' f = open(filename, "r") container = gwy.gwy_app_file_load(filename) ids = gwy.gwy_app_data_browser_get_data_ids(container) cons = gwy.gwy_app_data_browser_get_containers() for c in cons: dfields = gwyutils.get_data_fields_dir(c) for key in dfields.keys(): datafield = dfields[key] print(datafield.get_xreal()) gwy.gwy_app_data_browser_select_data_field(container, ids[0]) container['/%u/base/palette' % ids[0]] = 'Gold' gwy.gwy_process_func_run("level", container, gwy.RUN_INTERACTIVE) gwy.gwy_process_func_run("scars_remove", container, gwy.RUN_INTERACTIVE) gwy.gwy_file_save(container, '%s-%02u.png' % (basename, 0), gwy.RUN_NONINTERACTIVE)