diff python/events.py @ 708:a37c565f4b68

merged dev
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Wed, 22 Jul 2015 14:17:44 -0400
parents e395bffe1412
children 4e89341edd29
line wrap: on
line diff
--- a/python/events.py	Wed Jul 22 14:17:19 2015 -0400
+++ b/python/events.py	Wed Jul 22 14:17:44 2015 -0400
@@ -6,7 +6,6 @@
 from base import VideoFilenameAddable
 
 import numpy as np
-from numpy import arccos
 
 import multiprocessing
 import itertools
@@ -90,6 +89,8 @@
                       '',
                       '']
 
+    timeIndicators = ['Time to Collision', 'predicted Post Encroachment Time']
+
     def __init__(self, num = None, timeInterval = None, roaduserNum1 = None, roaduserNum2 = None, roadUser1 = None, roadUser2 = None, categoryNum = None):
         moving.STObject.__init__(self, num, timeInterval)
         if timeInterval is None and roadUser1 is not None and roadUser2 is not None:
@@ -113,20 +114,23 @@
         return self.roadUserNumbers
 
     def setRoadUsers(self, objects):
-        nums = list(self.getRoadUserNumbers())
-        if objects[nums[0]].getNum() == nums[0]:
+        nums = sorted(list(self.getRoadUserNumbers()))
+        if nums[0]<len(objects) and objects[nums[0]].getNum() == nums[0]:
             self.roadUser1 = objects[nums[0]]
-        if objects[nums[1]].getNum() == nums[1]:
+        if nums[1]<len(objects) and objects[nums[1]].getNum() == nums[1]:
             self.roadUser2 = objects[nums[1]]
 
-        i = 0
-        while i < len(objects) and self.roadUser2 is None:
-            if objects[i].getNum() in nums:
-                if self.roadUser1 is None:
-                    self.roadUser1 = objects[i]
-                else:
-                    self.roadUser2 = objects[i]
-            i += 1
+        if self.roadUser1 is None or self.roadUser2 is None:
+            self.roadUser1 = None
+            self.roadUser2 = None
+            i = 0
+            while i < len(objects) and self.roadUser2 is None:
+                if objects[i].getNum() in nums:
+                    if self.roadUser1 is None:
+                        self.roadUser1 = objects[i]
+                    else:
+                        self.roadUser2 = objects[i]
+                i += 1
 
     def getIndicator(self, indicatorName):
         return self.indicators.get(indicatorName, None)
@@ -177,14 +181,14 @@
             v1 = self.roadUser1.getVelocityAtInstant(instant)
             v2 = self.roadUser2.getVelocityAtInstant(instant)
             deltav = v2-v1
-            velocityAngles[instant] = arccos(moving.Point.dot(v1, v2)/(v1.norm2()*v2.norm2()))
+            velocityAngles[instant] = np.arccos(moving.Point.dot(v1, v2)/(v1.norm2()*v2.norm2()))
             collisionCourseDotProducts[instant] = moving.Point.dot(deltap, deltav)
             distances[instant] = deltap.norm2()
             speedDifferentials[instant] = deltav.norm2()
             if collisionCourseDotProducts[instant] > 0:
                 interactionInstants.append(instant)
             if distances[instant] != 0 and speedDifferentials[instant] != 0:
-                collisionCourseAngles[instant] = arccos(collisionCourseDotProducts[instant]/(distances[instant]*speedDifferentials[instant]))
+                collisionCourseAngles[instant] = np.arccos(collisionCourseDotProducts[instant]/(distances[instant]*speedDifferentials[instant]))
 
         if len(interactionInstants) >= 2:
             self.interactionInterval = moving.TimeInterval(interactionInstants[0], interactionInstants[-1])
@@ -192,16 +196,16 @@
             self.interactionInterval = moving.TimeInterval()
         self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[0], collisionCourseDotProducts))
         self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[1], collisionCourseAngles))
-        self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[2], distances))
+        self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[2], distances, mostSevereIsMax = False))
         self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[4], velocityAngles))
         self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[5], speedDifferentials))
 
         # if we have features, compute other indicators
         if self.roadUser1.hasFeatures() and self.roadUser2.hasFeatures():
-            minDistance={}
+            minDistances={}
             for instant in self.timeInterval:
