Package SmootLight :: Package util :: Module BehaviorQuerySystem
[hide private]
[frames] | no frames]

Source Code for Module SmootLight.util.BehaviorQuerySystem

 1  import types  
 2  """The behavior query system is a module that allows querying behaviors based on lambda-function 
 3  predicates.""" 
4 -def initBQS():
5 global behaviorList, initialized 6 behaviorList = [] 7 initialized = True
8
9 -def addBehavior(behavior):
10 """Add a behavior to the behavior registry.""" 11 behaviorList.append(behavior)
12
13 -def query(predicateList):
14 """BehaviorQuerySystem.query takes a list of predicates (functions with signature: 15 (behavior,output)), and 16 optionally a behavior to be compared to.""" 17 #want to do queries wrt: behavior itself, the behavior packet, the querying behavior 18 if isinstance(predicateList, types.FunctionType): 19 predicateList = [predicateList] 20 elif not isinstance(predicateList, list): 21 raise Exception('Predicate list must be a function or list of functions') 22 global behaviorList, initialized 23 ret = [] 24 if not initialized: 25 initBQS() 26 27 for behavior in behaviorList: #Consider every behavior 28 lastOutput = behavior.getLastOutput() 29 for output in lastOutput: #Look at every element it has output 30 validOutput = True 31 for pred in predicateList: #Evaluate every predicate. A predicate is a lambda function that 32 #takes a dict and returns a bool. 33 if not pred(output): 34 validOutput = False 35 break 36 if validOutput: 37 ret.append(output) 38 return ret
39
40 -def getDistLambda(loc, maxDist):
41 """Returns a lambda function that checks if for behaviors within maxDist of loc. Can be passed 42 in as an arg to query.""" 43 return lambda args:geo.dist(args['Location'], loc) <= maxDist
44
45 -def getBehaviorsNear(loc, maxdist):
46 """A premade method to do the common task of finding behavior near a location.""" 47 return query(getDistLambda(loc, maxDist))
48