def processResponse(self, sensor, recurs): ret = [] for sensory in sensor: opsensory = dict(sensory) isNew = self.insertStepIfMissing(opsensory) #TODO: update 19 to be a configurable variable if opsensory['isNew'] <= 0: results = bqs.query([ bqs.getBehaviorIdLambda(self['Id']),\ bqs.getDifferentUIDLambda(opsensory['UniqueResponseIdentifier']),\ bqs.getDistLambda(opsensory['Location'], 19) ]) if results: opsensory['XStep'] = -opsensory['XStep'] opsensory['Location'] = Geo.addLocations((opsensory['XStep'], opsensory['YStep']), opsensory['Location']) else: opsensory['isNew'] -= 1 if isNew: opsensory['Location'] = Geo.addLocations((2*opsensory['XStep'], opsensory['YStep']), opsensory['Location']) ret.append(opsensory) opsensory2 = dict(opsensory) opsensory2['XStep'] = -opsensory2['XStep'] opsensory2['Location'] = Geo.addLocations((2*opsensory2['XStep'], opsensory2['YStep']), opsensory['Location']) ret.append(opsensory2) else: opsensory['Location'] = Geo.addLocations((opsensory['XStep'], opsensory['YStep']), opsensory['Location']) ret.append(opsensory) return (ret, [])
def od_merge_mergeable(child_trip, father_trip): '''check if this pair of pairs is od-merge mergable and admissible-od-merge mergable''' if child_trip['start_point']['time'] >= father_trip['start_point']['time']: return False, False, -1 t_walkLeg1 = geo.distBetween( child_trip['start_point']['lat'], child_trip['start_point']['lng'], father_trip['start_point']['lat'], father_trip['start_point']['lng']) / Constants.PACE if child_trip['start_point']['time'] + t_walkLeg1 > father_trip[ 'start_point']['time']: return False, False, -1 t_walkLeg2 = geo.distBetween( child_trip['end_point']['lat'], child_trip['end_point']['lng'], father_trip['end_point']['lat'], father_trip['end_point']['lng']) / Constants.PACE delay = father_trip['end_point']['time'] + t_walkLeg2 - child_trip[ 'end_point']['time'] - child_trip['tt'] ''' if delay<0: print delay, 'f=(%d~%d), c=(%d~%d)'%(father_trip['start_point']['time'], father_trip['end_point']['time'], child_trip['start_point']['time'],child_trip['end_point']['time']) delay+=864000 ''' #if father_trip['end_point']['time']- child_trip['start_point']['time']+ t_walkLeg2 / PACE > child_trip['tt'] * (1 + DELTA): if delay > Constants.DELTA: return True, False, delay #print father_trip['tt'], t_walkLeg1, t_walkLeg2, child_trip['start_point']['time'], father_trip['start_point']['time'], child_trip['tt'], father_trip['tt']+(t_walkLeg1+t_walkLeg2)/PACE+(father_trip['start_point']['time']-child_trip['start_point']['time']-t_walkLeg1/PACE), child_trip['tt']*(1+DELTA/100) return True, True, delay
def processResponse(self, sensor, recurs): ret = [] for sensory in sensor: opsensory = dict(sensory) isNew = self.insertStepIfMissing(opsensory) #TODO: update 19 to be a configurable variable if opsensory['isNew'] <= 0: results = bqs.query([ bqs.getBehaviorIdLambda(self['Id']),\ bqs.getDifferentUIDLambda(opsensory['UniqueResponseIdentifier']),\ bqs.getDistLambda(opsensory['Location'], 19) ]) if results: opsensory['XStep'] = -opsensory['XStep'] opsensory['Location'] = Geo.addLocations((opsensory['XStep'], opsensory['YStep']), opsensory['Location']) else: opsensory['isNew'] -= 1 if isNew: if opsensory['Direction'] != 0: opsensory['Location'] = Geo.addLocations((2*opsensory['XStep'], opsensory['YStep']), opsensory['Location']) ret.append(opsensory) opsensory2 = dict(opsensory) opsensory2['XStep'] = -opsensory2['XStep'] opsensory2['Location'] = Geo.addLocations((2*opsensory2['XStep'], opsensory2['YStep']), opsensory['Location']) ret.append(opsensory2) else: opsensory['Location'] = Geo.addLocations((opsensory['XStep'], opsensory['YStep']), opsensory['Location']) ret.append(opsensory) return (ret, [])
def sensingLoop(self): #TODO: move to params currentTime = clock.time() if currentTime - self['LastEvent'] > self['Interval']: if 'MinX' in self.argDict and 'MinY' in self.argDict: self.respond({Strings.LOCATION: Geo.randomLoc( (self['MaxX'],self['MaxY']), (self['MinX'],self['MinY']) )}) else: self.respond({Strings.LOCATION: Geo.randomLoc((self['MaxX'],self['MaxY']))}) self['LastEvent'] = currentTime
def test_dist_query(self): validDist = lambda args:geo.dist(args['Location'], (0,0)) <= 5 invalidDist = lambda args:geo.dist(args['Location'], (0,0)) <= 2 doubleDist = lambda args:geo.dist(args['Location'], (0,0)) <= 20 assert bqs.query(validDist) == [{'Color':(255,0,0), 'Location':(3,4)}] assert bqs.query(invalidDist) == [] assert bqs.query(doubleDist) == [{'Color':(255,0,0), 'Location':(3,4)}, {'Color':(0,0,255),\ 'Location':(5,12)}]
def sensingLoop(self): # TODO: move to params currentTime = clock.time() if currentTime - self["LastEvent"] > self["Interval"]: if "MinX" in self.argDict and "MinY" in self.argDict: self.respond( {Strings.LOCATION: Geo.randomLoc((self["MaxX"], self["MaxY"]), (self["MinX"], self["MinY"]))} ) else: self.respond({Strings.LOCATION: Geo.randomLoc((self["MaxX"], self["MaxY"]))}) self["LastEvent"] = currentTime
def test_dist_query(self): validDist = lambda args: geo.dist(args['Location'], (0, 0)) <= 5 invalidDist = lambda args: geo.dist(args['Location'], (0, 0)) <= 2 doubleDist = lambda args: geo.dist(args['Location'], (0, 0)) <= 20 assert bqs.query(validDist) == [{ 'Color': (255, 0, 0), 'Location': (3, 4), 'BehaviorId': 'color' }] assert bqs.query(invalidDist) == [] assert bqs.query(doubleDist) == [{'Color':(255,0,0), 'Location':(3,4), 'BehaviorId':'color'}, {'Color':(0,0,255),\ 'Location':(5,12), 'BehaviorId':'color'}]
def mappingFunction(self, eventLocation, screen): returnPixels = [] [x,y] = eventLocation potentialPixels = screen.pixelsInRange(x-self.CutoffDist, \ x+self.CutoffDist) for (x,pixel) in screen.pixelsInRange(x-self.CutoffDist, \ x+self.CutoffDist): pixelDist = Geo.dist(pixel.location, eventLocation) if pixelDist < self.CutoffDist: w = Geo.gaussian(pixelDist, self.Height, 0, self.Width) if w > self.MinWeight: returnPixels.append((pixel, w)) return returnPixels
def is_valid_trip(trip_file_name, debug=False): """this function determines whether an extracted trip is valid based on some heuristics""" #filename=Constants.PROCESSED_DIR+dirname+'/trip_trajectory/'+str(trip_id)+'.txt' #gps_point=[] trip_file = open(trip_file_name, 'r') lines = trip_file.readlines() count = 0 for idx in range(len(lines)): _, lon, lat, _, _, time = lines[idx].split(',') lon = float(lon) lat = float(lat) time = int(time) if count == 5: #if the max distance from the start point does not increase in 5 consecutive steps, then disregard the trip return False if idx == 0: start_time = time start_point = (lat, lon) max_dist = 0 #gps_point.append((0, lat, lon)) else: dist = geo.distBetween(lat, lon, start_point[0], start_point[1]) if debug: print dist if dist < max_dist: count += 1 else: max_dist = dist #gps_point.append((dist, lat, lon)) if time - start_time < 30: #if travel time < half minute, disregard the trip return False return True
def state(self,timeDelay): if self.decayType == 1: decay = Geo.approxexp(timeDelay*-1*self.coefficient) if self.decayType == 2: decay = self.coefficient / timeDelay color = multiplyColor(self.color, decay) return color if (color[0] + color[1] + color[2]) > 5 else None
def behaviorInit(self): action = self['Action'] modifyParamArgs = { 'ParamType': 'Sensor', 'ParamName': self['ParamName'], 'ParamOp': self['Action'] } self.locBounds = self['LocationRestriction'] self.paramModifier = ModifyParam(modifyParamArgs) xmin, ymin, xmax, ymax = compReg.getComponent('Screen').getSize() replacementDict = { '{x}': 'l[0]', '{y}': 'l[1]', '{xmin}': str(xmin), '{xmax}': str(xmax), '{ymin}': str(ymin), '{ymax}': str(ymax) } if isinstance(self.locBounds, str): for key in replacementDict: self.locBounds = self.locBounds.replace( key, replacementDict[key]) self.locEval = eval('lambda l:' + self.locBounds) elif isinstance(self.locBounds, tuple): if len(self.locBounds) != 4: raise Exception('Must be in form (xmin,yin,xmax,ymax)') else: self.locEval = lambda l:Geo.pointWithinBoundingBox(l,\ self.LocBounds)
def mappingFunction(self, eventLocation, screen): if type(eventLocation) == type(tuple()): bestDist = sys.maxint bestPixel = None [x,y] = eventLocation for (x,pixel) in screen.pixelsInRange(x-self['CutoffDist'], \ x+self['CutoffDist']): pixelDist = Geo.dist(pixel.location, eventLocation) if pixelDist < bestDist: bestPixel = pixel bestDist = pixelDist if bestPixel != None: return [(bestPixel,1)] else: return [] else: #{x}>5,{y}<k ret = [] eventLocation = eventLocation.replace('{x}', 'pixel.location[0]') eventLocation = eventLocation.replace('{y}', 'pixel.location[1]') conditions = eventLocation.split(',') conditionLambdas = [eval('lambda pixel:'+condition) for condition in conditions] for pixel in screen: try: pixelValid = True for p in conditionLambdas: if p(pixel) == False: pixelValid = False continue if pixelValid: ret.append((pixel, 1)) except Exception as exp: raise Exception('Bad event condition') return ret
def test_complex_queries(self): validQuery = lambda args:args['Color']==(255,0,0) doubleDist = lambda args:geo.dist(args['Location'], (0,0)) <= 20 twoPartPredicate = lambda args:doubleDist(args) and validQuery(args) assert bqs.query(twoPartPredicate) == [{'Color':(255,0,0), 'Location':(3,4)}] assert bqs.query([validQuery, doubleDist]) == [{'Color':(255,0,0), 'Location':(3,4)}]
def is_valid_trip(trip_file_name, debug=False): """this function determines whether an extracted trip is valid based on some heuristics""" #filename=Constants.PROCESSED_DIR+dirname+'/trip_trajectory/'+str(trip_id)+'.txt' #gps_point=[] trip_file=open(trip_file_name, 'r') lines=trip_file.readlines() count=0 for idx in range(len(lines)): _, lon, lat, _, _, time=lines[idx].split(',') lon=float(lon) lat=float(lat) time=int(time) if count==5: #if the max distance from the start point does not increase in 5 consecutive steps, then disregard the trip return False if idx==0: start_time=time start_point=(lat, lon) max_dist=0 #gps_point.append((0, lat, lon)) else: dist=geo.distBetween(lat, lon, start_point[0], start_point[1]) if debug: print dist if dist<max_dist: count+=1 else: max_dist=dist #gps_point.append((dist, lat, lon)) if time-start_time<30: #if travel time < half minute, disregard the trip return False return True
def processResponse(self, sensor, recurs): ret = [] for loc in sensor: oploc = dict(loc) self.insertVelIfMissing(oploc) oploc['Location'] = Geo.addLocations((oploc['XVel'], oploc['YVel']), oploc['Location']) ret.append(oploc) return (ret, [])
def processResponse(self, sensors, recursives): ret = [] s = self['StepSize'] for sensory in sensors: step = [random.randint(-s,s), random.randint(-s,s)] outdict = dict(sensory) outdict[Strings.LOCATION] = Geo.addLocations(step, outdict[Strings.LOCATION]) ret.append(outdict) return (ret,recursives)
def processResponse(self, sensor, recurs): ret = [] for sensory in sensor: opsensory = dict(sensory) self.insertStepIfMissing(opsensory) #TODO: update 19 to be a configurable variable results = bqs.query([ bqs.getBehaviorIdLambda(self['Id']),\ bqs.getDifferentUIDLambda(opsensory['UniqueResponseIdentifier']),\ bqs.getDistLambda(opsensory['Location'], 19) ]) if results: print len(results) opsensory['XStep'] = -opsensory['XStep'] opsensory['Location'] = Geo.addLocations((opsensory['XStep'], opsensory['YStep']), opsensory['Location']) opsensory['Location'] = Geo.addLocations((opsensory['XStep'], opsensory['YStep']), opsensory['Location']) ret.append(opsensory) return (ret, [])
def getPixelLocations(self): #returns a complete list of locations of Pixels locations = self.layoutFunc() for pixel1, pixel2 in zip(locations[:-1], locations[1:]): if (Geo.dist(pixel1, pixel2) > self['pixelToPixelSpacing']): raise Exception('Illegal pixel location. Distance between adjacent ' + 'pixels must be less than pixelToPixelSpacing.' + 'Illegal distance is between {0} and {1}' .format(pixel1, pixel2)) return locations[::-1] if self['Reverse'] else locations
def processResponse(self, sensorInputs, recursiveInputs): newResponses = sensorInputs ret = [] ret += newResponses for recurInput in recursiveInputs: outDict = dict(recurInput) if not 'Dir' in outDict: outDict['Dir'] = 1 #to the right if not 'StepSize' in outDict: outDict['StepSize'] = self['StepSize'] outDict['Location']= Geo.addLocations(outDict['Location'], (outDict['StepSize']*outDict['Dir'],0)) if not Geo.pointWithinBoundingBox(outDict['Location'], \ compReg.getComponent('Screen').getSize()): outDict['Dir'] *= -1 ret.append(outDict) ret += newResponses return (ret, ret)
def od_merge_mergeable(child_trip, father_trip): '''check if this pair of pairs is od-merge mergable and admissible-od-merge mergable''' if child_trip['start_point']['time'] >= father_trip['start_point']['time']: return False, False, -1 t_walkLeg1 = geo.distBetween(child_trip['start_point']['lat'], child_trip['start_point']['lng'], father_trip['start_point']['lat'], father_trip['start_point']['lng']) / Constants.PACE if child_trip['start_point']['time'] + t_walkLeg1 > father_trip['start_point']['time']: return False, False, -1 t_walkLeg2 = geo.distBetween(child_trip['end_point']['lat'], child_trip['end_point']['lng'], father_trip['end_point']['lat'], father_trip['end_point']['lng']) / Constants.PACE delay = father_trip['end_point']['time'] + t_walkLeg2 - child_trip['end_point']['time']-child_trip['tt'] ''' if delay<0: print delay, 'f=(%d~%d), c=(%d~%d)'%(father_trip['start_point']['time'], father_trip['end_point']['time'], child_trip['start_point']['time'],child_trip['end_point']['time']) delay+=864000 ''' #if father_trip['end_point']['time']- child_trip['start_point']['time']+ t_walkLeg2 / PACE > child_trip['tt'] * (1 + DELTA): if delay > Constants.DELTA: return True, False, delay #print father_trip['tt'], t_walkLeg1, t_walkLeg2, child_trip['start_point']['time'], father_trip['start_point']['time'], child_trip['tt'], father_trip['tt']+(t_walkLeg1+t_walkLeg2)/PACE+(father_trip['start_point']['time']-child_trip['start_point']['time']-t_walkLeg1/PACE), child_trip['tt']*(1+DELTA/100) return True, True, delay
def processResponse(self, sensorInputs, recursiveInputs): newResponses = sensorInputs ret = [] ret += newResponses for recurInput in recursiveInputs: outDict = dict(recurInput) if not 'Dir' in outDict: outDict['Dir'] = 1 #to the right if not 'StepSize' in outDict: outDict['StepSize'] = self['StepSize'] outDict['Location']= Geo.addLocations(outDict['Location'], (outDict['StepSize']*outDict['Dir'],0)) if not Geo.pointWithinBoundingBox(outDict['Location'], \ compReg.getComponent('Screen').size): outDict['Dir'] *= -1 ret.append(outDict) ret += newResponses return (ret, ret)
def processResponse(self, sensor, recurs): ret = [] if self['NoBounceTime'] != None: noBounceTime = self['NoBounceTime'] else: noBounceTime = 1000 if self['BQSDistance'] != None: BQSDistance = self['BQSDistance'] else: BQSDistance = 19 for sensory in sensor: opsensory = dict(sensory) isNew = self.insertVelIfMissing(opsensory) if not 'NoBounceTime' in opsensory: opsensory['NoBounceTime'] = noBounceTime if opsensory['NoBounceTime'] <= 0: results = bqs.query([ bqs.getBehaviorIdLambda(self['Id']),\ bqs.getDifferentUIDLambda(opsensory['UniqueResponseIdentifier']),\ bqs.getDistLambda(opsensory['Location'], BQSDistance) ]) if results: opsensory['XVel'] = -opsensory['XVel'] opsensory['Location'] = Geo.addLocations((opsensory['XVel'], opsensory['YVel']), opsensory['Location']) else: opsensory['NoBounceTime'] -= 1 if isNew: if opsensory['Direction'] < 0: opsensory['XVel'] = -opsensory['XVel'] if opsensory['Direction'] != 0: opsensory['Location'] = Geo.addLocations((2*opsensory['XVel'], opsensory['YVel']), opsensory['Location']) ret.append(opsensory) else: opsensory['Location'] = Geo.addLocations((opsensory['XVel'], opsensory['YVel']), opsensory['Location']) ret.append(opsensory) return (ret, [])
def processResponse(self, sensor, recurs): ret = [] for loc in sensor: oploc = dict(loc) self.insertVelIfMissing(oploc) deltaT = timeOps.time() - oploc['EvalTime'] deltaLoc = (deltaT * oploc['XVel'], deltaT * oploc['YVel']) #print 'diff:',deltaLoc oploc['Location'] = Geo.addLocations(deltaLoc, oploc['Location']) oploc['EvalTime'] = timeOps.time() ret.append(oploc) return (ret, [])
def processResponse(self, sensor, recurs): ret = [] for loc in sensor: oploc = dict(loc) self.insertVelIfMissing(oploc) deltaT = timeOps.time() - oploc["EvalTime"] deltaLoc = (deltaT * oploc["XVel"], deltaT * oploc["YVel"]) # print 'diff:',deltaLoc oploc["Location"] = Geo.addLocations(deltaLoc, oploc["Location"]) oploc["EvalTime"] = timeOps.time() ret.append(oploc) return (ret, [])
def test_complex_queries(self): validQuery = lambda args: args['Color'] == (255, 0, 0) doubleDist = lambda args: geo.dist(args['Location'], (0, 0)) <= 20 twoPartPredicate = lambda args: doubleDist(args) and validQuery(args) assert bqs.query(twoPartPredicate) == [{ 'Color': (255, 0, 0), 'Location': (3, 4) }] assert bqs.query([validQuery, doubleDist]) == [{ 'Color': (255, 0, 0), 'Location': (3, 4) }]
def mappingFunction(self, eventLocation, screen): returnPixels = [] # TODO: consider preallocation and trimming [x, y] = eventLocation potentialPixels = screen.pixelsInRange(x - self.CutoffDist, x) for (xloc, pixel) in screen.pixelsInRange(x - self.CutoffDist, x): pixelDistx = math.fabs(pixel.location[0] - x) pixelDisty = math.fabs(pixel.location[1] - y) if pixelDistx < self.CutoffDist: if pixelDisty < 30: w = Geo.windtrail(pixelDistx, pixelDisty, self.Height, 0, self.Width) if w > self.MinWeight: returnPixels.append((pixel, w)) return returnPixels
def recalc(self): self.locBounds = self['LocationRestriction'] xmin,ymin,xmax,ymax = compReg.getComponent('Screen').size replacementDict = {'{x}':'l[0]','{y}':'l[1]', '{xmin}':str(xmin), '{xmax}':str(xmax), '{ymin}':str(ymin),'{ymax}':str(ymax)} if isinstance(self.locBounds, str) or isinstance(self.locBounds, unicode): for key in replacementDict: self.locBounds = self.locBounds.replace(key, replacementDict[key]) self.locEval = eval('lambda l:'+self.locBounds) elif isinstance(self.locBounds, tuple): if len(self.locBounds) != 4: raise Exception('Must be in form (xmin,yin,xmax,ymax)') else: self.locEval = lambda l:Geo.pointWithinBoundingBox(l,\ self.LocBounds)
def behaviorInit(self): action = self['Action'] modifyParamArgs = {'ParamType': 'Sensor', 'ParamName':self['ParamName'],'ParamOp':self['Action']} self.locBounds = self['LocationRestriction'] self.paramModifier = ModifyParam(modifyParamArgs) if isinstance(self.locBounds, str): self.locBounds = self.locBounds.replace('{x}', 'l[0]') self.locBounds = self.locBounds.replace('{y}', 'l[1]') self.locEval = eval('lambda l:'+self.locBounds) elif isinstance(self.locBounds, tuple): if len(self.locBounds) != 4: raise Exception('Must be in form (xmin,yin,xmax,ymax)') else: self.locEval = lambda l:Geo.pointWithinBoundingBox(l,\ self.LocBounds)
def getPixelLocations(self): #returns a complete list of locations of Pixels #for a strip locations = [self.argDict['originLocation']] for pixelIndex in range(self['numPixels']-1): #-1 because origin #already exists newLocation = self.layoutFunc(locations[-1]) if newLocation == None: raise Exception('Location cannot be null. layoutFunc not \ defined or improperly defined.') if Geo.dist(newLocation, locations[-1]) > \ self['pixelToPixelSpacing']: raise Exception('Illegal pixel location. Distance \ between adjacent pixels must be less than \ pixelToPixelSpacing.') locations.append(newLocation) if self['Reverse']: locations.reverse() return locations
def behaviorInit(self): modifyParamArgs = {'ParamType': 'Sensor', 'ParamName':self['ParamName'],'ParamOp':self['Action']} self.locBounds = self['LocationRestriction'] self.paramModifier = ModifyParam(modifyParamArgs) xmin,ymin,xmax,ymax = compReg.getComponent('Screen').size replacementDict = {'{x}':'l[0]','{y}':'l[1]', '{xmin}':str(xmin), '{xmax}':str(xmax), '{ymin}':str(ymin),'{ymax}':str(ymax)} if isinstance(self.locBounds, str): for key in replacementDict: self.locBounds = self.locBounds.replace(key, replacementDict[key]) self.locEval = eval('lambda l:'+self.locBounds) elif isinstance(self.locBounds, tuple): if len(self.locBounds) != 4: raise Exception('Must be in form (xmin,yin,xmax,ymax)') else: self.locEval = lambda l:Geo.pointWithinBoundingBox(l,\ self.LocBounds)
def processResponse(self, sensor, recurs): ret = [] for sensory in sensor: opsensory = dict(sensory) #TODO: update 19 to be a configurable variable self.insertVelIfMissing(opsensory) results = bqs.query([ bqs.getBehaviorIdLambda('accelerate'),\ bqs.getDirectionLambda('+'),\ bqs.getDistLambda(opsensory['Location'], 38) ]) if results: opsensory['XVel'] = opsensory['XVel'] + 10 opsensory['XVel'] = min(max(-1, opsensory['XVel'] - 1), 10) opsensory['Location'] = Geo.addLocations((-opsensory['XVel'], 0), opsensory['Location']) if opsensory['Location'][0] >= 800: #TODO: Make this dynamic opsensory['Location'] = tuple([799, 25]) ret.append(opsensory) return (ret, [])
def processResponse(self, sensor, recurs): ret = [] for sensory in sensor: opsensory = dict(sensory) self.insertStepIfMissing(opsensory) #TODO: update 19 to be a configurable variable results = bqs.query([ bqs.getBehaviorIdLambda(self['Id']),\ bqs.getDifferentUIDLambda(opsensory['UniqueResponseIdentifier']),\ bqs.getDistLambda(opsensory['Location'], 19) ]) if results: for result in results: new = opsensory['XStep'] + result['XStep'] if new >= 0: opsensory['XStep'] = min(20, new) if new < 0: opsensory['XStep'] = max(-20, new) opsensory['Location'] = Geo.addLocations( (opsensory['XStep'], opsensory['YStep']), opsensory['Location']) ret.append(opsensory) return (ret, [])
def recalc(self): self.locBounds = self['LocationRestriction'] xmin, ymin, xmax, ymax = compReg.getComponent('Screen').size replacementDict = { '{x}': 'l[0]', '{y}': 'l[1]', '{xmin}': str(xmin), '{xmax}': str(xmax), '{ymin}': str(ymin), '{ymax}': str(ymax) } if isinstance(self.locBounds, str) or isinstance( self.locBounds, unicode): for key in replacementDict: self.locBounds = self.locBounds.replace( key, replacementDict[key]) self.locEval = eval('lambda l:' + self.locBounds) elif isinstance(self.locBounds, tuple): if len(self.locBounds) != 4: raise Exception('Must be in form (xmin,yin,xmax,ymax)') else: self.locEval = lambda l:Geo.pointWithinBoundingBox(l,\ self.LocBounds)
def getPixelLocations(self): # returns a complete list of locations of Pixels # for a strip locations = [self.argDict["originLocation"]] for pixelIndex in range(self["numPixels"] - 1): # -1 because origin # already exists newLocation = self.layoutFunc(locations[-1]) if newLocation == None: raise Exception( "Location cannot be null. layoutFunc not \ defined or improperly defined." ) if Geo.dist(newLocation, locations[-1]) > self["pixelToPixelSpacing"]: raise Exception( "Illegal pixel location. Distance \ between adjacent pixels must be less than \ pixelToPixelSpacing. Illegal distance is between " + str(pixelIndex) + " and" + str(pixelIndex + 1) ) locations.append(newLocation) if self["Reverse"]: locations.reverse() return locations
def sensingLoop(self): #TODO: move to params currentTime = clock.time() if currentTime - self['LastEvent'] > 200+500*random.random(): self.respond({Strings.LOCATION: Geo.randomLoc((200,200))}) self['LastEvent'] = currentTime
def getDistLambda(loc, maxDist): """Returns a lambda function that checks if for behaviors within maxDist of loc. Can be passed in as an arg to query.""" return lambda args: Geo.dist(args["Location"], loc) <= maxDist
def extract_trip_from_one_file(file_name, trip_dir, trip_meta): #print file_name f = open(file_name) # Using a DictReader instead r = csv.DictReader(f, ['taxi_id', 'timestamp', 'lat', 'lng', 'unknown1', 'unknown2', 'occupied']) trips = [] max_lat = 0.0 min_lat = 180 max_lng = 0.0 min_lng = 180 lat = [] lng = [] timestamp = [] trip = [] travelDistance = 0.0 trip_meta_file = open(trip_meta, 'a+') trip_id = extract_trip_from_one_file.count for line in r: if "{occupied}".format(**line) == '1': day_of_week = int(time.strftime("%w", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S"))) hour_of_day = int(time.strftime("%H", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S"))) minute = int(time.strftime("%M", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S"))) sec = int(time.strftime("%S", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S"))) sec_of_day = hour_of_day * 3600 + minute * 60 + sec trip.append(("{taxi_id}".format(**line), float("{lat}".format(**line)), float("{lng}".format(**line)), day_of_week, hour_of_day, sec_of_day)) lat.append(float("{lat}".format(**line))) lng.append(float("{lng}".format(**line))) timestamp.append(sec_of_day) if len(lat) > 1: travelDistance += geo.distBetween(lat[-1], lng[-1], lat[-2], lng[-2]) else: if trip: if timestamp[-1] >= timestamp[0]: travelTime = timestamp[-1] - timestamp[0] else: # a trip crossed a day travelTime = timestamp[-1] - timestamp[0] + 60 * 60 * 24 if travelTime > 0 and travelDistance > 0: #filter trips with zero travel time/distance trips.append((trip, lat, lng, timestamp, travelDistance, travelTime)) #generate a trip file trip_file = open(trip_dir + str(trip_id) + '.txt', 'w') for line in trip: print >> trip_file, ','.join([str(field) for field in line]) trip_file.close() #update trip meta trip_meta_file.write(','.join([str(trip_id), str(trip[0][0]), str(lat[0]), str(lng[0]), str(timestamp[0]), str(lat[-1]), str(lng[-1]), str(timestamp[-1]), str(travelTime), str(travelDistance)])+'\n') trip_id += 1 max_lat = max(max(lat), max_lat) min_lat = min(min(lat), min_lat) max_lng = max(max(lng), max_lng) min_lng = min(min(lng), min_lng) lat = [] lng = [] timestamp = [] trip = [] travelDistance = 0.0 trip_meta_file.close() extract_trip_from_one_file.count = trip_id return trips, max_lat, min_lat, max_lng, min_lng
def getDistLambda(loc, maxDist): """Returns a lambda function that checks if for behaviors within maxDist of loc. Can be passed in as an arg to query.""" return lambda args: Geo.dist(args['Location'], loc) <= maxDist
def extract_trip_from_one_file(file_name, trip_dir, trip_meta): #print file_name f = open(file_name) # Using a DictReader instead r = csv.DictReader(f, [ 'taxi_id', 'timestamp', 'lat', 'lng', 'unknown1', 'unknown2', 'occupied' ]) trips = [] max_lat = 0.0 min_lat = 180 max_lng = 0.0 min_lng = 180 lat = [] lng = [] timestamp = [] trip = [] travelDistance = 0.0 trip_meta_file = open(trip_meta, 'a+') trip_id = extract_trip_from_one_file.count for line in r: if "{occupied}".format(**line) == '1': day_of_week = int( time.strftime( "%w", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S"))) hour_of_day = int( time.strftime( "%H", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S"))) minute = int( time.strftime( "%M", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S"))) sec = int( time.strftime( "%S", time.strptime("{timestamp}".format(**line), "%Y-%m-%d %H:%M:%S"))) sec_of_day = hour_of_day * 3600 + minute * 60 + sec trip.append( ("{taxi_id}".format(**line), float("{lat}".format(**line)), float("{lng}".format(**line)), day_of_week, hour_of_day, sec_of_day)) lat.append(float("{lat}".format(**line))) lng.append(float("{lng}".format(**line))) timestamp.append(sec_of_day) if len(lat) > 1: travelDistance += geo.distBetween(lat[-1], lng[-1], lat[-2], lng[-2]) else: if trip: if timestamp[-1] >= timestamp[0]: travelTime = timestamp[-1] - timestamp[0] else: # a trip crossed a day travelTime = timestamp[-1] - timestamp[0] + 60 * 60 * 24 if travelTime > 0 and travelDistance > 0: #filter trips with zero travel time/distance trips.append((trip, lat, lng, timestamp, travelDistance, travelTime)) #generate a trip file trip_file = open(trip_dir + str(trip_id) + '.txt', 'w') for line in trip: print >> trip_file, ','.join( [str(field) for field in line]) trip_file.close() #update trip meta trip_meta_file.write(','.join([ str(trip_id), str(trip[0][0]), str(lat[0]), str(lng[0]), str(timestamp[0]), str(lat[-1]), str(lng[-1]), str(timestamp[-1]), str(travelTime), str(travelDistance) ]) + '\n') trip_id += 1 max_lat = max(max(lat), max_lat) min_lat = min(min(lat), min_lat) max_lng = max(max(lng), max_lng) min_lng = min(min(lng), min_lng) lat = [] lng = [] timestamp = [] trip = [] travelDistance = 0.0 trip_meta_file.close() extract_trip_from_one_file.count = trip_id return trips, max_lat, min_lat, max_lng, min_lng
def sensingLoop(self): # TODO: move to params currentTime = clock.time() if currentTime - self["LastEvent"] > 2000: self.respond({Strings.LOCATION: Geo.randomLoc((50, 50))}) self["LastEvent"] = currentTime