def do_savemacro(self, macroname): '''SAVEMACRO Saves previously recorded macro into a script file for future use ------- Syntax: savemacro [macroname] If no macroname is supplied one will be interactively asked ''' saved_ok=0 if self.currentmacro==None: print 'No macro is being recorded!' return 0 if len(macroname)==0: macroname=linput.safeinput('Enter new macro name: ') if len(macroname) == 0: print 'Invalid name' macroname=os.path.join(self.macrodir,macroname+'.hkm') if os.path.exists(macroname): overwrite=linput.safeinput('That name is in use, overwrite?',['n']) if overwrite[0].lower()!='y': print 'Cancelled save' return 0 txtfile=open(macroname,'w+') self.currentmacro='\n'.join(self.currentmacro) txtfile.write(self.currentmacro) txtfile.close() print 'Saved on '+macroname self.currentmacro=[]
def do_exit(self,args): we_exit='N' if (not self.playlist_saved) or (not self.notes_saved): we_exit=linp.safeinput('You did not save your playlist and/or notes. Exit?',['n']) else: we_exit=linp.safeinput('Exit?',['y']) if we_exit[0].upper()=='Y': wx.CallAfter(self.frame.Close) sys.exit(0) else: return
def dump(self): # retrieves and saves data self.getdata() destination = linput.safeinput("Enter filename:", ["results.txt"]) destfile = open(destination, "w+") destfile.write("\n".join(self.data)) destfile.close()
def do_vwnew(self,args): #creates a new viewer self.viewerlist.append(lview.Ascii(self.outlet)) dt=linput.safeinput('What type of data will this viewer handle? (force/distance/all)',['force', 'distance', 'all']) #TODO update types, make a list somewhere? print dt self.viewerlist[-1].setdtype(dt)
def do_recordmacro(self, args): '''RECORDMACRO Stores input commands to create script files ------- Syntax: recordmacro [start / stop] If a macro is currently paused start resumes recording ''' if len(args)==0: args='start' if args=='stop': self.pause=0 self.prompt=self.auxprompt if len(self.currentmacro) != 0: answer=linput.safeinput('Do you want to save this macro? ',['y']) if answer[0].lower() == 'y': self.do_savemacro('') else: print 'Macro discarded' self.currentmacro=[] else: print 'Macro was empty' if args=='start': if self.pause==1: self.pause=0 self.collect() else: if len(self.currentmacro) != 0: answer=linput.safeinput('Another macro is already beign recorded\nDo you want to save it?',['y']) if answer[0].lower() == 'y': self.do_savemacro('') else: print 'Old macro discarded, you can start recording the new one' self.currentmacro=[] self.collect()
def do_jump(self,filename): ''' jumps to the curve with the given filename. if the filename is not in the playlist, it asks if we must add it or not. ''' if filename=='': filename=linp.safeinput('Jump to?') filepath=os.path.abspath(filename) print filepath c=0 item_not_found=1 while item_not_found: try: if self.current_list[c].path == filepath: self.pointer=c self.current=self.current_list[self.pointer] item_not_found=0 self.do_plot(0) else: c+=1 except IndexError: #We've found the end of the list. answer=linp.safeinput('Curve not found in playlist. Add it to list?',['y']) if answer.lower()[0]=='y': try: self.do_addtolist(filepath) except: print 'Curve file not found.' return self.current=self.current_list[-1] self.pointer=(len(current_list)-1) self.do_plot(0) item_not_found=0
def do_copylog(self,args): if len(args)==0: args=linp.safeinput('Destination directory?') #TODO default mydir=os.path.abspath(args) if not os.path.isdir(mydir): print 'Destination is not a directory.' return for item in self.current_list: if len(item.notes)>0: try: shutil.copy(item.path, mydir) except (OSError, IOError): print 'Cannot copy file. '+item.path+' Perhaps you gave me a wrong directory?'
def do_genlist(self,args): #args list is: input path, output name if len(args)==0: args=linp.safeinput('Input files?') arglist=args.split() list_path=arglist[0] #if it's a directory, is like /directory/*.* #FIXME: probably a bit kludgy. if os.path.isdir(list_path): if platform.system == 'Windows': SLASH="\\" else: SLASH="/" if list_path[-1] == SLASH: list_path=list_path+'*' else: list_path=list_path+SLASH+'*' #expanding correctly the input list with the glob module :) list_files=glob.glob(list_path) list_files.sort() self.current_list=[] for item in list_files: try: if os.path.isfile(item): self.current_list.append(lhc.HookeCurve(os.path.abspath(item))) except: pass self.pointer=0 if len(self.current_list)>0: self.current=self.current_list[self.pointer] else: print 'Empty list!' return #resets saved/notes saved state self.playlist_saved=0 self.playlist_name='' self.notes_saved=0 self.do_plot(0)
def do_notelog(self,args): if len(args)==0: args=linp.safeinput('Notelog filename?',['notelog.txt']) note_lines='Notes taken at '+time.asctime()+'\n' for item in self.current_list: if len(item.notes)>0: #FIXME: log should be justified #FIXME: file path should be truncated... note_string=(item.path+' | '+item.notes+'\n') note_lines+=note_string try: f=open(args,'a+') f.write(note_lines) f.close() except IOError, (ErrorNumber, ErrorMessage): print 'Error: notes cannot be saved. Catched exception:' print ErrorMessage
def do_loadlist(self, args): #checking for args: if nothing is given as input, we warn and exit. while len(args)==0: args=linp.safeinput('File to load?') arglist=args.split() play_to_load=arglist[0] #We assume a Hooke playlist has the extension .hkp if play_to_load[-4:] != '.hkp': play_to_load+='.hkp' try: playxml=PlaylistXML() self.current_list, self.playlist_generics=playxml.load(play_to_load) self.current_playxml=playxml except IOError: print 'File not found.' return print 'Loaded %s curves' %len(self.current_list) if 'pointer' in self.playlist_generics.keys(): self.pointer=int(self.playlist_generics['pointer']) else: #if no pointer is found, set the current curve as the first curve of the loaded playlist self.pointer=0 print 'Starting at curve ',self.pointer self.current=self.current_list[self.pointer] #resets saved/notes saved state self.playlist_saved=0 self.playlist_name='' self.notes_saved=0 self.do_plot(0)
def do_savelist(self,args): ''' SAVELIST Saves the current file playlist on disk. ------------ Syntax: savelist [filename] ''' while len(args)==0: args=linp.safeinput('Output file?',['savedlist.txt']) output_filename=args self.playlist_generics['pointer']=self.pointer #autocomplete filename if not specified if output_filename[-4:] != '.hkp': output_filename+='.hkp' playxml=PlaylistXML() playxml.export(self.current_list, self.playlist_generics) playxml.save(output_filename) #remembers we have saved playlist self.playlist_saved=1
def do_review(self, args): """ REVIEW (review.py) Presents curves (in current playlist) in groups of ten. User can indicate which curves will be selected to be saved in a separate directory for further analysis. By default curves are presented separated -30 nm in x and -100 pN in y. Curve number one of each set is the one showing the approach. ------------ Syntax: review [x spacing (nm)] [y spacing (pN] """ args = args.split() if len(args) == 2: try: xgap = int(args[0]) * 1e-9 # scale to SI units ygap = int(args[1]) * 1e-12 except: print "Spacings must be numeric! Using defaults" xgap = -30 * 1e-9 ygap = -100 * 1e-12 else: xgap = -30 * 1e-9 ygap = -100 * 1e-12 print "Processing playlist..." print "(Please wait)" keep_list = [] c = 0 print "You can stop the review at any moment by entering 'q' you can go back ten curves entering 'b'" print "What curve no. you would like to start? (Enter for starting from the first)" skip = raw_input() if skip.isdigit() == False: skip = 0 else: skip = int(skip) print "Skipping " + str(skip) + " curves" c = skip while c < len(self.current_list): # take a group of ten curves and plot them with some spacing curveset = self.current_list[c : c + 10] base = curveset[0] self.current = base self.do_plot(0) multiplot = copy.deepcopy(self._get_displayed_plot(0)) self.current.curve.close_all() for i in range(1, 10): if i >= len(curveset): print "End of the list" print "WARNING: maybe you want to finish!" break nextitem = curveset[i] if not nextitem.identify(self.drivers): continue nextplot = self.plotmanip_correct(nextitem.curve.default_plots()[0], nextitem) nextvect = nextplot.vectors nextitem.curve.close_all() nextx = nextvect[1][0] nexty = nextvect[1][1] # center y around 0 ymedian = np.median(nexty) pos = 0 for j in range(0, len(nextx)): nextx[j] = nextx[j] + i * xgap nexty[j] = nexty[j] + i * ygap - ymedian multiplot.add_set(nextx, nexty) multiplot.styles.append("lines") multiplot.colors.append(None) self._send_plot([multiplot]) print "Which ones you want to keep?" keep = raw_input() if keep.isalpha(): if keep == "b": print "Going back ten curves" c -= 10 if c < 0: print "We are already at the start" c = 0 continue if keep == "q": break else: for i in keep.split(): if ( i.isdigit() and int(i) > 0 and int(i) < 11 ): # if it is not digit the int() call is never made, so no exception should be happening keep_item = curveset[int(i) - 1].path if keep_item in keep_list: print "This curve (" + keep_item + ") was already selected, skipping" else: keep_list.append(keep_item) else: print "You entered an invalid value: " + i c += 10 # FIXME I don't know why the print below gives errors sometimes try: print "Kept " + str(len(keep_list)) + " curves from " + str(min(c + i + 1, len(self.current_list))) except: print "Display error, never mind, we continue. Below the amount of kept and total curves:" print str(len(keep_list)) print str(len(self.current_list)) allok = 0 # flag to keep from losing all the work in a slight mistake while allok == 0: if len(keep_list) == 0: return save = linp.safeinput("Do you want to save the selected curves?", ["y", "n"]) if save == "y": savedir = linp.safeinput("Destination directory?") savedir = os.path.abspath(savedir) if not os.path.isdir(savedir): print "Destination is not a directory. Try again" continue if save == "n": allok = 1 return for item in keep_list: try: shutil.copy(item, savedir) allok = 1 except (OSError, IOError): print "Cannot copy file. " + item + " Perhaps you gave me a wrong directory?" allok = 0 break return
def do_txt(self,args): def transposed2(lists, defval=0): ''' transposes a list of lists, i.e. from [[a,b,c],[x,y,z]] to [[a,x],[b,y],[c,z]] without losing elements (by Zoran Isailovski on the Python Cookbook online) ''' if not lists: return [] return map(lambda *row: [elem or defval for elem in row], *lists) whichplot=0 args=args.split() if len(args)==0: filename=linp.safeinput('Filename?',[self.current.path+'.txt']) else: filename=linp.checkalphainput(args[0],self.current.path+'.txt',[]) try: if args[1]=="all": whichplot="all" else: whichplot=int(args[1]) except: pass if whichplot!="all": try: outofplot=self.plots[whichplot].vectors except: print "Plot index out of range." return 0 columns=[] for dataset in self.plots[whichplot].vectors: for i in range(0,len(dataset)): columns.append([]) for value in dataset[i]: #columns[-1].append(str(value*(10**9))) columns[-1].append(str(value)) rows=transposed2(columns, 'nan') rows=[' , '.join(item) for item in rows] text='\n'.join(rows) txtfile=open(filename,'w+') #Save units of measure in header txtfile.write('X:'+self.plots[whichplot].units[0]+'\n') txtfile.write('Y:'+self.plots[whichplot].units[1]+'\n') txtfile.write(text) txtfile.close() else: columns=[] for wp in range(len(self.plots)): for dataset in self.plots[wp].vectors: for i in range(0,len(dataset)): columns.append([]) for value in dataset[i]: #columns[-1].append(str(value*(10**9))) columns[-1].append(str(value)) rows=transposed2(columns, 'nan') rows=[' , '.join(item) for item in rows] text='\n'.join(rows) txtfile=open(filename,'w+') #Save units of measure in header for i in range(len(self.plots)): txtfile.write('X:'+self.plots[i].units[0]+'\n') txtfile.write('Y:'+self.plots[i].units[1]+'\n') txtfile.write(text) txtfile.close()