1 from teamwork.agent.Entities import *
2 from teamwork.action.PsychActions import *
3 from teamwork.multiagent.GenericSociety import *
4 from teamwork.agent.DefaultBased import createEntity
5 from teamwork.multiagent.sequential import *
6 from teamwork.reward.MinMaxGoal import *
7 from teamwork.examples.InfoShare.PortClasses import *
8
9 from teamwork.math.Keys import *
10 from teamwork.math.fitting import *
11
12 import copy
13 import unittest
14
16 debug = None
17 increment = 0.25
18
20 """Creates the instantiated scenario used for testing"""
21 society = GenericSociety()
22 society.importDict(classHierarchy)
23 entities = []
24 self.instances = {'FirstResponder':['FirstResponder'],
25 'World':['World'],
26 'FederalAuthority':['FederalAuthority'],
27 'Shipper':['Shipper'],
28 }
29 for cls,names in self.instances.items():
30 for name in names:
31 entity = createEntity(cls,name,society,PsychEntity)
32 entities.append(entity)
33 self.entities = SequentialAgents(entities)
34 self.entities.applyDefaults()
35 self.entities.compileDynamics()
36
37 self.entity = self.entities['FirstResponder']
38 for action in self.entity.actions.getOptions():
39 if action[0]['type'] == 'inspect':
40 break
41 else:
42 self.fail('No inspect action found')
43 self.action = action
44 self.order = self.entity.policy.getSequence(self.entity)
45
46
47
48
49 self.features = {self.entity.name:{'waitTime':1,
50 'reputation':1,
51 },
52 'Shipper':{'containerDanger':1,
53 },
54 'FederalAuthority':{},
55 'World':{'socialWelfare':1,
56 },
57 }
58 self.keys = []
59 for entity,features in self.features.items():
60 for feature in features.keys():
61 self.keys.append(StateKey({'entity':entity,
62 'feature':feature}))
63
73
90
106
108 """Verifies that the given dynamics tree
109
110 Checks that the result of applying the tree in the given state
111 produces the same result as directly applying the action to
112 the entity (using the performAct method)"""
113
114 delta = tree[state]*state
115 state += delta
116
117 self.entity.entities.performAct({self.entity.name:action})
118 self.checkState(state)
119
121 """Verifies that the state vector is the same as the real state"""
122 for key in self.keys:
123 try:
124 value = state[key]
125 except KeyError:
126 value = 0.
127 if isinstance(key,StateKey):
128 real = self.entity.getBelief(key['entity'],
129 key['feature'])
130 msg = '%s:\n%f != %f' % \
131 (key.simpleText(),real,value)
132 self.assertAlmostEqual(float(real),value,5,msg)
133
137
148
155
167
169 "Verifies the given lookahead (delta only) tree"""
170
171 state = tree[state]*state
172
173 for t in range(length):
174 if t == 0:
175 self.entity.entities.performAct({self.entity.name:action})
176 else:
177 result = self.entity.entities.microstep()
178 self.assertEqual(self.order[t],result['decision'].keys())
179 self.checkState(state)
180
194
202
204 """Verifies the PWL policy in the given state"""
205 act,exp = entity.applyPolicy()
206 self.assertEqual(act,policy[state])
207
213
215 """Tests the fitting procedure"""
216 for desired in self.entity.actions.getOptions():
217 act,exp = self.entity.applyPolicy()
218 constraints = findAllConstraints(self.entity,desired,self.order)
219 if act == desired:
220
221 self.assertEqual(len(constraints),1)
222 constraint = constraints[0]
223 self.assertEqual(constraint['slope'],{})
224 self.assertEqual(constraint['solution'],{})
225 else:
226
227 for constraint in constraints:
228 for goal in self.entity.getGoals():
229 try:
230 slope = constraint['slope'][goal.toKey()]
231 except KeyError:
232 continue
233 weight = self.entity.getGoalWeight(goal)
234 try:
235 delta = -constraint['delta']/slope - epsilon
236 except ZeroDivisionError:
237 continue
238 change = None
239 if (slope > 0. and goal.isMax()) or \
240 (slope < 0. and not goal.isMax()):
241 if weight + delta < Interval.CEILING:
242 new = weight+delta
243 change = 1
244 else:
245 continue
246 elif (slope < 0. and goal.isMax()) or \
247 (slope > 0. and not goal.isMax()):
248 if weight > delta:
249 new = weight-delta
250 change = 1
251 else:
252 continue
253
254 self.entity.setGoalWeight(goal,new)
255 act,exp = self.entity.applyPolicy()
256 self.assertEqual(act,desired)
257 self.entity.setGoalWeight(goal,weight)
258
259 if __name__ == '__main__':
260 unittest.main()
261