Package teamwork :: Package widgets :: Module Grapher
[hide private]
[frames] | no frames]

Source Code for Module teamwork.widgets.Grapher

  1  #We need to do try/except imports just in case the matplotlib module isn't available 
  2  #Programs can check for availability by checking the graphAvailable variable 
  3  graphAvailable = True 
  4  try: 
  5      import pylab 
  6      from matplotlib.ticker import FuncFormatter, MultipleLocator 
  7      from matplotlib import rcParams 
  8      from matplotlib.figure import Figure 
  9      from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg 
 10      from matplotlib.font_manager import FontProperties 
 11      rcParams['toolbar'] = 'toolbar2' 
 12      rcParams['backend'] = 'TkAgg' 
 13  except ImportError: 
 14      graphAvailable = False 
 15   
16 -class TkGraphWindow:
17 - def __init__(self,win,entities):
18 import Tkinter as Tk 19 20 self.gw = win 21 22 #Create the figure and subplot and add it to the window 23 figure = Figure(figsize=(5,4), dpi=100) 24 plot = figure.add_subplot(111) 25 self.canvas = FigureCanvasTkAgg(figure,master=win.frame) 26 self.canvas.show() 27 self.canvas.get_tk_widget().pack(side=Tk.TOP,fill=Tk.BOTH,expand=1) 28 toolbar = NavigationToolbar2TkAgg(self.canvas,win.frame) 29 toolbar.update() 30 self.canvas._tkcanvas.pack(side=Tk.TOP,fill=Tk.BOTH,expand=1) 31 32 #Create the graph object 33 self.graph = Graph(entities,figure=figure) 34 35 #Now do the initial update 36 self.updateGraphWindow()
37
38 - def updateGraphWindow(self):
39 self.graph.plot() 40 self.canvas.draw() 41 self.gw.update()
42 43
44 -class Graph:
45 - def __init__(self,entities,figure=None):
46 47 #Initialize some stuff 48 self.availableColors = ['b','g','r','c','m','y','k','w'] 49 self.availableSymbols = ['o','^','v','<','>','s','+','x','D','d','1','2','3','4','h','H','p','|','_'] 50 self.usedSymbols = [] 51 self.startStyle='b--o' 52 self.stateHistory = {} 53 self.actionHistory = ["Initial State"] 54 self.entities = entities 55 self.figure = figure 56 self.initialized = False 57 58 #Initialize the figure if we have to 59 if not figure: 60 pylab.subplot(111) 61 self.figure = pylab.gcf() 62 63 #initialize the history 64 statevector = self.entities.getState().domain()[0] 65 for key in statevector.keys(): 66 if len(key) > 0: 67 self.stateHistory[str(key)] = {'val':[], 'style':self.getNextPointStyle()} 68 69 #maybe assert that the actionHistory == stateHistory length 70 self.loadHistory()
71 72
73 - def setupGraphAttributes(self):
74 ax = self.figure.gca() 75 76 #set up the locator and formatters to control the x-axis ticks 77 locator = MultipleLocator(base=1) 78 ax.xaxis.set_major_formatter(FuncFormatter(self.xAxisFormatter)) 79 ax.xaxis.set_major_locator(locator) 80 81 #set the title and other things 82 ax.legend(loc='best',prop=FontProperties(size='xx-small'),numpoints=2,handlelen=.03,labelsep=.002) 83 labels = ax.get_xticklabels() 84 ax.set_title("State change over time") 85 ax.set_xlabel("Step") 86 ax.set_ylabel("State Value") 87 pylab.setp(labels, 'rotation', 45, fontsize=8)
88
89 - def loadHistory(self):
90 #reset the state and action history 91 self.actionHistory = ["Initial State"] 92 for dict in self.stateHistory.values(): 93 dict['val'] = [] 94 95 #Load the agent's history if there is any into a format more suitable for our purposes 96 for history in self.entities.getHistory(): 97 statevector = history['previousState'] 98 action = history['action'] 99 self.actionHistory.append(str(action)) 100 for key in statevector.keys(): 101 if len(key) != 0: 102 self.stateHistory[str(key)]['val'].append(statevector[key]) 103 104 #Don't forget to add the current state 105 statevector = self.entities.getState().domain()[0] 106 for key in statevector.keys(): 107 if len(key) != 0: 108 self.stateHistory[str(key)]['val'].append(statevector[key])
109
110 - def plot(self):
111 112 #check to see if we have to load the history 113 self.loadHistory() 114 115 ax = self.figure.gca() 116 117 for state,dict in self.stateHistory.items(): 118 ax.plot(range(len(dict['val'])),dict['val'],dict['style'],label=state) 119 120 if not self.initialized: 121 self.setupGraphAttributes() 122 self.initialized = True 123 124 #Set up the axis size 125 ax.set_xlim(xmin=0) 126 ax.set_ylim(ymin=-1,ymax=1)
127
128 - def xAxisFormatter(self,x,pos):
129 if x < 0 or x >= len(self.actionHistory): 130 return "" 131 else: 132 return self.actionHistory[int(x)]
133
134 - def getNextPointStyle(self):
135 color = self.availableColors.pop(0) 136 self.availableColors.append(color) 137 if len(self.availableSymbols) > 0: 138 symbol = self.availableSymbols.pop(0) 139 self.usedSymbols.append(symbol) 140 else: 141 self.availableSymbols.extend(self.usedSymbols) 142 self.usedSymbols = [] 143 symbol = self.availableSymbols.pop(0) 144 if self.startStyle == "%s--%s" % (color,symbol): 145 self.availableSymbols.append(symbol) 146 symbol = self.availableSymbols.pop(0) 147 self.startStyle = "%s--%s" % (color,symbol) 148 self.usedSymbols.append(symbol) 149 return "%s--%s" % (color,symbol)
150 151 if __name__ == '__main__': 152 from teamwork.multiagent.GenericSociety import GenericSociety 153 from teamwork.multiagent.sequential import SequentialAgents 154 import teamwork.examples.school.SchoolClasses as classModule 155 from teamwork.multiagent.Historical import HistoricalAgents 156 157 #We need to get a scenario 158 society = GenericSociety() 159 society.importDict(classModule.classHierarchy) 160 161 #Instantiate the agents 162 victim = society.instantiate("Victim", "Victim") 163 onlooker = society.instantiate("Onlooker", "Onlooker") 164 bully = society.instantiate("Bully", "Bully") 165 teacher = society.instantiate("Teacher", "Teacher") 166 167 #Set up the relationships 168 victim.relationships['victim'] = ['Victim'] 169 onlooker.relationships['victim'] = ['Victim'] 170 bully.relationships['victim'] = ['Victim'] 171 172 #Instantiate the scenario 173 entities = [victim, onlooker, bully, teacher] 174 agents = SequentialAgents(entities) 175 agents.applyDefaults() 176 agents.compileDynamics() 177 178 #for debugging purposes, I have a specially made history thingy 179 agents.__class__ = HistoricalAgents 180 181 #Create the graph object 182 graph = Graph(agents) 183 for i in range(3): 184 agents.microstep() 185 graph.plot() 186 agents.microstep() 187 graph.plot() 188 pylab.show() 189