changeset 343:74e437ab5f11

first version of indicator loading code
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Fri, 21 Jun 2013 15:28:59 -0400
parents 4d69486869a5
children 14a2405f54f8
files python/moving.py python/storage.py scripts/safety-analysis.py
diffstat 3 files changed, 54 insertions(+), 32 deletions(-) [+]
line wrap: on
line diff
--- a/python/moving.py	Thu Jun 20 15:47:33 2013 -0400
+++ b/python/moving.py	Fri Jun 21 15:28:59 2013 -0400
@@ -399,6 +399,10 @@
     def addPosition(self, p):
         self.addPositionXY(p.x, p.y)
 
+    def duplicateLastPosition(self):
+        self.positions[0].append(self.positions[0][-1])
+        self.positions[1].append(self.positions[1][-1])
+
     @staticmethod
     def _draw(positions, options = '', withOrigin = False, lastCoordinate = None, timeStep = 1, **kwargs):
         from matplotlib.pylab import plot
--- a/python/storage.py	Thu Jun 20 15:47:33 2013 -0400
+++ b/python/storage.py	Fri Jun 21 15:28:59 2013 -0400
@@ -2,7 +2,9 @@
 # -*- coding: utf-8 -*-
 '''Various utilities to save and load data'''
 
-import utils, moving, events
+import utils, moving, events, indicators
+
+import sqlite3
 
 __metaclass__ = type
 
@@ -23,8 +25,6 @@
     @param[out] outFile -> the .sqlite file containting the written objects
     @param[in] objectNumber : number of objects loaded
     """
-
-    import sqlite3    
     connection = sqlite3.connect(outFilename)
     cursor = connection.cursor()
 
@@ -49,7 +49,6 @@
 def setRoadUserTypes(filename, objects):
     '''Saves the user types of the objects in the sqlite database stored in filename
     The objects should exist in the objects table'''
-    import sqlite3
     connection = sqlite3.connect(filename)
     cursor = connection.cursor()
     for obj in objects:
@@ -58,7 +57,7 @@
     connection.close()
 
 def printDBError(error):
-    print('DB Error: {0}'.format(err))
+    print('DB Error: {0}'.format(error))
 
 def loadPrototypeMatchIndexesFromSqlite(filename):
     """
