changeset 978:184f1dd307f9

corrected print and exception statements for Python 3
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Thu, 08 Feb 2018 05:53:50 -0500
parents 9c27a0315c4d
children cc89267b5ff9
files python/cvutils.py python/ml.py python/moving.py python/storage.py python/utils.py
diffstat 5 files changed, 50 insertions(+), 44 deletions(-) [+]
line wrap: on
line diff
--- a/python/cvutils.py	Tue Feb 06 11:50:43 2018 -0500
+++ b/python/cvutils.py	Thu Feb 08 05:53:50 2018 -0500
@@ -16,7 +16,7 @@
     print('Scikit-image library could not be loaded (HoG-based classification methods will not be available)')
     skimageAvailable = False
     
-from sys import stdout, maxint
+from sys import stdout
 from os import listdir
 from copy import deepcopy
 from math import floor, log10, ceil
@@ -315,7 +315,7 @@
             frameNum = firstFrameNum
             capture.set(cv2.cv.CV_CAP_PROP_POS_FRAMES, firstFrameNum)
             if lastFrameNumArg is None:
-                lastFrameNum = maxint
+                lastFrameNum = float("inf")
             else:
                 lastFrameNum = lastFrameNumArg
             if nZerosFilenameArg is None:
@@ -502,7 +502,7 @@
         except NameError:
             return None
         savetxt('intrinsic-camera.txt', camera_matrix)
-        print 'error: {}'.format(ret)
+        print('error: {}'.format(ret))
         return camera_matrix, dist_coeffs
 
     def undistortImage(img, intrinsicCameraMatrix = None, distortionCoefficients = None, undistortedImageMultiplication = 1., interpolation=cv2.INTER_LINEAR):
--- a/python/ml.py	Tue Feb 06 11:50:43 2018 -0500
+++ b/python/ml.py	Thu Feb 08 05:53:50 2018 -0500
@@ -11,7 +11,12 @@
 import matplotlib.pyplot as plt
 from scipy.cluster.vq import kmeans, whiten, vq
 from sklearn import mixture
-import cv2
+try:
+    import cv2
+    opencvAvailable = True
+except ImportError:
+    print('OpenCV library could not be loaded (video replay functions will not be available)') # TODO change to logging module
+    opencvAvailable = False
 
 import utils
 
@@ -38,29 +43,30 @@
     def save(self, filename):
         self.model.save(filename)
 
-class SVM(StatModel):
-    '''wrapper for OpenCV SimpleVectorMachine algorithm'''
-    def __init__(self, svmType = cv2.SVM_C_SVC, kernelType = cv2.SVM_RBF, degree = 0, gamma = 1, coef0 = 0, Cvalue = 1, nu = 0, p = 0):
-        self.model = cv2.SVM()
-        self.params = dict(svm_type = svmType, kernel_type = kernelType, degree = degree, gamma = gamma, coef0 = coef0, Cvalue = Cvalue, nu = nu, p = p)
-        # OpenCV3
-        # self.model = cv2.SVM()
-        # self.model.setType(svmType)
-        # self.model.setKernel(kernelType)
-        # self.model.setDegree(degree)
-        # self.model.setGamma(gamma)
-        # self.model.setCoef0(coef0)
-        # self.model.setC(Cvalue)
-        # self.model.setNu(nu)
-        # self.model.setP(p)
+if opencvAvailable:
+    class SVM(StatModel):
+        '''wrapper for OpenCV SimpleVectorMachine algorithm'''
+        def __init__(self, svmType = cv2.SVM_C_SVC, kernelType = cv2.SVM_RBF, degree = 0, gamma = 1, coef0 = 0, Cvalue = 1, nu = 0, p = 0):
+            self.model = cv2.SVM()
+            self.params = dict(svm_type = svmType, kernel_type = kernelType, degree = degree, gamma = gamma, coef0 = coef0, Cvalue = Cvalue, nu = nu, p = p)
+            # OpenCV3
+            # self.model = cv2.SVM()
+            # self.model.setType(svmType)
+            # self.model.setKernel(kernelType)
+            # self.model.setDegree(degree)
+            # self.model.setGamma(gamma)
+            # self.model.setCoef0(coef0)
+            # self.model.setC(Cvalue)
+            # self.model.setNu(nu)
+            # self.model.setP(p)
 
