在类内的多边形内创建随机点 [英] Create random points within a polygon within a class

查看:55
本文介绍了在类内的多边形内创建随机点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用用于基于代理的模型中的类在多边形内创建单个点.

I am trying to create a single point within a polygon using a class for use in an agent based model.

当前,我能够创建约束于多边形边界的随机点,但不能创建多边形本身.目前,我的代码似乎忽略了while循环中的if语句.我对python很陌生,所以这可能是我所缺少的限制.

Currently I am able to create random points constrained to the bounds of the polygon, but not the polygon itself. My code at present appears to ignore the if statement within the while loop. I am very new to python so this could be a limitation I am missing.

这是我当前的代码:

import geopandas as gpd
import matplotlib.pyplot as plt
import random
import pandas as pd

bounds = gpd.read_file("./data/liverpool_bounds.gpkg")


class Agent():
    def __init__(self, bounds):
        x_min, y_min, x_max, y_max = bounds.total_bounds

        counter = 0
        while counter != 1:
            x = random.uniform(x_min, x_max)
            y = random.uniform(y_min, y_max)
            df = pd.DataFrame({'x': [x], 'y': [y]})
            self.agent = gpd.GeoDataFrame(
                df, geometry=gpd.points_from_xy(df.x, df.y))

            if self.agent.within(bounds) is True:
                counter = 1

            # counter does not increase
            print(counter)
            # gives both True and False
            print(self.agent.within(bounds))


Agent(bounds).agent

此代码给出一个无限循环.预期的行为是停止给定布尔值True,然后继续False直到True值.

This code gives an infinite loop. Expected behavior would be to stop given a Boolean True value, and to continue with False, until a True value.

推荐答案

不要使用counter变量,而是在多边形内采样点时使用break语句.计数器变量在退出时始终为1,因此不会携带新信息.我对Geopandas库不是很熟悉,但是您可以使用 Shapely ,这是一个非常不错的库imo.通过这种程序结构,您的对象将变得更通用.

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()

这篇关于在类内的多边形内创建随机点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