2

みなさん、こんにちは(ここに初めて投稿するので、ひどく間違ったことをしていないことを願っています)...

各ポリゴンの各辺がl個の所定の線の 1 つに平行になるように、Python で 3 ~ 2lの辺を持つ一連の凸多角形をランダムに生成しようとしています。これを行う方法を誰かが知っていれば (CGAL や Shapely のような計算幾何学パッケージの助けを借りて、または使わずに)、それは素晴らしいことです。

2lの角度 (各線の方向、および各線の方向 + 平行辺の pi)を含むリストから始めます。作成する多角形ごとに、このリストから 3 ~ 2lの角度をランダムに選択し、角度が多角形を定義できるようにするために、前の角度と pi を超えて異なる角度がないように昇順に並べ替えます。ただし、その後、生成したポリゴンが凸状のままで、選択した線に平行な辺のみが含まれていることを確認できません。私のコードは現在次のようになっています。

def generate(l, n, w, h):
    """Generate n polygons with sides parallel to 
    at most l vectors in a w x h plane."""
    L = []
    polygons = []
    while len(L) < 2*l:
        i = random.uniform(0, math.pi)
        if i != math.pi and not i in L:
            L.append(i)
            L.append(i+math.pi)
    L.sort()
    while len(polygons) < n:
        Lp = list(L)
        rm = random.randint(0, 2*l-3)
        #Filter out rm lines, if possible
        for i in range(rm):
            i = random.randint(0, len(Lp)-1)
            for j in range(i, len(Lp)) + range(0, i):
                nxt = Lp[(j+1)%len(Lp)]
                prv = Lp[(j-1)%len(Lp)]
                if prv < nxt < prv+math.pi or nxt < (prv+math.pi)%(2*math.pi)-1e-14 < prv:
                    del Lp[j]
                    break

        # Choose a "center point, then generate a polygon consisting of points
        # a fixed distance away in the direction perpendicular to each angle.
        # This does not work however; resulting polygons may have sides not 
        # parallel to one of the original lines.
        cx, cy = random.uniform(-w/2,w/2), random.uniform(-h/2,h/2)
        points = []
        r = random.uniform(10,100) 
        for theta in Lp:
            # New point is r away from "center" in direction
            # perpendicular to theta
            x = cx + r * math.sin(theta)
            y = cy - r * math.cos(theta)
            points.append(polygon.Vector(x,y))     
        polygons.append(polygon.Polygon(points))
    return polygons
4

1 に答える 1