Spaces:
Runtime error
Runtime error
Upload 2 files
Browse filesFiles changed (2)
2772 unmodified lines27732774277527762777277827792772 unmodified lines# not necessary for proofing, but for visualization.c_args = list(map(lambda x: self.get(x, lambda: int(x)), c.args))self.additionally_draw(c.name, c_args)for points, bs in cdef.basics:if points:2772 unmodified lines27732774277527762777277827792772 unmodified lines# not necessary for proofing, but for visualization.c_args = list(map(lambda x: self.get(x, lambda: int(x)), c.args))# self.additionally_draw(c.name, c_args)for points, bs in cdef.basics:if points:
17 unmodified lines1819202122232 unmodified lines2627282930313233406 unmodified lines440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511277 unmodified lines789790791792793794795179 unmodified lines97597697797897998098152 unmodified lines103410351036103710381039104065 unmodified lines1106110711081109111011111 unmodified line1113111411151116111711181119112011211122112351 unmodified lines11751176117711781179118011814 unmodified lines11861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123065 unmodified lines129612971298129913001301130240 unmodified lines1343134413451346134713481349135013511352135313547 unmodified lines1362136313641365136613676 unmodified lines137413751376137713781379138013811382138313841385138613871388558 unmodified lines19471948194919501951195217 unmodified linesimport mathfrom typing import Any, Optional, Unionimport geometry as gmimport matplotlib2 unmodified linesimport numpy as npfrom numpy.random import uniform as unif # pylint: disable=g-importing-memberimport graph as ghmatplotlib.use('Agg')ATOM = 1e-12406 unmodified linesclass SemiCircle(Circle):"""Numerical semicircle, inherits from Circle."""def __init__(self,center: Optional[Point] = None,radius: Optional[float] = None,p1: Optional[Point] = None,p2: Optional[Point] = None,p3: Optional[Point] = None,):self.p1 = p1self.p2 = p2self.p3 = p3# Initialize as a Circlesuper().__init__(center, radius, p1, p2, p3)# If p1 and p2 define a diameter, set the center and radius accordinglyif p1 and p2 and not center:self.center = Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2)self.radius = p1.distance(p2) / 2self.r2 = self.radius ** 2# Define the direction or plane for the semicircle (important for sampling and boundaries)def is_within_boundary(self, point: Point) -> bool:"""Check if a point is within the boundary of the semicircle."""vector_to_point = point - self.centerangle = math.atan2(vector_to_point.y, vector_to_point.x)# Normalize the angle within [0, 2*pi]angle = angle if angle >= 0 else (2 * np.pi + angle)# Check if the point is within the semicircle (half of the circle)return -np.pi / 2 <= angle <= np.pi / 2def sample_within(self, points: list[Point], n: int = 5) -> list[Point]:"""Sample a point within the semicircle."""result = Nonebest = -1.0for _ in range(n):# Generate a random angle between -π/2 and π/2 for the semicircleang = unif(-0.5, 0.5) * np.pix = self.center + Point(np.cos(ang), np.sin(ang)) * self.radius# Check if the sampled point is within the active part of the semicircleif not self.is_within_boundary(x):continue# Find the minimum distance between the generated point and the provided pointsmind = min([x.distance(p) for p in points])if mind > best:best = mindresult = xreturn [result]def intersect(self, obj: Union[Line, Circle]) -> tuple[Point, ...]:"""Find intersection points with a Line or another Circle, constrained to the semicircle."""if isinstance(obj, Line):intersections = obj.intersect(self)elif isinstance(obj, Circle):intersections = circle_circle_intersection(self, obj)else:return tuple()# Filter intersections to only return points within the semicirclereturn tuple(p for p in intersections if self.is_within_boundary(p))class HoleCircle(Circle):277 unmodified linesdef check_cyclic(points: list[Point]) -> bool:points = list(set(points))(a, b, c, *ps) = pointscircle = Circle(p1=a, p2=b, p3=c)for d in ps:if not close_enough(d.distance(circle.center), circle.radius):179 unmodified linesdef naming_position(ax: matplotlib.axes.Axes, p: Point, lines: list[Line], circles: list[Circle]) -> tuple[float, float]:"""Figure out a good naming position on the drawing."""_ = ax52 unmodified linesname = name[0] + '_' + name[1:]ax.annotate(name, naming_position(ax, p, lines, circles), color=color, fontsize=15)65 unmodified linesax: matplotlib.axes.Axes, circle: Circle, color: Any = 'cyan') -> Circle:"""Draw a circle."""if circle.num is not None:circle = circle.numelse:1 unmodified lineif len(points) <= 2:returnpoints = [p.num for p in points]p1, p2, p3 = points[:3]circle = Circle(p1=p1, p2=p2, p3=p3)_draw_circle(ax, circle, color)return circledef check_points_semicircle(p1, p2, p3):"""51 unmodified lines}def _draw_semicircle(ax: matplotlib.axes.Axes, P1: Point, P2: Point, P3: Point, color: Any = 'cyan', lw: float = 1.2) -> None:"""Draws a semicircle passing through three points or with one or two points on the diameter.4 unmodified linescolor (Any): Color of the semicircle.lw (float): Line width of the semicircle."""result = check_points_semicircle((P1.x, P1.y), (P2.x, P2.y), (P3.x, P3.y))if not result['is_valid']:print("Points are collinear; cannot form a semicircle.")returncx, cy = result['center']radius = result['radius']diameter_points = result['diameter_points']# If no pair forms a diameter, determine angles for all three pointsif diameter_points is None:# Calculate angles of all three points relative to the circle's centerangles = np.arctan2([P1.y - cy, P2.y - cy, P3.y - cy],[P1.x - cx, P2.x - cx, P3.x - cx])angles = (angles + 2 * np.pi) % (2 * np.pi) # Normalize to [0, 2π]# Determine the start and end angle for the semicirclestart_angle = np.min(angles)end_angle = np.max(angles)if end_angle - start_angle > np.pi:start_angle, end_angle = end_angle, start_angle + 2 * np.pielse:# Use diameter points to define the semicircle anglespx, py = diameter_points[0]qx, qy = diameter_points[1]start_angle = np.arctan2(py - cy, px - cx)end_angle = np.arctan2(qy - cy, qx - cx)if end_angle - start_angle > np.pi:start_angle, end_angle = end_angle, start_angle + 2 * np.pi# Generate points for the semicirclet = np.linspace(start_angle, end_angle, 100)x = cx + radius * np.cos(t)y = cy + radius * np.sin(t)# Plot the semicircleax.plot(x, y, color=color, lw=lw)def draw_semicircle(ax: matplotlib.axes.Axes, semicircle: SemiCircle, color: Any = 'cyan'65 unmodified lines_draw_line(ax, c, d, color=color2, lw=2.0)if name == 'eqangle':a, b, c, d, e, f, g, h = argsx = line_line_intersection(Line(a, b), Line(c, d))if b.distance(x) > a.distance(x):a, b = b, a40 unmodified lines_draw_line(ax, c, d, color=color2, lw=2.0, alpha=0.5)_draw_line(ax, m, n, color=color1, lw=2.0, alpha=0.5)_draw_line(ax, p, q, color=color2, lw=2.0, alpha=0.5)elif name == 'semicircle':o, a, b, c = args_draw_semicircle(ax, SemiCircle(center=o, p1=a, p2=b, p3=c), color=color1, lw=2.0)HCOLORS = Nonedef _draw(ax: matplotlib.axes.Axes,7 unmodified lines):"""Draw everything."""colors = ['red', 'green', 'blue', 'orange', 'magenta', 'purple']pcolor = 'black'lcolor = 'black'ccolor = 'grey'6 unmodified linescolors = ['grey']line_boundaries = []for l in lines:p1, p2 = draw_line(ax, l, color=lcolor)line_boundaries.append((p1, p2))circles = [draw_circle(ax, c, color=ccolor) for c in circles]semicircles = [draw_semicircle(ax, c, color=ccolor) for c in semicircles]for p in points:draw_point(ax, p.num, p.name, line_boundaries, circles, semicircles, color=pcolor)if equals:for i, segs in enumerate(equals['segments']):color = colors[i % len(colors)]558 unmodified linesa, b = argsreturn (a + b) * 0.5def sketch_pentagon(args: tuple[gm.Point, ...]) -> tuple[Point, ...]:points = [Point(1.0, 0.0)]17 unmodified lines181920212223242 unmodified lines27282930313233343536406 unmodified lines443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514277 unmodified lines792793794795796797798179 unmodified lines97897998098198298398452 unmodified lines103710381039104010411042104365 unmodified lines11091110111111121113111411151 unmodified line1117111811191120112111221123112411251126112711281129113051 unmodified lines11821183118411851186118711884 unmodified lines1193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126365 unmodified lines13291330133113321333133440 unmodified lines13751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014117 unmodified lines14191420142114221423142414256 unmodified lines143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476558 unmodified lines20352036203720382039204020412042204317 unmodified linesimport mathfrom typing import Any, Optional, Unionimport randomimport geometry as gmimport matplotlib2 unmodified linesimport numpy as npfrom numpy.random import uniform as unif # pylint: disable=g-importing-memberimport graph as ghfrom collections import defaultdictfrom itertools import combinationsmatplotlib.use('TkAgg')ATOM = 1e-12406 unmodified linesclass SemiCircle(Circle):"""Numerical semicircle, inherits from Circle."""def __init__(self,center: Optional[Point] = None,radius: Optional[float] = None,p1: Optional[Point] = None,p2: Optional[Point] = None,p3: Optional[Point] = None,):self.p1 = p1self.p2 = p2self.p3 = p3# Initialize as a Circlesuper().__init__(center, radius, p1, p2, p3)# If p1 and p2 define a diameter, set the center and radius accordinglyif p1 and p2 and not center:self.center = Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2)self.radius = p1.distance(p2) / 2self.r2 = self.radius ** 2# Define the direction or plane for the semicircle (important for sampling and boundaries)def is_within_boundary(self, point: Point) -> bool:"""Check if a point is within the boundary of the semicircle."""vector_to_point = point - self.centerangle = math.atan2(vector_to_point.y, vector_to_point.x)# Normalize the angle within [0, 2*pi]angle = angle if angle >= 0 else (2 * np.pi + angle)# Check if the point is within the semicircle (half of the circle)return -np.pi / 2 <= angle <= np.pi / 2def sample_within(self, points: list[Point], n: int = 5) -> list[Point]:"""Sample a point within the semicircle."""result = Nonebest = -1.0for _ in range(n):# Generate a random angle between -π/2 and π/2 for the semicircleang = unif(-0.5, 0.5) * np.pix = self.center + Point(np.cos(ang), np.sin(ang)) * self.radius# Check if the sampled point is within the active part of the semicircleif not self.is_within_boundary(x):continue# Find the minimum distance between the generated point and the provided pointsmind = min([x.distance(p) for p in points])if mind > best:best = mindresult = xreturn [result]def intersect(self, obj: Union[Line, Circle]) -> tuple[Point, ...]:"""Find intersection points with a Line or another Circle, constrained to the semicircle."""if isinstance(obj, Line):intersections = obj.intersect(self)elif isinstance(obj, Circle):intersections = circle_circle_intersection(self, obj)else:return tuple()# Filter intersections to only return points within the semicirclereturn tuple(p for p in intersections if self.is_within_boundary(p))class HoleCircle(Circle):277 unmodified linesdef check_cyclic(points: list[Point]) -> bool:points = list(set(points))(a, b, c, *ps) = pointscircle = Circle(p1=a, p2=b, p3=c)for d in ps:if not close_enough(d.distance(circle.center), circle.radius):179 unmodified linesdef naming_position(ax: matplotlib.axes.Axes, p: Point, lines: list[Line], circles: list[Circle], semicircles: list[SemiCircle]) -> tuple[float, float]:"""Figure out a good naming position on the drawing."""_ = ax52 unmodified linesname = name[0] + '_' + name[1:]ax.annotate(name, naming_position(ax, p, lines, circles, semicircles), color=color, fontsize=15)65 unmodified linesax: matplotlib.axes.Axes, circle: Circle, color: Any = 'cyan') -> Circle:"""Draw a circle."""name_circle = circle.nameif circle.num is not None:circle = circle.numelse:1 unmodified lineif len(points) <= 2:returnpoints = [p.num for p in points]print(len(points))p1, p2, p3 = points[:3]circle = Circle(p1=p1, p2=p2, p3=p3)if "," in name_circle:_draw_circle(ax, circle, color)return circleelse:return circledef check_points_semicircle(p1, p2, p3):"""51 unmodified lines}def _draw_semicircle(ax: matplotlib.axes.Axes, P1: Point = None, P2: Point = None, P3: Point = None, color: Any = 'cyan', lw: float = 1.2) -> None:"""Draws a semicircle passing through three points or with one or two points on the diameter.4 unmodified linescolor (Any): Color of the semicircle.lw (float): Line width of the semicircle."""points = [P for P in (P1, P2, P3) if P is not None] # Filter out None valuesif len(points) == 2:cx = (P1.x + P2.x) / 2cy = (P1.y + P2.y) / 2radius = np.sqrt((P2.x - P1.x) ** 2 + (P2.y - P1.y) ** 2) / 2# Compute angle of the diameterangle_diameter = np.arctan2(P2.y - P1.y, P2.x - P1.x)# Randomly determine the orientation of the semicircleoffset_angle = np.pi / 2 if random.choice([True, False]) else -np.pi / 2# Start and end angles for the semicirclestart_angle = angle_diameter + offset_angleend_angle = start_angle + np.pi# Generate points for the semicirclet = np.linspace(start_angle, end_angle, 100)x = cx + radius * np.cos(t)y = cy + radius * np.sin(t)# Plot the semicircleax.plot(x, y, color=color, lw=lw)if len(points) == 3:result = check_points_semicircle((P1.x, P1.y), (P2.x, P2.y), (P3.x, P3.y))if not result['is_valid']:print("Points are collinear; cannot form a semicircle.")returncx, cy = result['center']radius = result['radius']diameter_points = result['diameter_points']# If no pair forms a diameter, determine angles for all three pointsif diameter_points is None:# Calculate angles of all three points relative to the circle's centerangles = np.arctan2([P1.y - cy, P2.y - cy, P3.y - cy],[P1.x - cx, P2.x - cx, P3.x - cx])angles = (angles + 2 * np.pi) % (2 * np.pi) # Normalize to [0, 2π]# Determine the start and end angle for the semicirclestart_angle = np.min(angles)end_angle = np.max(angles)if end_angle - start_angle > np.pi:start_angle, end_angle = end_angle, start_angle + 2 * np.pielse:# Use diameter points to define the semicircle anglespx, py = diameter_points[0]qx, qy = diameter_points[1]start_angle = np.arctan2(py - cy, px - cx)end_angle = np.arctan2(qy - cy, qx - cx)if end_angle - start_angle > np.pi:start_angle, end_angle = end_angle, start_angle + 2 * np.pi# Generate points for the semicirclet = np.linspace(start_angle, end_angle, 100)x = cx + radius * np.cos(t)y = cy + radius * np.sin(t)# Plot the semicircleax.plot(x, y, color=color, lw=lw)def draw_semicircle(ax: matplotlib.axes.Axes, semicircle: SemiCircle, color: Any = 'cyan'65 unmodified lines_draw_line(ax, c, d, color=color2, lw=2.0)if name == 'eqangle':a, b, c, d, e, f, g, h = argsx = line_line_intersection(Line(a, b), Line(c, d))if b.distance(x) > a.distance(x):a, b = b, a40 unmodified lines_draw_line(ax, c, d, color=color2, lw=2.0, alpha=0.5)_draw_line(ax, m, n, color=color1, lw=2.0, alpha=0.5)_draw_line(ax, p, q, color=color2, lw=2.0, alpha=0.5)if name == 'iso_triangle':a, b, c = args_draw_line(ax, c, b, color=color1, lw=2.0)_draw_line(ax, c, a, color=color1, lw=2.0)_draw_line(ax, b, a, color=color2, lw=2.0)if name == 'semicircle':o, a, b, c = args_draw_semicircle(ax, SemiCircle(center=o, p1=a, p2=b, p3=c), color=color1, lw=2.0)def convert_point(gm_point: gm.Point) -> Point:return Point(gm_point.num.x, gm_point.num.y)HCOLORS = Nonedef find_pairs_with_same_distance(line_lengths):# Step 1: Group point pairs by distancedistance_groups = defaultdict(list)for (p1, p2), distance in line_lengths.items():distance_groups[distance].append((p1, p2))# Step 2: Find combinations of pairs with the same distanceresult = []for pairs in distance_groups.values():if len(pairs) > 1: # Only consider distances with multiple pairsfor i in range(len(pairs)):for j in range(i + 1, len(pairs)):line1 = pairs[i]line2 = pairs[j]result.append((line1, line2)) # Group as ((p1, p2), (p3, p4))return resultdef _draw(ax: matplotlib.axes.Axes,7 unmodified lines):"""Draw everything."""colors = ['red', 'green', 'blue', 'orange', 'magenta', 'purple']colors_highlight = [color for color in mcolors.TABLEAU_COLORS.keys() if color not in colors]pcolor = 'black'lcolor = 'black'ccolor = 'grey'6 unmodified linescolors = ['grey']line_boundaries = []line_lengths = {}# Convert all pointsfor p in points:points_numericals = [convert_point(p) for p in points]for l in lines:p1, p2 = draw_line(ax, l, color=lcolor)line_boundaries.append((p1, p2))points_numericals.append(p1)points_numericals.append(p2)unique_points = []seen = set()for p in points_numericals:if (p.x, p.y) not in seen:unique_points.append(p)seen.add((p.x, p.y))print(len(unique_points))for p1, p2 in combinations(unique_points, 2):line_lengths[(p1, p2)] = round(p1.distance(p2), 9)circles = [draw_circle(ax, c, color=ccolor) for c in circles]semicircles = [draw_semicircle(ax, c, color=ccolor) for c in semicircles]for p in points:draw_point(ax, p.num, p.name, line_boundaries, circles, semicircles, color=pcolor)same_length_pairs = find_pairs_with_same_distance(line_lengths)print(len(same_length_pairs))length_color_map = {} # Dictionary to map length to its colorfor i, ((p1, p2), (p3, p4)) in enumerate(same_length_pairs):line_length = p1.distance(p2) # Calculate the length of the lineif line_length not in length_color_map: # Check if length is already in the dictionary#color = colors_highlight[i % len(colors_highlight)]color = colors_highlight[i % len(colors_highlight) ] # Assign a new colorlength_color_map[line_length] = color # Store the length and color in the dictionaryelse:color = length_color_map[line_length] # Use the existing color for this length# Call the highlight function with the determined colorhighlight(ax, 'cong', [p1, p2, p3, p4], lcolor, color, color)if equals:for i, segs in enumerate(equals['segments']):color = colors[i % len(colors)]558 unmodified linesa, b = argsreturn (a + b) * 0.5def sketch_foot(args: tuple[gm.Point, ...]) -> Point:a, b, c = argsreturn a.foot(Line(b, c))def sketch_pentagon(args: tuple[gm.Point, ...]) -> tuple[Point, ...]:points = [Point(1.0, 0.0)]
ag4masses/alphageometry/graph.py+1-1
ag4masses/alphageometry/numericals.py+207-116