diff python/moving.py @ 1012:01db14e947e4

resolved
author Wendlasida
date Fri, 01 Jun 2018 10:47:49 -0400
parents 4f0312bee393 cc7c6b821ae6
children d6f121ded971
line wrap: on
line diff
--- a/python/moving.py	Fri Jun 01 10:43:23 2018 -0400
+++ b/python/moving.py	Fri Jun 01 10:47:49 2018 -0400
@@ -122,7 +122,7 @@
         self.iterInstantNum = -1
         return self
 
-    def next(self):
+    def __next__(self):
         if self.iterInstantNum >= self.length()-1:
             raise StopIteration
         else:
@@ -172,6 +172,18 @@
     def getLastInstant(self):
         return self.timeInterval.last
 
+    def setFirstInstant(self, t):
+        if t <= self.timeInterval.last:
+            self.timeInterval.first = t
+        else:
+            print('new first instant is after last, not changing')
+
+    def setLastInstant(self, t):
+        if t >= self.timeInterval.first:
+            self.timeInterval.last = t
+        else:
+            print('new last instant is before first, not changing')
+
     def getTimeInterval(self):
         return self.timeInterval
 
@@ -379,7 +391,7 @@
             prepared_polygon = polygon
         else:
             prepared_polygon = prep(polygon)
-        return filter(prepared_polygon.contains, points)
+        return list(filter(prepared_polygon.contains, points))
 
 # Functions for coordinate transformation
 # From Paul St-Aubin's PVA tools
@@ -417,7 +429,7 @@
     'Approximates slope singularity by giving some slope roundoff; account for roundoff error'
     for spline in splines:
         p1 = spline[0]
-        for i in xrange(len(spline)-1):
+        for i in range(len(spline)-1):
             p2 = spline[i+1]
             if(round(p1.x, 10) == round(p2.x, 10)):
                 p2.x += 0.0000000001
@@ -666,7 +678,7 @@
         t = Trajectory()
         p0 = Point(p.x, p.y)
         t.addPosition(p0)
-        for i in xrange(nPoints-1):
+        for i in range(nPoints-1):
             p0 += v
             t.addPosition(p0)
         return t, Trajectory([[v.x]*nPoints, [v.y]*nPoints])
@@ -705,7 +717,7 @@
             raise TypeError("Invalid argument type.")
 
     def __str__(self):
-        return ' '.join([self.__getitem__(i).__str__() for i in xrange(self.length())])
+        return ' '.join([self.__getitem__(i).__str__() for i in range(self.length())])
 
     def __repr__(self):
         return self.__str__()
@@ -714,7 +726,7 @@
         self.iterInstantNum = 0
         return self
 
-    def next(self):
+    def __next__(self):
         if self.iterInstantNum >= self.length():
             raise StopIteration
         else:
@@ -819,7 +831,7 @@
 
     def differentiate(self, doubleLastPosition = False):
         diff = Trajectory()
-        for i in xrange(1, self.length()):
+        for i in range(1, self.length()):
             diff.addPosition(self[i]-self[i-1])
         if doubleLastPosition:
             diff.addPosition(diff[-1])
@@ -856,7 +868,7 @@
         self.cumulativeDistances = [0.]
         p1 = self[0]
         cumulativeDistance = 0.
-        for i in xrange(self.length()-1):
+        for i in range(self.length()-1):
             p2 = self[i+1]
             self.distances.append(Point.distanceNorm2(p1,p2))
             cumulativeDistance += self.distances[-1]
@@ -923,7 +935,7 @@
         indices = []
         intersections = []
 
-        for i in xrange(self.length()-1):
+        for i in range(self.length()-1):
             q1=self.__getitem__(i)
             q2=self.__getitem__(i+1)
             p = segmentIntersection(q1, q2, p1, p2)
@@ -945,7 +957,7 @@
         indices = []
         intersections = []
         
-        for i in xrange(self.length()-1):
+        for i in range(self.length()-1):
             q1=self.__getitem__(i)
             q2=self.__getitem__(i+1)
             p = segmentLineIntersection(p1, p2, q1, q2)
@@ -1078,7 +1090,7 @@
     def differentiate(self, doubleLastPosition = False):
         diff = CurvilinearTrajectory()
         p1 = self[0]
-        for i in xrange(1, self.length()):
+        for i in range(1, self.length()):
             p2 = self[i]
             diff.addPositionSYL(p2[0]-p1[0], p2[1]-p1[1], p1[2])
             p1=p2
