Python Code Ray Casting Multiple Points - python

I am trying write a Ray Casting python code, that will return a list of True or False, that will show if points are in polygons. I have a List of that contains Lat/Lons of multiple polygons, and two additional Lists, one being the Latitude, and the other being the Longitude of points. So essentially what I to do is use the Lists, to see if multiple points are in multiple polygons. Any advice would be very helpful, since I am new Python, and learning as I go!.
Below is the function that creates the Ray Casting to see if one point is one polygon, so what would be needed to see if multiple points are in multiple polygons returning a True or False for each point, so returning [True, False, True, False]
Ray Casting for one Point in Polygon:
def point_in_poly(x,y,poly):
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/float(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
## Test
polygon = [(0,11),(11,10),(11,0),(0,1)]
point_x = 12
point_y = 12
## Call the function with the points and the polygon
print (point_in_poly(point_x,point_y,polygon))

Related

My implementation of Bridson's algorithm Poisson-Disk Sampling seems to be stuck in an infinite loop

A video by Sebastion Lague explained the Bridson's algorithm really well.
To oversimplify,
Create cell grid that has sides of radius/sqrt(2).
Place initial point and list as spawnpoint.
Place point into cell in grid.
For any spawnpoint, spawn a point between radius and 2*radius.
Look at the cells 2 units away from cell of new point.
If contains other points, compare distance.
If any point is closer to new point than the radius, new point is invalid.
If new point is valid, new point is listed as spawnpoint and placed into cell in grid.
If spawnpoint spawns too many invalid points, spawnpoint is removed and turns into point.
Repeat until no more spawnpoints exists.
Return points.
I basically written the same thing down in Python 3.7.2 and pygame 1.7~, but as said in the title, I'm stuck in recursive purgatory.
I used one Point() class for this algorithm, which might seem redundant given that pygame.Vector2() exists, but I needed some elements for a separate algorithm (Delaunay's with infinite vertices) that required this class to work.
For the sake of simplicity I'm going to cut away all the Delaunay-specific elements and show the bare-bones of this class that is needed for this algorithm:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def DistanceToSquared(self,other):
return (self.x-other.x)**2 + (self.y-other.y)**2
The code that is related to the Bridson's algorithm is:
def PoissonDiskSampling(width, height, radius, startPos = None, spawnAttempts = 10):
if startPos == None:
startPos = [width//2,height//2]
cellSize = radius / math.sqrt(2)
cellNumberX = int(width // cellSize + 1) # Initialise a cells grid for optimisation
cellNumberY = int(height // cellSize + 1)
cellGrid = [[None for x in range(cellNumberX)] for y in range(cellNumberY)]
startingPoint = Point(startPos[0],startPos[1]) # Add an iniial point for spawning purposes
cellGrid[startingPoint.x//radius][startingPoint.y//radius] = startingPoint
points = [startingPoint] # Initialise 2 lists tracking all points and active points
spawnpoints = [startingPoint]
while len(spawnpoints) > 0:
spawnIndex = random.randint(0,len(spawnpoints)-1)
spawnpoint = spawnpoints[spawnIndex]
spawned = False
for i in range(spawnAttempts):
r = random.uniform(radius,2*radius)
radian = random.uniform(0,2*math.pi)
newPoint = Point(spawnpoint.x + r*math.cos(radian),
spawnpoint.y + r*math.sin(radian))
if 0 <= newPoint.x <= width and 0 <= newPoint.y <= height:
isValid = True
else:
continue
newPointIndex = [int(newPoint.x//cellSize), int(newPoint.y//cellSize)]
neighbours = FindNeighbours(cellNumberX,cellNumberY,newPointIndex,cellGrid)
for neighbour in neighbours:
if newPoint.DistanceToSquared(neighbour) < radius**2:
isValid = False
break
if isValid:
points.append(newPoint)
spawnpoints.append(newPoint)
spawned = True
break
else:
continue
if spawned == False:
spawnpoints.remove(spawnpoint)
return points
def FindNeighbours(cellNumberX, cellNumberY, index, cellGrid):
neighbours = []
for cellX in range(max(0,(index[0]-2)), min(cellNumberX,(index[1]+2))):
for cellY in range(max(0,(index[0]-2)), min(cellNumberY,(index[1]+2))):
if cellGrid[cellX][cellY] != None:
neighbours.append(cellGrid[cellX][cellY])
return neighbours
Please help.
The probably most important step is missing in your code:
If new point is valid, new point is listed as spawnpoint and placed into cell in grid.
I suggest to add the point to the cellGrid if it is valid:
if isValid:
cellGrid[newPointIndex[0]][newPointIndex[1]] = newPoint
points.append(newPoint)
spawnpoints.append(newPoint)
spawned = True
break
Further, you have to verify if the cell with the index newPointIndex is not already occupied before a point can be add:
newPointIndex = [int(newPoint.x/cellSize), int(newPoint.y/cellSize)]
if cellGrid[newPointIndex[0]][newPointIndex[1]] != None:
continue
neighbours = FindNeighbours(cellNumberX,cellNumberY,newPointIndex,cellGrid)
Finally there is an issue in the function FindNeighbours. range(start, stop) creates a range for x in start <= x < stop.
So the stop has to be index[0]+3 rather than index[0]+2.
Further the ranges which control the 2 nested for loops, run both from x-2 to y+2 rather than from x-2 to x+2 respectively from y-2 to y+2:
for cellX in range(max(0,(index[0]-2)), min(cellNumberX,(index[1]+2))):
for cellY in range(max(0,(index[0]-2)), min(cellNumberY,(index[1]+2)))
The fixed function has to be:
def FindNeighbours(cellNumberX, cellNumberY, index, cellGrid):
neighbours = []
for cellX in range(max(0, index[0]-2), min(cellNumberX, index[0]+3)):
for cellY in range(max(0, index[1]-2), min(cellNumberY, index[1]+3)):
if cellGrid[cellX][cellY] != None:
neighbours.append(cellGrid[cellX][cellY])
return neighbours
See the result, for a size of 300 x 300 and a radius of 15:
An even better result can be achieve, if always the 1st point of spawnpoints is used to rather than a random point:
# spawnIndex = random.randint(0,len(spawnpoints)-1)
spawnIndex = 0 # 0 rather than random
spawnpoint = spawnpoints[spawnIndex]

Deciding if a Point is Inside a Polygon

I am trying to detect if a given point(x,y) is in a polygon of n*2 array. But it seems that some points on the borders of the polygon return that it's not include.
def point_inside_polygon(x,y,poly):
n = len(poly)
inside =False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xinters = (y-p1y)*(p2x-p1x)/float((p2y-p1y))+p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x,p1y = p2x,p2y
return inside
Here is a simple way with multiple options
from shapely.geometry import Point, Polygon
# Point objects(Geo-coordinates)
p1 = Point(24.952242, 60.1696017)
p2 = Point(24.976567, 60.1612500)
# Polygon
coords = [(24.950899, 60.169158), (24.953492, 60.169158), (24.953510, 60.170104), (24.950958, 60.169990)]
poly = Polygon(coords)
Method 1:
Using within Function:
Syntax: point.within(polygon)
# Check if p1 is within the polygon using the within function
print(p1.within(poly))
# True
# Check if p2 is within the polygon
print(p2.within(poly))
# False
Method 2:
Using contains Function:
Syntax: polygon.contains(point)
# Check if polygon contains p1
print(poly.contains(p1))
# True
# Check if polygon contains p2
print(poly.contains(p2))
# False
To check if point is lying on the boundary of Polygon:
Using touches Function:
Syntax: polygon.touches(point)
poly1 = Polygon([(0, 0), (1, 0), (1, 1)])
point1 = Point(0, 0)
poly1.touches(point1)
# True
If you want to speed up the process then please use
import shapely.speedups
shapely.speedups.enable()
and
Make use of Geopandas
Reference:
https://automating-gis-processes.github.io/CSC18/lessons/L4/point-in-polygon.html#point-in-polygon-using-geopandas
https://shapely.readthedocs.io/en/latest/manual.html
https://streamhacker.com/2010/03/23/python-point-in-polygon-shapely/
You may use contains_point function from matplotlib.path with small negative and positive radius (small trick). Something like this:
import matplotlib.path as mplPath
import numpy as np
crd = np.array([[0,0], [0,1], [1,1], [1,0]])# poly
bbPath = mplPath.Path(crd)
pnts = [[0.0, 0.0],[1,1],[0.0,0.5],[0.5,0.0]] # points on edges
r = 0.001 # accuracy
isIn = [ bbPath.contains_point(pnt,radius=r) or bbPath.contains_point(pnt,radius=-r) for pnt in pnts]
The result is
[True, True, True, True]
By default (or r=0) all the points on borders are not included, and the result is
[False, False, False, False]
Here is the correct code that includes edges:
def point_inside_polygon(x, y, poly, include_edges=True):
'''
Test if point (x,y) is inside polygon poly.
poly is N-vertices polygon defined as
[(x1,y1),...,(xN,yN)] or [(x1,y1),...,(xN,yN),(x1,y1)]
(function works fine in both cases)
Geometrical idea: point is inside polygon if horisontal beam
to the right from point crosses polygon even number of times.
Works fine for non-convex polygons.
'''
n = len(poly)
inside = False
p1x, p1y = poly[0]
for i in range(1, n + 1):
p2x, p2y = poly[i % n]
if p1y == p2y:
if y == p1y:
if min(p1x, p2x) <= x <= max(p1x, p2x):
# point is on horisontal edge
inside = include_edges
break
elif x < min(p1x, p2x): # point is to the left from current edge
inside = not inside
else: # p1y!= p2y
if min(p1y, p2y) <= y <= max(p1y, p2y):
xinters = (y - p1y) * (p2x - p1x) / float(p2y - p1y) + p1x
if x == xinters: # point is right on the edge
inside = include_edges
break
if x < xinters: # point is to the left from current edge
inside = not inside
p1x, p1y = p2x, p2y
return inside
Updated: fixed a bug

Python Test If Point is in Rectangle

I am new to python and still learning the ropes but I am hoping someone with more experience can help me out.
I am trying to write a python script that:
creates four points
creates four rectangles
check if each of the point is in any of the rectangles then write out the results to a output file.
The problem involves two data structures Point and Rectangle class. I have already started to create the Point class and Rectangle classes. Rectangle class should hold relevant data sets created from random module’s random method. As you can tell from my attempts that I am kind of all over the place but I have used #comments to try to get what I am trying to do.
Specific questions I have are:
1) how can I get this script working?
2) What variables or functions am I missing to generate random rectangles and see if specific points are in those rectangles?
## 1. Declare the Point class
class Point:
def __init__(self,x = 0.0, y = 0.0):
self.x = x
self.y = y
pass
## 2. Declare the Rectangle class
class Rectangle:
def __int__(self): ## A rectangle can be determined aby (minX, maxX) (minY, maxY)
self.minX = self.minY = 0.0
self.maxX = self.maxY = 1.0
def contains(self, point): ## add code to check if a point is within a rectangle
"""Return true if a point is inside the rectangle."""
# Determine if a point is inside a given polygon or not
# Polygon is a list of (x,y) pairs. This function
# returns True or False.
def point_in_poly(x,y,poly):
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
return inside
## 3. Generate four points
##define a Point list to keep four points
points = []
##add codes to generate four points and append to the points list
polygon = [(0,10),(10,10),(10,0),(0,0)]
point_x = 5
point_y = 5
## 4. Generate four rectangles
##define a Rectangle list
rects = []
for i in range(4):
rectangle = Rectangle()
## Generate x
x1 = random.random()
x2 = random.random()
## make sure minX != maxX
while(x1 == x2):
x1 = random.random()
if x1<x2:
rectangle.minX=x1
rectangle.maxX=x2
elif x1>x2:
rectangle.minX=x2
rectangle.maxX=x1
rects.append(rectangle)
## Develop codes to generate y values below
## make sure minY != maxY
while(y1 == y2):
y1 = random.random()
if y1<y2:
rectangle.minY=y1
rectangle.maxY=y2
elif y1>y2:
recetangle.minY=y2
racetangle.maxY=y1
## add to the list
rects.append(rectangle)
## 5. Add code to check which point is in which rectangle
resultList = [] ## And use a list to keep the results
for i in range(4):
for j in range(4):
if points[i] in rectangle[j]:
print i
# write the results to file
f=open('Code5_4_1_Results.txt','w')
for result in resultList:
f.write(result+'\n')
f.close()
This is pretty simple math. Given a rectangle with points (x1,y1) and (x2,y2) and assuming x1 < x2 and y1 < y2 (if not, you can just swap them), a point (x,y) is within that rectangle if x1 < x < x2 and y1 < y < y2. Since Python comparison operators can be chained, this is even valid Python code which should produce the correct result (in other languages you'd have to write something like x1 < x and x < x2, etc).
If you want, you can use <= instead of <. Using <= means points on the boundary of the rectangle (eg, the point (x1,y1)) count as being inside it, while using < so means such points are outside it.
It is better to write a separate function to do the job. Here's my function. You can just copy it if you want
def pointInRect(point,rect):
x1, y1, w, h = rect
x2, y2 = x1+w, y1+h
x, y = point
if (x1 < x and x < x2):
if (y1 < y and y < y2):
return True
return False

Scipy interpolation.griddata freezes when called on a particular point

I am trying to perform a simple 2D linear interpolation with Scipy interpolation.griddata but it behaves in a strange way : it runs forever and the computation can't be interrupted (100% CPU, RAM doesn't move, and I have to kill the process).
The data + coordinates that should be interpolated are located inside a polygon. At first, I tried to use a meshgrid containing only points located inside that polygon, but it didn't solve the problem.
I also tried to reduce to a very tiny interpolation grid (10*10), but it kept on freezing.
Then I tried to interpolate the meshgrid points one by one and found out that only some of them were causing the issue, and I can't figure out why.
Here is a sample of the code :
# Sets negative levels to zero
x_a = x_a.clip(min = 0)
coordinate = np.array(coordinate)
# Experiment zone polygon.
if city == "sf":
zone = [[-122.397752, 37.799137],
[-122.423329, 37.795746],
[-122.418523, 37.772886],
[-122.39243, 37.793982]]
zone.append(zone[0]) # to close the polygon.
# Background map extent lat/long coordinates.
x_min_map = min([xy[0] for xy in zone])
x_max_map = max([xy[0] for xy in zone])
y_min_map = min([xy[1] for xy in zone])
y_max_map = max([xy[1] for xy in zone])
def IsPointInsidePolygon(x, y, poly):
n = len(poly)
inside = False
p1x, p1y = poly[0]
for i in range(n + 1):
p2x, p2y = poly[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
# Creates a mesh grid adapted to the sf zone, on which to interpolate.
N = 10
xi = np.linspace(x_min_map, x_max_map, N)
yi = np.linspace(y_min_map, y_max_map, N)
xi, yi = np.meshgrid(xi, yi)
xi, yi = xi.flatten(), yi.flatten()
all_points = np.vstack((xi, yi)).T
delete_index = []
for i, point in enumerate(all_points):
if not IsPointInsidePolygon(point[0], point[1], zone):
delete_index.append(i)
grid_points = np.delete(all_points, delete_index, axis = 0)
# Interpolation
zi = interpolate.griddata(coordinate, x_a, grid_points, method = "linear")
The "coordinate" variable is an array that contains approximately 1e4 float coordinates that are located inside the "zone" polygon.
The x_min_map etc. are the computed max and min x, y values of the polygon, so that the original meshgrid is the smallest rectangle containing the whole polygon.
Any advice will be appreciated !

Python: find if point lay on the border of a polygon

I have a point-i and i wish to create a function to know if this point lies on the border of a polygon.
using:
def point_inside_polygon(x, y, poly):
"""Deciding if a point is inside (True, False otherwise) a polygon,
where poly is a list of pairs (x,y) containing the coordinates
of the polygon's vertices. The algorithm is called the 'Ray Casting Method'"""
n = len(poly)
inside = False
p1x, p1y = poly[0]
for i in range(n):
p2x, p2y = poly[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
if p1y != p2y:
xinters = (y-p1y) * (p2x-p1x) / (p2y-p1y) + p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside
I am able to know only if the points lies within the polygon.
poly = [(0,0), (2,0), (2,2), (0,2)]
point_inside_polygon(1,1, poly)
True
point_inside_polygon(0,0, poly)
false
point_inside_polygon(2,0, poly)
False
point_inside_polygon(2,2, poly)
True
point_inside_polygon(0,2, poly)
True
How can I write a function to find if a point lay on the border of a polygon instead?
It might help to break down the problem into three steps:
Write a function that can determine if a point is on a line segment.
Compute all of the line segments that make up the border of the polygon.
The point is on the border if it is on any of the line segments.
Here's some python code, assuming you've written or found a suitable candidate for isPointOnLineSegmentBetweenPoints:
def pointOnPolygon(point, polygonVertices):
n = len(polygonVertices)
for i in range(n):
p1 = polygonVertices[i]
p2 = polygonVertices[-n+i+1]
if isPointOnLineSegmentBetweenPoints(point, p1, p2):
return true
return false
I haven't tested this, but the general idea is:
def pointOnBorder(x, y, poly):
n = len(poly)
for(i in range(n)):
p1x, p1y = poly[i]
p2x, p2y = poly[(i + 1) % n]
v1x = p2x - p1x
v1y = p2y - p1y #vector for the edge between p1 and p2
v2x = x - p1x
v2y = y - p1y #vector from p1 to the point in question
if(v1x * v2y - v1y * v2x == 0): #if vectors are parallel
if(v2x / v1x > 0): #if vectors are pointing in the same direction
if(v1x * v1x + v1y * v1y >= v2x * v2x + v2y * v2y): #if v2 is shorter than v1
return true
return false
For each pair of adjacent vertices A,B:
construct a vector from A to B, call it p
now construct a vector from A to your test point X call it q
the dot product formula for a pair of vectors is p.q = |p||q|cosC
where C is the angle between the vectors.
so if p.q/|p||q| == 1 then the points AX and AB are co-linear. Working on a computer, you will want 1 - p.q/|p||q| < some_small_value depending on how accurate you want to be.
also need to check that |q| < |p| (ie X is closer to A than B)
if 4&5 are true your point is on the border.
Edit
The other way I think I've seen this done is to take your test point X, and construct a line through X perpendicular to the line between A and B. Find where this line and the line A->B cross. Work out the distance from X to this crossing point, if that is sufficiently small you consider the point as being on the line.
Edit -- fun little exercise!
Posted some code that was wrong earlier due to me misremembering some maths.
Had a play in Pythonista on the train home and came up with this which seems to basically work. Have left the maths proof out as editing posts on iPad is painful!
Not much testing done, no testing for division by zero etc, caveat user.
# we determine the point of intersection X between
# the line between A and B and a line through T
# that is perpendicular to the line AB (can't draw perpendicular
# in ascii, you'll have to imagine that angle between AB and XT is 90
# degrees.
#
# B
# /
#. X
# / \
# / T
# A
# once we know X we can work out the closest the line AB
# comes to T, if that distance is 0 (or small enough)
# we can consider T to be on the line
import math
# work out where the line through test point t
# that is perpendicular to ab crosses ab
#
# inputs must be 2-tuples or 2-element lists of floats (x,y)
# returns (x,y) of point of intersection
def intersection_of_perpendicular(a,b,t):
if a[0] == b[0]:
return (a[0],t[1])
if a[1] == b[1]:
return (t[0],a[1])
m = (a[1] - b[1])/(a[0] - b[0]) #slope of ab
x_inter = (t[1] - a[1] + m*a[0] + (1/m)*t[0])*m/(m**2 + 1)
y_inter = m*(x_inter - a[0]) + a[1]
y_inter2 = -(1/m)*(x_inter - t[0]) + t[1]
#print '...computed ',m,(x_inter, y_inter), y_inter2
return (x_inter, y_inter)
# basic Pythagorean formula for distance between two points
def distance(a,b):
return math.sqrt( (a[0]-b[0])**2 + (a[1]-b[1])**2 )
# check if a point is within the box defined by a,b at
# diagonally opposite corners
def point_in_box(a,b,t):
xmin = min(a[0],b[0])
xmax = max(a[0],b[0])
ymin = min(a[1],b[1])
ymax = max(a[1],b[1])
x_in_bounds = True
if xmax != xmin:
x_in_bounds = xmin <= t[0] <= xmax
y_in_bounds = True
if ymax != ymin:
y_in_bounds = ymin <= t[1] <= ymax
return x_in_bounds and y_in_bounds
# determine if point t is within 'tolerance' distance
# of the line between a and b
# returns Boolean
def is_on_line_between(a,b,t,tolerance=0.01):
intersect = intersection_of_perpendicular(a,b,t)
dist = distance(intersect, t)
in_bounds = point_in_box(a,b,t)
return in_bounds and (dist < tolerance)
a = (0,0)
b = (2,2)
t = (0,2)
p = intersection_of_perpendicular(a,b,t)
bounded = point_in_box(a,b,t)
print 'd ',distance(p,t), ' p ',p, bounded
a = (0,2)
b = (2,2)
t = (1,3)
p = intersection_of_perpendicular(a,b,t)
bounded = point_in_box(a,b,t)
print 'd ',distance(p,t),' p ',p, bounded
a = (0.0,2.0)
b = (2.0,7.0)
t = (1.7,6.5)
p = intersection_of_perpendicular(a,b,t)
bounded = point_in_box(a,b,t)
on = is_on_line_between(a,b,t,0.2)
print 'd ',distance(p,t),' p ',p, bounded,on
Everyone is overcomplicating things. Here is a short point on polygon, assuming you have a distance function and a small EPSILON.
def pointOnPolygon(point, poly):
for i in range(len(poly)):
a, b = poly[i - 1], poly[i]
if abs(dist(a, point) + dist(b, point) - dist(a, b)) < EPSILON:
return true
return false
For a convex polygon, you can solve the problem in O(log n) time by ordering vertices clock-wise and storing for each vertex the angle between the vertex and a point c in the interior of the polygon. Then for a query point x, you get the angle from c to x and binary search to find the unique pair of adjacent vertices (v1,v2) such that the angle to x is between the angles to v1 and to v2. Then x is either on the edge (v1,v2), or x is not on the boundary.
If you have a more complicated polygon, then you can try decomposing the polygon into a union of convex polygons by adding some interior edges (e.g. first triangulate and then remove edges to get bigger convex polygons); if the number of convex polygons you get is small (say k), then you can test each convex polygon to see if a point is on an edge, and the overall running time is O(k lg n) where n is the total number of vertices in your polygon.
Alternatively, if you are not worried about using extra space, and you really want to quickly determine if you're on an edge, then you can break up each edge into equally spaced segments by adding extra "vertices" along each edge; it's hard to say how many is enough (sounds like an interesting math problem), but clearly if you add enough extra vertices along each edge then you can tell which edge a point must lie on simply by finding the nearest neighbor out of your set of vertices (original vertices and the ones you added), and then just test the one or two edges that the nearest neighbor vertex lies on. You can very quickly find k-nearest neighbors in 2-d if you use a 2-dimensional kd-tree (you build the tree as a pre-processing step, and then the tree supports fast k-nearest neighbor queries), and the kd-tree tree only uses linear space.
Found the solution to this at: http://geospatialpython.com/2011/08/point-in-polygon-2-on-line.html
Here the code:
# Improved point in polygon test which includes edge
# and vertex points
def point_in_poly(x,y,poly):
# check if point is a vertex
if (x,y) in poly: return "IN"
# check if point is on a boundary
for i in range(len(poly)):
p1 = None
p2 = None
if i==0:
p1 = poly[0]
p2 = poly[1]
else:
p1 = poly[i-1]
p2 = poly[i]
if p1[1] == p2[1] and p1[1] == y and x > min(p1[0], p2[0]) and x < max(p1[0], p2[0]):
return "IN"
n = len(poly)
inside = False
p1x,p1y = poly[0]
for i in range(n+1):
p2x,p2y = poly[i % n]
if y > min(p1y,p2y):
if y <= max(p1y,p2y):
if x <= max(p1x,p2x):
if p1y != p2y:
xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
if p1x == p2x or x <= xints:
inside = not inside
p1x,p1y = p2x,p2y
if inside: return "IN"
else: return "OUT"
# Test a vertex for inclusion
polygon = [(-33.416032,-70.593016), (-33.415370,-70.589604),
(-33.417340,-70.589046), (-33.417949,-70.592351),
(-33.416032,-70.593016)]
lat= -33.416032
lon= -70.593016
print point_in_poly(lat, lon, polygon)
# test a boundary point for inclusion
poly2 = [(1,1), (5,1), (5,5), (1,5), (1,1)]
x = 3
y = 1
print point_in_poly(x, y, poly2)

Categories