Skip to content Skip to sidebar Skip to footer

Create Random Points Within A Polygon Within A Class

I am trying to create a single point within a polygon using a class for use in an agent based model. Currently I am able to create random points constrained to the bounds of the po

Solution 1:

Don't use the counter variable, but a break statement when the point is sampled within the polygon. The counter variable will always be one on exit so this does not carry new information. I'm not really familiar with the Geopandas library, but you can achieve a solution with Shapely, which is a very nice library imo. With this program structure your object becomes more generally useable.

from shapely.geometry import Point, Polygon
import random


bounds = [(0, 0), (1, 0), (1, 1), (0, 1)]


class Agent():
    def __init__(self, bounds):
        self.polygon = Polygon(bounds)

        # implement your object wide dataframe here to which you can append

    def add_random_point(self):
        xmin, ymin, xmax, ymax = self.polygon.bounds
        while True:
            x = random.uniform(xmin, xmax)
            y = random.uniform(ymin, ymax)

            if Point(x, y).within(self.polygon):
                # if this condition is true, add to a dataframe here

                print(x, y)
                break


obj = Agent(bounds)
obj.add_random_point()

Post a Comment for "Create Random Points Within A Polygon Within A Class"