@@ -67,7 +66,6 @@
     """
     matched_indexes = []
 
-    import sqlite3    
     connection = sqlite3.connect(filename)
     cursor = connection.cursor()
 
@@ -105,8 +103,6 @@
     can be positions or velocities
 
     returns a moving object'''
-    import sqlite3
-
     cursor = connection.cursor()
 
     try:
@@ -145,8 +141,6 @@
     TODO: load feature numbers and not average feature trajectories
     TODO: other ways of averaging trajectories (load all points, sorted by frame_number and leave the agregation to be done in python)
     '''
-    import sqlite3
-    
     connection = sqlite3.connect(filename) # add test if it open
 
     objects = loadTrajectoriesFromTable(connection, 'positions', trajectoryType, objectNumbers)
@@ -156,6 +150,7 @@
         for o,v in zip(objects, objectVelocities):
             if o.getNum() == v.getNum():
                 o.velocities = v.positions
+                o.velocities.duplicateLastPosition() # avoid having velocity shorter by one position than positions
             else:
                 print('Could not match positions {0} with velocities {1}'.format(o.getNum(), v.getNum()))
 
@@ -198,7 +193,6 @@
 
 def removeObjectsFromSqlite(filename):
     'Removes the objects and object_features tables in the filename'
-    import sqlite3
     connection = sqlite3.connect(filename)
     utils.dropTables(connection, ['objects', 'objects_features'])
     connection.close()
@@ -208,7 +202,7 @@
     pass
 
 def createInteractionTable(cursor):
-    cursor.execute('CREATE TABLE IF NOT EXISTS interactions (id INTEGER PRIMARY KEY, object_id1 INTEGER, object_id2 INTEGER, FOREIGN KEY(object_id1) REFERENCES objects(id), FOREIGN KEY(object_id2) REFERENCES objects(id))')
+    cursor.execute('CREATE TABLE IF NOT EXISTS interactions (id INTEGER PRIMARY KEY, object_id1 INTEGER, object_id2 INTEGER, first_frame_number INTEGER, last_frame_number INTEGER, FOREIGN KEY(object_id1) REFERENCES objects(id), FOREIGN KEY(object_id2) REFERENCES objects(id))')
 
 def createIndicatorTables(cursor):
     # cursor.execute('CREATE TABLE IF NOT EXISTS indicators (id INTEGER PRIMARY KEY, interaction_id INTEGER, indicator_type INTEGER, FOREIGN KEY(interaction_id) REFERENCES interactions(id))')
@@ -217,11 +211,10 @@
 
 def saveInteraction(cursor, interaction):
     roadUserNumbers = list(interaction.getRoadUserNumbers())
-    cursor.execute('INSERT INTO interactions VALUES({}, {}, {})'.format(interaction.getNum(), roadUserNumbers[0], roadUserNumbers[1]))
+    cursor.execute('INSERT INTO interactions VALUES({}, {}, {}, {}, {})'.format(interaction.getNum(), roadUserNumbers[0], roadUserNumbers[1], interaction.getFirstInstant(), interaction.getLastInstant()))
 
 def saveInteractions(filename, interactions):
     'Saves the interactions in the table'
-    import sqlite3
     connection = sqlite3.connect(filename)
     cursor = connection.cursor()
     try:
@@ -238,9 +231,8 @@
         if indicator[instant]:
             cursor.execute('INSERT INTO indicators VALUES({}, {}, {}, {})'.format(interactionNum, events.Interaction.indicatorNameToIndices[indicator.getName()], instant, indicator[instant]))
 
-def saveIndicators(filename, interactions, indicatorNames):
+def saveIndicators(filename, interactions, indicatorNames = events.Interaction.indicatorNames):
     'Saves the indicator values in the table'
-    import sqlite3
     connection = sqlite3.connect(filename)
     cursor = connection.cursor()
     try:
@@ -258,26 +250,46 @@
     connection.close()
 
 def loadIndicators(filename):
-    indicators = []
+    '''Loads interaction indicators
+    
+    TODO choose the interactions to load'''
+    interactions = []
     connection = sqlite3.connect(filename)
     cursor = connection.cursor()
     try:
-        cursor.execute('select INT.id, INT.object_id1, INT.object_id2, IND.indicator_type, IND.frame_number, IND.value from interactions INT, indicators IND where INT.id = IND.interaction_id, ORDER BY INT.id, IND.indicator_type')
+        cursor.execute('select INT.id, INT.object_id1, INT.object_id2, INT.first_frame_number, INT.last_frame_number, IND.indicator_type, IND.frame_number, IND.value from interactions INT, indicators IND where INT.id = IND.interaction_id ORDER BY INT.id, IND.indicator_type')
         interactionNum = -1
         indicatorTypeNum = -1
+        tmpIndicators = {}
         for row in cursor:
-            if row[0] != interactionNum:
-                if indicatorNum >= 0:
-                    interactions.append(events.Interaction(interactionNum, moving.TimeInterval(), roadUserNumbers[0], roadUserNumbers[1])) # todo time interval from distance indicator (if available) and link to road user objects
+            if row[0] != interactionNum: # save interaction and create new interaction
+                if interactionNum >= 0:
+                    interactions.append(events.Interaction(interactionNum, moving.TimeInterval(row[3],row[4]), roadUserNumbers[0], roadUserNumbers[1]))
+                    interactions[-1].indicators = tmpIndicators
+                    tmpIndicators = {}
                 interactionNum = row[0]
                 roadUserNumbers = row[1:3]
-                indicatorName = events.Interaction.indicatorNames[row[3]]
-                indicatorValues = {row[4]:row[5]}
-                # test when new interaction or new indicator indicatorTypeNum != row[3]
-
+            if indicatorTypeNum != row[5]:
+                if indicatorTypeNum >= 0:
+                    indicatorName = events.Interaction.indicatorNames[indicatorTypeNum]
+                    tmpIndicators[indicatorName] = indicators.SeverityIndicator(indicatorName, indicatorValues)
+                indicatorTypeNum = row[5]
+                indicatorValues = {row[6]:row[7]}
+            else:
+                indicatorValues[row[6]] = row[7]
+        if interactionNum >= 0:
+            if indicatorTypeNum >= 0:
+                indicatorName = events.Interaction.indicatorNames[indicatorTypeNum]
+                tmpIndicators[indicatorName] = indicators.SeverityIndicator(indicatorName, indicatorValues)
+            interactions.append(events.Interaction(interactionNum, moving.TimeInterval(row[3],row[4]), roadUserNumbers[0], roadUserNumbers[1]))
+            interactions[-1].indicators = tmpIndicators
     except sqlite3.OperationalError as error:
         printDBError(error)
+        return []
     connection.close()
+    return interactions
+# load first and last object instants
+# CREATE TEMP TABLE IF NOT EXISTS object_instants AS SELECT OF.object_id, min(frame_number) as first_instant, max(frame_number) as last_instant from positions P, objects_features OF where P.trajectory_id = OF.trajectory_id group by OF.object_id order by OF.object_id
 
 
 #########################
--- a/scripts/safety-analysis.py	Thu Jun 20 15:47:33 2013 -0400
+++ b/scripts/safety-analysis.py	Fri Jun 21 15:28:59 2013 -0400
@@ -27,6 +27,8 @@
 collisionDistanceThreshold= 1.8 # m
 computeCZ = True
 
+display = False
+
 # parameters for prediction methods
 constantVelocityPredictionParameters = prediction.ConstantPredictionParameters(maxSpeed)
 
@@ -52,14 +54,18 @@
 
 interactions = events.createInteractions(objects)
 for inter in interactions[:2]:
-    inter.computeCrossingsCollisions(constantVelocityPredictionParameters, collisionDistanceThreshold, timeHorizon, computeCZ)
+    inter.computeIndicators()
+    # inter.computeCrossingsCollisions(constantVelocityPredictionParameters, collisionDistanceThreshold, timeHorizon, computeCZ)
+
+storage.saveIndicators(params.databaseFilename, interactions)
 
-plt.figure()
-plt.axis('equal')
-for inter in interactions[:2]:
-    for collisionPoints in inter.collisionPoints.values():
-        for cp in collisionPoints:
-            plot([cp.x], [cp.y], 'x')
+if display:
+    plt.figure()
+    plt.axis('equal')
+    for inter in interactions[:2]:
+        for collisionPoints in inter.collisionPoints.values():
+            for cp in collisionPoints:
+                plot([cp.x], [cp.y], 'x')
 
 # for the demo, output automatically a map
 # possibility to process longitudinal coords only