I want to be able to find out the value of a point inside a polygon if I have assigned weights to its vertices.
In the figure below, some weights have been applied to the green dots. For some red interior point, I need to calculate
I have use the inverse of the distance from the point to a vertex as my correction factor.
This is my code so far to get the weighted value at one red point:
def add_weights(poly, weights):
poly.weights = [float(w) for w in weights]+[weights[0]] #need to add the first weight
# at the end to account for
# the first point being added to close the loop
def distance(a,b):
dist = ( (b.x - a.x)**2 + (b.y - a.y)**2 )**0.5
if dist == 0: dist = 0.000000001
return dist
def get_weighted_sum(poly, point):
return sum([poly.weights[n]/distance(point,p) for n,p in enumerate(poly.points_shapely) if poly.weights[n] != 'nan'])
def get_weighted_dist(poly, point):
return sum([1/distance(point,p) for n,p in enumerate(poly.points_shapely) if poly.weights[n] != 'nan'])
def get_point_weighted_value(poly, point):
return get_weighted_sum(poly,point)/get_weighted_dist(poly,point)
Note that my polygon can be irregular. Also, not all the vertices might have a weight, in which case the vertex is skipped for the calculation: in the example above it would mean that the value of the weight would only be calculated using two vertices rather than three.
And this is a test code sample:
import shapely.geometry as shapely
class MyPoly(shapely.Polygon):
def __init__(self,points):
closed_path = list(points)+[points[0]]
super(MyPoly,self).__init__(closed_path)
self.points = closed_path
self.points_shapely = [shapely.Point(p[0],p[1]) for p in closed_path]
def convert_to_shapely_poly(poly):
poly_shapely = MyPoly(poly)
return poly_shapely
#inputs
poly = [[0,0],[5,10],[10,0]]
#conversion to shapely format
mypoly = convert_to_shapely_poly(poly)
#adding weights to the vertices of the polygone
add_weights(mypoly,[2,11,5])
#calculate the weighted value of a point inside the polygon:
get_point_weighted_value(mypoly,shapely.Point(7,2))
Any suggestion on improving this code would be welcome!