diff python/moving.py @ 79:5d487f183fe2

added method to test points in polygons and tests
author Nicolas Saunier <nicolas.saunier@polymtl.ca>
date Fri, 11 Mar 2011 18:12:29 -0500
parents d3e1a7cf3375
children 41da2cdcd91c
line wrap: on
line diff
--- a/python/moving.py	Fri Feb 25 14:25:34 2011 -0500
+++ b/python/moving.py	Fri Mar 11 18:12:29 2011 -0500
@@ -139,6 +139,29 @@
     def aslist(self):
         return [self.x, self.y]
 
+    def inPolygon(self, poly):
+        '''Returns if the point x, y is inside the polygon.
+        The polygon is defined by the ordered list of points in poly
+        
+        taken from http://www.ariel.com.au/a/python-point-int-poly.html'''
+
+        n = len(poly);
+        counter = 0;
+
+        p1 = poly[0];
+        for i in range(n+1):
+            p2 = poly[i % n];
+            if self.y > min(p1.y,p2.y):
+                if self.y <= max(p1.y,p2.y):
+                    if self.x <= max(p1.x,p2.x):
+                        if p1.y != p2.y:
+                            xinters = (self.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
+                        if p1.x == p2.x or self.x <= xinters:
+                            counter+=1;
+            p1=p2
+        return (counter%2 == 1);
+
+
     @staticmethod
     def dot(p1, p2):
         return p1.x*p2.x+p1.y*p2.y
@@ -158,7 +181,7 @@
 
     the class is iterable.'''
 
-    def __init__(self, positions):
+    def __init__(self, positions=None):
         self.positions = positions
 
     @staticmethod
@@ -194,7 +217,7 @@
             self.positions[1].append(y)
 
     def addPosition(self, p):
-        self.addPosition(p.x, p.y)
+        self.addPositionXY(p.x, p.y)
         
     def draw(self, options = ''):
         from matplotlib.pylab import plot
@@ -258,10 +281,19 @@
         else:
             return None
     
-    def getTrajectoryInPolygon(self, polygon):
+    def getTrajectoryInPolygon1(self, polygon):
         'Returns the set of points inside the polygon'
-        # use shapely polygon contains
-        pass
+        t = Trajectory()
+        for i in xrange(self.length()):
+            p = self.__getitem__(i)
+            if p.inPolygon(polygon):
+                t.addPosition(p)
+        if t.length()>0:
+            return t
+        else:
+            return None
+
+    # version 2: use shapely polygon contains
 
 ##################
 # Moving Objects