Great suggestion! Here's an enhanced version that will recursively subdivide squares to fit inside the curve more precisely:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.patches import Rectangle
class LoopSquarer:
def __init__(self, csv_path):
# Load data from CSV
data = pd.read_csv(csv_path)
self.x = data['x'].values
self.y = data['y'].values
# Close the loop if not already closed
if (self.x[0] != self.x[-1]) or (self.y[0] != self.y[-1]):
self.x = np.append(self.x, self.x[0])
self.y = np.append(self.y, self.y[0])
def calculate_area(self):
"""Calculate loop area using Shoelace formula"""
return 0.5 * np.abs(np.sum(self.x[:-1] * self.y[1:] - self.x[1:] * self.y[:-1]))
def is_inside(self, x_point, y_point):
"""Ray casting algorithm to check if point is inside the loop"""
n = len(self.x)
inside = False
for i in range(n-1):
x1, y1 = self.x[i], self.y[i]
x2, y2 = self.x[i+1], self.y[i+1]
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
def is_square_inside(self, x, y, size):
"""Check if a square is fully or partially inside the loop"""
# Check all 4 corners and center
check_points = [
(x, y), # bottom-left
(x + size, y), # bottom-right
(x, y + size), # top-left
(x + size, y + size), # top-right
(x + size/2, y + size/2) # center
]
# Count how many points are inside
inside_points = sum(self.is_inside(px, py) for px, py in check_points)
return inside_points
def subdivide_squares(self, min_size=0.01):
"""Recursively find squares that fit inside the loop"""
squares = []
# Get loop bounds
x_min, x_max = np.min(self.x), np.max(self.x)
y_min, y_max = np.min(self.y), np.max(self.y)
def recursive_square_search(x, y, size):
# Stop if square is too small
if size < min_size:
return
# Check square's fit
fit = self.is_square_inside(x, y, size)
if fit == 5: # Fully inside
squares.append((x, y, size))
elif fit > 0: # Partially inside, subdivide
half_size = size / 2
recursive_square_search(x, y, half_size)
recursive_square_search(x + half_size, y, half_size)
recursive_square_search(x, y + half_size, half_size)
recursive_square_search(x + half_size, y + half_size, half_size)
# Start searching from loop bounds with initial large square
initial_size = max(x_max - x_min, y_max - y_min)
recursive_square_search(x_min, y_min, initial_size)
return squares
def plot(self, min_size=0.01):
"""Plot the loop and fitting squares"""
# Calculate total loop area
area = self.calculate_area()
print(f"Loop Area: {area:.2f}")
# Create plot
plt.figure(figsize=(10, 10))
plt.plot(self.x, self.y, 'b-', linewidth=2, label=f"Loop (Area = {area:.2f})")
# Find and plot squares
squares = self.subdivide_squares(min_size)
# Plot squares
for x, y, size in squares:
square = Rectangle((x, y), size, size,
fill=True, color='orange', alpha=0.5)
plt.gca().add_patch(square)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Loop with Fitting Squares')
plt.legend()
plt.grid(True)
plt.axis('equal')
plt.show()
# Usage
squarer = LoopSquarer('loop_data.csv')
squarer.plot(min_size=0.01) # Adjust min_size for more/fewer squares
Key Enhancements
-
Recursive Square Subdivision
- Starts with a large square covering the entire loop
- Recursively subdivides squares that are partially inside
- Stops when squares become smaller than
min_size
-
Flexible Fitting
- Checks multiple points (corners and center) to determine square fit
- Supports fully and partially inside squares
-
Customizable Precision
min_size parameter controls square subdivision
- Smaller values = more squares, more precise fitting
-
Object-Oriented Design
- Encapsulates loop processing in a class
- Easy to reuse and modify
Usage Tips
- Adjust
min_size to control square density
- Lower values (e.g., 0.01) give more squares
- Higher values (e.g., 0.1) give fewer squares
Example CSV Format
x,y
0,0
1,0
1,1
0,1
0,0
Output
- Prints total loop area
- Displays plot with orange squares fitting inside the loop
The script provides a flexible, precise method to find squares that fit inside an arbitrary closed loop.