Certainly! Below is the complete function-based version of your original class-based code. This refactored code maintains the exact functionality and structure of the original while converting all classes and their methods into standalone functions. You can run this script locally by saving it into a .py file and executing it with Python. Make sure to install all the required libraries (svgpathtools, numpy, matplotlib, scipy) before running the script.
import csv
import math
import heapq
from collections import defaultdict
from typing import List, Tuple
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial.distance import cdist
def are_approximately_equal(p1: Tuple[float, float], p2: Tuple[float, float], tol: float = 5.0) -> bool:
"""
Check if two points are approximately equal within a given tolerance.
Args:
p1 (tuple): The first point as (x, y).
p2 (tuple): The second point as (x, y).
tol (float): The tolerance for approximation (default is 5.0).
Returns:
bool: True if the distance between the points is less than the tolerance, False otherwise.
"""
return np.linalg.norm(np.array(p1) - np.array(p2)) < tol
def compute_slope(p1: Tuple[float, float], p2: Tuple[float, float]) -> float:
"""
Compute the slope of the line passing through two points.
Args:
p1 (tuple): The first point as (x, y).
p2 (tuple): The second point as (x, y).
Returns:
float: The slope of the line. Returns np.inf if the line is vertical.
"""
if p2[0] == p1[0]:
return np.inf
return (p2[1] - p1[1]) / (p2[0] - p1[0])
def load_points_from_csv(csv_file: str) -> List[Tuple[str, float, float, float]]:
"""
Loads data points from the CSV file.
Args:
csv_file (str): Path to the CSV file.
Returns:
list: A list of tuples containing curve index and point coordinates.
"""
all_points = []
with open(csv_file, newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
curve_index = row[0]
x = float(row[2])
y = float(row[3])
all_points.append((curve_index, 0.0000, x, y))
return all_points
def point_line_distance(point: Tuple[float, float], start: Tuple[float, float], end: Tuple[float, float]) -> float:
"""
Calculates the perpendicular distance from a point to a line segment.
Args:
point (tuple): The point as (x, y).
start (tuple): The start point of the line segment as (x, y).
end (tuple): The end point of the line segment as (x, y).
Returns:
float: The perpendicular distance.
"""
point = np.array(point)
start = np.array(start)
end = np.array(end)
if np.array_equal(start, end):
return np.linalg.norm(point - start)
else:
n = abs((end[1] - start[1]) * point[0] - (end[0] - start[0]) * point[1] + end[0] * start[1] - end[1] * start[0])
d = np.linalg.norm(end - start)
return n / d
def ramer_douglas_peucker(points: List[Tuple[float, float]], epsilon: float) -> Tuple[List[Tuple[float, float]], List[int]]:
"""
Simplifies a list of points using the Ramer-Douglas-Peucker algorithm.
Args:
points (list): List of points as (x, y).
epsilon (float): The epsilon parameter for simplification.
Returns:
tuple: A tuple containing the simplified points and their original indices.
"""
dmax = 0.0
index = 0
end = len(points)
for i in range(1, end - 1):
d = point_line_distance(points[i], points[0], points[-1])
if d > dmax:
index = i
dmax = d
if dmax > epsilon:
rec_results1, idx1 = ramer_douglas_peucker(points[:index + 1], epsilon)
rec_results2, idx2 = ramer_douglas_peucker(points[index:], epsilon)
result = rec_results1[:-1] + rec_results2
result_indices = idx1[:-1] + [i + index for i in idx2]
else:
result = [points[0], points[-1]]
result_indices = [0, len(points) - 1]
return result, result_indices
def simplify_curves(curves: dict, epsilon: float = 5.0) -> Tuple[dict, dict, dict]:
"""
Simplifies all curves and stores segment information.
Args:
curves (dict): Dictionary of curves with curve indices as keys and list of points as values.
epsilon (float): The epsilon parameter for simplification (default is 5.0).
Returns:
tuple: A tuple containing simplified curves, inverse dictionary, and segment points dictionary.
"""
simplified_curves = {}
inverse_dict = {}
segment_points_dict = {}
segment_id = 0
for index, points in curves.items():
simplified_points, indices = ramer_douglas_peucker(points, epsilon)
for i in range(len(simplified_points) - 1):
start_point = tuple(simplified_points[i])
end_point = tuple(simplified_points[i + 1])
line_key = (start_point, end_point)
segment_indices = indices[i:i + 2]
segment_start_idx = segment_indices[0]
segment_end_idx = segment_indices[1]
simplified_curves[segment_id] = [start_point, end_point]
inverse_dict[line_key] = segment_id
segment_points_dict[segment_id] = points[segment_start_idx:segment_end_idx + 1]
segment_id += 1
return simplified_curves, inverse_dict, segment_points_dict
def distance(p1: Tuple[float, float], p2: Tuple[float, float]) -> float:
"""
Computes the Euclidean distance between two points.
Args:
p1 (tuple): First point as (x, y).
p2 (tuple): Second point as (x, y).
Returns:
float: The Euclidean distance.
"""
return np.linalg.norm(np.array(p1) - np.array(p2))
def midpoint(p1: Tuple[float, float], p2: Tuple[float, float]) -> Tuple[float, float]:
"""
Returns the midpoint between two points.
Args:
p1 (tuple): First point as (x, y).
p2 (tuple): Second point as (x, y).
Returns:
tuple: Midpoint as (x, y).
"""
return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)
def round_point(point: Tuple[float, float]) -> Tuple[float, float]:
"""
Rounds the coordinates of a point to one decimal place.
Args:
point (tuple): Point as (x, y).
Returns:
tuple: Rounded point as (x, y).
"""
return (round(point[0], 1), round(point[1], 1))
def update_endpoints_with_midpoints(simplified_curves: dict,
threshold: float = 5.0) -> Tuple[dict, dict]:
"""
Adjusts segment endpoints based on proximity and rounds the results.
Args:
simplified_curves (dict): Simplified curves with segment IDs as keys.
threshold (float): Distance threshold for adjusting endpoints (default is 5.0).
Returns:
tuple: Updated curves and inverse dictionary.
"""
endpoints = {}
updated_curves = {k: v[:] for k, v in simplified_curves.items()}
inverse_dict = {}
for key, points in simplified_curves.items():
endpoints[key] = (points[0], points[-1])
# Adjust endpoints based on proximity
for key, (start, end) in endpoints.items():
if distance(start, end) < threshold:
mid = midpoint(start, end)
updated_curves[key][0] = mid
updated_curves[key][-1] = mid
# Compare all pairs to adjust midpoints
keys = list(endpoints.keys())
for i in range(len(keys)):
key1 = keys[i]
start1, end1 = endpoints[key1]
for j in range(i + 1, len(keys)):
key2 = keys[j]
start2, end2 = endpoints[key2]
if distance(start1, start2) < threshold:
mid = midpoint(start1, start2)
updated_curves[key1][0] = mid
updated_curves[key2][0] = mid
if distance(start1, end2) < threshold:
mid = midpoint(start1, end2)
updated_curves[key1][0] = mid
updated_curves[key2][-1] = mid
if distance(end1, start2) < threshold:
mid = midpoint(end1, start2)
updated_curves[key1][-1] = mid
updated_curves[key2][0] = mid
if distance(end1, end2) < threshold:
mid = midpoint(end1, end2)
updated_curves[key1][-1] = mid
updated_curves[key2][-1] = mid
# Round points
for key, points in updated_curves.items():
updated_curves[key] = [round_point(point) for point in points]
# Reconstruct inverse_dict
for index, points in updated_curves.items():
for i in range(len(points) - 1):
start_point = tuple(points[i])
end_point = tuple(points[i + 1])
line_key = (start_point, end_point)
inverse_dict[line_key] = index
return updated_curves, inverse_dict
def plot_segments(inverse_dict: dict, title: str):
"""
Plots line segments with labels.
Args:
inverse_dict (dict): Inverse dictionary mapping line segments to segment IDs.
title (str): Title of the plot.
"""
plt.figure(figsize=(10, 6))
plotted_labels = set()
for (start, end), segment_id in inverse_dict.items():
x = [start[0], end[0]]
y = [start[1], end[1]]
label = f'Segment {segment_id}' if segment_id not in plotted_labels else ""
plt.plot(x, y, marker='o', label=label)
plotted_labels.add(segment_id)
plt.title(title)
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid(True)
plt.show()
def plot_points(curves: dict, title: str):
"""
Plots points for all curves.
Args:
curves (dict): Dictionary of curves with segment IDs as keys and list of points as values.
title (str): Title of the plot.
"""
plt.figure(figsize=(10, 6))
for points in curves.values():
x, y = zip(*points)
plt.plot(x, y, marker='o', linestyle='None')
plt.title(title)
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
plt.show()
def construct_adj_list(updated_curves: dict) -> Tuple[defaultdict, List[Tuple[float, float], Tuple[float, float]]]:
"""
Creates an adjacency list and segment list from the updated curves.
Args:
updated_curves (dict): Updated curves with segment IDs as keys.
Returns:
tuple: Adjacency list and list of segments.
"""
adj_list = defaultdict(list)
segments = []
for polyline in updated_curves.values():
for i in range(len(polyline) - 1):
start, end = polyline[i], polyline[i + 1]
adj_list[start].append(end)
adj_list[end].append(start)
segments.append((start, end))
return adj_list, segments
def find_cycles(adj_list: defaultdict) -> List[List[Tuple[float, float]]]:
"""
Finds all unique cycles in the graph using depth-first search (DFS).
Args:
adj_list (defaultdict): Adjacency list of the graph.
Returns:
list: List of unique cycles, each cycle is a list of points.
"""
def dfs(node, start, visited, path, cycles):
visited[node] = True
path.append(node)
for neighbor in adj_list[node]:
if neighbor == start and len(path) > 2:
cycle = path[:] + [start]
cycles.append(cycle)
elif not visited[neighbor]:
dfs(neighbor, start, visited, path, cycles)
path.pop()
visited[node] = False
cycles = []
visited = defaultdict(bool)
for node in adj_list:
if not visited[node]:
dfs(node, node, visited, [], cycles)
unique_cycles = []
for cycle in cycles:
cycle_set = set(cycle)
if all(cycle_set != set(c) for c in unique_cycles):
unique_cycles.append(cycle)
return unique_cycles
def separate_non_cycle_lines(segments: List[Tuple[Tuple[float, float], Tuple[float, float]]],
cycles: List[List[Tuple[float, float]]]) -> List[Tuple[float, float]]:
"""
Separates non-cycle lines from the list of segments.
Args:
segments (list): List of segments as tuples of points.
cycles (list): List of cycles, each cycle is a list of points.
Returns:
list: List of non-cycle segments.
"""
cycle_edges = set()
for cycle in cycles:
for i in range(len(cycle) - 1):
edge = tuple(sorted([cycle[i], cycle[i + 1]]))
cycle_edges.add(edge)
non_cycle_lines = []
for start, end in segments:
edge = tuple(sorted([start, end]))
if edge not in cycle_edges:
non_cycle_lines.append((start, end))
return non_cycle_lines
def process_cycles(updated_curves: dict) -> Tuple[List[List[Tuple[float, float]]], List[Tuple[float, float]]]:
"""
Detects cycles and separates non-cycle lines.
Args:
updated_curves (dict): Updated curves with segment IDs as keys.
Returns:
tuple: List of cycles and list of non-cycle lines.
"""
adj_list, segments = construct_adj_list(updated_curves)
cycles = find_cycles(adj_list)
non_cycle_lines = separate_non_cycle_lines(segments, cycles)
return cycles, non_cycle_lines
def mean_square_circle_error(polygon: np.ndarray, center: np.ndarray, radius: float, num_points: int = 10) -> float:
"""
Calculate the mean squared error of fitting a circle to a polygon.
Args:
polygon (np.ndarray): Array of points representing the polygon.
center (np.ndarray): Center of the circle.
radius (float): Radius of the circle.
num_points (int): Number of points to sample per segment (default is 10).
Returns:
float: Mean squared error of the circle fit.
"""
total_error = 0
total_samples = 0
for i in range(len(polygon)):
p1 = polygon[i]
p2 = polygon[(i + 1) % len(polygon)]
segment_points = np.linspace(p1, p2, num_points)
for point in segment_points:
closest_point = closest_point_on_circle(point, center, radius)
dist = np.linalg.norm(point - closest_point)
error = dist ** 2
total_error += error
total_samples += len(segment_points)
mse = total_error / total_samples
return mse
def closest_point_on_circle(point: np.ndarray, center: np.ndarray, radius: float) -> np.ndarray:
"""
Find the closest point on the circle to a given point.
Args:
point (np.ndarray): Point for which closest circle point is computed.
center (np.ndarray): Center of the circle.
radius (float): Radius of the circle.
Returns:
np.ndarray: Closest point on the circle to the given point.
"""
direction = point - center
norm = np.linalg.norm(direction)
if norm == 0:
return center + np.array([radius, 0])
direction /= norm
return center + direction * radius
def best_fit_circle(polygon: List[Tuple[float, float]]) -> Tuple[np.ndarray, float, float]:
"""
Find the best fit circle for a polygon using random sampling.
Args:
polygon (list): List of points representing the polygon.
Returns:
tuple: Center (np.ndarray), radius (float), and mean squared error (float) of the best fit circle.
"""
polygon = np.array(polygon)
best_mse = float('inf')
best_center = None
best_radius = None
for _ in range(50):
sample_indices = np.random.choice(len(polygon), 3, replace=False)
sample_points = polygon[sample_indices]
A, B, C = sample_points
D = 2 * (A[0] * (B[1] - C[1]) +
B[0] * (C[1] - A[1]) +
C[0] * (A[1] - B[1]))
if D == 0:
continue
Ux = ((A[0] ** 2 + A[1] ** 2) * (B[1] - C[1]) +
(B[0] ** 2 + B[1] ** 2) * (C[1] - A[1]) +
(C[0] ** 2 + C[1] ** 2) * (A[1] - B[1])) / D
Uy = ((A[0] ** 2 + A[1] ** 2) * (C[0] - B[0]) +
(B[0] ** 2 + B[1] ** 2) * (A[0] - C[0]) +
(C[0] ** 2 + C[1] ** 2) * (B[0] - A[0])) / D
center = np.array([Ux, Uy])
radius = np.linalg.norm(center - A)
mse = mean_square_circle_error(polygon, center, radius)
if mse < best_mse:
best_mse = mse
best_center = center
best_radius = radius
return best_center, best_radius, best_mse
def plot_polygon_and_circle(polygon: List[Tuple[float, float]], center: np.ndarray, radius: float, label: str):
"""
Plot the polygon and the best fit circle.
Args:
polygon (list): List of points representing the polygon.
center (numpy.ndarray): Center of the circle.
radius (float): Radius of the circle.
label (str): Label for the circle in the plot.
"""
polygon = np.array(polygon)
theta = np.linspace(0, 2 * np.pi, 100)
circle_x = center[0] + radius * np.cos(theta)
circle_y = center[1] + radius * np.sin(theta)
plt.plot(circle_x, circle_y, 'r--', label=label)
plt.scatter(*center, color='green', zorder=5, label='Center')
def plot_remaining_sides(unique_cycles: List[List[Tuple[float, float]]], marked_sides: set):
"""
Plot remaining sides of polygons that are not marked.
Args:
unique_cycles (list): List of polygons where each polygon is a list of points.
marked_sides (set): Set of marked sides.
"""
for polygon in unique_cycles:
for i in range(len(polygon)):
next_i = (i + 1) % len(polygon)
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[next_i])]))
if side not in marked_sides:
plt.plot([polygon[i][0], polygon[next_i][0]],
[polygon[i][1], polygon[next_i][1]],
'k-', label='Remaining Side' if i == 0 else "")
def best_fit_rectangle(vertices: np.ndarray, lines: List[Tuple[Tuple[float, float], Tuple[float, float]]]) -> Tuple[np.ndarray, float, None]:
"""
Attempt to fit a rectangle to the given vertices.
Args:
vertices (numpy.ndarray): Array of vertices.
lines (list): List of lines as tuples of points.
Returns:
tuple: Rectangle vertices, rotation angle, and radius (None).
"""
if len(vertices) != 4:
return None, None, None
side_lengths = np.array([np.linalg.norm(vertices[i] - vertices[(i + 1) % 4]) for i in range(4)])
if not (np.isclose(side_lengths[0], side_lengths[2], rtol=0.1) and np.isclose(side_lengths[1], side_lengths[3], rtol=0.1)):
return None, None, None
min_adjacent_ratio = np.min(side_lengths) / np.max(side_lengths)
if min_adjacent_ratio > 0.5:
return None, None, None
centroid = np.mean(vertices, axis=0)
best_rotation_angle = 0 # Placeholder for rotation calculation
rectangle_vertices = np.array([
centroid + np.array([-side_lengths[0] / 2, -side_lengths[1] / 2]),
centroid + np.array([side_lengths[0] / 2, -side_lengths[1] / 2]),
centroid + np.array([side_lengths[0] / 2, side_lengths[1] / 2]),
centroid + np.array([-side_lengths[0] / 2, side_lengths[1] / 2])
])
return rectangle_vertices, best_rotation_angle, None
def get_best_fit_polygon(vertices: np.ndarray, lines: List[Tuple[Tuple[float, float], Tuple[float, float]]]) -> Tuple[np.ndarray, float, float]:
"""
Find the best fit regular polygon for the given vertices and lines.
Args:
vertices (numpy.ndarray): Array of vertices.
lines (list): List of lines as tuples of points.
Returns:
tuple: Approximate polygon vertices, rotation angle, and radius.
"""
centroid = np.mean(vertices, axis=0)
distances = np.linalg.norm(vertices - centroid, axis=1)
average_radius = np.mean(distances)
n_vertices = len(vertices)
def generate_regular_polygon(centroid, radius, n_vertices, rotation_angle=0):
angles = np.linspace(0, 2 * np.pi, n_vertices, endpoint=False) + rotation_angle
return np.array([
[centroid[0] + radius * np.cos(angle), centroid[1] + radius * np.sin(angle)]
for angle in angles
])
def fit_score(vertices, approx_vertices):
return np.sum(cdist(vertices, approx_vertices, 'euclidean').min(axis=1))
def line_fit_score(lines, approx_vertices):
total_distance = 0
total_samples = 0
for line in lines:
p1, p2 = line
segment_points = np.linspace(p1, p2, 10)
distances = cdist(segment_points, approx_vertices, 'euclidean').min(axis=1)
total_distance += np.sum(distances)
total_samples += len(distances)
return total_distance / total_samples
best_fit_polygon = None
best_fit_score = float('inf')
best_rotation_angle = 0
best_radius = average_radius
radii = np.linspace(average_radius - 1, average_radius + 1, 3)
for radius in radii:
for angle in np.linspace(0, 2 * np.pi, 360):
approx_vertices = generate_regular_polygon(centroid, radius, n_vertices, rotation_angle=angle)
vertex_score = fit_score(vertices, approx_vertices)
line_score = line_fit_score(lines, approx_vertices)
score = vertex_score + line_score
if score < best_fit_score:
best_fit_score = score
best_fit_polygon = approx_vertices
best_rotation_angle = angle
best_radius = radius
return best_fit_polygon, best_rotation_angle, best_radius
def get_best_fit_star_shape(vertices: np.ndarray, lines: List[Tuple[Tuple[float, float], Tuple[float, float]]]) -> Tuple[np.ndarray, float, float]:
"""
Attempt to fit a star shape to the given vertices and lines.
Args:
vertices (numpy.ndarray): Array of vertices.
lines (list): List of lines as tuples of points.
Returns:
tuple: Star shape vertices, rotation angle, and radius.
"""
centroid = np.mean(vertices, axis=0)
distances = np.linalg.norm(vertices - centroid, axis=1)
angles = np.arctan2(vertices[:, 1] - centroid[1], vertices[:, 0] - centroid[0])
sorted_indices = np.argsort(angles)
sorted_vertices = vertices[sorted_indices]
outer_vertices = sorted_vertices[::2]
inner_vertices = sorted_vertices[1::2]
star_points = np.empty((len(vertices), 2))
star_points[::2] = outer_vertices
star_points[1::2] = inner_vertices
best_rotation_angle = 0
best_radius = np.mean(distances[sorted_indices[::2]])
return star_points, best_rotation_angle, best_radius
def get_best_fit_shape(vertices: np.ndarray,
lines: List[Tuple[Tuple[float, float], Tuple[float, float]]]) -> Tuple[np.ndarray, float, float, str]:
"""
Determine the best fit shape (polygon, rectangle, or star) for the given vertices and lines.
Args:
vertices (numpy.ndarray): Array of vertices.
lines (list): List of lines as tuples of points.
Returns:
tuple: Best fit polygon vertices, rotation angle, radius, and type of polygon.
"""
centroid = np.mean(vertices, axis=0)
# Attempt to fit a rectangle
if len(vertices) == 4:
best_fit_rectangle_vertices, best_rotation_angle, _ = get_best_fit_rectangle(vertices, lines)
if best_fit_rectangle_vertices is not None:
polygon_type = "rectangle"
return best_fit_rectangle_vertices, best_rotation_angle, None, polygon_type
# Attempt to fit a star shape
if len(vertices) % 2 == 0 and len(vertices) >= 8:
best_fit_star_vertices, best_rotation_angle, best_radius = get_best_fit_star_shape(vertices, lines)
if best_fit_star_vertices is not None:
polygon_type = "star"
return best_fit_star_vertices, best_rotation_angle, best_radius, polygon_type
# Fallback to regular polygon
best_fit_polygon, best_rotation_angle, best_radius = get_best_fit_polygon(vertices, lines)
polygon_type = "polygon"
return best_fit_polygon, best_rotation_angle, best_radius, polygon_type
def filter_points(points: np.ndarray) -> np.ndarray:
"""
Filters out points that are too close to each other based on a threshold.
Args:
points (numpy.ndarray): Array of points.
Returns:
numpy.ndarray: Filtered array of points.
"""
distances = [np.linalg.norm(points[i] - points[(i + 1) % len(points)]) for i in range(len(points))]
avg_distance = np.mean(distances)
threshold = 0.85 * avg_distance
i = 0
while i < len(points):
if distances[i] < threshold:
dist_prev = np.linalg.norm(points[(i - 1) % len(points)] - points[i])
dist_next = np.linalg.norm(points[(i + 1) % len(points)] - points[(i + 2) % len(points)])
if dist_prev <= dist_next:
points = np.delete(points, i, axis=0)
else:
points = np.delete(points, (i + 1) % len(points), axis=0)
distances = [np.linalg.norm(points[j] - points[(j + 1) % len(points)]) for j in range(len(points))]
else:
i += 1
return points
def calculate_internal_angle(p1: Tuple[float, float], p2: Tuple[float, float], p3: Tuple[float, float]) -> float:
"""
Calculates the internal angle at p2 formed by p1, p2, p3.
Args:
p1 (tuple): Previous point as (x, y).
p2 (tuple): Current point as (x, y).
p3 (tuple): Next point as (x, y).
Returns:
float: The internal angle in degrees.
"""
vec1 = np.array(p2) - np.array(p1)
vec2 = np.array(p3) - np.array(p2)
dot_product = np.dot(vec1, vec2)
magnitude1 = np.linalg.norm(vec1)
magnitude2 = np.linalg.norm(vec2)
if magnitude1 == 0 or magnitude2 == 0:
return 0
cos_theta = dot_product / (magnitude1 * magnitude2)
cos_theta = min(1, max(-1, cos_theta))
return math.degrees(math.acos(cos_theta))
def calculate_area_contribution(p1: Tuple[float, float], p2: Tuple[float, float],
p3: Tuple[float, float]) -> float:
"""
Calculate the signed area of the triangle formed by p1, p2, p3.
Args:
p1 (tuple): First point as (x, y).
p2 (tuple): Second point as (x, y).
p3 (tuple): Third point as (x, y).
Returns:
float: Signed area of the triangle.
"""
return 0.5 * abs(p1[0] * (p2[1] - p3[1]) +
p2[0] * (p3[1] - p1[1]) +
p3[0] * (p1[1] - p2[1]))
def process_polygons(polygons: List[List[Tuple[float, float]]]) -> Tuple[List[np.ndarray], List[List[Tuple[float, float]]]]:
"""
Processes polygons to identify concave vertices and filter points.
Args:
polygons (list): List of polygons, each polygon is a list of points.
Returns:
tuple: List of processed vertices arrays and corresponding lines.
"""
vertices_arr = []
lines_arr = []
for points in polygons:
lines = [(points[i], points[(i + 1) % len(points)]) for i in range(len(points))]
concave_vertices = []
for i in range(len(points)):
p_prev = points[i - 1]
p_curr = points[i]
p_next = points[(i + 1) % len(points)]
angle = calculate_internal_angle(p_prev, p_curr, p_next)
if angle > 180:
concave_vertices.append(p_curr)
points = [p for p in points if p not in concave_vertices]
points = filter_points(np.array(points))
heap = []
for i in range(len(points)):
p_prev = points[i - 1]
p_curr = points[i]
p_next = points[(i + 1) % len(points)]
area_contribution = calculate_area_contribution(p_prev, p_curr, p_next)
heapq.heappush(heap, (-area_contribution, p_curr))
vertices = set()
while heap:
_, vertex = heapq.heappop(heap)
vertex_tuple = tuple(vertex)
if not any(are_approximately_equal(vertex, v, tol=1.0) for v in vertices):
vertices.add(vertex_tuple)
vertices = np.array([np.array(v) for v in vertices])
vertices_arr.append(vertices)
lines_arr.append(lines)
return vertices_arr, lines_arr
def sample_points_along_segment(p1: Tuple[float, float], p2: Tuple[float, float],
num_points: int = 10) -> np.ndarray:
"""
Samples points along a line segment.
Args:
p1 (tuple): Start point as (x, y).
p2 (tuple): End point as (x, y).
num_points (int): Number of points to sample (default is 10).
Returns:
numpy.ndarray: Array of sampled points.
"""
return np.linspace(p1, p2, num_points)
def process_polygons_with_fit(vertices_list: List[np.ndarray],
lines_list: List[List[Tuple[float, float]]],
error_threshold: float = 150.0) -> Tuple[List[Tuple[np.ndarray, float, float, str]],
List[Tuple[float, float], Tuple[float, float]],
List[Tuple[float, float], Tuple[float, float]]]:
"""
Processes polygons by fitting shapes and filtering based on error thresholds.
Args:
vertices_list (list): List of vertices arrays.
lines_list (list): List of lines corresponding to each polygon.
error_threshold (float): Maximum allowed error for fitting (default is 150.0).
Returns:
tuple: Valid polygons, rejected polygons, and remaining segments.
"""
valid_polygons = []
rejected_polygons = []
remaining_segments = []
for vertices, lines in zip(vertices_list, lines_list):
if len(vertices) == 0 or len(lines) == 0:
continue
best_fit_polygon, best_rotation_angle, best_radius, polygon_type = get_best_fit_shape(vertices, lines)
if best_fit_polygon is None:
continue
line_errors = []
for line in lines:
p1, p2 = line
segment_points = sample_points_along_segment(p1, p2)
distances = cdist(segment_points, best_fit_polygon, 'euclidean').min(axis=1)
line_errors.append(np.mean(distances))
if any(error > error_threshold for error in line_errors):
rejected_polygons.append((vertices, lines))
remaining_segments += lines
continue
valid_polygons.append((best_fit_polygon, best_rotation_angle, best_radius, polygon_type))
return valid_polygons, rejected_polygons, remaining_segments
def plot_lines_of_symmetry(polygon_vertices: np.ndarray, polygon_type: str = "polygon"):
"""
Plot lines of symmetry for regular polygons and rectangles.
Args:
polygon_vertices (numpy.ndarray): Array of vertices for the polygon/rectangle.
polygon_type (str): Type of polygon, either "polygon", "rectangle", or "star".
"""
centroid = np.mean(polygon_vertices, axis=0)
plt.figure(figsize=(6, 6))
plt.plot(*polygon_vertices.T, 'r-', label='Polygon')
plt.plot([polygon_vertices[-1, 0], polygon_vertices[0, 0]],
[polygon_vertices[-1, 1], polygon_vertices[0, 1]], 'r-')
plt.plot(centroid[0], centroid[1], 'ro', label='Centroid')
if polygon_type in ["polygon", "star"]:
for vertex in polygon_vertices:
plt.plot([vertex[0], centroid[0]], [vertex[1], centroid[1]], 'g--', label='Line of Symmetry')
if len(polygon_vertices) % 2 == 0 and polygon_type == "polygon":
num_vertices = len(polygon_vertices)
for i in range(num_vertices // 2):
opposite_vertex = polygon_vertices[(i + num_vertices // 2) % num_vertices]
plt.plot([polygon_vertices[i][0], opposite_vertex[0]],
[polygon_vertices[i][1], opposite_vertex[1]], 'b--', label='Bisecting Line')
for i in range(num_vertices):
next_i = (i + 1) % num_vertices
midpoint = (polygon_vertices[i] + polygon_vertices[next_i]) / 2
opposite_midpoint = (polygon_vertices[(i + num_vertices // 2) % num_vertices] +
polygon_vertices[(next_i + num_vertices // 2) % num_vertices]) / 2
plt.plot([midpoint[0], opposite_midpoint[0]], [midpoint[1], opposite_midpoint[1]],
'r--', label='Perpendicular Bisector')
elif polygon_type == "rectangle":
diagonals = [
(polygon_vertices[0], polygon_vertices[2]),
(polygon_vertices[1], polygon_vertices[3])
]
for diagonal in diagonals:
plt.plot([diagonal[0][0], diagonal[1][0]], [diagonal[0][1], diagonal[1][1]],
'g--', label='Diagonal')
for i in range(2):
midpoint = (polygon_vertices[i] + polygon_vertices[(i + 2) % 4]) / 2
plt.plot([midpoint[0], centroid[0]], [midpoint[1], centroid[1]],
'b--', label='Midline')
plt.axis('equal')
plt.legend()
plt.title('Lines of Symmetry')
plt.show()
def handle_remaining_segments(remaining_segments: List[Tuple[Tuple[float, float], Tuple[float, float]]],
error_threshold: float = 150.0) -> List[Tuple[np.ndarray, float, float]]:
"""
Handles remaining segments by attempting to fit polygons.
Args:
remaining_segments (list): List of remaining segments as tuples of points.
error_threshold (float): Maximum allowed error for fitting (default is 150.0).
Returns:
list: List of final fitted polygons.
"""
heapq.heapify(remaining_segments)
final_polygons = []
utilized_segments = set()
while remaining_segments:
current_segment = heapq.heappop(remaining_segments)
if tuple(map(tuple, current_segment)) in utilized_segments:
continue
remaining_polygons = [current_segment]
vertices = np.array([point for segment in remaining_polygons for point in segment])
lines = remaining_polygons
best_fit_polygon, best_rotation_angle, best_radius = get_best_fit_polygon(vertices, lines)
if best_fit_polygon is None:
continue
line_errors = []
for line in lines:
p1, p2 = line
segment_points = sample_points_along_segment(p1, p2)
distances = cdist(segment_points, best_fit_polygon, 'euclidean').min(axis=1)
line_errors.append(np.mean(distances))
if any(error > error_threshold for error in line_errors):
for line in lines:
heapq.heappush(remaining_segments, line)
continue
final_polygons.append((best_fit_polygon, best_rotation_angle, best_radius))
for segment in lines:
utilized_segments.add(tuple(map(tuple, segment)))
return final_polygons
def plot_all(valid_polygons: List[Tuple[np.ndarray, float, float, str]],
possible_circles: List[Tuple[np.ndarray, float, List[Tuple[float, float]]]],
remaining_sides: set,
curves: dict,
inverse_dict: dict,
merged_segments: List[Tuple[float, float]],
xlim: float = None,
ylim: float = None):
"""
Plots all fitted polygons, circles, remaining sides, original curves, and merged segments.
Args:
valid_polygons (list): List of valid fitted polygons.
possible_circles (list): List of possible circles with centers, radii, and polygons.
remaining_sides (set): Set of remaining sides as tuples of points.
curves (dict): Original curves with curve indices as keys.
inverse_dict (dict): Inverse dictionary mapping line segments to curve indices.
merged_segments (list): List of merged segments as tuples of points.
xlim (float, optional): X-axis limit for the plot.
ylim (float, optional): Y-axis limit for the plot.
"""
plt.figure(figsize=(12, 12))
remaining_sides = set([
((float(x1), float(y1)), (float(x2), float(y2)))
for ((x1, y1), (x2, y2)) in remaining_sides
])
all_x = []
all_y = []
for best_fit_polygon, best_rotation_angle, best_radius, polygon_type in valid_polygons:
all_x.extend(best_fit_polygon[:, 0])
all_y.extend(best_fit_polygon[:, 1])
plt.plot(np.append(best_fit_polygon[:, 0], best_fit_polygon[0, 0]),
np.append(best_fit_polygon[:, 1], best_fit_polygon[0, 1]),
'ro-', label='Best Fit Polygon')
for center, radius, circle_points in possible_circles:
circle = plt.Circle(center, radius, color='b', fill=False, label='Best Fit Circle')
plt.gca().add_artist(circle)
all_x.append(center[0] + radius)
all_x.append(center[0] - radius)
all_y.append(center[1] + radius)
all_y.append(center[1] - radius)
circle_points = np.array(circle_points)
all_x.extend(circle_points[:, 0])
all_y.extend(circle_points[:, 1])
plotted_curves = set()
for side in remaining_sides:
if side in inverse_dict:
curve_num = inverse_dict[side]
elif (side[1], side[0]) in inverse_dict:
curve_num = inverse_dict[(side[1], side[0])]
else:
continue
if curve_num not in plotted_curves:
if curve_num in curves:
points = curves[curve_num]
x_values, y_values = zip(*points)
all_x.extend(x_values)
all_y.extend(y_values)
plt.plot(x_values, y_values, label=f'Curve {curve_num}')
plotted_curves.add(curve_num)
for segment in merged_segments:
(x1, y1), (x2, y2) = segment
all_x.extend([x1, x2])
all_y.extend([y1, y2])
plt.plot([x1, x2], [y1, y2], 'g-', label='Merged Segment')
if xlim is not None and ylim is not None:
plt.xlim(-50, xlim)
plt.ylim(-50, ylim)
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Regularized Shapes')
plt.grid(True)
plt.show()
def detect_circles(unique_cycles: List[List[Tuple[float, float]]],
threshold: float = 25.0) -> Tuple[List[List[Tuple[float, float]]],
List[Tuple[np.ndarray, float, List[Tuple[float, float]]]],
set]:
"""
Detects circles fitting the polygons and plots the results.
Args:
unique_cycles (list): List of unique cycles, each cycle is a list of points.
threshold (float): Maximum allowed mean squared error for a valid circle (default is 25.0).
Returns:
tuple: Filtered unused loops, possible circles, and remaining sides.
"""
marked_sides = set()
remaining_sides = set()
possible_circles = []
unused_loops = []
min_heap = []
for polygon in unique_cycles:
center, radius, mse = best_fit_circle(polygon)
heapq.heappush(min_heap, (mse, center, radius, polygon))
while min_heap:
mse, center, radius, polygon = heapq.heappop(min_heap)
contains_marked_side = False
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
if side in marked_sides:
contains_marked_side = True
break
if contains_marked_side:
unused_loops.append(polygon)
continue
plot_polygon_and_circle(polygon, center, radius, label='Best Fit Circle')
plot_remaining_sides(unique_cycles, marked_sides)
plt.legend()
plt.axis('equal')
plt.show()
print(f'Mean Square Fitting Error: {mse:.4f}')
if mse < threshold:
possible_circles.append((center, radius, polygon))
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
marked_sides.add(side)
else:
unused_loops.append(polygon)
filtered_unused_loops = []
for loop in unused_loops:
all_sides_unused = True
for i in range(len(loop)):
side = tuple(sorted([tuple(loop[i]), tuple(loop[(i + 1) % len(loop)])]))
if side in marked_sides:
all_sides_unused = False
break
if all_sides_unused:
filtered_unused_loops.append(loop)
# Plot remaining sides
plt.figure()
plot_remaining_sides(unique_cycles, marked_sides)
# Update remaining sides
for polygon in unique_cycles:
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
if side not in marked_sides:
remaining_sides.add(side)
remaining_sides = set([
((float(x1), float(y1)), (float(x2), float(y2)))
for ((x1, y1), (x2, y2)) in remaining_sides
])
print("Final Possible Circles are:")
for center, radius, polygon in possible_circles:
plot_polygon_and_circle(polygon, center, radius, label='Best Fit Circle')
plt.legend()
plt.axis('equal')
plt.show()
return filtered_unused_loops, possible_circles, remaining_sides
def merge_collinear_segments(segments: List[Tuple[Tuple[float, float], Tuple[float, float]]],
tol: float = 1.0) -> Tuple[List[Tuple[float, float], Tuple[float, float]], dict]:
"""
Merge collinear segments into single segments based on proximity and slope similarity.
Args:
segments (list): List of segments where each segment is represented as a tuple of two points ((x1, y1), (x2, y2)).
tol (float): Tolerance for considering segments as collinear (default is 1.0).
Returns:
tuple: Merged segments and a mapping from merged segments to original segments.
"""
merged_segments = []
used = set()
segment_map = {}
def are_collinear(s1, s2, tol):
slope1 = compute_slope(s1[0], s1[1])
slope2 = compute_slope(s2[0], s2[1])
return abs(slope1 - slope2) < tol
while len(used) < len(segments):
for i, (start1, end1) in enumerate(segments):
if i not in used:
break
collinear_group = [(start1, end1)]
used.add(i)
while True:
merged = False
for j, (start2, end2) in enumerate(segments):
if j in used:
continue
if are_collinear((start1, end1), (start2, end2), tol):
if (are_approximately_equal(start1, start2, tol) or
are_approximately_equal(start1, end2, tol) or
are_approximately_equal(end1, start2, tol) or
are_approximately_equal(end1, end2, tol)):
collinear_group.append((start2, end2))
used.add(j)
merged = True
if not merged:
break
# Create merged segment
all_points = np.array([point for segment in collinear_group for point in segment])
min_idx = np.argmin(all_points[:, 0])
max_idx = np.argmax(all_points[:, 0])
min_y_idx = np.argmin(all_points[:, 1])
max_y_idx = np.argmax(all_points[:, 1])
if abs(compute_slope(start1, end1)) < tol:
merged_segment = (tuple(all_points[min_idx]), tuple(all_points[max_idx]))
segment_map[merged_segment] = collinear_group
merged_segments.append(merged_segment)
else:
merged_segment = (tuple(all_points[min_y_idx]), tuple(all_points[max_y_idx]))
segment_map[merged_segment] = collinear_group
merged_segments.append(merged_segment)
return merged_segments, segment_map
def find_segments_with_common_vertices(merged_segments: List[Tuple[Tuple[float, float], Tuple[float, float]]],
tol: float = 1.0) -> List[Tuple[Tuple[float, float], Tuple[float, float]]]:
"""
Identify segments from the merged segments that share common vertices.
Args:
merged_segments (list): List of merged segments.
tol (float): Tolerance for considering vertices as common (default is 1.0).
Returns:
list: List of segments that have common vertices.
"""
common_vertex_segments = []
for i, (start1, end1) in enumerate(merged_segments):
for j, (start2, end2) in enumerate(merged_segments):
if i != j:
if (are_approximately_equal(start1, start2, tol) or
are_approximately_equal(start1, end2, tol) or
are_approximately_equal(end1, start2, tol) or
are_approximately_equal(end1, end2, tol)):
common_vertex_segments.append((start1, end1))
break
return common_vertex_segments
def revert_to_original_segments(common_vertex_segments: List[Tuple[Tuple[float, float], Tuple[float, float]]],
segment_map: dict) -> List[Tuple[float, float], Tuple[float, float]]:
"""
Revert the merged segments back to their original segments.
Args:
common_vertex_segments (list): List of segments with common vertices.
segment_map (dict): Mapping from merged segments to original segments.
Returns:
list: List of original segments corresponding to the common vertex segments.
"""
reverted_segments = []
for segment in common_vertex_segments:
reverted_segments += segment_map.get(segment, [])
return reverted_segments
def filter_merged_segments(merged_segments: List[Tuple[Tuple[float, float], Tuple[float, float]]],
common_vertex_segments: List[Tuple[Tuple[float, float], Tuple[float, float]]]) -> List[Tuple[float, float], Tuple[float, float]]:
"""
Filter out the merged segments that are also in the list of common vertex segments.
Args:
merged_segments (list): List of merged segments.
common_vertex_segments (list): List of segments with common vertices.
Returns:
list: Filtered list of merged segments.
"""
filtered_merged_segments = [seg for seg in merged_segments if seg not in common_vertex_segments]
return filtered_merged_segments
def process_segments(segments: List[Tuple[Tuple[float, float], Tuple[float, float]]],
tol: float = 1.0) -> Tuple[List[Tuple[float, float], Tuple[float, float]], List[Tuple[float, float], Tuple[float, float]]]:
"""
Processes segments by merging collinear ones and identifying common vertices.
Args:
segments (list): List of segments as tuples of points.
tol (float): Tolerance for merging (default is 1.0).
Returns:
tuple: Filtered merged segments and reverted original segments.
"""
merged_segments, segment_map = merge_collinear_segments(segments, tol)
common_vertex_segments = find_segments_with_common_vertices(merged_segments, tol)
reverted_segments = revert_to_original_segments(common_vertex_segments, segment_map)
filtered_merged_segments = filter_merged_segments(merged_segments, common_vertex_segments)
return filtered_merged_segments, reverted_segments
def best_fit_star_shape(vertices: np.ndarray,
lines: List[Tuple[Tuple[float, float], Tuple[float, float]]]) -> Tuple[np.ndarray, float, float]:
"""
Detects a star shape that best fits the given vertices and lines.
Args:
vertices (numpy.ndarray): Array of vertices.
lines (list): List of lines as tuples of points.
Returns:
tuple: Star shape vertices, rotation angle, and radius.
"""
centroid = np.mean(vertices, axis=0)
distances = np.linalg.norm(vertices - centroid, axis=1)
angles = np.arctan2(vertices[:, 1] - centroid[1], vertices[:, 0] - centroid[0])
sorted_indices = np.argsort(angles)
sorted_vertices = vertices[sorted_indices]
outer_vertices = sorted_vertices[::2]
inner_vertices = sorted_vertices[1::2]
star_points = np.empty((len(vertices), 2))
star_points[::2] = outer_vertices
star_points[1::2] = inner_vertices
best_rotation_angle = 0
best_radius = np.mean(distances[sorted_indices[::2]])
return star_points, best_rotation_angle, best_radius
def detect_circles(unique_cycles: List[List[Tuple[float, float]]],
threshold: float = 25.0) -> Tuple[List[List[Tuple[float, float]]],
List[Tuple[np.ndarray, float, List[Tuple[float, float]]]],
set]:
"""
Detects circles fitting the polygons and plots the results.
Args:
unique_cycles (list): List of unique cycles, each cycle is a list of points.
threshold (float): Maximum allowed mean squared error for a valid circle (default is 25.0).
Returns:
tuple: Filtered unused loops, possible circles, and remaining sides.
"""
marked_sides = set()
remaining_sides = set()
possible_circles = []
unused_loops = []
min_heap = []
for polygon in unique_cycles:
center, radius, mse = best_fit_circle(polygon)
heapq.heappush(min_heap, (mse, center, radius, polygon))
while min_heap:
mse, center, radius, polygon = heapq.heappop(min_heap)
contains_marked_side = False
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
if side in marked_sides:
contains_marked_side = True
break
if contains_marked_side:
unused_loops.append(polygon)
continue
plot_polygon_and_circle(polygon, center, radius, label='Best Fit Circle')
plot_remaining_sides(unique_cycles, marked_sides)
plt.legend()
plt.axis('equal')
plt.show()
print(f'Mean Square Fitting Error: {mse:.4f}')
if mse < threshold:
possible_circles.append((center, radius, polygon))
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
marked_sides.add(side)
else:
unused_loops.append(polygon)
filtered_unused_loops = []
for loop in unused_loops:
all_sides_unused = True
for i in range(len(loop)):
side = tuple(sorted([tuple(loop[i]), tuple(loop[(i + 1) % len(loop)])]))
if side in marked_sides:
all_sides_unused = False
break
if all_sides_unused:
filtered_unused_loops.append(loop)
# Plot remaining sides
plt.figure()
plot_remaining_sides(unique_cycles, marked_sides)
# Update remaining sides
for polygon in unique_cycles:
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
if side not in marked_sides:
remaining_sides.add(side)
remaining_sides = set([
((float(x1), float(y1)), (float(x2), float(y2)))
for ((x1, y1), (x2, y2)) in remaining_sides
])
print("Final Possible Circles are:")
for center, radius, polygon in possible_circles:
plot_polygon_and_circle(polygon, center, radius, label='Best Fit Circle')
plt.legend()
plt.axis('equal')
plt.show()
return filtered_unused_loops, possible_circles, remaining_sides
def regularize(path: str, xlim: float = None, ylim: float = None):
"""
Main function to regularize the input CSV and process all steps.
Args:
path (str): Path to the CSV file.
xlim (float, optional): X-axis limit for plotting (default is None).
ylim (float, optional): Y-axis limit for plotting (default is None).
"""
# Load points from CSV
all_points = load_points_from_csv(csv_file=path)
# Organize curves
curves = defaultdict(list)
for point in all_points:
curve_index, _, x, y = point
curves[curve_index].append((x, y))
# Simplify curves using RDP
simplified_curves, inverse_dict, segment_points_dict = simplify_curves(curves)
# Update endpoints with midpoints
updated_curves, updated_inverse_dict = update_endpoints_with_midpoints(simplified_curves)
# Plot simplified segments
plot_segments(updated_inverse_dict, "Simplified Segments")
# Detect cycles and separate non-cycle lines
cycles, non_cycle_lines = process_cycles(updated_curves)
# Detect circles fitting the cycles
print("\nAttempting to fit circles in loops:\n")
filtered_unused_loops, possible_circles, remaining_sides = detect_circles(cycles)
# Handle filtered unused loops and update remaining sides
unique_cycles = cycles
for loop in filtered_unused_loops:
for polygon in unique_cycles:
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
remaining_sides.add(side)
# Remove sides in possible circles
for _, _, polygon in possible_circles:
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
if side in remaining_sides:
remaining_sides.remove(side)
# Remove sides in filtered unused loops
for polygon in filtered_unused_loops:
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
if side in remaining_sides:
remaining_sides.remove(side)
# Process segments by merging collinear ones
segments = list(non_cycle_lines)
filtered_merged_segments, reverted_segments = process_segments(segments)
# Plot merged and reverted segments
plot_segments({i: seg for i, seg in enumerate(filtered_merged_segments)}, "Merged Segments Excluding Common Vertices")
plot_segments({i: seg for i, seg in enumerate(reverted_segments)}, "Original Segments with Common Vertices")
remaining_sides = remaining_sides.union(set(reverted_segments))
# Polygon detection
polygon_detection = process_polygons(filtered_unused_loops)
vertices_arr, lines_arr = polygon_detection
if xlim is not None and ylim is not None:
plt.xlim(-50, xlim)
plt.ylim(-50, ylim)
if len(vertices_arr) > 0 or len(lines_arr) > 0 or len(filtered_unused_loops) > 0:
print("Impact Points in current loop are:")
plt.figure(figsize=(10, 10))
for vertices in vertices_arr:
if len(vertices) > 0:
plt.plot(vertices[:, 0], vertices[:, 1], 'o', label='Processed Vertices')
for lines in lines_arr:
for line in lines:
plt.plot([p[0] for p in line], [p[1] for p in line], 'k--', alpha=0.5)
for points in filtered_unused_loops:
plt.plot([p[0] for p in points], [p[1] for p in points], 'x--', label='Original Points')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Impact Points')
plt.legend()
plt.grid(True)
plt.show()
# Fit shapes to polygons and filter based on error
valid_polygons, rejected_polygons, remaining_segments = process_polygons_with_fit(vertices_arr, lines_arr)
# Plot lines of symmetry for valid polygons
for polygon_data in valid_polygons:
polygon_vertices, rotation_angle, radius, polygon_type = polygon_data
plot_lines_of_symmetry(polygon_vertices, polygon_type=polygon_type)
# Handle remaining segments by fitting additional polygons
final_polygons = handle_remaining_segments(remaining_segments)
# Plot approximated polygons
if len(valid_polygons) > 0 or len(final_polygons) > 0:
plt.figure(figsize=(10, 10))
for best_fit_polygon, best_rotation_angle, best_radius, polygon_type in valid_polygons:
plt.plot(np.append(best_fit_polygon[:, 0], best_fit_polygon[0, 0]),
np.append(best_fit_polygon[:, 1], best_fit_polygon[0, 1]),
'ro-', label='Best Fit Polygon')
for best_fit_polygon, best_rotation_angle, best_radius in final_polygons:
plt.plot(np.append(best_fit_polygon[:, 0], best_fit_polygon[0, 0]),
np.append(best_fit_polygon[:, 1], best_fit_polygon[0, 1]),
'go-', label='Final Polygon')
if xlim is not None and ylim is not None:
plt.xlim(-50, xlim)
plt.ylim(-50, ylim)
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Approximated Polygons')
plt.grid(True)
plt.show()
# Final comprehensive plot
plot_all(valid_polygons, possible_circles, remaining_sides, curves, inverse_dict,
filtered_merged_segments, xlim, ylim)
# Example usage:
# Replace "/content/isolated.csv" with your local CSV file path.
# Optionally, set xlim and ylim for plotting boundaries.
if __name__ == "__main__":
regularize("/content/isolated.csv", xlim=100, ylim=100)
Instructions to Run Locally:
-
Install Required Libraries:
Ensure you have all the required Python libraries installed. You can install them using pip:
pip install svgpathtools numpy matplotlib scipy
-
Save the Script:
Save the above code into a Python file, e.g., regularize.py.
-
Prepare Your CSV File:
Ensure your CSV file (isolated.csv in this example) is correctly formatted and located at the specified path. Update the regularize function call at the bottom of the script with the correct path to your CSV file.
-
Run the Script:
Execute the script using Python:
python regularize.py
If you placed your CSV file elsewhere or want different plot limits, adjust the regularize function parameters accordingly.
Notes:
-
Functionality Preservation: All functionalities from the original class-based implementation are preserved in this function-based version. This includes loading points from CSV, simplifying curves, detecting cycles and circles, merging segments, polygon detection, and comprehensive plotting.
-
Plotting: The script will generate multiple plots at different stages of processing. Ensure your environment supports graphical display (e.g., running locally on your machine rather than a headless server).
-
Parameters:
epsilon in simplify_curves controls the degree of curve simplification.
threshold in update_endpoints_with_midpoints determines how close endpoints should be to adjust.
error_threshold in detect_circles and process_polygons_with_fit controls the fitting accuracy for circles and polygons respectively.
tol in various functions controls the tolerance for point and slope comparisons.
-
Customization: Depending on your specific use case and data characteristics, you might need to tweak these parameters for optimal results.
Feel free to further modularize or optimize the code as per your requirements. If you encounter any issues or have further questions, feel free to ask!