forked from google-deepmind/alphageometry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
numericals.py
1921 lines (1491 loc) · 48 KB
/
numericals.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2023 DeepMind Technologies Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Numerical representation of geometry."""
from __future__ import annotations
import math
from typing import Any, Optional, Union
import geometry as gm
import matplotlib
from matplotlib import pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from numpy.random import uniform as unif # pylint: disable=g-importing-member
matplotlib.use('TkAgg')
ATOM = 1e-12
# Some variables are there for better code reading.
# pylint: disable=unused-assignment
# pylint: disable=unused-argument
# pylint: disable=unused-variable
# Naming in geometry is a little different
# we stick to geometry naming to better read the code.
# pylint: disable=invalid-name
class Point:
"""Numerical point."""
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other: Point) -> bool:
return (self.x, self.y) < (other.x, other.y)
def __gt__(self, other: Point) -> bool:
return (self.x, self.y) > (other.x, other.y)
def __add__(self, p: Point) -> Point:
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p: Point) -> Point:
return Point(self.x - p.x, self.y - p.y)
def __mul__(self, f: float) -> Point:
return Point(self.x * f, self.y * f)
def __rmul__(self, f: float) -> Point:
return self * f
def __truediv__(self, f: float) -> Point:
return Point(self.x / f, self.y / f)
def __floordiv__(self, f: float) -> Point:
div = self / f # true div
return Point(int(div.x), int(div.y))
def __str__(self) -> str:
return 'P({},{})'.format(self.x, self.y)
def close(self, point: Point, tol: float = 1e-12) -> bool:
return abs(self.x - point.x) < tol and abs(self.y - point.y) < tol
def midpoint(self, p: Point) -> Point:
return Point(0.5 * (self.x + p.x), 0.5 * (self.y + p.y))
def distance(self, p: Union[Point, Line, Circle]) -> float:
if isinstance(p, Line):
return p.distance(self)
if isinstance(p, Circle):
return abs(p.radius - self.distance(p.center))
dx = self.x - p.x
dy = self.y - p.y
return np.sqrt(dx * dx + dy * dy)
def distance2(self, p: Point) -> float:
if isinstance(p, Line):
return p.distance(self)
dx = self.x - p.x
dy = self.y - p.y
return dx * dx + dy * dy
def rotatea(self, ang: float) -> Point:
sinb, cosb = np.sin(ang), np.cos(ang)
return self.rotate(sinb, cosb)
def rotate(self, sinb: float, cosb: float) -> Point:
x, y = self.x, self.y
return Point(x * cosb - y * sinb, x * sinb + y * cosb)
def flip(self) -> Point:
return Point(-self.x, self.y)
def perpendicular_line(self, line: Line) -> Line:
return line.perpendicular_line(self)
def foot(self, line: Line) -> Point:
if isinstance(line, Line):
l = line.perpendicular_line(self)
return line_line_intersection(l, line)
elif isinstance(line, Circle):
c, r = line.center, line.radius
return c + (self - c) * r / self.distance(c)
raise ValueError('Dropping foot to weird type {}'.format(type(line)))
def parallel_line(self, line: Line) -> Line:
return line.parallel_line(self)
def norm(self) -> float:
return np.sqrt(self.x**2 + self.y**2)
def cos(self, other: Point) -> float:
x, y = self.x, self.y
a, b = other.x, other.y
return (x * a + y * b) / self.norm() / other.norm()
def dot(self, other: Point) -> float:
return self.x * other.x + self.y * other.y
def sign(self, line: Line) -> int:
return line.sign(self)
def is_same(self, other: Point) -> bool:
return self.distance(other) <= ATOM
class Line:
"""Numerical line."""
def __init__(
self,
p1: Point = None,
p2: Point = None,
coefficients: tuple[int, int, int] = None,
):
if p1 is None and p2 is None and coefficients is None:
self.coefficients = None, None, None
return
a, b, c = coefficients or (
p1.y - p2.y,
p2.x - p1.x,
p1.x * p2.y - p2.x * p1.y,
)
# Make sure a is always positive (or always negative for that matter)
# With a == 0, Assuming a = +epsilon > 0
# Then b such that ax + by = 0 with y>0 should be negative.
if a < 0.0 or a == 0.0 and b > 0.0:
a, b, c = -a, -b, -c
self.coefficients = a, b, c
def parallel_line(self, p: Point) -> Line:
a, b, _ = self.coefficients
return Line(coefficients=(a, b, -a * p.x - b * p.y)) # pylint: disable=invalid-unary-operand-type
def perpendicular_line(self, p: Point) -> Line:
a, b, _ = self.coefficients
return Line(p, p + Point(a, b))
def greater_than(self, other: Line) -> bool:
a, b, _ = self.coefficients
x, y, _ = other.coefficients
# b/a > y/x
return b * x > a * y
def __gt__(self, other: Line) -> bool:
return self.greater_than(other)
def __lt__(self, other: Line) -> bool:
return other.greater_than(self)
def same(self, other: Line) -> bool:
a, b, c = self.coefficients
x, y, z = other.coefficients
return close_enough(a * y, b * x) and close_enough(b * z, c * y)
def equal(self, other: Line) -> bool:
a, b, _ = self.coefficients
x, y, _ = other.coefficients
# b/a == y/x
return b * x == a * y
def less_than(self, other: Line) -> bool:
a, b, _ = self.coefficients
x, y, _ = other.coefficients
# b/a > y/x
return b * x < a * y
def intersect(self, obj: Union[Line, Circle]) -> tuple[Point, ...]:
if isinstance(obj, Line):
return line_line_intersection(self, obj)
if isinstance(obj, Circle):
return line_circle_intersection(self, obj)
def distance(self, p: Point) -> float:
a, b, c = self.coefficients
return abs(self(p.x, p.y)) / math.sqrt(a * a + b * b)
def __call__(self, x: Point, y: Point = None) -> float:
if isinstance(x, Point) and y is None:
return self(x.x, x.y)
a, b, c = self.coefficients
return x * a + y * b + c
def is_parallel(self, other: Line) -> bool:
a, b, _ = self.coefficients
x, y, _ = other.coefficients
return abs(a * y - b * x) < ATOM
def is_perp(self, other: Line) -> bool:
a, b, _ = self.coefficients
x, y, _ = other.coefficients
return abs(a * x + b * y) < ATOM
def cross(self, other: Line) -> float:
a, b, _ = self.coefficients
x, y, _ = other.coefficients
return a * y - b * x
def dot(self, other: Line) -> float:
a, b, _ = self.coefficients
x, y, _ = other.coefficients
return a * x + b * y
def point_at(self, x: float = None, y: float = None) -> Optional[Point]:
"""Get a point on line closest to (x, y)."""
a, b, c = self.coefficients
# ax + by + c = 0
if x is None and y is not None:
if a != 0:
return Point((-c - b * y) / a, y) # pylint: disable=invalid-unary-operand-type
else:
return None
elif x is not None and y is None:
if b != 0:
return Point(x, (-c - a * x) / b) # pylint: disable=invalid-unary-operand-type
else:
return None
elif x is not None and y is not None:
if a * x + b * y + c == 0.0:
return Point(x, y)
return None
def diff_side(self, p1: Point, p2: Point) -> Optional[bool]:
d1 = self(p1.x, p1.y)
d2 = self(p2.x, p2.y)
if d1 == 0 or d2 == 0:
return None
return d1 * d2 < 0
def same_side(self, p1: Point, p2: Point) -> Optional[bool]:
d1 = self(p1.x, p1.y)
d2 = self(p2.x, p2.y)
if d1 == 0 or d2 == 0:
return None
return d1 * d2 > 0
def sign(self, point: Point) -> int:
s = self(point.x, point.y)
if s > 0:
return 1
elif s < 0:
return -1
return 0
def is_same(self, other: Line) -> bool:
a, b, c = self.coefficients
x, y, z = other.coefficients
return abs(a * y - b * x) <= ATOM and abs(b * z - c * y) <= ATOM
def sample_within(self, points: list[Point], n: int = 5) -> list[Point]:
"""Sample a point within the boundary of points."""
center = sum(points, Point(0.0, 0.0)) * (1.0 / len(points))
radius = max([p.distance(center) for p in points])
if close_enough(center.distance(self), radius):
center = center.foot(self)
a, b = line_circle_intersection(self, Circle(center.foot(self), radius))
result = None
best = -1.0
for _ in range(n):
rand = unif(0.0, 1.0)
x = a + (b - a) * rand
mind = min([x.distance(p) for p in points])
if mind > best:
best = mind
result = x
return [result]
class InvalidLineIntersectError(Exception):
pass
class HalfLine(Line):
"""Numerical ray."""
def __init__(self, tail: Point, head: Point): # pylint: disable=super-init-not-called
self.line = Line(tail, head)
self.coefficients = self.line.coefficients
self.tail = tail
self.head = head
def intersect(self, obj: Union[Line, HalfLine, Circle, HoleCircle]) -> Point:
if isinstance(obj, (HalfLine, Line)):
return line_line_intersection(self.line, obj)
exclude = [self.tail]
if isinstance(obj, HoleCircle):
exclude += [obj.hole]
a, b = line_circle_intersection(self.line, obj)
if any([a.close(x) for x in exclude]):
return b
if any([b.close(x) for x in exclude]):
return a
v = self.head - self.tail
va = a - self.tail
vb = b - self.tail
if v.dot(va) > 0:
return a
if v.dot(vb) > 0:
return b
raise InvalidLineIntersectError()
def sample_within(self, points: list[Point], n: int = 5) -> list[Point]:
center = sum(points, Point(0.0, 0.0)) * (1.0 / len(points))
radius = max([p.distance(center) for p in points])
if close_enough(center.distance(self.line), radius):
center = center.foot(self)
a, b = line_circle_intersection(self, Circle(center.foot(self), radius))
if (a - self.tail).dot(self.head - self.tail) > 0:
a, b = self.tail, a
else:
a, b = self.tail, b # pylint: disable=self-assigning-variable
result = None
best = -1.0
for _ in range(n):
x = a + (b - a) * unif(0.0, 1.0)
mind = min([x.distance(p) for p in points])
if mind > best:
best = mind
result = x
return [result]
def _perpendicular_bisector(p1: Point, p2: Point) -> Line:
midpoint = (p1 + p2) * 0.5
return Line(midpoint, midpoint + Point(p2.y - p1.y, p1.x - p2.x))
def same_sign(
a: Point, b: Point, c: Point, d: Point, e: Point, f: Point
) -> bool:
a, b, c, d, e, f = map(lambda p: p.sym, [a, b, c, d, e, f])
ab, cb = a - b, c - b
de, fe = d - e, f - e
return (ab.x * cb.y - ab.y * cb.x) * (de.x * fe.y - de.y * fe.x) > 0
class Circle:
"""Numerical circle."""
def __init__(
self,
center: Optional[Point] = None,
radius: Optional[float] = None,
p1: Optional[Point] = None,
p2: Optional[Point] = None,
p3: Optional[Point] = None,
):
if not center:
if not (p1 and p2 and p3):
self.center = self.radius = self.r2 = None
return
# raise ValueError('Circle without center need p1 p2 p3')
l12 = _perpendicular_bisector(p1, p2)
l23 = _perpendicular_bisector(p2, p3)
center = line_line_intersection(l12, l23)
self.center = center
self.a, self.b = center.x, center.y
if not radius:
if not (p1 or p2 or p3):
raise ValueError('Circle needs radius or p1 or p2 or p3')
p = p1 or p2 or p3
self.r2 = (self.a - p.x) ** 2 + (self.b - p.y) ** 2
self.radius = math.sqrt(self.r2)
else:
self.radius = radius
self.r2 = radius * radius
def intersect(self, obj: Union[Line, Circle]) -> tuple[Point, ...]:
if isinstance(obj, Line):
return obj.intersect(self)
if isinstance(obj, Circle):
return circle_circle_intersection(self, obj)
def sample_within(self, points: list[Point], n: int = 5) -> list[Point]:
"""Sample a point within the boundary of points."""
result = None
best = -1.0
for _ in range(n):
ang = unif(0.0, 2.0) * np.pi
x = self.center + Point(np.cos(ang), np.sin(ang)) * self.radius
mind = min([x.distance(p) for p in points])
if mind > best:
best = mind
result = x
return [result]
class HoleCircle(Circle):
"""Numerical circle with a missing point."""
def __init__(self, center: Point, radius: float, hole: Point):
super().__init__(center, radius)
self.hole = hole
def intersect(self, obj: Union[Line, HalfLine, Circle, HoleCircle]) -> Point:
if isinstance(obj, Line):
a, b = line_circle_intersection(obj, self)
if a.close(self.hole):
return b
return a
if isinstance(obj, HalfLine):
return obj.intersect(self)
if isinstance(obj, Circle):
a, b = circle_circle_intersection(obj, self)
if a.close(self.hole):
return b
return a
if isinstance(obj, HoleCircle):
a, b = circle_circle_intersection(obj, self)
if a.close(self.hole) or a.close(obj.hole):
return b
return a
def solve_quad(a: float, b: float, c: float) -> tuple[float, float]:
"""Solve a x^2 + bx + c = 0."""
a = 2 * a
d = b * b - 2 * a * c
if d < 0:
return None # the caller should expect this result.
y = math.sqrt(d)
return (-b - y) / a, (-b + y) / a
def circle_circle_intersection(c1: Circle, c2: Circle) -> tuple[Point, Point]:
"""Returns a pair of Points as intersections of c1 and c2."""
# circle 1: (x0, y0), radius r0
# circle 2: (x1, y1), radius r1
x0, y0, r0 = c1.a, c1.b, c1.radius
x1, y1, r1 = c2.a, c2.b, c2.radius
d = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
if d == 0:
raise InvalidQuadSolveError()
a = (r0**2 - r1**2 + d**2) / (2 * d)
h = r0**2 - a**2
if h < 0:
raise InvalidQuadSolveError()
h = np.sqrt(h)
x2 = x0 + a * (x1 - x0) / d
y2 = y0 + a * (y1 - y0) / d
x3 = x2 + h * (y1 - y0) / d
y3 = y2 - h * (x1 - x0) / d
x4 = x2 - h * (y1 - y0) / d
y4 = y2 + h * (x1 - x0) / d
return Point(x3, y3), Point(x4, y4)
class InvalidQuadSolveError(Exception):
pass
def line_circle_intersection(line: Line, circle: Circle) -> tuple[Point, Point]:
"""Returns a pair of points as intersections of line and circle."""
a, b, c = line.coefficients
r = float(circle.radius)
center = circle.center
p, q = center.x, center.y
if b == 0:
x = -c / a
x_p = x - p
x_p2 = x_p * x_p
y = solve_quad(1, -2 * q, q * q + x_p2 - r * r)
if y is None:
raise InvalidQuadSolveError()
y1, y2 = y
return (Point(x, y1), Point(x, y2))
if a == 0:
y = -c / b
y_q = y - q
y_q2 = y_q * y_q
x = solve_quad(1, -2 * p, p * p + y_q2 - r * r)
if x is None:
raise InvalidQuadSolveError()
x1, x2 = x
return (Point(x1, y), Point(x2, y))
c_ap = c + a * p
a2 = a * a
y = solve_quad(
a2 + b * b, 2 * (b * c_ap - a2 * q), c_ap * c_ap + a2 * (q * q - r * r)
)
if y is None:
raise InvalidQuadSolveError()
y1, y2 = y
return Point(-(b * y1 + c) / a, y1), Point(-(b * y2 + c) / a, y2)
def _check_between(a: Point, b: Point, c: Point) -> bool:
"""Whether a is between b & c."""
return (a - b).dot(c - b) > 0 and (a - c).dot(b - c) > 0
def circle_segment_intersect(
circle: Circle, p1: Point, p2: Point
) -> list[Point]:
l = Line(p1, p2)
px, py = line_circle_intersection(l, circle)
result = []
if _check_between(px, p1, p2):
result.append(px)
if _check_between(py, p1, p2):
result.append(py)
return result
def line_segment_intersection(l: Line, A: Point, B: Point) -> Point: # pylint: disable=invalid-name
a, b, c = l.coefficients
x1, y1, x2, y2 = A.x, A.y, B.x, B.y
dx, dy = x2 - x1, y2 - y1
alpha = (-c - a * x1 - b * y1) / (a * dx + b * dy)
return Point(x1 + alpha * dx, y1 + alpha * dy)
def line_line_intersection(l1: Line, l2: Line) -> Point:
a1, b1, c1 = l1.coefficients
a2, b2, c2 = l2.coefficients
# a1x + b1y + c1 = 0
# a2x + b2y + c2 = 0
d = a1 * b2 - a2 * b1
if d == 0:
raise InvalidLineIntersectError
return Point((c2 * b1 - c1 * b2) / d, (c1 * a2 - c2 * a1) / d)
def check_too_close(
newpoints: list[Point], points: list[Point], tol: int = 0.1
) -> bool:
if not points:
return False
avg = sum(points, Point(0.0, 0.0)) * 1.0 / len(points)
mindist = min([p.distance(avg) for p in points])
for p0 in newpoints:
for p1 in points:
if p0.distance(p1) < tol * mindist:
return True
return False
def check_too_far(
newpoints: list[Point], points: list[Point], tol: int = 4
) -> bool:
if len(points) < 2:
return False
avg = sum(points, Point(0.0, 0.0)) * 1.0 / len(points)
maxdist = max([p.distance(avg) for p in points])
for p in newpoints:
if p.distance(avg) > maxdist * tol:
return True
return False
def check_aconst(args: list[Point]) -> bool:
a, b, c, d, num, den = args
d = d + a - c
ang = ang_between(a, b, d)
if ang < 0:
ang += np.pi
return close_enough(ang, num * np.pi / den)
def check(name: str, args: list[Union[gm.Point, Point]]) -> bool:
"""Numerical check."""
if name == 'eqangle6':
name = 'eqangle'
elif name == 'eqratio6':
name = 'eqratio'
elif name in ['simtri2', 'simtri*']:
name = 'simtri'
elif name in ['contri2', 'contri*']:
name = 'contri'
elif name == 'para':
name = 'para_or_coll'
elif name == 'on_line':
name = 'coll'
elif name in ['rcompute', 'acompute']:
return True
elif name in ['fixl', 'fixc', 'fixb', 'fixt', 'fixp']:
return True
fn_name = 'check_' + name
if fn_name not in globals():
return None
fun = globals()['check_' + name]
args = [p.num if isinstance(p, gm.Point) else p for p in args]
return fun(args)
def check_circle(points: list[Point]) -> bool:
if len(points) != 4:
return False
o, a, b, c = points
oa, ob, oc = o.distance(a), o.distance(b), o.distance(c)
return close_enough(oa, ob) and close_enough(ob, oc)
def check_coll(points: list[Point]) -> bool:
a, b = points[:2]
l = Line(a, b)
for p in points[2:]:
if abs(l(p.x, p.y)) > ATOM:
return False
return True
def check_ncoll(points: list[Point]) -> bool:
return not check_coll(points)
def check_sameside(points: list[Point]) -> bool:
b, a, c, y, x, z = points
# whether b is to the same side of a & c as y is to x & z
ba = b - a
bc = b - c
yx = y - x
yz = y - z
return ba.dot(bc) * yx.dot(yz) > 0
def check_para_or_coll(points: list[Point]) -> bool:
return check_para(points) or check_coll(points)
def check_para(points: list[Point]) -> bool:
a, b, c, d = points
ab = Line(a, b)
cd = Line(c, d)
if ab.same(cd):
return False
return ab.is_parallel(cd)
def check_perp(points: list[Point]) -> bool:
a, b, c, d = points
ab = Line(a, b)
cd = Line(c, d)
return ab.is_perp(cd)
def check_cyclic(points: list[Point]) -> bool:
points = list(set(points))
(a, b, c), *ps = points
circle = Circle(p1=a, p2=b, p3=c)
for d in ps:
if not close_enough(d.distance(circle.center), circle.radius):
return False
return True
def bring_together(
a: Point, b: Point, c: Point, d: Point
) -> tuple[Point, Point, Point, Point]:
ab = Line(a, b)
cd = Line(c, d)
x = line_line_intersection(ab, cd)
unit = Circle(center=x, radius=1.0)
y, _ = line_circle_intersection(ab, unit)
z, _ = line_circle_intersection(cd, unit)
return x, y, x, z
def same_clock(
a: Point, b: Point, c: Point, d: Point, e: Point, f: Point
) -> bool:
ba = b - a
cb = c - b
ed = e - d
fe = f - e
return (ba.x * cb.y - ba.y * cb.x) * (ed.x * fe.y - ed.y * fe.x) > 0
def check_const_angle(points: list[Point]) -> bool:
"""Check if the angle is equal to the given constant."""
a, b, c, d, m, n = points
a, b, c, d = bring_together(a, b, c, d)
ba = b - a
dc = d - c
a3 = np.arctan2(ba.y, ba.x)
a4 = np.arctan2(dc.y, dc.x)
y = a3 - a4
return close_enough(m / n % 1, y / np.pi % 1)
def check_eqangle(points: list[Point]) -> bool:
"""Check if 8 points make 2 equal angles."""
a, b, c, d, e, f, g, h = points
ab = Line(a, b)
cd = Line(c, d)
ef = Line(e, f)
gh = Line(g, h)
if ab.is_parallel(cd):
return ef.is_parallel(gh)
if ef.is_parallel(gh):
return ab.is_parallel(cd)
a, b, c, d = bring_together(a, b, c, d)
e, f, g, h = bring_together(e, f, g, h)
ba = b - a
dc = d - c
fe = f - e
hg = h - g
sameclock = (ba.x * dc.y - ba.y * dc.x) * (fe.x * hg.y - fe.y * hg.x) > 0
if not sameclock:
ba = ba * -1.0
a1 = np.arctan2(fe.y, fe.x)
a2 = np.arctan2(hg.y, hg.x)
x = a1 - a2
a3 = np.arctan2(ba.y, ba.x)
a4 = np.arctan2(dc.y, dc.x)
y = a3 - a4
xy = (x - y) % (2 * np.pi)
return close_enough(xy, 0, tol=1e-11) or close_enough(
xy, 2 * np.pi, tol=1e-11
)
def check_eqratio(points: list[Point]) -> bool:
a, b, c, d, e, f, g, h = points
ab = a.distance(b)
cd = c.distance(d)
ef = e.distance(f)
gh = g.distance(h)
return close_enough(ab * gh, cd * ef)
def check_cong(points: list[Point]) -> bool:
a, b, c, d = points
return close_enough(a.distance(b), c.distance(d))
def check_midp(points: list[Point]) -> bool:
a, b, c = points
return check_coll(points) and close_enough(a.distance(b), a.distance(c))
def check_simtri(points: list[Point]) -> bool:
"""Check if 6 points make a pair of similar triangles."""
a, b, c, x, y, z = points
ab = a.distance(b)
bc = b.distance(c)
ca = c.distance(a)
xy = x.distance(y)
yz = y.distance(z)
zx = z.distance(x)
tol = 1e-9
return close_enough(ab * yz, bc * xy, tol) and close_enough(
bc * zx, ca * yz, tol
)
def check_contri(points: list[Point]) -> bool:
a, b, c, x, y, z = points
ab = a.distance(b)
bc = b.distance(c)
ca = c.distance(a)
xy = x.distance(y)
yz = y.distance(z)
zx = z.distance(x)
tol = 1e-9
return (
close_enough(ab, xy, tol)
and close_enough(bc, yz, tol)
and close_enough(ca, zx, tol)
)
def check_ratio(points: list[Point]) -> bool:
a, b, c, d, m, n = points
ab = a.distance(b)
cd = c.distance(d)
return close_enough(ab * n, cd * m)
def draw_angle(
ax: matplotlib.axes.Axes,
head: Point,
p1: Point,
p2: Point,
color: Any = 'red',
alpha: float = 0.5,
frac: float = 1.0,
) -> None:
"""Draw an angle on plt ax."""
d1 = p1 - head
d2 = p2 - head
a1 = np.arctan2(float(d1.y), float(d1.x))
a2 = np.arctan2(float(d2.y), float(d2.x))
a1, a2 = a1 * 180 / np.pi, a2 * 180 / np.pi
a1, a2 = a1 % 360, a2 % 360
if a1 > a2:
a1, a2 = a2, a1
if a2 - a1 > 180:
a1, a2 = a2, a1
b1, b2 = a1, a2
if b1 > b2:
b2 += 360
d = b2 - b1
# if d >= 90:
# return
scale = min(2.0, 90 / d)
scale = max(scale, 0.4)
fov = matplotlib.patches.Wedge(
(float(head.x), float(head.y)),
unif(0.075, 0.125) * scale * frac,
a1,
a2,
color=color,
alpha=alpha,
)
ax.add_artist(fov)
def 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."""
_ = ax
r = 0.08
c = Circle(center=p, radius=r)
avoid = []
for p1, p2 in lines:
try:
avoid.extend(circle_segment_intersect(c, p1, p2))
except InvalidQuadSolveError:
continue
for x in circles:
try:
avoid.extend(circle_circle_intersection(c, x))
except InvalidQuadSolveError:
continue
if not avoid:
return [p.x + 0.01, p.y + 0.01]
angs = sorted([ang_of(p, a) for a in avoid])
angs += [angs[0] + 2 * np.pi]
angs = [(angs[i + 1] - a, a) for i, a in enumerate(angs[:-1])]
d, a = max(angs)
ang = a + d / 2
name_pos = p + Point(np.cos(ang), np.sin(ang)) * r
x, y = (name_pos.x - r / 1.5, name_pos.y - r / 1.5)
return x, y
def draw_point(
ax: matplotlib.axes.Axes,
p: Point,
name: str,
lines: list[Line],
circles: list[Circle],
color: Any = 'white',
size: float = 15,
) -> None:
"""draw a point."""
ax.scatter(p.x, p.y, color=color, s=size)
if color == 'white':
color = 'lightgreen'
else:
color = 'grey'
name = name.upper()
if len(name) > 1:
name = name[0] + '_' + name[1:]
ax.annotate(
name, naming_position(ax, p, lines, circles), color=color, fontsize=15
)
def _draw_line(
ax: matplotlib.axes.Axes,
p1: Point,
p2: Point,
color: Any = 'white',
lw: float = 1.2,
alpha: float = 0.8,
) -> None:
"""Draw a line in matplotlib."""
ls = '-'
if color == '--':
color = 'black'
ls = '--'
lx, ly = (p1.x, p2.x), (p1.y, p2.y)
ax.plot(lx, ly, color=color, lw=lw, alpha=alpha, ls=ls)
def draw_line(
ax: matplotlib.axes.Axes, line: Line, color: Any = 'white'
) -> tuple[Point, Point]:
"""Draw a line."""
points = line.neighbors(gm.Point)
if len(points) <= 1:
return
points = [p.num for p in points]
p1, p2 = points[:2]
pmin, pmax = (p1, 0.0), (p2, (p2 - p1).dot(p2 - p1))
for p in points[2:]:
v = (p - p1).dot(p2 - p1)
if v < pmin[1]:
pmin = p, v
if v > pmax[1]:
pmax = p, v
p1, p2 = pmin[0], pmax[0]
_draw_line(ax, p1, p2, color=color)
return p1, p2
def _draw_circle(
ax: matplotlib.axes.Axes, c: Circle, color: Any = 'cyan', lw: float = 1.2
) -> None:
ls = '-'
if color == '--':
color = 'black'
ls = '--'