-                minDistance[instant] = moving.MovingObject.minDistance(self.roadUser1, self.roadUser2, instant)
-            self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[3], minDistance))
+                minDistances[instant] = moving.MovingObject.minDistance(self.roadUser1, self.roadUser2, instant)
+            self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[3], minDistances, mostSevereIsMax = False))
 
     def computeCrossingsCollisions(self, predictionParameters, collisionDistanceThreshold, timeHorizon, computeCZ = False, debug = False, timeInterval = None, nProcesses = 1, usePrototypes=False, route1= (-1,-1), route2=(-1,-1), prototypes={}, secondStepPrototypes={}, nMatching={}, objects=[], noiseEntryNums=[], noiseExitNums=[], minSimilarity=0.1, mostMatched=None, useDestination=True, useSpeedPrototype=True, acceptPartialLength=30, step=1):
         '''Computes all crossing and collision points at each common instant for two road users. '''
@@ -217,11 +221,12 @@
         self.collisionPoints, crossingZones = predictionParameters.computeCrossingsCollisions(self.roadUser1, self.roadUser2, collisionDistanceThreshold, timeHorizon, computeCZ, debug, commonTimeInterval, nProcesses,usePrototypes,route1,route2,prototypes,secondStepPrototypes,nMatching,objects,noiseEntryNums,noiseExitNums,minSimilarity,mostMatched,useDestination,useSpeedPrototype,acceptPartialLength, step)
         for i, cp in self.collisionPoints.iteritems():
             TTCs[i] = prediction.SafetyPoint.computeExpectedIndicator(cp)
-        self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[7], TTCs, mostSevereIsMax=False))
+        if len(TTCs) > 0:
+            self.addIndicator(indicators.SeverityIndicator(Interaction.indicatorNames[7], TTCs, mostSevereIsMax=False))
         
         # crossing zones and pPET
         if computeCZ:
-            self.crossingZones[predictionParameters.name] = crossingZones
+            self.crossingZones = crossingZones
             pPETs = {}
             for i, cz in self.crossingZones.iteritems():
                 pPETs[i] = prediction.SafetyPoint.computeExpectedIndicator(cz)
@@ -242,18 +247,11 @@
         else:
             return None
 
-    def getCrossingZones(self, predictionMethodName):
-        if self.crossingZones is not None:
-            return self.crossingZones[predictionMethodName]
-        else:
-            return None
+    def getCollisionPoints(self):
+        return self.collisionPoints
 
-    def getCollisionPoints(self, predictionMethodName):
-        if self.collisionPoints is not None:
-            return self.collisionPoints[predictionMethodName]
-        else:
-            return None
-
+    def getCrossingZones(self):
+        return self.crossingZones
 
 def createInteractions(objects, _others = None):
     '''Create all interactions of two co-existing road users'''
@@ -282,22 +280,19 @@
     else:
         return None
 
-def aggregateSafetyPoints(interactions, predictionMethodName = None, pointType = 'collision'):
+def aggregateSafetyPoints(interactions, pointType = 'collision'):
     '''Put all collision points or crossing zones in a list for display'''
-    if predictionMethodName is None and len(interactions)>0:
-        predictionMethodName = interactions[0].collisionPoints.keys()[0]
-
     allPoints = []
     if pointType == 'collision':
         for i in interactions:
-            for points in i.collisionPoints[predictionMethodName].values():
+            for points in i.collisionPoints.values():
                 allPoints += points
     elif pointType == 'crossing':
         for i in interactions:
-            for points in i.crossingZones[predictionMethodName].values():
+            for points in i.crossingZones.values():
                 allPoints += points
     else:
-        print('unknown type of point '+pointType)
+        print('unknown type of point: '+pointType)
     return allPoints
 
 def prototypeCluster(interactions, similarityMatrix, alignmentMatrix, indicatorName, minSimilarity):
