changeset 777:ef6dd60be2e1 dev

added function to save feature trajectories
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Fri, 05 Feb 2016 17:19:13 -0500
parents 84420159c5f4
children bd684e57c431
files python/storage.py python/tests/storage.txt
diffstat 2 files changed, 73 insertions(+), 59 deletions(-) [+]
line wrap: on
line diff
--- a/python/storage.py	Fri Feb 05 17:17:12 2016 -0500
+++ b/python/storage.py	Fri Feb 05 17:19:13 2016 -0500
@@ -89,38 +89,6 @@
     except sqlite3.OperationalError as error:
         printDBError(error)
 
-# TODO: add test if database connection is open
-# IO to sqlite
-def writeTrajectoriesToSqlite(objects, outputFilename, trajectoryType, objectNumbers = -1):
-    """
-    This function writers trajectories to a specified sqlite file
-    @param[in] objects -> a list of trajectories
-    @param[in] trajectoryType -
-    @param[out] outputFilename -> the .sqlite file containting the written objects
-    @param[in] objectNumber : number of objects loaded
-    """
-    connection = sqlite3.connect(outputFilename)
-    cursor = connection.cursor()
-
-    schema = "CREATE TABLE IF NOT EXISTS \"positions\"(trajectory_id INTEGER,frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))"
-    cursor.execute(schema)
-
-    trajectory_id = 0
-    frame_number = 0
-    if trajectoryType == 'feature':
-        if type(objectNumbers) == int and objectNumbers == -1:
-            for trajectory in objects:
-                trajectory_id += 1
-                frame_number = 0
-                for position in trajectory.getPositions():
-                    frame_number += 1
-                    query = "insert into positions (trajectory_id, frame_number, x_coordinate, y_coordinate) values (?,?,?,?)"
-                    cursor.execute(query,(trajectory_id,frame_number,position.x,position.y))
-                    
-    connection.commit()
-    connection.close()
-    
-
 def loadPrototypeMatchIndexesFromSqlite(filename):
     """
     This function loads the prototypes table in the database of name <filename>.
@@ -185,7 +153,7 @@
                 queryStatement += ' WHERE object_id '+objectCriteria
             queryStatement += ' ORDER BY object_id, frame_number'
         else:
-            print('no trajectory type was chosen')
+            print('Unknown trajectory type {}'.format(trajectoryType))
         if queryStatement is not None:
             cursor.execute(queryStatement)
             logging.debug(queryStatement)
@@ -227,7 +195,10 @@
     return userTypes
 
 def loadTrajectoriesFromSqlite(filename, trajectoryType, objectNumbers = None, withFeatures = False):
-    '''Loads the first objectNumbers objects or the indices in objectNumbers from the database'''
+    '''Loads the trajectories (in the general sense, 
+    either features, objects (feature groups) or bounding box series) 
+    The number loaded is either the first objectNumbers objects,
+    or the indices in objectNumbers from the database'''
     connection = sqlite3.connect(filename)
 
     objects = loadTrajectoriesFromTable(connection, 'positions', trajectoryType, objectNumbers)
@@ -457,37 +428,55 @@
     connection.close()
     return boundingBoxes
 
+def saveTrajectoriesToSqlite(outputFilename, objects, trajectoryType, withFeatures = False):
+    '''Writes features, ie the trajectories positions (and velocities if exist)
+    with their instants to a specified sqlite file
+
+    TODO: Not implemented for other trajectoryType than features
+    For objects, with features will control whether the features
+    corresponding to the object are also saved'''
+
+    connection = sqlite3.connect(outputFilename)
+    try:
+        cursor = connection.cursor()
+
+        if trajectoryType == 'feature':
+            cursor.execute("CREATE TABLE IF NOT EXISTS positions (trajectory_id INTEGER, frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))")
+            cursor.execute("CREATE TABLE IF NOT EXISTS velocities (trajectory_id INTEGER, frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))")
+
+            positionQuery = "insert into positions (trajectory_id, frame_number, x_coordinate, y_coordinate) values (?,?,?,?)"
+            velocityQuery = "insert into velocities (trajectory_id, frame_number, x_coordinate, y_coordinate) values (?,?,?,?)"
+            for obj in objects:
+                num = obj.getNum()
+                frame_number = obj.getFirstInstant()
+                for position in obj.getPositions():
+                    cursor.execute(positionQuery, (num, frame_number, position.x, position.y))
+                    frame_number += 1
+                if obj.getVelocities() is not None:
+                    frame_number = obj.getFirstInstant()
+                    velocities = obj.getVelocities()
+                    for i in xrange(velocities.length()-1):
+                        v = velocities[i]
+                        cursor.execute(velocityQuery, (num, frame_number, v.x, v.y))
+                        frame_number += 1
+            connection.commit()
+        #elif trajectoryType == 'feature':
+        else:
+            print('Unknown trajectory type {}'.format(trajectoryType))
+    except sqlite3.OperationalError as error:
+        printDBError(error)
+    connection.close()
+
 #########################
 # saving and loading for scene interpretation (Mohamed Gomaa Mohamed's PhD)
 #########################
 
-def writeFeaturesToSqlite(objects, outputFilename, trajectoryType, objectNumbers = -1):
-    '''write features trajectories maintain trajectory ID,velocities dataset  '''
-    connection = sqlite3.connect(outputFilename)
-    cursor = connection.cursor()
-
-    cursor.execute("CREATE TABLE IF NOT EXISTS \"positions\"(trajectory_id INTEGER,frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))")
-    cursor.execute("CREATE TABLE IF NOT EXISTS \"velocities\"(trajectory_id INTEGER,frame_number INTEGER, x_coordinate REAL, y_coordinate REAL, PRIMARY KEY(trajectory_id, frame_number))")
-    
-    if trajectoryType == 'feature':
-        if type(objectNumbers) == int and objectNumbers == -1:
-            for trajectory in objects:
-                trajectory_id = trajectory.num
-                frame_number = trajectory.timeInterval.first
-                for position,velocity in zip(trajectory.getPositions(),trajectory.getVelocities()):
-                    cursor.execute("insert into positions (trajectory_id, frame_number, x_coordinate, y_coordinate) values (?,?,?,?)",(trajectory_id,frame_number,position.x,position.y))
-                    cursor.execute("insert into velocities (trajectory_id, frame_number, x_coordinate, y_coordinate) values (?,?,?,?)",(trajectory_id,frame_number,velocity.x,velocity.y))
-                    frame_number += 1
-                    
-    connection.commit()
-    connection.close()
-    
 def writePrototypesToSqlite(prototypes,nMatching, outputFilename):
     """ prototype dataset is a dictionary with  keys== routes, values== prototypes Ids """
     connection = sqlite3.connect(outputFilename)
     cursor = connection.cursor()
 
-    cursor.execute("CREATE TABLE IF NOT EXISTS \"prototypes\"(prototype_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, nMatching INTEGER, PRIMARY KEY(prototype_id))")
+    cursor.execute("CREATE TABLE IF NOT EXISTS prototypes (prototype_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, nMatching INTEGER, PRIMARY KEY(prototype_id))")
     
     for route in prototypes.keys():
         if prototypes[route]!=[]:
@@ -530,7 +519,7 @@
     connection = sqlite3.connect(outputFilename)
     cursor = connection.cursor()
 
-    cursor.execute("CREATE TABLE IF NOT EXISTS \"labels\"(object_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, prototype_id INTEGER, PRIMARY KEY(object_id))")
+    cursor.execute("CREATE TABLE IF NOT EXISTS labels (object_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, prototype_id INTEGER, PRIMARY KEY(object_id))")
     
     for route in labels.keys():
         if labels[route]!=[]:
@@ -570,7 +559,7 @@
     connection = sqlite3.connect(outFilename)
     cursor = connection.cursor()
 
-    cursor.execute("CREATE TABLE IF NOT EXISTS \"speedprototypes\"(spdprototype_id INTEGER,prototype_id INTEGER,routeID_start INTEGER, routeID_end INTEGER, nMatching INTEGER, PRIMARY KEY(spdprototype_id))")
+    cursor.execute("CREATE TABLE IF NOT EXISTS speedprototypes (spdprototype_id INTEGER,prototype_id INTEGER,routeID_start INTEGER, routeID_end INTEGER, nMatching INTEGER, PRIMARY KEY(spdprototype_id))")
     
     for route in prototypes.keys():
         if prototypes[route]!={}:
@@ -615,7 +604,7 @@
     connection = sqlite3.connect(outputFilename)
     cursor = connection.cursor()
 
-    cursor.execute("CREATE TABLE IF NOT EXISTS \"routes\"(object_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, PRIMARY KEY(object_id))")
+    cursor.execute("CREATE TABLE IF NOT EXISTS routes (object_id INTEGER,routeIDstart INTEGER,routeIDend INTEGER, PRIMARY KEY(object_id))")
     
     for route in Routes.keys():
         if Routes[route]!=[]:
--- a/python/tests/storage.txt	Fri Feb 05 17:17:12 2016 -0500
+++ b/python/tests/storage.txt	Fri Feb 05 17:19:13 2016 -0500
@@ -1,5 +1,6 @@
 >>> from storage import *
 >>> from StringIO import StringIO
+>>> from moving import MovingObject, Point, TimeInterval
 
 >>> f = openCheck('non_existant_file.txt')
 File non_existant_file.txt could not be opened.
@@ -15,6 +16,30 @@
 >>> 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
+>>> saveTrajectoriesToSqlite('test.sqlite', [o1, o2], 'feature')
+>>> objects = loadTrajectoriesFromSqlite('test.sqlite', 'feature')
+>>> objects[0].getNum() == o1.num
+True
+>>> objects[1].getNum() == o2.num
+True
+>>> o1.getTimeInterval() == objects[0].getTimeInterval()
+True
+>>> o2.getTimeInterval() == objects[1].getTimeInterval()
+True
+>>> o1.getVelocities() == objects[0].getVelocities()
+True
+>>> o2.getVelocities() == objects[1].getVelocities()
+True
+>>> o1.getPositions() == objects[0].getPositions()
+True
+>>> o2.getPositions() == objects[1].getPositions()
+True
+>>> remove('test.sqlite')
+
 >>> strio = StringIO('# asdlfjasdlkj0\nsadlkfjsdlakjf')
 >>> readline(strio)
 'sadlkfjsdlakjf'