-    def train(self, samples, responses, computePerformance = False):
-        self.model.train(samples, responses, params = self.params)
-        if computePerformance:
-            return computeConfusionMatrix(self, samples, responses)
+        def train(self, samples, responses, computePerformance = False):
+            self.model.train(samples, responses, params = self.params)
+            if computePerformance:
+                return computeConfusionMatrix(self, samples, responses)
 
-    def predict(self, hog):
-        return self.model.predict(hog)
+        def predict(self, hog):
+            return self.model.predict(hog)
 
 
 #####################
--- a/python/moving.py	Tue Feb 06 11:50:43 2018 -0500
+++ b/python/moving.py	Thu Feb 08 05:53:50 2018 -0500
@@ -114,7 +114,7 @@
             if isinstance(i, int):
                 return self.first+i
             else:
-                raise TypeError, "Invalid argument type."
+                raise TypeError("Invalid argument type.")
             #elif isinstance( key, slice ):
 
     def __iter__(self):
@@ -697,7 +697,7 @@
         elif isinstance(i, slice):
             return Trajectory([self.positions[0][i],self.positions[1][i]])
         else:
-            raise TypeError, "Invalid argument type."
+            raise TypeError("Invalid argument type.")
 
     def __str__(self):
         return ' '.join([self.__getitem__(i).__str__() for i in xrange(self.length())])
@@ -792,7 +792,7 @@
     def add(self, traj2):
         '''Returns a new trajectory of the same length'''
         if self.length() != traj2.length():