@@ -1092,7 +1104,7 @@
         (in provided lane if lane is not None)
         Returns an empty list if there is no crossing'''
         indices = []
-        for i in xrange(self.length()-1):
+        for i in range(self.length()-1):
             q1=self.__getitem__(i)
             q2=self.__getitem__(i+1)
             if q1[0] <= S1 < q2[0] and (lane is None or (self.lanes[i] == lane and self.lanes[i+1] == lane)):
@@ -1261,10 +1273,10 @@
     @staticmethod
     def concatenate(obj1, obj2, num = None):
         '''Concatenates two objects supposed to overlap temporally '''
-	if num is None:
-		newNum = obj1.getNum()
-	else:
-		newNum = num
+        if num is None:
+            newNum = obj1.getNum()
+        else:
+            newNum = num
         commonTimeInterval = obj1.commonTimeInterval(obj2)
         if commonTimeInterval.empty():
             print('The two objects\' time intervals do not overlap: obj1 {} and obj2 {}'.format(obj1.getTimeInterval(), obj2.getTimeInterval()))
@@ -1289,8 +1301,7 @@
 	    newObject = MovingObject(newNum, emptyInterval, positions, velocities, userType = obj1.getUserType())
 	    newObject.features = [MovingObject(newNum, emptyInterval, positions, velocities, userType = obj1.getUserType())] #In case there is features to add when we recursively call concatenate 
             return MovingObject.concatenate(MovingObject.concatenate(obj1, newObject),obj2)
-            
-            
+                     
         else:
             newTimeInterval = TimeInterval.union(obj1.getTimeInterval(), obj2.getTimeInterval())
             # positions
@@ -1424,7 +1435,7 @@
                 if withOrigin and len(instants)>0:
                     plot([instants[0]], [coords[0]], 'ro', **kwargs)
         else:
-            print('Object {} has no curvilinear positions'.format(self.getNum()))        
+            print('Object {} has no curvilinear positions'.format(self.getNum()))
 
     def setUserType(self, userType):
         self.userType = userType
@@ -1533,7 +1544,7 @@
 
     def speedDiagnostics(self, framerate = 1., display = False, nInstantsIgnoredAtEnds=0):
         speeds = framerate*self.getSpeeds(nInstantsIgnoredAtEnds)
-        coef = utils.linearRegression(range(len(speeds)), speeds)
+        coef = utils.linearRegression(list(range(len(speeds))), speeds)
         print('min/5th perc speed: {} / {}\nspeed diff: {}\nspeed stdev: {}\nregression: {}'.format(min(speeds), scoreatpercentile(speeds, 5), speeds[-2]-speeds[1], std(speeds), coef[0]))
         if display:
             from matplotlib.pyplot import figure, axis
@@ -1668,7 +1679,7 @@
         self.curvilinearPositions = CurvilinearTrajectory()
 
         #For each point
-        for i in xrange(int(self.length())):
+        for i in range(int(self.length())):
             result = getSYfromXY(self.getPositionAt(i), alignments)
 
             # Error handling
@@ -1684,7 +1695,7 @@
         ## Recalculate projected point to new lane
         lanes = self.curvilinearPositions.getLanes()
         if(lanes != smoothed_lanes):
-            for i in xrange(len(lanes)):
+            for i in range(len(lanes)):
                 if(lanes[i] != smoothed_lanes[i]):
                     result = getSYfromXY(self.getPositionAt(i),[alignments[smoothed_lanes[i]]])
 
@@ -1708,8 +1719,8 @@
         else:
             # compute the relative position vectors
             relativePositions = {} # relativePositions[(i,j)] is the position of j relative to i
-            for i in xrange(nFeatures):
-                for j in xrange(i):
+            for i in range(nFeatures):
+                for j in range(i):
                     fi = self.features[i]
                     fj = self.features[j]
                     inter = fi.commonTimeInterval(fj)
@@ -1962,7 +1973,7 @@
     else:
         gtMatches = None
         toMatches = None
-    for t in xrange(firstInstant, lastInstant+1):
+    for t in range(firstInstant, lastInstant+1):
         previousMatches = matches.copy()
         # go through currently matched GT-TO and check if they are still matched withing matchingDistance
         toDelete = []
@@ -1979,8 +1990,8 @@
             del matches[a]
 
         # match all unmatched GT-TO
-        matchedGTs = matches.keys()
-        matchedTOs = matches.values()
+        matchedGTs = list(matches.keys())
+        matchedTOs = list(matches.values())
         costs = []
         unmatchedGTs = [a for a in annotations if a.existsAtInstant(t) and a not in matchedGTs]
         unmatchedTOs = [o for o in objects if o.existsAtInstant(t) and o not in matchedTOs]
@@ -1996,9 +2007,9 @@
                     matches[unmatchedGTs[k]]=unmatchedTOs[v]
                     dist += costs[k][v]
         if debug:
-            print('{} '.format(t)+', '.join(['{} {}'.format(k.getNum(), v.getNum()) for k,v in matches.iteritems()]))
+            print('{} '.format(t)+', '.join(['{} {}'.format(k.getNum(), v.getNum()) for k,v in matches.items()]))
         if returnMatches:
-            for a,o in matches.iteritems():
+            for a,o in matches.items():
                 gtMatches[a.getNum()][t] = o.getNum()
                 toMatches[o.getNum()][t] = a.getNum()
         
@@ -2014,10 +2025,10 @@
             if a in previousMatches:
                 if matches[a] != previousMatches[a]:
                     mismatches.append(a)
-            elif matches[a] in previousMatches.values():
+            elif matches[a] in list(previousMatches.values()):
                 mismatches.append(matches[a])
         for a in previousMatches:
-            if a not in matches and previousMatches[a] in matches.values():
+            if a not in matches and previousMatches[a] in list(matches.values()):
                 mismatches.append(previousMatches[a])
         if debug: 
             for mm in set(mismatches):