Scale the circle inside polygon as the size of polygon changes

52 views Asked by At

I am creating shapely Polygons and in each polygon I am creating circles with a fixed radius and distance between them.

import matplotlib.pyplot as plt
from shapely.geometry import Polygon, Point
import numpy as np

def pack_circles_inside_polygon(polygon, radius, distance):
    circles = []
    
    # Calculate the number of circles that can fit in each row and column
    num_rows = int((polygon.bounds[3] - polygon.bounds[1] - 2 * radius) / (2 * radius + distance)) + 1
    num_cols = int((polygon.bounds[2] - polygon.bounds[0] - 2 * radius) / (2 * radius + distance)) + 1

    # Generate coordinates for the centers of the circles
    for i in range(num_rows):
        for j in range(num_cols):
            x = polygon.bounds[0] + (2 * radius + distance) * j + radius
            y = polygon.bounds[1] + (2 * radius + distance) * i + radius
            center = Point(x, y)
            if polygon.contains(center.buffer(radius)):
                circle = center.buffer(radius)
                circles.append(circle)

    return circles

polygon_vertices = [(2, 2), (5, 8), (10, 6), (7, 1)]
polygon = Polygon(polygon_vertices)
radius = 0.5
distance = 0.5
polygon2 = polygon.buffer(-distance,join_style=2)
# Pack circles inside the polygon
circles = pack_circles_inside_polygon(polygon2, radius, distance)
print(circles)
# Plot the polygon and circles
fig, ax = plt.subplots()
x, y = polygon.exterior.xy
ax.plot(x, y, color='blue', alpha=0.7, linewidth=2, solid_capstyle='round')
ax.fill(x, y, color='blue', alpha=0.3)

for circle in circles:
    x, y = circle.exterior.xy
    ax.plot(x, y, color='red', alpha=0.5)

ax.set_aspect('equal', 'datalim')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Circles Packed Inside Polygon')
plt.grid(True)
plt.show()

This is what I have done so far. Here, I have only one polygon and created circles as per my needs. In the next step, I want to create different polygons by making slight changes to this one and create circles.

My requirement is: if the polygon size is different compared to the original one, then I want to resize the circles plotted. I mean, the size of each circle should depend on the size of the polygon. So, in the first polygon, if there were 3 circles, and in the second polygon, there isn't enough space for 3 circles with the same radius and distance, then decrease the radius. This will create a scaling effect on the circles based on the polygon size.

0

There are 0 answers