簡體   English   中英

在 class 內的多邊形內創建隨機點

[英]Create random points within a polygon within a class

我正在嘗試使用 class 在多邊形內創建一個點,以用於基於代理的 model。

目前,我能夠創建受限於多邊形邊界的隨機點,但不能創建多邊形本身。 我目前的代碼似乎忽略了 while 循環中的 if 語句。 我對 python 很陌生,所以這可能是我缺少的限制。

這是我當前的代碼:

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

這段代碼給出了一個無限循環。 預期的行為將是停止給定 Boolean True 值,並繼續 False,直到 True 值。

不要使用 counter 變量,而是在多邊形內對點進行采樣時使用 break 語句。 計數器變量在退出時將始終為 1,因此它不攜帶新信息。 我對 Geopandas 庫不是很熟悉,但是您可以使用Shapely實現解決方案,這是一個非常好的庫 imo。 使用此程序結構,您的 object 變得更普遍可用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM