Great! Let's enhance the script to add smaller squares that fit inside the curve where full-sized squares cannot. We'll implement a recursive subdivision approach:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.patches import Rectangle
# Load data from CSV using pandas
data = pd.read_csv('loop_data.csv') # Columns: 'x' and 'y'
x = data['x'].values
y = data['y'].values
# Close the loop (if not already closed)
if (x[0] != x[-1]) or (y[0] != y[-1]):
x = np.append(x, x[0])
y = np.append(y, y[0])
# Calculate the area using the Shoelace formula
def calculate_area(x, y):
return 0.5 * np.abs(np.sum(x[:-1] * y[1:] - x[1:] * y[:-1]))
area = calculate_area(x, y)
print(f"Loop Area: {area:.2f}")
# Plot the loop
plt.figure(figsize=(10, 10))
plt.plot(x, y, 'b-', linewidth=2, label=f"Loop (Area = {area:.2f})")
# Function to check if a point is inside the loop (Ray Casting Algorithm)
def is_inside(x_point, y_point, x_poly, y_poly):
n = len(x_poly)
inside = False
for i in range(n):
x1, y1 = x_poly[i], y_poly[i]
x2, y2 = x_poly[(i + 1) % n], y_poly[(i + 1) % n]
if y_point > min(y1, y2):
if y_point <= max(y1, y2):
if x_point <= max(x1, x2):
if y1 != y2:
x_intersect = (y_point - y1) * (x2 - x1) / (y2 - y1) + x1
if x1 == x2 or x_point <= x_intersect:
inside = not inside
return inside
# Function to check if all corners of a square are inside the loop
def square_fully_inside(x_center, y_center, size, x_poly, y_poly):
half_size = size / 2
corners = [
(x_center - half_size, y_center - half_size), # bottom-left
(x_center + half_size, y_center - half_size), # bottom-right
(x_center + half_size, y_center + half_size), # top-right
(x_center - half_size, y_center + half_size) # top-left
]
return all(is_inside(x, y, x_poly, y_poly) for x, y in corners)
# Function to recursively add squares
def add_squares(x_center, y_center, size, min_size, x_poly, y_poly):
# Check if center is inside the loop
if not is_inside(x_center, y_center, x_poly, y_poly):
return
# Try to place a square of the current size
if square_fully_inside(x_center, y_center, size, x_poly, y_poly):
# Add the square to the plot
square = Rectangle((x_center - size/2, y_center - size/2), size, size,
fill=True, color='orange', alpha=0.5,
linewidth=1, edgecolor='black')
plt.gca().add_patch(square)
return
# If square doesn't fit and we haven't reached minimum size, subdivide
if size > min_size:
new_size = size / 2
quarter_size = new_size / 2
# Try 4 smaller squares (subdivide)
add_squares(x_center - quarter_size, y_center - quarter_size, new_size, min_size, x_poly, y_poly) # bottom-left
add_squares(x_center + quarter_size, y_center - quarter_size, new_size, min_size, x_poly, y_poly) # bottom-right
add_squares(x_center + quarter_size, y_center + quarter_size, new_size, min_size, x_poly, y_poly) # top-right
add_squares(x_center - quarter_size, y_center + quarter_size, new_size, min_size, x_poly, y_poly) # top-left
# Define initial grid spacing and minimum square size
initial_size = min(np.max(x) - np.min(x), np.max(y) - np.min(y)) / 10
min_size = initial_size / 8 # Minimum square size (adjust as needed)
# Generate initial grid points and start recursive subdivision
x_range = np.max(x) - np.min(x)
y_range = np.max(y) - np.min(y)
grid_spacing = initial_size
for xi in np.arange(np.min(x) + grid_spacing/2, np.max(x), grid_spacing):
for yi in np.arange(np.min(y) + grid_spacing/2, np.max(y), grid_spacing):
add_squares(xi, yi, initial_size, min_size, x, y)
# Calculate total area of squares (approximate)
total_square_area = 0
for patch in plt.gca().patches:
total_square_area += patch.get_width() ** 2
print(f"Total area covered by squares: {total_square_area:.2f}")
print(f"Coverage percentage: {(total_square_area/area)*100:.2f}%")
plt.xlabel('x')
plt.ylabel('y')
plt.title('Loop with Adaptive Squares Inside')
plt.legend()
plt.grid(True)
plt.axis('equal')
plt.tight_layout()
plt.show()
How This Enhanced Version Works:
-
Recursive Square Subdivision:
- We start with larger squares at regular grid points.
- If a square doesn't fully fit inside the loop (not all corners inside), we subdivide it into 4 smaller squares.
- We continue subdividing until we reach a minimum square size (
min_size).
-
Square Placement Logic:
square_fully_inside() checks if all 4 corners of a square are inside the loop.
add_squares() recursively tries to place squares of decreasing sizes.
-
Adaptive Coverage:
- Larger squares are placed where possible.
- Smaller squares fill in the gaps near the boundary.
- The minimum square size prevents infinite recursion and controls detail level.
-
Area Calculation:
- We calculate both the loop area and the total area covered by squares.
- We report the coverage percentage to show how well the squares approximate the loop area.
Adjustable Parameters:
initial_size: Controls the size of the largest squares (default: 1/10 of the loop's extent).
min_size: Controls the smallest squares to consider (default: 1/8 of the initial size).
grid_spacing: Controls the spacing of the initial grid points (default: same as initial_size).
This approach will give you a much better approximation of the loop's area using squares of various sizes, with larger squares in the interior and progressively smaller squares near the boundary.