-            print 'Trajectories of different lengths'
+            print('Trajectories of different lengths')
             return None
         else:
             return Trajectory([[a+b for a,b in zip(self.getXCoordinates(),traj2.getXCoordinates())],
@@ -801,7 +801,7 @@
     def subtract(self, traj2):
         '''Returns a new trajectory of the same length'''
         if self.length() != traj2.length():
-            print 'Trajectories of different lengths'
+            print('Trajectories of different lengths')
             return None
         else:
             return Trajectory([[a-b for a,b in zip(self.getXCoordinates(),traj2.getXCoordinates())],
@@ -1048,7 +1048,7 @@
         if isinstance(i, int):
             return [self.positions[0][i], self.positions[1][i], self.lanes[i]]
         else:
-            raise TypeError, "Invalid argument type."
+            raise TypeError("Invalid argument type.")
             #elif isinstance( key, slice ):
 
     def getSCoordinates(self):
@@ -1200,7 +1200,7 @@
                 obj.velocities = self.velocities.getTrajectoryInInterval(trajectoryInterval)
             return obj
         else:
-            print 'The object does not exist at '+str(inter)
+            print('The object does not exist at {}'.format(inter))
             return None
 
     def getObjectsInMask(self, mask, homography = None, minLength = 1):
@@ -1874,7 +1874,7 @@
                 mismatches.append(previousMatches[a])
         if debug: 
             for mm in set(mismatches):
-                print type(mm), mm.getNum()
+                print('{} {}'.format(type(mm), mm.getNum()))
         # some object mismatches may appear twice
         mme += len(set(mismatches))
         
--- a/python/storage.py	Tue Feb 06 11:50:43 2018 -0500
+++ b/python/storage.py	Thu Feb 08 05:53:50 2018 -0500
@@ -880,7 +880,7 @@
     try:
         return open(filename, option)
     except IOError:
-        print 'File {} could not be opened.'.format(filename)
+        print('File {} could not be opened.'.format(filename))
         if quitting:
             from sys import exit
             exit()
@@ -952,7 +952,7 @@
     return read_csv(filename, delimiter = ',', names = headers)
         
 def generatePDLaneColumn(data):
-    data['LANE'] = data['LANE\LINK\NO'].astype(str)+'_'+data['LANE\INDEX'].astype(str)
+    data['LANE'] = data['LANE\\LINK\\NO'].astype(str)+'_'+data['LANE\\INDEX'].astype(str)
 
 def convertTrajectoriesVissimToSqlite(filename):
     '''Relies on a system call to sqlite3
@@ -1098,7 +1098,7 @@
     if filename.endswith(".fzp"):
         columns = ['NO', '$VEHICLE:SIMSEC', 'POS']
         if lanes is not None:
-            columns += ['LANE\LINK\NO', 'LANE\INDEX']
+            columns += ['LANE\\LINK\\NO', 'LANE\\INDEX']
         data = read_csv(filename, delimiter=';', comment='*', header=0, skiprows = 1, usecols = columns, low_memory = lowMemory)
         data = selectPDLanes(data, lanes)
         data.sort(['$VEHICLE:SIMSEC'], inplace = True)
@@ -1128,15 +1128,15 @@
     (if the time are closer than collisionTimeDifference)
     If lanes is not None, only the data for the selected lanes will be provided
     (format as string x_y where x is link index and y is lane index)'''
-    data = read_csv(filename, delimiter=';', comment='*', header=0, skiprows = 1, usecols = ['LANE\LINK\NO', 'LANE\INDEX', '$VEHICLE:SIMSEC', 'NO', 'POS'], low_memory = lowMemory)
+    data = read_csv(filename, delimiter=';', comment='*', header=0, skiprows = 1, usecols = ['LANE\\LINK\\NO', 'LANE\\INDEX', '$VEHICLE:SIMSEC', 'NO', 'POS'], low_memory = lowMemory)
     data = selectPDLanes(data, lanes)
     data = data.convert_objects(convert_numeric=True)
 
-    merged = merge(data, data, how='inner', left_on=['LANE\LINK\NO', 'LANE\INDEX', '$VEHICLE:SIMSEC'], right_on=['LANE\LINK\NO', 'LANE\INDEX', '$VEHICLE:SIMSEC'], sort = False)
+    merged = merge(data, data, how='inner', left_on=['LANE\\LINK\\NO', 'LANE\\INDEX', '$VEHICLE:SIMSEC'], right_on=['LANE\\LINK\\NO', 'LANE\\INDEX', '$VEHICLE:SIMSEC'], sort = False)
     merged = merged[merged['NO_x']>merged['NO_y']]
 
     nCollisions = 0
-    for name, group in merged.groupby(['LANE\LINK\NO', 'LANE\INDEX', 'NO_x', 'NO_y']):
+    for name, group in merged.groupby(['LANE\\LINK\\NO', 'LANE\\INDEX', 'NO_x', 'NO_y']):
         diff = group['POS_x']-group['POS_y']
         # diff = group['POS_x']-group['POS_y'] # to check the impact of convert_objects and the possibility of using type conversion in read_csv or function to convert strings if any
         if len(diff) >= 2 and npmin(diff) < 0 and npmax(diff) > 0:
@@ -1188,7 +1188,7 @@
         if obj.getNum() != int(numbers[0]):
             # check and adapt the length to deal with issues in NGSIM data
             if (obj.length() != obj.positions.length()):
-                print 'length pb with object %s (%d,%d)' % (obj.getNum(),obj.length(),obj.positions.length())
+                print('length pb with object {} ({},{})'.format(obj.getNum(),obj.length(),obj.positions.length()))
                 obj.last = obj.getFirstInstant()+obj.positions.length()-1
                 #obj.velocities = utils.computeVelocities(f.positions) # compare norm to speeds ?
             objects.append(obj)
@@ -1206,9 +1206,9 @@
             obj.timeHeadways.append(float(numbers[17]))
 
             if (obj.size[0] != float(numbers[8])):
-                print 'changed length obj %d' % (obj.getNum())
+                print('changed length obj {}'.format(obj.getNum()))
             if (obj.size[1] != float(numbers[9])):
-                print 'changed width obj %d' % (obj.getNum())
+                print('changed width obj {}'.format(obj.getNum()))
     
     inputfile.close()
     return objects
@@ -1227,7 +1227,7 @@
         nObjectsPerType[f.userType-1] += 1
         f.write(out)
 
-    print nObjectsPerType
+    print(nObjectsPerType)
         
     out.close()
 
--- a/python/utils.py	Tue Feb 06 11:50:43 2018 -0500
+++ b/python/utils.py	Thu Feb 08 05:53:50 2018 -0500
@@ -421,7 +421,7 @@
         for x in independentVariableValues:
             print('Shapiro-Wilk normality test for {} when {}={}: {} obs'.format(dependentVariable,independentVariable, x, len(tmp.loc[tmp[independentVariable] == x, dependentVariable])))
             if len(tmp.loc[tmp[independentVariable] == x, dependentVariable]) >= 3:
-                print shapiro(tmp.loc[tmp[independentVariable] == x, dependentVariable])
+                print(shapiro(tmp.loc[tmp[independentVariable] == x, dependentVariable]))
         if plotFigure:
             plt.figure()
             plt.boxplot([tmp.loc[tmp[independentVariable] == x, dependentVariable] for x in independentVariableValues])
@@ -442,7 +442,7 @@
                       +'\\end{minipage}\n'
                       +'\\ \\vspace{0.5cm}\n')
         else:
-            print table
+            print(table)
         return testResult
     else:
         return None