?? bbvis.py
字號:
#!/usr/bin/env python# -*- coding: iso-8859-1 -*-## This file is a part of the Bayes Blocks library## Copyright (C) 2001-2006 Markus Harva, Antti Honkela, Alexander# Ilin, Tapani Raiko, Harri Valpola and Tomas 謘tman.## 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, 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 (included in file License.txt in the# program package) for more details.## $Id: BBVis.py 5 2006-10-26 09:44:54Z ah $#"""Tkinter GUI for BBNet visualiser"""import osimport tempfileimport Tkinterfrom Tkconstants import *import tkFileDialogimport tkColorChooserimport tkMessageBoximport Pmwimport stringimport copyimport DotWriter# Node count for warning of too large networkLARGENETLIMIT = 100class BBVis: """GUI for Bayes Blocks Visualiser""" def __init__(self, net): self.writer = DotWriter.PlainWriter(net) self.root = Tkinter.Tk() self.root.title('BBNet Visualiser') Pmw.initialise(self.root, size = 14, fontScheme = 'pmw1') # Supported zoomlevels and related font sizes etc. self.zoomlevels = ['10 %', '25 %', '50 %', '100 %', '200 %', '400 %'] self.zoomvals = {'10 %': .1, '25 %': .25, '50 %': .5, '100 %': 1.0, '200 %': 2.0, '400 %': 4.0} self.zoomfonts = {.1: 2, .25: 5, .5: 9, 1.0: 14, 2.0: 28, 4.0: 56} self.textitems = [] # Included node types and other active modifications self.selectedtypes = copy.deepcopy(self.writer.types) self.mods = {} # Supported modifications and their handlers self.modhandlers = {'Combine sum trees': self.CombineSumtrees, 'Drop all indices': self.DropIndices} # Add all the necessary GUI elements self.canvas = Tkinter.Canvas(self.root) self.commandframe = Tkinter.Frame(self.root) self.typeframe = Tkinter.Frame( self.commandframe, borderwidth=2, relief='ridge') self.typeframe.pack(side=TOP, padx = 8, pady = 8, fill=X) self.typebutton = Tkinter.Button( self.typeframe, text='Select types', command=self.RunTypeSelector) self.typebutton.pack(side=TOP) self.treeselect = Pmw.RadioSelect(self.commandframe, buttontype = 'checkbutton', orient = 'vertical', labelpos = 'n', label_text = 'Modifications', command = self.ApplyMod, hull_borderwidth = 2, hull_relief = 'ridge', selectmode = 'multiple') self.treeselect.pack(side=TOP, padx = 8, pady = 8, fill=X) for t in ['Combine sum trees', 'Drop all indices']: self.treeselect.add(t) self.dropframe = Tkinter.Frame( self.commandframe, borderwidth=2, relief='ridge') self.dropframe.pack(side=TOP, padx = 8, pady = 8, fill=X) self.dropbutton = Tkinter.Button( self.dropframe, text='Selectively drop indices', command=self.RunIndexSelector) self.dropbutton.pack(side=TOP) self.propframe = Tkinter.Frame( self.commandframe, borderwidth=2, relief='ridge') self.propframe.pack(side=TOP, padx = 8, pady = 8, fill=X) self.propbutton = Tkinter.Button( self.propframe, text='Select node properties', command=self.RunPropertySelector) self.propbutton.pack(side=TOP) self.propmenu = Pmw.OptionMenu(self.propframe, labelpos = 'n', label_text = 'Node type', items = self.writer.types ) self.propmenu.pack(side=TOP, padx = 8, pady = 8, expand = 0) self.zoombutton = Pmw.OptionMenu(self.commandframe, labelpos = 'n', label_text = 'Zoom level', items = self.zoomlevels, command = self.ZoomToLevel, hull_borderwidth = 2, hull_relief = 'ridge', initialitem='100 %' ) self.zoombutton.pack(side=TOP, padx = 8, pady = 8, fill=X) self.zoomlevel = 1.0 self.savebutton = Tkinter.Button(self.commandframe, text='Save graph', command=self.SaveToFile) self.savebutton.pack(side=TOP, padx = 40) self.quitbutton = Tkinter.Button(self.commandframe, text='Quit', command=self.root.quit) self.quitbutton.pack(side=TOP, padx = 40) if len(self.writer.d_act.keys()) > LARGENETLIMIT: tkMessageBox.showwarning("Too large net", "Large net - dropping indices.\nTry to simplify the structure before returning to full view.") self.treeselect.setvalue(['Drop all indices']) self.mods['Drop all indices'] = 1 self.PerformOps() val = self.GenerateFigure() if not val: self.PackGUI() def _AdjustScrollregion(self): """Internal function to adjust the scroll region of the canvas""" self.bbox = self.canvas.bbox('everything') self.scrollregion = (self.bbox[0] - 50, self.bbox[1] - 50, self.bbox[2] + 50, self.bbox[3] + 50) self.canvas.config(scrollregion=self.scrollregion) def _TagText(self): """Internal function to tag all text items""" self.textitems = [] for i in self.canvas.find_all(): try: font = self.canvas.itemcget(i, 'font') self.textitems.append(i) except: pass def ResizeText(self, newsize): """Resize all text items to given size""" for i in self.textitems: font = self.canvas.itemcget(i, 'font') components = font.split('-') components[7] = `newsize` newfont = string.join(components, '-') self.canvas.itemconfigure(i, font=newfont) def Zoom(self, factor): """Zoom the canvas""" self.canvas.scale('everything', 1.0, 1.0, float(factor), float(factor)) self._AdjustScrollregion() def ZoomToLevel(self, factor): """Handler for GUI zoom operation""" newlevel = self.zoomvals[factor] if newlevel != self.zoomlevel: self.Zoom(newlevel / self.zoomlevel) self.ResizeText(self.zoomfonts[newlevel]) self.zoomlevel = newlevel def PerformOps(self): """Perform all requested modifications to the graph""" self.writer.ResetFilter() self.writer.FilterButType(self.selectedtypes) self.writer.SelectivelyDropIndices() for k in self.mods.keys(): if self.mods[k]: self.modhandlers[k]() def GenerateFigure(self): """(Re)generate the figure""" # Issue a warning if the net seems too large if len(self.writer.d_act.keys()) > LARGENETLIMIT and \ not tkMessageBox.askyesno("Large net", "Visualising this large graph (" + str(len(self.writer.d_act.keys())) + " nodes) may take very long time. Are you sure you want to proceed?"): return 0 # Generate a temporary filename for the graph and write to the file fname = tempfile.mktemp('tk') self.writer.WriteToTk(fname) # Destroy the old figure self.canvas.destroy() # Show the new figure and delete the temporary file self.ShowFigure(fname) os.unlink(fname) # Set zoom to correct level self.Zoom(self.zoomlevel) self.ResizeText(self.zoomfonts[self.zoomlevel]) return 1 def ShowFigure(self, file): """Load a graph for Tk source file and display it""" # Run the Tk source self.root.tk.call('source', file) # Substitute the generated canvas to existing Python class # for easier handling self.canvas._name = 'c' self.canvas._w = '.c' self.canvas.addtag_all('everything') self._AdjustScrollregion() self._TagText() self.canvas.config(width=500, height=500) self.PackGUI() def PackGUI(self): self.xbar = Tkinter.Scrollbar(self.canvas) self.xbar.config(orient='horizontal') self.ybar = Tkinter.Scrollbar(self.canvas) self.xbar.config(command=self.canvas.xview) self.ybar.config(command=self.canvas.yview) self.canvas.config(xscrollcommand=self.xbar.set) self.canvas.config(yscrollcommand=self.ybar.set) self.xbar.pack(side=BOTTOM, fill=X) self.ybar.pack(side=RIGHT, fill=Y) self.canvas.pack(side=RIGHT, expand=YES, fill=BOTH) self.canvas.config(width=500, height=500) self.commandframe.pack(side=LEFT, fill=Y) def RunTypeSelector(self): TypeSelector(self.writer.types, self.writer.variables, self.selectedtypes, self) def ApplyMod(self, button, val): """Apply a new modification to the graph""" self.mods[button] = val self.PerformOps() self.GenerateFigure() def CombineSumtrees(self): self.writer.CombineSumtrees() def DropIndices(self): self.writer.DropIndices() def SaveToFile(self): """Save the dot source of the current net""" fname = tkFileDialog.asksaveasfilename( filetypes=[('dot source files', '*.dot')]) if fname: self.writer.WriteGraph(fname) def RunPropertySelector(self): PropertySelector(self, self.writer.properties[self.propmenu.getvalue()]) def RunIndexSelector(self): IndexSelector(self, self.writer.GetAllLabels(), self.writer.indexdrops) def ApplyTypeSelections(self, selected=None): if selected: if `self.selectedtypes` != `selected`: self.selectedtypes = selected self.PerformOps() self.GenerateFigure()
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -