1
2
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
42
43
45 - def __init__(self,entities,figure=None):
46
47
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
59 if not figure:
60 pylab.subplot(111)
61 self.figure = pylab.gcf()
62
63
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
70 self.loadHistory()
71
72
74 ax = self.figure.gca()
75
76
77 locator = MultipleLocator(base=1)
78 ax.xaxis.set_major_formatter(FuncFormatter(self.xAxisFormatter))
79 ax.xaxis.set_major_locator(locator)
80
81
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
91 self.actionHistory = ["Initial State"]
92 for dict in self.stateHistory.values():
93 dict['val'] = []
94
95
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
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
111
112
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
125 ax.set_xlim(xmin=0)
126 ax.set_ylim(ymin=-1,ymax=1)
127
133
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
158 society = GenericSociety()
159 society.importDict(classModule.classHierarchy)
160
161
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
168 victim.relationships['victim'] = ['Victim']
169 onlooker.relationships['victim'] = ['Victim']
170 bully.relationships['victim'] = ['Victim']
171
172
173 entities = [victim, onlooker, bully, teacher]
174 agents = SequentialAgents(entities)
175 agents.applyDefaults()
176 agents.compileDynamics()
177
178
179 agents.__class__ = HistoricalAgents
180
181
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