@@ -343,130 +338,6 @@
     Non-prototype interactions will be assigned to an existing prototype if all indicators are similar enough'''
     pass
 
-# TODO:
-#http://stackoverflow.com/questions/3288595/multiprocessing-using-pool-map-on-a-function-defined-in-a-class
-#http://www.rueckstiess.net/research/snippets/show/ca1d7d90
-def calculateIndicatorPipe(pairs, predParam, timeHorizon=75,collisionDistanceThreshold=1.8):  
-    collisionPoints, crossingZones = prediction.computeCrossingsCollisions(pairs.roadUser1, pairs.roadUser2, predParam, collisionDistanceThreshold, timeHorizon)      
-    #print pairs.num    
-    # Ignore empty collision points
-    empty = 1
-    for i in collisionPoints:
-        if(collisionPoints[i] != []):
-            empty = 0
-    if(empty == 1):
-        pairs.hasCP = 0
-    else:
-        pairs.hasCP = 1
-    pairs.CP = collisionPoints
-    
-    # Ignore empty crossing zones
-    empty = 1
-    for i in crossingZones:
-        if(crossingZones[i] != []):
-            empty = 0
-    if(empty == 1):
-        pairs.hasCZ = 0
-    else:
-        pairs.hasCZ = 1
-    pairs.CZ = crossingZones
-    return pairs
-
-def calculateIndicatorPipe_star(a_b):
-    """Convert `f([1,2])` to `f(1,2)` call."""
-    return calculateIndicatorPipe(*a_b)
-
-class VehPairs():
-    '''Create a veh-pairs object from objects list'''
-    def __init__(self,objects):
-        self.pairs = createInteractions(objects)
-        self.interactionCount = 0
-        self.CPcount = 0
-        self.CZcount = 0
-    
-    # Process indicator calculation with support for multi-threading
-    def calculateIndicators(self,predParam,threads=1,timeHorizon=75,collisionDistanceThreshold=1.8):       
-        if(threads > 1):
-            pool = multiprocessing.Pool(threads)
-            self.pairs = pool.map(calculateIndicatorPipe_star, itertools.izip(self.pairs, itertools.repeat(predParam)))
-            pool.close()
-        else:
-            #prog = Tools.ProgressBar(0, len(self.pairs), 77) #Removed in traffic-intelligenc port
-            for j in xrange(len(self.pairs)):
-                #prog.updateAmount(j) #Removed in traffic-intelligenc port
-                collisionPoints, crossingZones = prediction.computeCrossingsCollisions(self.pairs[j].roadUser1, self.pairs[j].roadUser2, predParam, collisionDistanceThreshold, timeHorizon)      
-                
-                # Ignore empty collision points
-                empty = 1
-                for i in collisionPoints:
-                    if(collisionPoints[i] != []):
-                        empty = 0
-                if(empty == 1):
-                    self.pairs[j].hasCP = 0
-                else:
-                    self.pairs[j].hasCP = 1
-                self.pairs[j].CP = collisionPoints
-                
-                # Ignore empty crossing zones
-                empty = 1
-                for i in crossingZones:
-                    if(crossingZones[i] != []):
-                        empty = 0
-                if(empty == 1):
-                    self.pairs[j].hasCZ = 0
-                else:
-                    self.pairs[j].hasCZ = 1
-                self.pairs[j].CZ = crossingZones       
-                
-        for j in self.pairs:
-            self.interactionCount = self.interactionCount + len(j.CP)
-        self.CPcount = len(self.getCPlist())
-        self.Czcount = len(self.getCZlist())
-    
-    
-    def getPairsWCP(self):
-        lists = []
-        for j in self.pairs:
-            if(j.hasCP):
-                lists.append(j.num)
-        return lists
-        
-    def getPairsWCZ(self):
-        lists = []
-        for j in self.pairs:
-            if(j.hasCZ):
-                lists.append(j.num)
-        return lists
-    
-    def getCPlist(self,indicatorThreshold=float('Inf')):
-        lists = []
-        for j in self.pairs:
-            if(j.hasCP):
-                for k in j.CP:
-                    if(j.CP[k] != [] and j.CP[k][0].indicator < indicatorThreshold):
-                        lists.append([k,j.CP[k][0]])
-        return lists
-     
-    def getCZlist(self,indicatorThreshold=float('Inf')):
-        lists = []
-        for j in self.pairs:
-            if(j.hasCZ):
-                for k in j.CZ:
-                    if(j.CZ[k] != [] and j.CZ[k][0].indicator < indicatorThreshold):
-                        lists.append([k,j.CZ[k][0]])
-        return lists
-        
-    def genIndicatorHistogram(self, CPlist=False, bins=range(0,100,1)):
-        if(not CPlist):
-            CPlist = self.getCPlist()
-        if(not CPlist):
-            return False
-        TTC_list = []
-        for i in CPlist:
-            TTC_list.append(i[1].indicator)
-        histo = np.histogram(TTC_list,bins=bins)
-        histo += (histo[0].astype(float)/np.sum(histo[0]),)
-        return histo
 
 class Crossing(moving.STObject):
     '''Class for the event of a street crossing