changeset 918:3a06007a4bb7

modularized save trajectories, added slice to Trajectory, etc
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Wed, 05 Jul 2017 12:19:59 -0400
parents 89cc05867c4c
children 7b3f2e0a2652
files python/moving.py python/storage.py python/tests/events.txt python/tests/moving.txt python/tests/storage.txt
diffstat 5 files changed, 87 insertions(+), 76 deletions(-) [+]
line wrap: on
line diff
--- a/python/moving.py	Tue Jul 04 18:00:01 2017 -0400
+++ b/python/moving.py	Wed Jul 05 12:19:59 2017 -0400
@@ -682,9 +682,10 @@
     def __getitem__(self, i):
         if isinstance(i, int):
             return Point(self.positions[0][i], self.positions[1][i])
+        elif isinstance(i, slice):
+            return Trajectory([self.positions[0][i],self.positions[1][i]])
         else:
             raise TypeError, "Invalid argument type."
-            #elif isinstance( key, slice ):
 
     def __str__(self):
         return ' '.join([self.__getitem__(i).__str__() for i in xrange(self.length())])
@@ -1091,9 +1092,9 @@
         # compute bounding polygon from trajectory
 
     @staticmethod
-    def generate(p, v, timeInterval):
+    def generate(num, p, v, timeInterval):
         positions, velocities = Trajectory.generate(p, v, int(timeInterval.length())) 
-        return MovingObject(timeInterval = timeInterval, positions = positions, velocities = velocities)
+        return MovingObject(num = num, timeInterval = timeInterval, positions = positions, velocities = velocities)
 
     @staticmethod
     def concatenate(obj1, obj2, num = None):
--- a/python/storage.py	Tue Jul 04 18:00:01 2017 -0400
+++ b/python/storage.py	Wed Jul 05 12:19:59 2017 -0400
@@ -375,7 +375,70 @@
     if len(missingObjectNumbers) > 0:
         print('List of missing objects to attach corresponding curvilinear trajectories: {}'.format(missingObjectNumbers))
 
