from svgpathtools import svg2paths, Path, Line, CubicBezier, QuadraticBezier, Arc
import numpy as np
import csv
from collections import defaultdict
from typing import List, Tuple
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
import heapq
from scipy.spatial.distance import cdist
import math
from collections import defaultdict
import heapq
class CSVProcessor:
"""
Processes and loads data points from a CSV file.
"""
code
def __init__(self, csv_file: str):
"""
Initializes with the CSV file path.
"""
self.csv_file = csv_file
self.all_points = []
def load_points_from_csv(self):
"""
Loads data points from the CSV file into all_points.
"""
with open(self.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])
self.all_points.append((curve_index, 0.0000, x, y))
class CurveProcessor:
"""
Processes curves for simplification and refinement based on given parameters.
"""
code
Assistant
def __init__(self, curves: dict[int, List[Tuple[float, float]]], epsilon: float = 5.0, threshold: float = 5.0):
"""
Initializes with curves, epsilon for simplification, and threshold for endpoint adjustment.
"""
self.curves = curves
self.epsilon = epsilon
self.threshold = threshold
self.simplified_curves = {}
self.inverse_dict = {}
self.segment_points_dict = {}
self.updated_curves = {}
def point_line_distance(self, point, start, end):
"""
Calculates the perpendicular distance from a point to a line segment.
"""
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(self, points, epsilon):
"""
Simplifies a list of points using the Ramer-Douglas-Peucker algorithm.
"""
dmax = 0.0
index = 0
end = len(points)
for i in range(1, end - 1):
d = self.point_line_distance(points[i], points[0], points[-1])
if d > dmax:
index = i
dmax = d
if dmax > epsilon:
rec_results1, idx1 = self.ramer_douglas_peucker(points[:index+1], epsilon)
rec_results2, idx2 = self.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(self):
"""
Simplifies all curves and stores segment information.
"""
simplified_curves = {}
inverse_dict = {}
segment_points_dict = {}
segment_id = 0
for index, points in self.curves.items():
simplified_points, indices = self.ramer_douglas_peucker(points, self.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
self.simplified_curves = simplified_curves
self.inverse_dict = inverse_dict
self.segment_points_dict = segment_points_dict
def distance(self, point1, point2):
"""
Computes the Euclidean distance between two points.
"""
return np.linalg.norm(np.array(point1) - np.array(point2))
def midpoint(self, point1, point2):
"""
Returns the midpoint between two points.
"""
return ((point1[0] + point2[0]) / 2, (point1[1] + point2[1]) / 2)
def round_point(self, point):
"""
Rounds the coordinates of a point to one decimal place.
"""
return (round(point[0], 1), round(point[1], 1))
def update_endpoints_with_midpoints(self):
"""
Adjusts segment endpoints based on proximity and rounds the results.
"""
endpoints = {}
updated_curves = {k: v[:] for k, v in self.simplified_curves.items()}
inverse_dict = {}
for key, points in self.simplified_curves.items():
endpoints[key] = (points[0], points[-1])
for key, (start, end) in endpoints.items():
if self.distance(start, end) < self.threshold:
mid = self.midpoint(start, end)
updated_curves[key][0] = mid
updated_curves[key][-1] = mid
for key1, (start1, end1) in endpoints.items():
for key2, (start2, end2) in endpoints.items():
if key1 < key2:
if self.distance(start1, start2) < self.threshold:
mid = self.midpoint(start1, start2)
updated_curves[key1][0] = mid
updated_curves[key2][0] = mid
if self.distance(start1, end2) < self.threshold:
mid = self.midpoint(start1, end2)
updated_curves[key1][0] = mid
updated_curves[key2][-1] = mid
if self.distance(end1, start2) < self.threshold:
mid = self.midpoint(end1, start2)
updated_curves[key1][-1] = mid
updated_curves[key2][0] = mid
if self.distance(end1, end2) < self.threshold:
mid = self.midpoint(end1, end2)
updated_curves[key1][-1] = mid
updated_curves[key2][-1] = mid
for key, points in updated_curves.items():
updated_curves[key] = [self.round_point(point) for point in points]
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
self.updated_curves = updated_curves
self.inverse_dict = inverse_dict
def plot_segments(self, curves, inverse_dict, title):
"""
Plots line segments with labels.
"""
plt.figure(figsize=(10, 6))
for (start, end), segment_id in inverse_dict.items():
x = [start[0], end[0]]
y = [start[1], end[1]]
plt.plot(x, y, marker='o', label=f'Segment {segment_id}')
plt.title(title)
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.grid(True)
plt.show()
def plot_points(self, curves, title):
"""
Plots points for all curves.
"""
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 process(self):
"""
Executes curve simplification and endpoint updates.
"""
self.simplify_curves()
self.update_endpoints_with_midpoints()
class CycleDetector:
"""Detects cycles in a set of updated curves."""
code
def __init__(self, updated_curves: dict[int, List[Tuple[float, float]]]):
"""Initialize with updated curves and construct adjacency list."""
self.adj_list, self.segments = self.construct_adj_list(updated_curves)
def construct_adj_list(self, updated_curves):
"""Create an adjacency list and segment list from the updated curves."""
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(self, graph):
"""Find all cycles in the graph using depth-first search (DFS)."""
def dfs(node, start, visited, path):
visited[node] = True
path.append(node)
for neighbor in graph[node]:
if neighbor == start and len(path) > 2:
cycle = path[:] + [start]
cycles.append(cycle)
elif not visited[neighbor]:
dfs(neighbor, start, visited, path)
path.pop()
visited[node] = False
cycles = []
visited = defaultdict(bool)
for node in graph:
if not visited[node]:
dfs(node, node, visited, [])
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(self, segments, cycles):
"""Separate non-cycle lines from the 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(self):
"""Detect cycles and separate non-cycle lines."""
cycles = self.find_cycles(self.adj_list)
non_cycle_lines = self.separate_non_cycle_lines(self.segments, cycles)
return cycles, non_cycle_lines
class CircleDetector:
"""Detects circles that best fit polygons and identifies remaining sides."""
code
def __init__(self, unique_cycles):
"""Initialize with a list of unique cycles.
Args:
unique_cycles (list): List of polygons where each polygon is a list of points.
"""
self.unique_cycles = unique_cycles
self.remaining_sides = set()
self.marked_sides = set()
def point_to_segment_dist(self, p, v, w):
"""Compute the squared distance from point p to the segment vw.
Args:
p (np.array): Point for which distance is to be computed.
v (np.array): One endpoint of the segment.
w (np.array): The other endpoint of the segment.
Returns:
float: Squared distance from p to the segment vw.
"""
l2 = np.sum((v - w) ** 2)
if l2 == 0:
return np.sum((p - v) ** 2)
t = max(0, min(1, np.dot(p - v, w - v) / l2))
projection = v + t * (w - v)
return np.sum((p - projection) ** 2)
def mean_square_circle_error(self, polygon, center, radius, num_points=10):
"""Calculate the mean squared error of fitting a circle to a polygon.
Args:
polygon (list): List of points representing the polygon.
center (np.array): Center of the circle.
radius (float): Radius of the circle.
num_points (int): Number of points to sample per segment.
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 = self.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(self, point, center, radius):
"""Find the closest point on the circle to a given point.
Args:
point (np.array): Point for which closest circle point is computed.
center (np.array): Center of the circle.
radius (float): Radius of the circle.
Returns:
np.array: Closest point on the circle to the given point.
"""
direction = point - center
direction /= np.linalg.norm(direction)
return center + direction * radius
def best_fit_circle(self, polygon):
"""Find the best fit circle for a polygon using random sampling.
Args:
polygon (list): List of points representing the polygon.
Returns:
tuple: Center (np.array), 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 = sample_points[0]
B = sample_points[1]
C = sample_points[2]
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 = self.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(self, polygon, center, radius, label):
"""Plot the polygon and the best fit circle.
Args:
polygon (list): List of points representing the polygon.
center (np.array): 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(self, unique_cycles, marked_sides):
"""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:
polygon = np.array(polygon)
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
if side not in marked_sides:
plt.plot(*np.array([polygon[i], polygon[(i + 1) % len(polygon)]]).T, 'k-', label='Remaining Side' if i == 0 else "")
def detect_circles(self):
"""Detect circles fitting the polygons and plot results.
Returns:
tuple: A tuple containing two elements:
- filtered_unused_loops (list): List of polygons that do not fit any circle.
- possible_circles (list): List of tuples (center, radius, polygon) for possible circles.
"""
min_heap = []
possible_circles = []
unused_loops = []
for polygon in self.unique_cycles:
center, radius, mse = self.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 self.marked_sides:
contains_marked_side = True
break
if contains_marked_side:
unused_loops.append(polygon)
continue
self.plot_polygon_and_circle(polygon, center, radius, label='Best Fit Circle')
self.plot_remaining_sides(self.unique_cycles, self.marked_sides)
plt.legend()
plt.axis('equal')
plt.show()
print(f'Mean Square Fitting Error: {mse:.4f}')
if mse < 25:
possible_circles.append((center, radius, polygon))
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
self.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 self.marked_sides:
all_sides_unused = False
break
if all_sides_unused:
filtered_unused_loops.append(loop)
plt.figure()
self.plot_remaining_sides(self.unique_cycles, self.marked_sides)
for polygon in self.unique_cycles:
polygon = np.array(polygon)
for i in range(len(polygon)):
side = tuple(sorted([tuple(polygon[i]), tuple(polygon[(i + 1) % len(polygon)])]))
if side not in self.marked_sides:
self.remaining_sides.add(side)
self.remaining_sides = set([
((float(x1), float(y1)), (float(x2), float(y2)))
for ((x1, y1), (x2, y2)) in self.remaining_sides
])
print("Final Possible Circles are : ")
for center, radius, polygon in possible_circles:
self.plot_polygon_and_circle(polygon, center, radius, label='Best Fit Circle')
plt.legend()
plt.axis('equal')
plt.show()
return filtered_unused_loops, possible_circles
def are_approximately_equal(p1, p2, tol=5):
"""
Check if two points are approximately equal within a given tolerance.
code
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).
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, p2):
"""
Compute the slope of the line passing through two points.
code
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])
class SegmentProcessor:
def init(self, segments, tol=1):
"""
Initialize the SegmentProcessor.
code
Args:
segments (list): A 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).
"""
self.segments = segments
self.tol = tol
self.merged_segments = []
self.map = {}
self.common_vertex_segments = []
self.filtered_merged_segments = []
def merge_collinear_segments(self):
"""
Merge collinear segments into single segments based on proximity and slope similarity.
"""
merged_segments = []
used = set()
segment_map = {}
while len(used) < len(self.segments):
for i, (start1, end1) in enumerate(self.segments):
if i not in used:
break
collinear_group = [(start1, end1)]
used.add(i)
while True:
merged = False
for j, (start2, end2) in enumerate(self.segments):
if j in used:
continue
if (np.abs(compute_slope(start1, end1) - compute_slope(start2, end2)) < self.tol):
if any(are_approximately_equal(start, start2) or
are_approximately_equal(start, end2) or
are_approximately_equal(end, start2) or
are_approximately_equal(end, end2) for start, end in collinear_group):
collinear_group.append((start2, end2))
used.add(j)
merged = True
if not merged:
break
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 np.abs(compute_slope(start1, end1)) < self.tol:
merged_segments.append((tuple(all_points[min_idx]), tuple(all_points[max_idx])))
segment_map[(tuple(all_points[min_idx]), tuple(all_points[max_idx]))] = collinear_group
else:
segment_map[(tuple(all_points[min_y_idx]), tuple(all_points[max_y_idx]))] = collinear_group
merged_segments.append((tuple(all_points[min_y_idx]), tuple(all_points[max_y_idx])))
self.merged_segments = merged_segments
self.map = segment_map
def find_segments_with_common_vertices(self):
"""
Identify segments from the merged segments that share common vertices.
Returns:
list: A list of segments that have common vertices.
"""
common_vertex_segments = []
for i, (start1, end1) in enumerate(self.merged_segments):
for j, (start2, end2) in enumerate(self.merged_segments):
if i != j:
if are_approximately_equal(start1, start2, self.tol) or are_approximately_equal(start1, end2, self.tol) or \
are_approximately_equal(end1, start2, self.tol) or are_approximately_equal(end1, end2, self.tol):
common_vertex_segments.append((start1, end1))
break
self.common_vertex_segments = common_vertex_segments
def revert_to_original_segments(self):
"""
Revert the merged segments back to their original segments.
Returns:
list: A list of original segments corresponding to the common vertex segments.
"""
reverted_segments = []
for segment in self.common_vertex_segments:
reverted_segments += self.map[segment]
return reverted_segments
def filter_merged_segments(self):
"""
Filter out the merged segments that are also in the list of common vertex segments.
"""
self.filtered_merged_segments = [seg for seg in self.merged_segments if seg not in self.common_vertex_segments]
def plot_segments(self, segments, title, highlight_segments=None):
"""
Plot segments with an optional highlight for specific segments.
Args:
segments (list): A list of segments where each segment is represented as a tuple of two points ((x1, y1), (x2, y2)).
title (str): Title of the plot.
highlight_segments (list, optional): Segments to be highlighted in a different color (default is None).
"""
plt.figure(figsize=(10, 8))
for (start, end) in segments:
plt.plot([start[0], end[0]], [start[1], end[1]], marker='o', color='blue')
if highlight_segments:
for (start, end) in highlight_segments:
plt.plot([start[0], end[0]], [start[1], end[1]], marker='o', color='red')
plt.title(title)
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)
plt.show()
curves = defaultdict(list)
for point in csv_processor.all_points:
curve_index, _, x, y = point
curves[curve_index].append((x, y))
curve_processor = CurveProcessor(curves)
curve_processor.process()
curves = curve_processor.segment_points_dict
cycle_detector = CycleDetector(curve_processor.updated_curves)
cycles, non_cycle_lines = cycle_detector.process_cycles()
circle_detector = CircleDetector(cycles)
print("\ntry to fit circle in loops : \n")
remaining_sides = circle_detector.remaining_sides
filtered_unused_loops, possible_circles = circle_detector.detect_circles()
unique_cycles = circle_detector.unique_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)
segments = list(non_cycle_lines)
segment_processor = SegmentProcessor(segments)
segment_processor.merge_collinear_segments()
segment_processor.find_segments_with_common_vertices()
rem = segment_processor.revert_to_original_segments()
segment_processor.filter_merged_segments()
segment_processor.plot_segments(segment_processor.filtered_merged_segments, "Merged Segments Excluding Common Vertices")
segment_processor.plot_segments(rem, "Original Segments with Common Vertices")
remaining_sides = remaining_sides.union(set(rem))
polygon_detection = PolygonDetection()
vertices_arr, lines_arr = polygon_detection.process_polygons(filtered_unused_loops)
if xlim!=None and ylim!= None:
plt.xlim(-50, ylim)
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:
x_values, y_values = zip(*line)
plt.plot(x_values, y_values, '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()
valid_polygons, rejected_polygons, remaining_segments = polygon_detection.process_polygons_with_fit(vertices_arr, lines_arr)
polygon_detection.plot_all_polygons_with_symmetry()
final_polygons = polygon_detection.handle_remaining_segments(remaining_segments)
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!=None and ylim!= None:
plt.xlim(-50, ylim)
plt.ylim(-50, ylim)
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Approximated Polygons')
plt.grid(True)
plt.show()
def plot_all(valid_polygons, possible_circles, remaining_sides, curves, inverse_dict, merged_segments):
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)
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!=None and ylim!= None:
plt.xlim(-50, ylim)
plt.ylim(-50, ylim)
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Regularized Shapes')
plt.grid(True)
plt.show()
if xlim!=None and ylim!= None:
plt.xlim(-50, ylim)
plt.ylim(-50, ylim)
plot_all(valid_polygons, possible_circles, remaining_sides, curves, curve_processor.inverse_dict, segment_processor.filtered_merged_segments)
regularize("/content/isolated.csv")
hey what does this script does
This Python script is a comprehensive tool designed to process and analyze geometric data, particularly focusing on curves and shapes extracted from data points in a CSV file. Here's a detailed breakdown of its functionality:
1. Overview
The script performs the following primary tasks:
Data Loading: Reads and loads curve data points from a CSV file.
Curve Simplification: Simplifies complex curves using the Ramer-Douglas-Peucker (RDP) algorithm.
Cycle Detection: Identifies closed loops (cycles) within the simplified curves.
Circle Fitting: Fits circles to the detected cycles to determine circular shapes.
Segment Processing: Merges collinear line segments and identifies common vertices.
Polygon Detection: Detects and fits regular polygons (like rectangles and stars) to the remaining segments.
Visualization: Generates various plots to visualize the processed and detected shapes.
2. Detailed Components
a. CSVProcessor
Purpose: Loads and processes data points from a CSV file.
Functionality:
Reads each row of the CSV file.
Extracts the curve index and the (x, y) coordinates of each point.
Stores all points in a list for further processing.
b. CurveProcessor
Purpose: Simplifies and refines the loaded curves.
Functionality:
Simplification: Uses the RDP algorithm to reduce the number of points in each curve while maintaining its overall shape. This is controlled by the epsilon parameter, which determines the degree of simplification.
Endpoint Adjustment: Adjusts the endpoints of segments based on proximity to ensure smoother transitions between segments. This is governed by the threshold parameter.
Visualization: Provides methods to plot the simplified segments and points for visual verification.
c. CycleDetector
Purpose: Detects cycles (closed loops) within the simplified curves.
Functionality:
Adjacency List Construction: Builds an adjacency list to represent connections between points.
Cycle Detection: Uses Depth-First Search (DFS) to find all unique cycles in the graph.
Segregation: Separates cycle edges from non-cycle edges for further analysis.
d. CircleDetector
Purpose: Fits circles to the detected cycles to identify circular shapes.
Functionality:
Best Fit Circle: For each cycle, it attempts to find the best-fitting circle using random sampling of points.
Error Calculation: Computes the Mean Squared Error (MSE) to evaluate the fit quality.
Visualization: Plots the fitted circles alongside the original polygons and remaining sides.
Classification: Determines whether a cycle sufficiently fits a circle based on the MSE threshold.
e. SegmentProcessor
Purpose: Processes and merges collinear line segments.
Functionality:
Merging: Combines segments that are collinear and within a specified tolerance to simplify the overall structure.
Common Vertices Identification: Finds segments that share common vertices to identify interconnected parts of the shape.
Visualization: Provides plotting capabilities to visualize merged and original segments.
f. PolygonDetection
Purpose: Detects and fits regular polygons (like rectangles and stars) to the remaining segments.
Functionality:
Point Sampling: Samples points along each segment to facilitate accurate fitting.
Angle Calculation: Determines internal angles to identify convex and concave vertices.
Shape Fitting: Attempts to fit regular polygons (e.g., rectangles) or star shapes based on the number of vertices and their distribution.
Error Evaluation: Assesses the fit quality by calculating distance errors between the original segments and the fitted shapes.
Symmetry Analysis: Identifies and plots lines of symmetry for the detected polygons.
Visualization: Plots all detected polygons, their symmetries, and any remaining segments that didn't fit well.
3. Regularization Process
The regularize function orchestrates the entire process:
Data Loading:
Initializes CSVProcessor with the provided CSV file path.
Loads all data points into memory.
Curve Simplification:
Initializes CurveProcessor with the loaded curves.
Simplifies the curves and adjusts their endpoints.
Cycle Detection and Circle Fitting:
Initializes CycleDetector with the updated curves.
Detects cycles and separates non-cycle lines.
Initializes CircleDetector to fit circles to the detected cycles and identify remaining sides.
Segment Processing:
Initializes SegmentProcessor with the non-cycle lines.
Merges collinear segments and identifies common vertices.
Plots the merged and original segments.
Polygon Detection:
Initializes PolygonDetection.
Processes the remaining loops to detect and fit polygons.
Plots the detected polygons and their symmetries.
Handles any remaining segments that didn't fit into regular polygons.
Final Visualization:
Combines all the processed data and plots the final regularized shapes, including fitted polygons and circles, along with any remaining segments.
4. Execution
At the end of the script, the regularize function is called with the path to a CSV file ("/content/isolated.csv"). This execution triggers the entire processing pipeline, resulting in several visualizations that depict:
Simplified curves.
Detected cycles and fitted circles.
Merged line segments.
Detected and fitted regular polygons.
Final regularized geometric shapes.
5. Practical Applications
This script can be used in various applications, including but not limited to:
Vector Graphics Processing: Simplifying and regularizing SVG paths for cleaner and more efficient vector graphics.
Computer Vision: Preprocessing and analyzing shapes detected in images or scans.
Geometric Data Analysis: Identifying and regularizing geometric patterns in large datasets.
Mathematical Modeling: Studying and modeling regular shapes and their properties from raw data.
6. Customization and Extensibility
The script is modular, with each class handling a specific aspect of the processing pipeline. This design allows for easy customization and extension. For instance:
Adjusting Simplification: Tuning the epsilon parameter in CurveProcessor for different levels of curve simplification.
Modifying Fit Thresholds: Changing the error_threshold in PolygonDetection to control the acceptance of fitted shapes.
Extending Shape Detection: Adding methods to detect other regular shapes like triangles, hexagons, etc.
Conclusion
In summary, this script provides a robust framework for processing, simplifying, and regularizing geometric data from CSV files. Through a series of systematic steps and visualizations, it identifies meaningful geometric patterns and shapes, making it a valuable tool for various analytical and graphical applications.