changeset 546:6c0923f1ce68

add some functions for behaviour analysis
author MohamedGomaa
date Thu, 03 Jul 2014 14:30:20 -0400
parents bd1ad468e928
children 97c5fef5b2d6
files python/moving.py python/storage.py
diffstat 2 files changed, 167 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/python/moving.py	Thu Jul 03 13:57:32 2014 -0400
+++ b/python/moving.py	Thu Jul 03 14:30:20 2014 -0400
@@ -450,6 +450,7 @@
     def __repr__(self):
         return self.__str__()
 
+
     def __iter__(self):
         self.iterInstantNum = 0
         return self
@@ -803,6 +804,17 @@
         return MovingObject.distances(obj1, obj2, instant).min()
 
     @staticmethod
+    def distances2(obj1, obj2, instant1,instant2):
+        from scipy.spatial.distance import cdist
+        positions1 = [f.getPositionAtInstant(instant1).astuple() for f in obj1.features if f.existsAtInstant(instant1)]
+        positions2 = [f.getPositionAtInstant(instant2).astuple() for f in obj2.features if f.existsAtInstant(instant2)]
+        return cdist(positions1, positions2, metric = 'euclidean')
+        
+    @staticmethod
+    def minDistance2(obj1, obj2, instant1,instant2):
+        return MovingObject.distances2(obj1, obj2, instant1,instant2).min()
+
+    @staticmethod
     def maxDistance(obj1, obj2, instant):
         return MovingObject.distances(obj1, obj2, instant).max()
 
@@ -821,7 +833,11 @@
         else:
             print('Load features to compute a maximum size')
             return None
-            
+			
+    def setRoutes(self,startCode,endCode):
+        self.startRouteID=startCode
+        self.endRouteID=endCode
+           
     def getInstantsCrossingLane(self, p1, p2):
         '''Returns the instant(s)
         at which the object passes from one side of the segment to the other
@@ -942,6 +958,7 @@
         # what to do: threshold for most common type? self.setUserType()
         return possibleUserTypes
 
+
     @staticmethod
     def collisionCourseDotProduct(movingObject1, movingObject2, instant):
         'A positive result indicates that the road users are getting closer'
--- a/python/storage.py	Thu Jul 03 13:57:32 2014 -0400
+++ b/python/storage.py	Thu Jul 03 14:30:20 2014 -0400
@@ -63,6 +63,155 @@
                     
     connection.commit()
     connection.close()
+	
+def writeFeaturesToSqlite(objects, outFilename, trajectoryType, objectNumbers = -1):
+	'''write features trajectories maintain trajectory ID,velocities dataset  '''
+    connection = sqlite3.connect(outFilename)
+    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, outFilename):
+    """ prototype dataset is a dictionary with  keys== routes, values== prototypes Ids """
+    connection = sqlite3.connect(outFilename)
+    cursor = connection.cursor()
+
+    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]!=[]:
+            for i in prototypes[route]:
+                cursor.execute("insert into prototypes (prototype_id, routeIDstart,routeIDend, nMatching) values (?,?,?,?)",(i,route[0],route[1],nMatching[route][i]))
+                    
+    connection.commit()
+    connection.close()
+	
+def loadPrototypesFromSqlite(filename):
+    """
+    This function loads the prototype file in the database 
+    It returns a dictionary for prototypes for each route and nMatching
+    """
+    prototypes = {}
+    nMatching={}
+
+    connection = sqlite3.connect(filename)
+    cursor = connection.cursor()
+
+    try:
+        cursor.execute('SELECT * from prototypes order by prototype_id, routeIDstart,routeIDend, nMatching')
+    except sqlite3.OperationalError as error:
+        utils.printDBError(error)
+        return []
+
+    for row in cursor:
+        route=(row[1],row[2])
+        if route not in prototypes.keys():
+            prototypes[route]=[]
+        prototypes[route].append(row[0])
+        nMatching[row[0]]=row[3]
+
+    connection.close()
+    return prototypes,nMatching
+	
+def writeLabelsToSqlite(labels, outFilename):
+    """ labels is a dictionary with  keys: routes, values: prototypes Ids
+    """
+    connection = sqlite3.connect(outFilename)
+    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))")
+	
+    for route in labels.keys():
+        if labels[route]!=[]:
+            for i in labels[route]:
+                for j in labels[route][i]:
+                    cursor.execute("insert into labels (object_id, routeIDstart,routeIDend, prototype_id) values (?,?,?,?)",(j,route[0],route[1],i))
+                    
+    connection.commit()
+    connection.close()
+	
+def loadLabelsFromSqlite(filename):
+    labels = {}
+
+    connection = sqlite3.connect(filename)
+    cursor = connection.cursor()
+
+    try:
+        cursor.execute('SELECT * from labels order by object_id, routeIDstart,routeIDend, prototype_id')
+    except sqlite3.OperationalError as error:
+        utils.printDBError(error)
+        return []
+
+    for row in cursor:
+        route=(row[1],row[2])
+        p=row[3]
+        if route not in labels.keys():
+            labels[route]={}
+        if p not in labels[route].keys():
+            labels[route][p]=[]
+        labels[route][p].append(row[0])
+
+    connection.close()
+    return labels
+
+def writeRoutesToSqlite(Routes, outFilename):
+    """ This function writes the activity path define by start and end IDs"""
+    connection = sqlite3.connect(outFilename)
+    cursor = connection.cursor()
+
+    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]!=[]:
+            for i in Routes[route]:
+                cursor.execute("insert into routes (object_id, routeIDstart,routeIDend) values (?,?,?)",(i,route[0],route[1]))
+                    
+    connection.commit()
+    connection.close()
+	
+def loadRoutesFromSqlite(filename):
+    Routes = {}
+
+    connection = sqlite3.connect(filename)
+    cursor = connection.cursor()
+
+    try:
+        cursor.execute('SELECT * from routes order by object_id, routeIDstart,routeIDend')
+    except sqlite3.OperationalError as error:
+        utils.printDBError(error)
+        return []
+
+    for row in cursor:
+        route=(row[1],row[2])
+        if route not in Routes.keys():
+            Routes[route]=[]
+        Routes[route].append(row[0])
+
+    connection.close()
+    return Routes	
+
+def setRoutes(filename, objects):
+    connection = sqlite3.connect(filename)
+    cursor = connection.cursor()
+    for obj in objects:
+        cursor.execute('update objects set startRouteID = {} where object_id = {}'.format(obj.startRouteID, obj.getNum()))
+        cursor.execute('update objects set endRouteID = {} where object_id = {}'.format(obj.endRouteID, obj.getNum()))	        
+    connection.commit()
+    connection.close()
 
 def setRoadUserTypes(filename, objects):
     '''Saves the user types of the objects in the sqlite database stored in filename