-def saveTrajectoriesToSqlite(outputFilename, objects, trajectoryType, withFeatures = False):
+def saveTrajectoriesToTable(connection, objects, trajectoryType, tablePrefix = None):
+    'Saves trajectories in table tableName'
+    cursor = connection.cursor()
+    # Parse feature and/or object structure and commit to DB
+    if(trajectoryType == 'feature' or trajectoryType == 'object'):
+        # Extract features from objects
+        if trajectoryType == 'object':
+            features = []
+            for obj in objects:
+                if obj.hasFeatures():
+                    features += obj.getFeatures()
+            if len(features) == 0:
+                print('Warning, objects have no features') # todo save centroid trajectories?
+        elif trajectoryType == 'feature':
+            features = objects
+        # Setup feature queries
+        if tablePrefix is None:
+            prefix = ''
+        else:
+            prefix = tablePrefix+'_'
+        createTrajectoryTable(cursor, prefix+"positions")
+        createTrajectoryTable(cursor, prefix+"velocities")
+        positionQuery = insertTrajectoryQuery(prefix+"positions")
+        velocityQuery = insertTrajectoryQuery(prefix+"velocities")
+        # Setup object queries
+        if trajectoryType == 'object':    
+            createObjectsTable(cursor)
+            createObjectsFeaturesTable(cursor)
+            objectQuery = insertObjectQuery()
+            objectFeatureQuery = insertObjectFeatureQuery()
+        for feature in features:
+            num = feature.getNum()
+            frameNum = feature.getFirstInstant()
+            for p in feature.getPositions():
+                cursor.execute(positionQuery, (num, frameNum, p.x, p.y))
+                frameNum += 1
+            velocities = feature.getVelocities()
+            if velocities is not None:
+                frameNum = feature.getFirstInstant()
+                for v in velocities[:-1]:
+                    cursor.execute(velocityQuery, (num, frameNum, v.x, v.y))
+                    frameNum += 1
+        if trajectoryType == 'object':
+            for obj in objects:
+                if obj.hasFeatures():
+                    for feature in obj.getFeatures():
+                        featureNum = feature.getNum()
+                        cursor.execute(objectFeatureQuery, (obj.getNum(), featureNum))
+                cursor.execute(objectQuery, (obj.getNum(), obj.getUserType(), 1))   
+    # Parse curvilinear position structure
+    elif(trajectoryType == 'curvilinear'):
+        createCurvilinearTrajectoryTable(cursor)
+        curvilinearQuery = "insert into curvilinear_positions (trajectory_id, frame_number, s_coordinate, y_coordinate, lane) values (?,?,?,?,?)"
+        for obj in objects:
+            num = obj.getNum()
+            frameNum = obj.getFirstInstant()
+            for p in obj.getCurvilinearPositions():
+                cursor.execute(curvilinearQuery, (num, frameNum, p[0], p[1], p[2]))
+                frameNum += 1
+    else:
+        print('Unknown trajectory type {}'.format(trajectoryType))
+    connection.commit()
+
+def saveTrajectoriesToSqlite(outputFilename, objects, trajectoryType):
     '''Writes features, ie the trajectory positions (and velocities if exist)
     with their instants to a specified sqlite file
     Either feature positions (and velocities if they exist)
@@ -383,60 +446,7 @@
 
     connection = sqlite3.connect(outputFilename)
     try:
-        cursor = connection.cursor()
-        # Parse feature and/or object structure and commit to DB
-        if(trajectoryType == 'feature' or trajectoryType == 'object'):
-            # Extract features from objects
-            if(trajectoryType == 'object'):
-                features = []
-                for obj in objects:
-                    if(obj.hasFeatures()):
-                        features += obj.getFeatures()
-            elif(trajectoryType == 'feature'):
-                features = objects
-            # Setup feature queries
-            createTrajectoryTable(cursor, "positions")
-            createTrajectoryTable(cursor, "velocities")
-            positionQuery = insertTrajectoryQuery("positions")
-            velocityQuery = insertTrajectoryQuery("velocities")
-            # Setup object queries
-            if(trajectoryType == 'object'):    
-                createObjectsTable(cursor)
-                createObjectsFeaturesTable(cursor)
-                objectQuery = insertObjectQuery()
-                objectFeatureQuery = insertObjectFeatureQuery()
-            for feature in features:
-                num = feature.getNum()
-                frameNum = feature.getFirstInstant()
-                for position in feature.getPositions():
-                    cursor.execute(positionQuery, (num, frameNum, position.x, position.y))
-                    frameNum += 1
-                velocities = feature.getVelocities()
-                if velocities is not None:
-                    frameNum = feature.getFirstInstant()
-                    for i in xrange(velocities.length()-1):
-                        v = velocities[i]
-                        cursor.execute(velocityQuery, (num, frameNum, v.x, v.y))
-                        frameNum += 1    
-            if(trajectoryType == 'object'):
-                for obj in objects:
-                    for feature in obj.getFeatures():
-                        featureNum = feature.getNum()
-                        cursor.execute(objectFeatureQuery, (obj.getNum(), featureNum))
-                    cursor.execute(objectQuery, (obj.getNum(), obj.getUserType(), 1))   
-        # Parse curvilinear position structure
-        elif(trajectoryType == 'curvilinear'):
-            createCurvilinearTrajectoryTable(cursor)
-            curvilinearQuery = "insert into curvilinear_positions (trajectory_id, frame_number, s_coordinate, y_coordinate, lane) values (?,?,?,?,?)"
-            for obj in objects:
-                num = obj.getNum()
-                frameNum = obj.getFirstInstant()
-                for position in obj.getCurvilinearPositions():
-                    cursor.execute(curvilinearQuery, (num, frameNum, position[0], position[1], position[2]))
-                    frameNum += 1
-        else:
-            print('Unknown trajectory type {}'.format(trajectoryType))
-        connection.commit()
+        saveTrajectoriesToTable(connection, objects, trajectoryType, None)
     except sqlite3.OperationalError as error:
         printDBError(error)
     connection.close()
@@ -598,7 +608,7 @@
                 dbfn = filename
             cursor.execute('INSERT INTO prototypes (id, dbfilename, trajectory_type, nmatchings, positions_id) VALUES ({},\"{}\",\"{}\",{}, {})'.format(protoId, dbfn, trajectoryType, n, i))
         #cursor.execute('SELECT * from sqlite_master WHERE type = \"table\" and name = \"{}\"'.format(tableNames[trajectoryType]))
-        if objects is not None:
+        if objects is not None: # save positions and velocities
             pass 
     except sqlite3.OperationalError as error:
         printDBError(error)
--- a/python/tests/events.txt	Tue Jul 04 18:00:01 2017 -0400
+++ b/python/tests/events.txt	Wed Jul 05 12:19:59 2017 -0400
@@ -11,8 +11,8 @@
 >>> len([i for i in interactions if len(i.roadUserNumbers) == 1])
 0
 
->>> o1 = MovingObject.generate(Point(-5.,0.), Point(1.,0.), TimeInterval(0,10))
->>> o2 = MovingObject.generate(Point(0.,-5.), Point(0.,1.), TimeInterval(0,10))
+>>> o1 = MovingObject.generate(1, Point(-5.,0.), Point(1.,0.), TimeInterval(0,10))
+>>> o2 = MovingObject.generate(2, Point(0.,-5.), Point(0.,1.), TimeInterval(0,10))
 >>> inter = Interaction(roadUser1 = o1, roadUser2 = o2)
 >>> inter.computeIndicators()
 >>> predictionParams = ConstantPredictionParameters(10.)
--- a/python/tests/moving.txt	Tue Jul 04 18:00:01 2017 -0400
+++ b/python/tests/moving.txt	Wed Jul 05 12:19:59 2017 -0400
@@ -171,14 +171,14 @@
 >>> objects[0].hasFeatures()
 True
 
->>> o1 = MovingObject.generate(Point(-5.,0.), Point(1.,0.), TimeInterval(0,10))
->>> o2 = MovingObject.generate(Point(0.,-5.), Point(0.,1.), TimeInterval(0,10))
+>>> o1 = MovingObject.generate(1, Point(-5.,0.), Point(1.,0.), TimeInterval(0,10))
+>>> o2 = MovingObject.generate(2, Point(0.,-5.), Point(0.,1.), TimeInterval(0,10))
 >>> MovingObject.computePET(o1, o2, 0.1)
 (0.0, 5, 5)
->>> o2 = MovingObject.generate(Point(0.,-5.), Point(0.,1.), TimeInterval(5,15))
+>>> o2 = MovingObject.generate(2, Point(0.,-5.), Point(0.,1.), TimeInterval(5,15))
 >>> MovingObject.computePET(o1, o2, 0.1)
 (5.0, 5, 10)
->>> o2 = MovingObject.generate(Point(0.,-5.), Point(0.,1.), TimeInterval(15,30))
+>>> o2 = MovingObject.generate(2, Point(0.,-5.), Point(0.,1.), TimeInterval(15,30))
 >>> MovingObject.computePET(o1, o2, 0.1)
 (15.0, 5, 20)
 
@@ -191,7 +191,7 @@
 >>> t.differentiate().empty()
 True
 
->>> o1 = MovingObject.generate(Point(0., 2.), Point(0., 1.), TimeInterval(0,2))
+>>> o1 = MovingObject.generate(1, Point(0., 2.), Point(0., 1.), TimeInterval(0,2))
 >>> o1.classifyUserTypeSpeedMotorized(0.5, np.median)
 >>> userTypeNames[o1.getUserType()]
 'car'
@@ -199,8 +199,8 @@
 >>> userTypeNames[o1.getUserType()]
 'pedestrian'
 
->>> o1 = MovingObject.generate(Point(0.,0.), Point(1.,0.), TimeInterval(0,10))
->>> gt1 = BBMovingObject(1, TimeInterval(0,10), MovingObject.generate(Point(0.2,0.6), Point(1.,0.), TimeInterval(0,10)), MovingObject.generate(Point(-0.2,-0.4), Point(1.,0.), TimeInterval(0,10)))
+>>> o1 = MovingObject.generate(1, Point(0.,0.), Point(1.,0.), TimeInterval(0,10))
+>>> gt1 = BBMovingObject(1, TimeInterval(0,10), MovingObject.generate(1, Point(0.2,0.6), Point(1.,0.), TimeInterval(0,10)), MovingObject.generate(2, Point(-0.2,-0.4), Point(1.,0.), TimeInterval(0,10)))
 >>> gt1.computeCentroidTrajectory()
 >>> computeClearMOT([gt1], [], 0.2, 0, 10)
 (None, 0.0, 11, 0, 0, 11)
--- a/python/tests/storage.txt	Tue Jul 04 18:00:01 2017 -0400
+++ b/python/tests/storage.txt	Wed Jul 05 12:19:59 2017 -0400
@@ -16,10 +16,8 @@
 >>> from os import remove
 >>> remove(nonexistentFilename)
 
->>> o1 = MovingObject.generate(Point(0.,0.), Point(1.,0.), TimeInterval(0,10))
->>> o1.num = 2
->>> o2 = MovingObject.generate(Point(1.,1.), Point(-0.5,-0.2), TimeInterval(0,9))
->>> o2.num = 3
+>>> o1 = MovingObject.generate(2, Point(0.,0.), Point(1.,0.), TimeInterval(0,10))
+>>> o2 = MovingObject.generate(3, Point(1.,1.), Point(-0.5,-0.2), TimeInterval(0,9))
 >>> saveTrajectoriesToSqlite('test.sqlite', [o1, o2], 'feature')
 >>> objects = loadTrajectoriesFromSqlite('test.sqlite', 'feature')
 >>> objects[0].getNum() == o1.num
@@ -30,6 +28,10 @@
 True
 >>> o2.getTimeInterval() == objects[1].getTimeInterval()
 True
+>>> o1.getVelocities().length() == objects[0].getVelocities().length()
+True
+>>> o2.getVelocities().length() == objects[1].getVelocities().length()
+True
 >>> o1.getVelocities() == objects[0].getVelocities()
 True
 >>> o2.getVelocities() == objects[1].getVelocities()
@@ -71,10 +73,8 @@
 True
 >>> remove('test.sqlite')
 
->>> f1 = MovingObject.generate(Point(0.,0.), Point(1.,0.), TimeInterval(0,10))
->>> f1.num = 3
->>> f2 = MovingObject.generate(Point(1.,1.), Point(-0.5,-0.2), TimeInterval(0,9))
->>> f2.num = 4
+>>> f1 = MovingObject.generate(3, Point(0.,0.), Point(1.,0.), TimeInterval(0,10))
+>>> f2 = MovingObject.generate(4, Point(1.,1.), Point(-0.5,-0.2), TimeInterval(0,9))
 >>> o1 = MovingObject(num = 1, userType = 1)
 >>> o1.features = [f1, f2]
 >>> saveTrajectoriesToSqlite('test.sqlite', [o1], 'object')