def OnDoubleClick(self): """Called on a double-click on the icon.""" self.status.set(self.path) # Directories: list them in window if os.path.isdir(self.path): dirmax = int(self.textbox.limits[3].get()) dirsize = os.path.getsize(self.path) if dirsize > dirmax: basename = os.path.basename(self.path) txt = "%s may contain a very large number of files.\nDisplay anyway?" % (basename) if not askyesno("Warning", txt): return cmd = "ls -lF %s " % self.path out = getoutput(cmd) filelisting = self.path + "\n" + out self.textbox.clear() self.textbox.settext(filelisting) # view text files in window (sometimes pdfs slip thru) elif self.ext != ".pdf" and Spiderutils.istextfile(self.path): # check if html files are sent to browser if self.ext == ".html" or self.ext == ".htm": browser = self.textbox.limits[4].get() if browser: webbrowser.open(self.path) return textmax = self.textbox.limits[2] tmax = int(textmax.get()) textsize = os.path.getsize(self.path) if textsize > tmax: basename = os.path.basename(self.path) txt = "%s is %d bytes.\nDisplay anyway?" % (basename, textsize) if not askyesno("Warning", txt): return try: fp = open(self.path,'r') B = fp.readlines() except: pass fp.close() self.textbox.clear() for line in B: self.textbox.component('text').insert(END, str(line)) # binaries else: spidertype = Spiderutils.isSpiderBin(self.path) if spidertype != 0: #== "image": infotxt = self.getSpiderInfo(self.path) self.textbox.clear() self.textbox.component('text').insert(END, infotxt) if spidertype == "image": self.putImage(self.path, clear=0) elif self.ext.lower() in self.imagetypes: self.putImage(self.path)
def GetIconName(self): if not self.IsExpandable(): name, ext = os.path.splitext(self.path) if ext in ['.py']: #, '.pyc','.pyo']: return "python" if ext.lower() in self.imagetypes: return "image" typ = Spiderutils.istextfile(self.path) if typ == 1: if Spiderutils.isSpiderDocfile(self.path): return "docfile" elif Spiderutils.isSpiderBatchfile(self.path): return "procfile" elif Spiderutils.isSpiderProcedurefile(self.path): return "procfile" else: return "text" elif typ == -1: return "unknown" spi = Spiderutils.isSpiderBin(self.path) if spi == "image" or spi == "Fourier" or spi == "stack": return "spider" elif spi == "volume": return "volume" return "binary" # i.e. a non-spider binary file
def hello(self, im): " filename is the classavg image " if self.docfile == "" or self.serfile == "": self.callTemplates() filename = im.info['filename'] #print "hello from " + filename tmp = self.doctemplate.get() fn = Spiderutils.template2filename(tmp, os.path.basename(filename)) if len(fn) < 1: return if not os.path.exists(fn): print "Unable to find " + fn return D = Spiderutils.readdoc(fn, keys='all') plist = [] files = D.keys() for f in files: num = int(D[f][0]) # each element is a list (of column data) imgfilename = Spiderutils.template2filename(self.serfile, num) plist.append(imgfilename) title = "images for class: " + os.path.basename(filename) newtop = Toplevel(self.top) m = montage.montage(newtop, imagelist=plist, title=title, useLabels=0) m.makeMenus() m.createMontage()
def getdata(self, filename=None, xcol=None, ycol=None): if filename == None or filename == "": filename = self.filename if self.filename == None or self.filename == "": return try: #D = spiderutils.readSpiderDocFile(filename, [xcol,ycol]) D = Spiderutils.readdoc(filename, keys='all') except: print "Unable to get data from %s" % filename return keys = D.keys() if len(keys) < 1: print "%s contains no data" % filename return f = D[keys[0]] xmin = f[0] xmax = f[0] ymin = f[1] ymax = f[1] for k in keys: x = D[k][0] y = D[k][1] if x < xmin: xmin = x elif x > xmax: xmax = x if y < ymin: ymin = y elif y > ymax: ymax = y vector_x = (xmin,xmax) vector_y = (ymin,ymax) return (D, vector_x, vector_y)
def __init__(self, master, classTemplate, max_depth=5, savefilename='outfile.dat', margin_width=3, canvasWidth=1600, labelBorder=3) : # store passed values self.master = master self.classTemplate = classTemplate self.max_depth = max_depth self.savefilename = savefilename self.margin_width = margin_width self.canvasWidth = canvasWidth self.labelBorder = labelBorder # initialize self.coords_dictionary={} self.photo_list=[] self.select_dictionary = {} # get image dimensions: ix,iy = im.size # dimensions classname = Spiderutils.template2filename(self.classTemplate,n=1) classavg = Image.open(classname) self.xdim = classavg.size[0] + 2*self.labelBorder self.ydim = classavg.size[1] + 2*self.labelBorder + self.margin_width # colors self.good_color = 'green' self.select_flag = 1 self.bad_color = 'red'
def callTemplates(self): gtwin = Toplevel(self.top) self.getTemplates(gtwin) self.top.wait_window(gtwin) # wait til template window gone # if they typed in w/o asterisks.. doc = self.doctemplate.get() if len(doc) > 0: self.docfile = doc if string.find(doc,"*") < 0: tmp = Spiderutils.name2template(doc) self.doctemplate.set(tmp) ser = self.sertemplate.get() if len(ser) > 0: self.serfile = ser if string.find(ser,"*") < 0: tmp = Spiderutils.name2template(ser) self.sertemplate.set(tmp)
def writedoc(filename, column1=1, column2=0): column1 = integer(column1) column2 = integer(column2) # If file already exists if os.path.exists(filename): # if it's a doc file, try to get the last key if Spiderutils.isSpiderDocfile(filename): lastline = getoutput("tail -1 %s" % filename) if len(lastline) > 0: key = 1 + int(string.split(lastline)[0]) else: key = 1 else: # if it's not a doc file... os.remove(filename) key = 1 data = "%5d 2 %11d% 11d\n" % (key, column1, column2) try: fp = open(filename, 'a') # append fp.write(data) fp.close() except: print "Unable to write to %s" % filename return 0 # if it's a new file else: try: fp = open(filename, 'w') fname = os.path.basename(filename) ext = os.path.splitext(filename)[1] ext = ext[1:] # remove dot date,time,id = Spiderutils.nowisthetime() h = " ;ctf/%s %s AT %s %s\n" % (ext,date,time,fname) fp.write(h) fp.write(" ; / MICROGRAPH DEFOCUS\n") key = 1 data = "%5d 2 %11d %11d\n" % (key, column1, column2) fp.write(data) fp.close() except: print "Unable to create %s" % filename return 0 return 1
def setTemplates(self, parent, which='doc'): filename = askopenfilename(parent=parent, filetypes=self.filetypes) if len(filename) < 1: return tmp = Spiderutils.name2template(filename) if which == 'doc': self.doctemplate.set(tmp) else: self.sertemplate.set(tmp)
def saveSelections(self): """ savasfilename can't append to a file - if the file exists an error message pops up. if output specified, don't ask (put it in window in menubar?) """ filename = asksaveasfilename(title="Save points into a doc file", initialfile=self.savefilename) if len(filename) == 0: return # construct a dictionary to pass to writedocfile headers = ['file_number', 'class'] F = {} key = self.startkey.get() try: key = int(key) except: key = 1 for photo in self.photolist: filenumber = Spiderutils.getfilenumber(photo.filename) try: int(filenumber) if hasattr(photo, 'selectvalue'): val = photo.selectvalue else: val = '0' F[key] = [filenumber, val] key = key + 1 except: print "error getting file number from %s" % photo.filename continue if Spiderutils.writedoc(filename, F, headers=headers, mode='a'): showinfo("Data saved to file", "Data written to %s" % os.path.basename(filename)) else: showerror("Error!", "Unable to write to %s" % os.path.basename(filename))
def getSpiderInfo(self, filename): info = Spiderutils.spiderInfo(filename) if info == 0: return "" type = info[0] dims = info[1] infotxt = os.path.basename(filename) + "\n" infotxt += "Spider %s file %s\n" % (type, str(dims)) if len(info) > 2: stats = info[2] infotxt += "max %5.4f, min %5.4f, avg %5.4f, stdev %5.4f\n" % (stats[0],stats[1],stats[2],stats[3]) return infotxt
def saveSelectedMarkers(self, filename=None): if self.selectedPolygon == "": self.statusMessage("no polygon selected") return if filename == None: filename = asksaveasfilename(title="Save points into a doc file") if len(filename) == 0: return print filename if type(filename) == type( (1,2) ): print 'filename is a tuple!' poly = self.Polygons[self.selectedPolygon] e = poly.elements e.sort() E = [] # Make header for doc file and column headings E.append(Spiderutils.makeDocfileHeader(filename)) xaxis = self.xaxisVar.get() if xaxis == "": xaxis = 'x axis' if len(xaxis) > 11: xaxis = xaxis[:11] # just use first 11 chars else: xaxis = string.center(xaxis,11) yaxis = self.yaxisVar.get() if yaxis == "": yaxis = 'y axis' if len(yaxis) > 11: yaxis = yaxis[:11] # just use first 11 chars else: yaxis = string.center(yaxis,11) keyhdr = string.center('keys',11) E.append(" ; / %s %s %s\n" %(keyhdr, xaxis, yaxis)) n = len(e) for i in range(n): key = i+1 val = e[i] x,y = self.D[val][0], self.D[val][1] line = "%5d %2d %11.1f %11f %11f\n" % (key, 3, float(e[i]), x, y) E.append(line) try: fp = open(filename,'w') fp.writelines(E) fp.close() self.statusMessage('Data written to %s' % filename) except: self.statusMessage('ERROR: unable to write to %s' % filename, timeout=0)
def saveSelections(self): """ Savasfilename can't append to a file - if the file exists an error message pops up. if output specified, don't ask (put it in window in menubar?) """ filename = asksaveasfilename(title="Save points into a doc file", initialfile=self.savefilename) if len(filename) == 0: return # Construct a dictionary to pass to writedocfile headers = ['file_number', 'class'] F = {} key = self.startkey.get() try: key = int(key) except: key = 1 for photo in self.photolist: filenumber = Spiderutils.getfilenumber(photo.filename) try: int(filenumber) if hasattr(photo, 'selectvalue'): val = photo.selectvalue else: val = '0' F[key] = [filenumber, val] key = key + 1 except: print "error getting file number from %s" % photo.filename continue if Spiderutils.writedoc(filename, F, headers=headers, mode='a'): showinfo("Data saved to file", "Data written to %s" % os.path.basename(filename)) else: showerror("Error!", "Unable to write to %s" % os.path.basename(filename))
def readDefocus(filename): " returns list of (mic#, defocus) pairs (mic=int defocus=string)" # F = spiderutils.readSpiderDocFile(filename, col_list=(1,2)) F = Spiderutils.readdoc(filename, keys='all') if F == None: return [] keys = F.keys() keys.sort() M = [] for key in keys: mic = int(F[key][0]) defocus = str(int(F[key][1])) M.append( (mic, defocus) ) return M
def getSpiderInfo(self, filename): info = Spiderutils.spiderInfo(filename) if info == 0: return "" type = info[0] dims = info[1] infotxt = os.path.basename(filename) + "\n" infotxt += "Spider %s file %s\n" % (type, str(dims)) if len(info) > 2: stats = info[2] infotxt += "max %5.4f, min %5.4f, avg %5.4f, stdev %5.4f\n" % ( stats[0], stats[1], stats[2], stats[3]) return infotxt
def readDefocus(filename): " returns list of (mic#, defocus) pairs (mic=int defocus=string)" # F = spiderutils.readSpiderDocFile(filename, col_list=(1,2)) F = Spiderutils.readdoc(filename, keys='all') if F == None: return [] keys = F.keys() keys.sort() M = [] for key in keys: mic = int(F[key][0]) defocus = str(int(F[key][1])) M.append((mic, defocus)) return M
def readdoc(filename, factor=1.0, squared=1): F = Spiderutils.readdoc(filename, keys='all') if F == None: return [] roofile = 0 A = [] B = [] C = [] D = [] E = [] keys = F.keys() keys.sort() # get the 1st line of data, test if roo (cols 3 & 4 = 1) k = keys[0] vals = F[k] vlen = len(vals) if vlen < 4: roofile = 1 else: # if vals[2] == 1 and vals[3] == 1: roofile = 1 # get the data for key in keys: if roofile: a = factor * F[key][0] D.append(a) else: freq = F[key][0] bgd = factor * F[key][1] sub = factor * F[key][2] env = factor * F[key][3] roo = bgd + sub # get original spectrum if squared == 1: k = env + bgd roo = roo * roo # square the spectrum bgd = bgd * bgd # square the background sub = roo - bgd # new subtracted curve env = k * k - bgd # new envelope A.append(freq) B.append(bgd) C.append(sub) D.append(env) E.append(roo) if roofile: return [D] else: return [A, B, C, D, E]
def readdoc(filename, factor=1.0, squared=1): F = Spiderutils.readdoc(filename, keys='all') if F == None: return [] roofile = 0 A = []; B = []; C = []; D = []; E = [] keys = F.keys() keys.sort() # get the 1st line of data, test if roo (cols 3 & 4 = 1) k = keys[0] vals = F[k] vlen = len(vals) if vlen < 4: roofile = 1 else: # if vals[2] == 1 and vals[3] == 1: roofile = 1 # get the data for key in keys: if roofile: a = factor * F[key][0] D.append(a) else: freq = F[key][0] bgd = factor * F[key][1] sub = factor * F[key][2] env = factor * F[key][3] roo = bgd + sub # get original spectrum if squared == 1: k = env + bgd roo = roo * roo # square the spectrum bgd = bgd * bgd # square the background sub = roo - bgd # new subtracted curve env = k*k - bgd # new envelope A.append(freq) B.append(bgd) C.append(sub) D.append(env) E.append(roo) if roofile: return [D] else: return [A,B,C,D,E]
def saveSelections(self, event=None) : headers = ['class_num'] spiderDictionary = {} key = 0 selectKeys = self.select_dictionary.keys() selectKeys.sort() for counter in selectKeys: key = key + 1 spiderDictionary[key] = [counter, self.select_dictionary[counter]] # if non-empty, backup prior versions if len(self.select_dictionary) > 0 : backup(self.savefilename) if Spiderutils.writeSpiderDocFile(self.savefilename, spiderDictionary, headers=headers, append=1): print 'Wrote', key, 'keys to %s' % os.path.basename(self.savefilename) else: print "Unable to write to", self.savefilename
def saveDefocus(self, filename=None): "save current defocus and file number to a doc file" if filename != None: self.savefile = filename if self.savefile == "": filename = asksaveasfilename() if filename == "": return self.savefile = filename self.setFileLabels() if self.tfedfile == "": print "defocus data will be saved to %s" % self.savefile return micnum = self.filenumber(os.path.basename(self.tfedfile)) defocus = int(float(self.defocus.get())) outfile = self.savefile headers = Spiderutils.getDocfileHeaders(outfile) if os.path.exists(outfile): # try to replace the line d = Spiderutils.readdoc(outfile, keys='all') keys = d.keys() found = 0 for k in keys: mic = d[k][0] if mic == micnum: d[k][1] = defocus found = 1 break if found: Spiderutils.writedoc(outfile, columns=d) else: Spiderutils.writedoc(outfile, columns=[[micnum], [defocus]], mode='a') else: Spiderutils.writedoc(outfile, columns=[[micnum], [defocus]], headers=headers) #if writedoc(self.savefile, column1=micnum, column2=defocus): print "defocus %s saved to %s" % (defocus, outfile)
def saveDefocus(self, filename=None): "save current defocus and file number to a doc file" if filename != None: self.savefile = filename if self.savefile == "": filename = asksaveasfilename() if filename == "": return self.savefile = filename self.setFileLabels() if self.tfedfile == "": print "defocus data will be saved to %s" % self.savefile return micnum = self.filenumber(os.path.basename(self.tfedfile)) defocus = int(float(self.defocus.get())) outfile = self.savefile headers = Spiderutils.getDocfileHeaders(outfile) if os.path.exists(outfile): # try to replace the line d = Spiderutils.readdoc(outfile, keys='all') keys = d.keys() found = 0 for k in keys: mic = d[k][0] if mic == micnum: d[k][1] = defocus found = 1 break if found: Spiderutils.writedoc(outfile,columns=d) else: Spiderutils.writedoc(outfile,columns=[[micnum],[defocus]],mode='a') else: Spiderutils.writedoc(outfile,columns=[[micnum],[defocus]],headers=headers) #if writedoc(self.savefile, column1=micnum, column2=defocus): print "defocus %s saved to %s" % (defocus, outfile)
def readSelections(self, event=None) : if os.path.exists(self.savefilename): goodclassdoc = Spiderutils.readSpiderDocFile(self.savefilename) goodclasskeys = goodclassdoc.keys() found_counter = 0 for key in goodclasskeys : filenumber = int(goodclassdoc[key][0]) classnum = int(goodclassdoc[key][1]) # map particle to label and goodclass_label.configure if self.class2label.has_key(filenumber) : goodclass_label = self.class2label[filenumber] goodclass_label.configure(background=self.good_color) self.select_dictionary[filenumber] = self.select_flag found_counter = found_counter + 1 else : print "WARNING readSelections: image", key, filenumber, "not found" print found_counter, "keys found" else: print outfile, 'does not exist'
def readSelections(self, event=None): if os.path.exists(self.savefilename): goodclassdoc = Spiderutils.readSpiderDocFile(self.savefilename) goodclasskeys = goodclassdoc.keys() found_counter = 0 for key in goodclasskeys: filenumber = int(goodclassdoc[key][0]) classnum = int(goodclassdoc[key][1]) # map particle to label and goodclass_label.configure if self.class2label.has_key(filenumber): goodclass_label = self.class2label[filenumber] goodclass_label.configure(background=self.good_color) self.select_dictionary[filenumber] = self.select_flag found_counter = found_counter + 1 else: print "WARNING readSelections: image", key, filenumber, "not found" print found_counter, "keys found" else: print outfile, 'does not exist'
# read contents for line in listL: key += 1 split = line.split() xdim = float(split[2]) ydim = float(split[3]) xcoord = float(split[0]) ycoord = float(split[1]) xcenter = xcoord + xdim/2 ycenter = ycoord + ydim/2 # ycenter = mic_y - (ycoord + ydim/2) dictF[key] = [xcenter,ycenter,key,dummy] # print filenum # headers = ['XCOORD','YCOORD','PARTICLE','PEAK_HT','XDIM','YDIM'] headers = ['XCOORD','YCOORD','PARTICLE','PEAK_HT'] backup(outputdoc) if Spiderutils.writeSpiderDocFile(outputdoc,dictF, headers=headers, append=0): print 'Wrote', key, 'keys to %s' % os.path.basename(outputdoc) else: print "Error!", "Unable to write to %s" % os.path.basename(outputdoc) else: print "Error!", "Unable to read %s" % file else: print "syntax: emancoords2spiderdoc.py input_eman_coords output_spider_doc" # print "syntax: emancoords2spiderdoc.py input_eman_coords input_micrograph output_spider_doc"
# read contents for line in listL: key += 1 split = line.split() xdim = float(split[2]) ydim = float(split[3]) xcoord = float(split[0]) ycoord = float(split[1]) xcenter = xcoord + xdim/2 ycenter = ycoord + ydim/2 # ycenter = mic_y - (ycoord + ydim/2) dictF[key] = [key,xcenter,ycenter,xcenter,ycenter,dummy] # print filenum # headers = ['XCOORD','YCOORD','PARTICLE','PEAK_HT','XDIM','YDIM'] headers = ['XCOORD','YCOORD','PARTICLE','PEAK_HT'] backup(outputdoc) if Spiderutils.writeSpiderDocFile(outputdoc,dictF, headers=headers, append=0): print 'Wrote', key, 'keys to %s' % os.path.basename(outputdoc) else: print "Error!", "Unable to write to %s" % os.path.basename(outputdoc) else: print "Error!", "Unable to read %s" % file else: print "syntax: emanrctcoords2spiderdoc.py input_eman_coords output_spider_doc" # print "syntax: emancoords2spiderdoc.py input_eman_coords input_micrograph output_spider_doc"
def drawTree(self): self.class2label = {} # lookup table to find an image # loop through depths, from bottom for depthCounter in range(self.max_depth): # range is 0..max_depth-1 currentDepth = depthCounter + 1 firstNode = 2**(currentDepth - 1) lastNode = 2**(currentDepth) - 1 nodesRow = lastNode - firstNode + 1 bandWidth = self.canvasx / nodesRow nodeCoordy = currentDepth * self.ydim # loop through nodes for rowNode in range(nodesRow): # range is 0..nodesRow-1 current_node = rowNode + firstNode # range is firstNode..lastNode nodeCoordx = (rowNode + 0.5) * bandWidth # write coordinates to dictionary self.coords_dictionary[str(current_node)] = [ nodeCoordx, nodeCoordy ] # if not top row, then draw line to parent node if currentDepth != 1: # calculate node# for daughter nodes parentNode = current_node / 2 # will convert to INT (rightly so) if odd # get coordinates for daughter nodes parentCoordx = self.coords_dictionary[str(parentNode)][0] parentCoordy = self.coords_dictionary[str( parentNode)][1] - self.ydim + self.margin_width # check if image exists classname = Spiderutils.template2filename(self.classTemplate, n=current_node) # if file exists, then draw lines and paste image if os.path.exists(classname): # draw line to parent if currentDepth != 1: self.tree_canvas.create_line(nodeCoordx, nodeCoordy - self.ydim, parentCoordx, parentCoordy, tag='parent_line') self.tree_canvas.lower( 'parent_line' ) # otherwise lines are on top of images # prepare image window and store info classavg = Image.open(classname) Tkimage = ImageTk.PhotoImage(classavg.convert2byte(), palette=256) image_label = Label(self.tree_canvas, image=Tkimage, borderwidth=self.labelBorder) image_label.photo = Tkimage image_label.filenum = current_node self.class2label[current_node] = image_label image_label.bind( '<Button-1>', lambda event, w=image_label: self.selectClass(w)) self.photo_list.append(image_label) # draw image window self.tree_canvas.create_window(nodeCoordx, nodeCoordy, window=image_label, anchor=S) last_node = classname # necessary? # Finish drawing self.tree_canvas.pack() self.master.bind('<Control-t>', self.test) self.master.bind('<Control-s>', self.saveSelections) self.master.bind('<Control-r>', self.readSelections)
found_counter = found_counter + 1 else: print "WARNING readSelections: image", key, filenumber, "not found" print found_counter, "keys found" else: print outfile, 'does not exist' if __name__ == "__main__": argCounter = 0 argCounter = argCounter + 1 if sys.argv[argCounter:]: file_example = sys.argv[argCounter:] nodeTemplate = Spiderutils.name2template(file_example[0]) # print 'file template:', nodeTemplate else: print print "syntax: tree.py node_img001.ext {selectfile.ext max_depth margin_width canvas_width}" print sys.exit() argCounter = argCounter + 1 if sys.argv[argCounter:]: max_depth = int(sys.argv[argCounter]) else: max_depth = 5 print 'max_depth:', max_depth argCounter = argCounter + 1
if sys.argv[1:]: file = sys.argv[1] filename = sys.argv[2] F = {} # initialize dictionary key = 0 # initialize key if os.path.exists(file): input = open(file, 'r') L = input.readlines() # read line-by-line input.close() # read contents for line in L: filenum = Spiderutils.getfilenumber(line) key += 1 F[key] = [filenum] # print filenum headers = ['file_number'] if Spiderutils.writeSpiderDocFile(filename, F, headers=headers, append=0): print 'Wrote', key, 'keys to %s' % os.path.basename(filename) else: print "Error!", "Unable to write to %s" % os.path.basename( filename) else: print "Error!", "Unable to read %s" % file
def drawTree(self): # calculate canvas dimensions self.canvasx = 2**(self.max_depth - 1) * (self.xdim + self.margin_width) self.canvasy = self.max_depth * self.ydim if hasattr(self, 'tree_canvas'): self.tree_canvas.destroy() if hasattr(self, 'HscrollBar'): self.HscrollBar.destroy() if hasattr(self, 'VscrollBar'): self.VscrollBar.destroy() # define canvas self.tree_canvas = Canvas(self.master, height=self.canvasy) self.tree_canvas.configure(width=self.canvasx) self.tree_canvas.configure(scrollregion=(0, 0, self.canvasx, self.canvasy)) print 'Canvas dimensions:', self.canvasx, self.canvasy # scrollbars self.HscrollBar = Scrollbar(self.master, command=self.tree_canvas.xview, orient=HORIZONTAL) self.tree_canvas.configure(xscrollcommand=self.HscrollBar.set) self.HscrollBar.pack(side=BOTTOM, fill=X) self.VscrollBar = Scrollbar(self.master, command=self.tree_canvas.yview, orient=VERTICAL) self.tree_canvas.configure(yscrollcommand=self.VscrollBar.set) self.VscrollBar.pack(side=RIGHT, fill=Y) self.class2label = {} # lookup table to find an image # loop through depths, from bottom for depthCounter in range(self.max_depth): # range is 0..max_depth-1 currentDepth = depthCounter + 1 firstNode = 2**(currentDepth - 1) lastNode = 2**(currentDepth) - 1 nodesRow = lastNode - firstNode + 1 bandWidth = self.canvasx / nodesRow nodeCoordy = currentDepth * self.ydim # loop through nodes for rowNode in range(nodesRow): # range is 0..nodesRow-1 current_node = rowNode + firstNode # range is firstNode..lastNode nodeCoordx = (rowNode + 0.5) * bandWidth # write coordinates to dictionary self.coords_dictionary[str(current_node)] = [ nodeCoordx, nodeCoordy ] # if not top row, then draw line to parent node if currentDepth != 1: # calculate node# for daughter nodes parentNode = current_node / 2 # will convert to INT (rightly so) if odd # get coordinates for daughter nodes parentCoordx = self.coords_dictionary[str(parentNode)][0] parentCoordy = self.coords_dictionary[str( parentNode)][1] - self.ydim + self.margin_width # check if image exists classname = Spiderutils.template2filename(self.classTemplate, n=current_node) # if file exists, then draw lines and paste image if os.path.exists(classname): # draw line to parent if currentDepth != 1: self.tree_canvas.create_line(nodeCoordx, nodeCoordy - self.ydim, parentCoordx, parentCoordy, tag='parent_line') self.tree_canvas.lower( 'parent_line' ) # otherwise lines are on top of images # prepare image window and store info classavg = Image.open(classname) Tkimage = ImageTk.PhotoImage(classavg.convert2byte(), palette=256) image_label = Label(self.tree_canvas, image=Tkimage, borderwidth=self.labelBorder) image_label.photo = Tkimage image_label.filenum = current_node self.class2label[current_node] = image_label image_label.bind( '<Button-1>', lambda event, w=image_label: self.selectClass(w)) self.photo_list.append(image_label) # draw image window self.tree_canvas.create_window(nodeCoordx, nodeCoordy, window=image_label, anchor=S) last_node = classname # necessary? # Finish drawing self.tree_canvas.pack() self.master.bind('<Control-t>', self.test) self.master.bind('<Control-s>', self.saveSelections) self.master.bind('<Control-r>', self.readSelections) self.master.bind('<Control-w>', self.closeWindow) self.master.bind('<plus>', self.levelUp) self.master.bind('<minus>', self.levelDown)
def drawTree(self) : # calculate canvas dimensions self.canvasx = 2**(self.max_depth-1)*(self.xdim + self.margin_width) self.canvasy = self.max_depth * self.ydim if hasattr(self,'tree_canvas'): self.tree_canvas.destroy() if hasattr(self,'HscrollBar'): self.HscrollBar.destroy() if hasattr(self,'VscrollBar'): self.VscrollBar.destroy() # define canvas self.tree_canvas = Canvas(self.master,height=self.canvasy) self.tree_canvas.configure(width=self.canvasx) self.tree_canvas.configure(scrollregion=(0,0,self.canvasx,self.canvasy)) print 'Canvas dimensions:',self.canvasx,self.canvasy # scrollbars self.HscrollBar = Scrollbar(self.master, command=self.tree_canvas.xview, orient=HORIZONTAL) self.tree_canvas.configure(xscrollcommand=self.HscrollBar.set) self.HscrollBar.pack(side=BOTTOM, fill=X) self.VscrollBar = Scrollbar(self.master, command=self.tree_canvas.yview, orient=VERTICAL) self.tree_canvas.configure(yscrollcommand=self.VscrollBar.set) self.VscrollBar.pack(side=RIGHT, fill=Y) self.class2label = {} # lookup table to find an image # loop through depths, from bottom for depthCounter in range(self.max_depth): # range is 0..max_depth-1 currentDepth = depthCounter + 1 firstNode = 2**(currentDepth-1) lastNode = 2**(currentDepth) - 1 nodesRow = lastNode-firstNode+1 bandWidth = self.canvasx / nodesRow nodeCoordy = currentDepth * self.ydim # loop through nodes for rowNode in range(nodesRow): # range is 0..nodesRow-1 current_node = rowNode+firstNode # range is firstNode..lastNode nodeCoordx = (rowNode+0.5)*bandWidth # write coordinates to dictionary self.coords_dictionary[str(current_node)] = [nodeCoordx,nodeCoordy] # if not top row, then draw line to parent node if currentDepth != 1 : # calculate node# for daughter nodes parentNode = current_node/2 # will convert to INT (rightly so) if odd # get coordinates for daughter nodes parentCoordx = self.coords_dictionary[str(parentNode)][0] parentCoordy = self.coords_dictionary[str(parentNode)][1] - self.ydim + self.margin_width # check if image exists classname = Spiderutils.template2filename(self.classTemplate,n=current_node) # if file exists, then draw lines and paste image if os.path.exists(classname): # draw line to parent if currentDepth != 1 : self.tree_canvas.create_line(nodeCoordx,nodeCoordy-self.ydim, parentCoordx,parentCoordy, tag='parent_line') self.tree_canvas.lower('parent_line') # otherwise lines are on top of images # prepare image window and store info classavg = Image.open(classname) Tkimage = ImageTk.PhotoImage(classavg.convert2byte(), palette=256) image_label = Label(self.tree_canvas, image=Tkimage, borderwidth=self.labelBorder) image_label.photo = Tkimage image_label.filenum = current_node self.class2label[current_node] = image_label image_label.bind('<Button-1>', lambda event, w=image_label : self.selectClass(w)) self.photo_list.append(image_label) # draw image window self.tree_canvas.create_window(nodeCoordx,nodeCoordy, window=image_label, anchor=S) last_node = classname # necessary? # Finish drawing self.tree_canvas.pack() self.master.bind('<Control-t>', self.test) self.master.bind('<Control-s>', self.saveSelections) self.master.bind('<Control-r>', self.readSelections) self.master.bind('<Control-w>', self.closeWindow) self.master.bind('<plus>', self.levelUp) self.master.bind('<minus>', self.levelDown)
def OnDoubleClick(self): """Called on a double-click on the icon.""" self.status.set(self.path) # Directories: list them in window if os.path.isdir(self.path): dirmax = int(self.textbox.limits[3].get()) dirsize = os.path.getsize(self.path) if dirsize > dirmax: basename = os.path.basename(self.path) txt = "%s may contain a very large number of files.\nDisplay anyway?" % ( basename) if not askyesno("Warning", txt): return cmd = "ls -lF %s " % self.path out = getoutput(cmd) filelisting = self.path + "\n" + out self.textbox.clear() self.textbox.settext(filelisting) # view text files in window (sometimes pdfs slip thru) elif self.ext != ".pdf" and Spiderutils.istextfile(self.path): # check if html files are sent to browser if self.ext == ".html" or self.ext == ".htm": browser = self.textbox.limits[4].get() if browser: webbrowser.open(self.path) return textmax = self.textbox.limits[2] tmax = int(textmax.get()) textsize = os.path.getsize(self.path) if textsize > tmax: basename = os.path.basename(self.path) txt = "%s is %d bytes.\nDisplay anyway?" % (basename, textsize) if not askyesno("Warning", txt): return try: fp = open(self.path, 'r') B = fp.readlines() except: pass fp.close() self.textbox.clear() for line in B: self.textbox.component('text').insert(END, str(line)) # binaries else: spidertype = Spiderutils.isSpiderBin(self.path) if spidertype != 0: #== "image": infotxt = self.getSpiderInfo(self.path) self.textbox.clear() self.textbox.component('text').insert(END, infotxt) if spidertype == "image": self.putImage(self.path, clear=0) elif self.ext.lower() in self.imagetypes: self.putImage(self.path)
else : print "WARNING readSelections: image", key, filenumber, "not found" print found_counter, "keys found" else: print outfile, 'does not exist' if __name__ == "__main__": argCounter = 0 argCounter = argCounter + 1 if sys.argv[argCounter:] : file_example = sys.argv[argCounter:] nodeTemplate = Spiderutils.name2template(file_example[0]) # print 'file template:', nodeTemplate else : print print "syntax: tree.py node_img001.ext {selectfile.ext max_depth margin_width canvas_width}" print sys.exit() argCounter = argCounter + 1 if sys.argv[argCounter:] : max_depth = int(sys.argv[argCounter]) else : max_depth = 5 print 'max_depth:', max_depth argCounter = argCounter + 1
# This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. import sys from Spider import Spiderutils if sys.argv[1:]: filelist = sys.argv[1:] NodeTemplate = Spiderutils.name2template(filelist[0]) # print 'file template:', NodeTemplate else: print print "syntax: tree.py node_img001.ext {max_depth margin_width canvas_width}" print sys.exit() if sys.argv[2:]: maxDepth = int(sys.argv[2]) else: maxDepth = 6 print 'max_depth:', maxDepth last_node = 2**(maxDepth) - 1 last_file = Spiderutils.template2filename(NodeTemplate, n=last_node)