diff python/moving.py @ 998:933670761a57

updated code to python 3 (tests pass and scripts run, but non-executed parts of code are probably still not correct)
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Sun, 27 May 2018 23:22:48 -0400
parents 4f3387a242a1
children cc7c6b821ae6
line wrap: on
line diff
--- a/python/moving.py	Fri May 25 18:15:18 2018 -0400
+++ b/python/moving.py	Sun May 27 23:22:48 2018 -0400
@@ -121,7 +121,7 @@
         self.iterInstantNum = -1
         return self
 
-    def next(self):
+    def __next__(self):
         if self.iterInstantNum >= self.length()-1:
             raise StopIteration
         else:
@@ -378,7 +378,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
@@ -416,7 +416,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
@@ -665,7 +665,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])
@@ -704,7 +704,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__()
@@ -713,7 +713,7 @@
         self.iterInstantNum = 0
         return self
 
-    def next(self):
+    def __next__(self):
         if self.iterInstantNum >= self.length():
             raise StopIteration
         else:
@@ -818,7 +818,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])
@@ -855,7 +855,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]
@@ -922,7 +922,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)
@@ -944,7 +944,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)
@@ -1077,7 +1077,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
@@ -1091,7 +1091,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)):
@@ -1312,7 +1312,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
@@ -1421,7 +1421,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
@@ -1556,7 +1556,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
@@ -1572,7 +1572,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]]])
 
@@ -1596,8 +1596,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)
@@ -1850,7 +1850,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 = []
@@ -1867,8 +1867,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]
@@ -1884,9 +1884,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()
         
@@ -1902,10 +1902,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):