-
Notifications
You must be signed in to change notification settings - Fork 464
/
graph.py
3057 lines (2577 loc) · 87.9 KB
/
graph.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.
# ==============================================================================
"""Implements the graph representation of the proof state."""
# pylint: disable=g-multiple-import
from __future__ import annotations
from collections import defaultdict # pylint: disable=g-importing-member
from typing import Callable, Generator, Optional, Type, Union
from absl import logging
import ar
import geometry as gm
from geometry import Angle, Direction, Length, Ratio
from geometry import Circle, Line, Point, Segment
from geometry import Measure, Value
import graph_utils as utils
import numericals as nm
import problem
from problem import Dependency, EmptyDependency
np = nm.np
FREE = [
'free',
'segment',
'r_triangle',
'risos',
'triangle',
'triangle12',
'ieq_triangle',
'eq_quadrangle',
'eq_trapezoid',
'eqdia_quadrangle',
'quadrangle',
'r_trapezoid',
'rectangle',
'isquare',
'trapezoid',
'pentagon',
'iso_triangle',
]
INTERSECT = [
'angle_bisector',
'angle_mirror',
'eqdistance',
'lc_tangent',
'on_aline',
'on_bline',
'on_circle',
'on_line',
'on_pline',
'on_tline',
'on_dia',
's_angle',
'on_opline',
'eqangle3',
]
# pylint: disable=protected-access
# pylint: disable=unused-argument
class DepCheckFailError(Exception):
pass
class PointTooCloseError(Exception):
pass
class PointTooFarError(Exception):
pass
class Graph:
"""Graph data structure representing proof state."""
def __init__(self):
self.type2nodes = {
Point: [],
Line: [],
Segment: [],
Circle: [],
Direction: [],
Length: [],
Angle: [],
Ratio: [],
Measure: [],
Value: [],
}
self._name2point = {}
self._name2node = {}
self.rconst = {} # contains all constant ratios
self.aconst = {} # contains all constant angles.
self.halfpi, _ = self.get_or_create_const_ang(1, 2)
self.vhalfpi = self.halfpi.val
self.atable = ar.AngleTable()
self.dtable = ar.DistanceTable()
self.rtable = ar.RatioTable()
# to quick access deps.
self.cache = {}
self._pair2line = {}
self._triplet2circle = {}
def copy(self) -> Graph:
"""Make a copy of self."""
p, definitions = self.build_def
p = p.copy()
for clause in p.clauses:
clause.nums = []
for pname in clause.points:
clause.nums.append(self._name2node[pname].num)
g, _ = Graph.build_problem(p, definitions, verbose=False, init_copy=False)
g.build_clauses = list(getattr(self, 'build_clauses', []))
return g
def _create_const_ang(self, n: int, d: int) -> None:
n, d = ar.simplify(n, d)
ang = self.aconst[(n, d)] = self.new_node(Angle, f'{n}pi/{d}')
ang.set_directions(None, None)
self.connect_val(ang, deps=None)
def _create_const_rat(self, n: int, d: int) -> None:
n, d = ar.simplify(n, d)
rat = self.rconst[(n, d)] = self.new_node(Ratio, f'{n}/{d}')
rat.set_lengths(None, None)
self.connect_val(rat, deps=None)
def get_or_create_const_ang(self, n: int, d: int) -> None:
n, d = ar.simplify(n, d)
if (n, d) not in self.aconst:
self._create_const_ang(n, d)
ang1 = self.aconst[(n, d)]
n, d = ar.simplify(d - n, d)
if (n, d) not in self.aconst:
self._create_const_ang(n, d)
ang2 = self.aconst[(n, d)]
return ang1, ang2
def get_or_create_const_rat(self, n: int, d: int) -> None:
n, d = ar.simplify(n, d)
if (n, d) not in self.rconst:
self._create_const_rat(n, d)
rat1 = self.rconst[(n, d)]
if (d, n) not in self.rconst:
self._create_const_rat(d, n) # pylint: disable=arguments-out-of-order
rat2 = self.rconst[(d, n)]
return rat1, rat2
def add_algebra(self, dep: Dependency, level: int) -> None:
"""Add new algebraic predicates."""
_ = level
if dep.name not in [
'para',
'perp',
'eqangle',
'eqratio',
'aconst',
'rconst',
'cong',
]:
return
name, args = dep.name, dep.args
if name == 'para':
ab, cd = dep.algebra
self.atable.add_para(ab, cd, dep)
if name == 'perp':
ab, cd = dep.algebra
self.atable.add_const_angle(ab, cd, 90, dep)
if name == 'eqangle':
ab, cd, mn, pq = dep.algebra
if (ab, cd) == (pq, mn):
self.atable.add_const_angle(ab, cd, 90, dep)
else:
self.atable.add_eqangle(ab, cd, mn, pq, dep)
if name == 'eqratio':
ab, cd, mn, pq = dep.algebra
if (ab, cd) == (pq, mn):
self.rtable.add_eq(ab, cd, dep)
else:
self.rtable.add_eqratio(ab, cd, mn, pq, dep)
if name == 'aconst':
bx, ab, y = dep.algebra
self.atable.add_const_angle(bx, ab, y, dep)
if name == 'rconst':
l1, l2, m, n = dep.algebra
self.rtable.add_const_ratio(l1, l2, m, n, dep)
if name == 'cong':
a, b, c, d = args
ab, _ = self.get_line_thru_pair_why(a, b)
cd, _ = self.get_line_thru_pair_why(c, d)
self.dtable.add_cong(ab, cd, a, b, c, d, dep)
ab, cd = dep.algebra
self.rtable.add_eq(ab, cd, dep)
def add_eqrat_const(
self, args: list[Point], deps: EmptyDependency
) -> list[Dependency]:
"""Add new algebraic predicates of type eqratio-constant."""
a, b, c, d, num, den = args
nd, dn = self.get_or_create_const_rat(num, den)
if num == den:
return self.add_cong([a, b, c, d], deps)
ab = self._get_or_create_segment(a, b, deps=None)
cd = self._get_or_create_segment(c, d, deps=None)
self.connect_val(ab, deps=None)
self.connect_val(cd, deps=None)
if ab.val == cd.val:
raise ValueError(f'{ab.name} and {cd.name} cannot be equal')
args = [a, b, c, d, nd]
i = 0
for x, y, xy in [(a, b, ab), (c, d, cd)]:
i += 1
x_, y_ = list(xy._val._obj.points)
if {x, y} == {x_, y_}:
continue
if deps:
deps = deps.extend(self, 'rconst', list(args), 'cong', [x, y, x_, y_])
args[2 * i - 2] = x_
args[2 * i - 1] = y_
ab_cd, cd_ab, why = self._get_or_create_ratio(ab, cd, deps=None)
if why:
dep0 = deps.populate('rconst', [a, b, c, d, nd])
deps = EmptyDependency(level=deps.level, rule_name=None)
deps.why = [dep0] + why
lab, lcd = ab_cd._l
a, b = list(lab._obj.points)
c, d = list(lcd._obj.points)
add = []
if not self.is_equal(ab_cd, nd):
args = [a, b, c, d, nd]
dep1 = deps.populate('rconst', args)
dep1.algebra = ab._val, cd._val, num, den
self.make_equal(nd, ab_cd, deps=dep1)
self.cache_dep('rconst', [a, b, c, d, nd], dep1)
add += [dep1]
if not self.is_equal(cd_ab, dn):
args = [c, d, a, b, dn]
dep2 = deps.populate('rconst', args)
dep2.algebra = cd._val, ab._val, num, den
self.make_equal(dn, cd_ab, deps=dep2)
self.cache_dep('rconst', [c, d, a, b, dn], dep2)
add += [dep2]
return add
def do_algebra(self, name: str, args: list[Point]) -> list[Dependency]:
"""Derive (but not add) new algebraic predicates."""
if name == 'para':
a, b, dep = args
if gm.is_equiv(a, b):
return []
(x, y), (m, n) = a._obj.points, b._obj.points
return self.add_para([x, y, m, n], dep)
if name == 'aconst':
a, b, n, d, dep = args
ab, ba, why = self.get_or_create_angle_d(a, b, deps=None)
nd, dn = self.get_or_create_const_ang(n, d)
(x, y), (m, n) = a._obj.points, b._obj.points
if why:
dep0 = dep.populate('aconst', [x, y, m, n, nd])
dep = EmptyDependency(level=dep.level, rule_name=None)
dep.why = [dep0] + why
a, b = ab._d
(x, y), (m, n) = a._obj.points, b._obj.points
added = []
if not self.is_equal(ab, nd):
if nd == self.halfpi:
added += self.add_perp([x, y, m, n], dep)
# else:
name = 'aconst'
args = [x, y, m, n, nd]
dep1 = dep.populate(name, args)
self.cache_dep(name, args, dep1)
self.make_equal(nd, ab, deps=dep1)
added += [dep1]
if not self.is_equal(ba, dn):
if dn == self.halfpi:
added += self.add_perp([m, n, x, y], dep)
name = 'aconst'
args = [m, n, x, y, dn]
dep2 = dep.populate(name, args)
self.cache_dep(name, args, dep2)
self.make_equal(dn, ba, deps=dep2)
added += [dep2]
return added
if name == 'rconst':
a, b, c, d, num, den, dep = args
return self.add_eqrat_const([a, b, c, d, num, den], dep)
if name == 'eqangle':
d1, d2, d3, d4, dep = args
a, b = d1._obj.points
c, d = d2._obj.points
e, f = d3._obj.points
g, h = d4._obj.points
return self.add_eqangle([a, b, c, d, e, f, g, h], dep)
if name == 'eqratio':
d1, d2, d3, d4, dep = args
a, b = d1._obj.points
c, d = d2._obj.points
e, f = d3._obj.points
g, h = d4._obj.points
return self.add_eqratio([a, b, c, d, e, f, g, h], dep)
if name in ['cong', 'cong2']:
a, b, c, d, dep = args
if not (a != b and c != d and (a != c or b != d)):
return []
return self.add_cong([a, b, c, d], dep)
return []
def derive_algebra(
self, level: int, verbose: bool = False
) -> tuple[
dict[str, list[tuple[Point, ...]]], dict[str, [tuple[Point, ...]]]
]:
"""Derive new algebraic predicates."""
derives = {}
ang_derives = self.derive_angle_algebra(level, verbose=verbose)
dist_derives = self.derive_distance_algebra(level, verbose=verbose)
rat_derives = self.derive_ratio_algebra(level, verbose=verbose)
derives.update(ang_derives)
derives.update(dist_derives)
derives.update(rat_derives)
# Separate eqangle and eqratio derivations
# As they are too numerous => slow down DD+AR.
# & reserve them only for last effort.
eqs = {'eqangle': derives.pop('eqangle'), 'eqratio': derives.pop('eqratio')}
return derives, eqs
def derive_ratio_algebra(
self, level: int, verbose: bool = False
) -> dict[str, list[tuple[Point, ...]]]:
"""Derive new eqratio predicates."""
added = {'cong2': [], 'eqratio': []}
for x in self.rtable.get_all_eqs_and_why():
x, why = x[:-1], x[-1]
dep = EmptyDependency(level=level, rule_name='a01')
dep.why = why
if len(x) == 2:
a, b = x
if gm.is_equiv(a, b):
continue
(m, n), (p, q) = a._obj.points, b._obj.points
added['cong2'].append((m, n, p, q, dep))
if len(x) == 4:
a, b, c, d = x
added['eqratio'].append((a, b, c, d, dep))
return added
def derive_angle_algebra(
self, level: int, verbose: bool = False
) -> dict[str, list[tuple[Point, ...]]]:
"""Derive new eqangles predicates."""
added = {'eqangle': [], 'aconst': [], 'para': []}
for x in self.atable.get_all_eqs_and_why():
x, why = x[:-1], x[-1]
dep = EmptyDependency(level=level, rule_name='a02')
dep.why = why
if len(x) == 2:
a, b = x
if gm.is_equiv(a, b):
continue
(e, f), (p, q) = a._obj.points, b._obj.points
if not nm.check('para', [e, f, p, q]):
continue
added['para'].append((a, b, dep))
if len(x) == 3:
a, b, (n, d) = x
(e, f), (p, q) = a._obj.points, b._obj.points
if not nm.check('aconst', [e, f, p, q, n, d]):
continue
added['aconst'].append((a, b, n, d, dep))
if len(x) == 4:
a, b, c, d = x
added['eqangle'].append((a, b, c, d, dep))
return added
def derive_distance_algebra(
self, level: int, verbose: bool = False
) -> dict[str, list[tuple[Point, ...]]]:
"""Derive new cong predicates."""
added = {'inci': [], 'cong': [], 'rconst': []}
for x in self.dtable.get_all_eqs_and_why():
x, why = x[:-1], x[-1]
dep = EmptyDependency(level=level, rule_name='a00')
dep.why = why
if len(x) == 2:
a, b = x
if a == b:
continue
dep.name = f'inci {a.name} {b.name}'
added['inci'].append((x, dep))
if len(x) == 4:
a, b, c, d = x
if not (a != b and c != d and (a != c or b != d)):
continue
added['cong'].append((a, b, c, d, dep))
if len(x) == 6:
a, b, c, d, num, den = x
if not (a != b and c != d and (a != c or b != d)):
continue
added['rconst'].append((a, b, c, d, num, den, dep))
return added
@classmethod
def build_problem(
cls,
pr: problem.Problem,
definitions: dict[str, problem.Definition],
verbose: bool = True,
init_copy: bool = True,
) -> tuple[Graph, list[Dependency]]:
"""Build a problem into a gr.Graph object."""
check = False
g = None
added = None
if verbose:
logging.info(pr.url)
logging.info(pr.txt())
while not check:
try:
g = Graph()
added = []
plevel = 0
for clause in pr.clauses:
adds, plevel = g.add_clause(
clause, plevel, definitions, verbose=verbose
)
added += adds
g.plevel = plevel
except (nm.InvalidLineIntersectError, nm.InvalidQuadSolveError):
continue
except DepCheckFailError:
continue
except (PointTooCloseError, PointTooFarError):
continue
if not pr.goal:
break
args = list(map(lambda x: g.get(x, lambda: int(x)), pr.goal.args))
check = nm.check(pr.goal.name, args)
g.url = pr.url
g.build_def = (pr, definitions)
for add in added:
g.add_algebra(add, level=0)
return g, added
def all_points(self) -> list[Point]:
"""Return all nodes of type Point."""
return list(self.type2nodes[Point])
def all_nodes(self) -> list[gm.Node]:
"""Return all nodes."""
return list(self._name2node.values())
def add_points(self, pnames: list[str]) -> list[Point]:
"""Add new points with given names in list pnames."""
result = [self.new_node(Point, name) for name in pnames]
self._name2point.update(zip(pnames, result))
return result
def names2nodes(self, pnames: list[str]) -> list[gm.Node]:
return [self._name2node[name] for name in pnames]
def names2points(
self, pnames: list[str], create_new_point: bool = False
) -> list[Point]:
"""Return Point objects given names."""
result = []
for name in pnames:
if name not in self._name2node and not create_new_point:
raise ValueError(f'Cannot find point {name} in graph')
elif name in self._name2node:
obj = self._name2node[name]
else:
obj = self.new_node(Point, name)
result.append(obj)
return result
def names2points_or_int(self, pnames: list[str]) -> list[Point]:
"""Return Point objects given names."""
result = []
for name in pnames:
if name.isdigit():
result += [int(name)]
elif 'pi/' in name:
n, d = name.split('pi/')
ang, _ = self.get_or_create_const_ang(int(n), int(d))
result += [ang]
elif '/' in name:
n, d = name.split('/')
rat, _ = self.get_or_create_const_rat(int(n), int(d))
result += [rat]
else:
result += [self._name2point[name]]
return result
def get(self, pointname: str, default_fn: Callable[str, Point]) -> Point:
if pointname in self._name2point:
return self._name2point[pointname]
if pointname in self._name2node:
return self._name2node[pointname]
return default_fn()
def new_node(self, oftype: Type[gm.Node], name: str = '') -> gm.Node:
node = oftype(name, self)
self.type2nodes[oftype].append(node)
self._name2node[name] = node
if isinstance(node, Point):
self._name2point[name] = node
return node
def merge(self, nodes: list[gm.Node], deps: Dependency) -> gm.Node:
"""Merge all nodes."""
if len(nodes) < 2:
return
node0, *nodes1 = nodes
all_nodes = self.type2nodes[type(node0)]
# find node0 that exists in all_nodes to be the rep
# and merge all other nodes into node0
for node in nodes:
if node in all_nodes:
node0 = node
nodes1 = [n for n in nodes if n != node0]
break
return self.merge_into(node0, nodes1, deps)
def merge_into(
self, node0: gm.Node, nodes1: list[gm.Node], deps: Dependency
) -> gm.Node:
"""Merge nodes1 into a single node0."""
node0.merge(nodes1, deps)
for n in nodes1:
if n.rep() != n:
self.remove([n])
nodes = [node0] + nodes1
if any([node._val for node in nodes]):
for node in nodes:
self.connect_val(node, deps=None)
vals1 = [n._val for n in nodes1]
node0._val.merge(vals1, deps)
for v in vals1:
if v.rep() != v:
self.remove([v])
return node0
def remove(self, nodes: list[gm.Node]) -> None:
"""Remove nodes out of self because they are merged."""
if not nodes:
return
for node in nodes:
all_nodes = self.type2nodes[type(nodes[0])]
if node in all_nodes:
all_nodes.remove(node)
if node.name in self._name2node.values():
self._name2node.pop(node.name)
def connect(self, a: gm.Node, b: gm.Node, deps: Dependency) -> None:
a.connect_to(b, deps)
b.connect_to(a, deps)
def connect_val(self, node: gm.Node, deps: Dependency) -> gm.Node:
"""Connect a node into its value (equality) node."""
if node._val:
return node._val
name = None
if isinstance(node, Line):
name = 'd(' + node.name + ')'
if isinstance(node, Angle):
name = 'm(' + node.name + ')'
if isinstance(node, Segment):
name = 'l(' + node.name + ')'
if isinstance(node, Ratio):
name = 'r(' + node.name + ')'
v = self.new_node(gm.val_type(node), name)
self.connect(node, v, deps=deps)
return v
def is_equal(self, x: gm.Node, y: gm.Node, level: int = None) -> bool:
return gm.is_equal(x, y, level)
def add_piece(
self, name: str, args: list[Point], deps: EmptyDependency
) -> list[Dependency]:
"""Add a new predicate."""
if name in ['coll', 'collx']:
return self.add_coll(args, deps)
elif name == 'para':
return self.add_para(args, deps)
elif name == 'perp':
return self.add_perp(args, deps)
elif name == 'midp':
return self.add_midp(args, deps)
elif name == 'cong':
return self.add_cong(args, deps)
elif name == 'circle':
return self.add_circle(args, deps)
elif name == 'cyclic':
return self.add_cyclic(args, deps)
elif name in ['eqangle', 'eqangle6']:
return self.add_eqangle(args, deps)
elif name in ['eqratio', 'eqratio6']:
return self.add_eqratio(args, deps)
# numerical!
elif name == 's_angle':
return self.add_s_angle(args, deps)
elif name == 'aconst':
a, b, c, d, ang = args
if isinstance(ang, str):
name = ang
else:
name = ang.name
num, den = name.split('pi/')
num, den = int(num), int(den)
return self.add_aconst([a, b, c, d, num, den], deps)
elif name == 's_angle':
b, x, a, b, ang = ( # pylint: disable=redeclared-assigned-name,unused-variable
args
)
if isinstance(ang, str):
name = ang
else:
name = ang.name
n, d = name.split('pi/')
ang = int(n) * 180 / int(d)
return self.add_s_angle([a, b, x, ang], deps)
elif name == 'rconst':
a, b, c, d, rat = args
if isinstance(rat, str):
name = rat
else:
name = rat.name
num, den = name.split('/')
num, den = int(num), int(den)
return self.add_eqrat_const([a, b, c, d, num, den], deps)
# composite pieces:
elif name == 'cong2':
return self.add_cong2(args, deps)
elif name == 'eqratio3':
return self.add_eqratio3(args, deps)
elif name == 'eqratio4':
return self.add_eqratio4(args, deps)
elif name == 'simtri':
return self.add_simtri(args, deps)
elif name == 'contri':
return self.add_contri(args, deps)
elif name == 'simtri2':
return self.add_simtri2(args, deps)
elif name == 'contri2':
return self.add_contri2(args, deps)
elif name == 'simtri*':
return self.add_simtri_check(args, deps)
elif name == 'contri*':
return self.add_contri_check(args, deps)
elif name in ['acompute', 'rcompute']:
dep = deps.populate(name, args)
self.cache_dep(name, args, dep)
return [dep]
elif name in ['fixl', 'fixc', 'fixb', 'fixt', 'fixp']:
dep = deps.populate(name, args)
self.cache_dep(name, args, dep)
return [dep]
elif name in ['ind']:
return []
raise ValueError(f'Not recognize {name}')
def check(self, name: str, args: list[Point]) -> bool:
"""Symbolically check if a predicate is True."""
if name == 'ncoll':
return self.check_ncoll(args)
if name == 'npara':
return self.check_npara(args)
if name == 'nperp':
return self.check_nperp(args)
if name == 'midp':
return self.check_midp(args)
if name == 'cong':
return self.check_cong(args)
if name == 'perp':
return self.check_perp(args)
if name == 'para':
return self.check_para(args)
if name == 'coll':
return self.check_coll(args)
if name == 'cyclic':
return self.check_cyclic(args)
if name == 'circle':
return self.check_circle(args)
if name == 'aconst':
return self.check_aconst(args)
if name == 'rconst':
return self.check_rconst(args)
if name == 'acompute':
return self.check_acompute(args)
if name == 'rcompute':
return self.check_rcompute(args)
if name in ['eqangle', 'eqangle6']:
if len(args) == 5:
return self.check_aconst(args)
return self.check_eqangle(args)
if name in ['eqratio', 'eqratio6']:
if len(args) == 5:
return self.check_rconst(args)
return self.check_eqratio(args)
if name in ['simtri', 'simtri2', 'simtri*']:
return self.check_simtri(args)
if name in ['contri', 'contri2', 'contri*']:
return self.check_contri(args)
if name == 'sameside':
return self.check_sameside(args)
if name in 'diff':
a, b = args
return not a.num.close(b.num)
if name in ['fixl', 'fixc', 'fixb', 'fixt', 'fixp']:
return self.in_cache(name, args)
if name in ['ind']:
return True
raise ValueError(f'Not recognize {name}')
def get_lines_thru_all(self, *points: list[gm.Point]) -> list[Line]:
line2count = defaultdict(lambda: 0)
points = set(points)
for p in points:
for l in p.neighbors(Line):
line2count[l] += 1
return [l for l, count in line2count.items() if count == len(points)]
def _get_line(self, a: Point, b: Point) -> Optional[Line]:
linesa = a.neighbors(Line)
for l in b.neighbors(Line):
if l in linesa:
return l
return None
def _get_line_all(self, a: Point, b: Point) -> Generator[Line, None, None]:
linesa = a.neighbors(Line, do_rep=False)
linesb = b.neighbors(Line, do_rep=False)
for l in linesb:
if l in linesa:
yield l
def _get_lines(self, *points: list[Point]) -> list[Line]:
"""Return all lines that connect to >= 2 points."""
line2count = defaultdict(lambda: 0)
for p in points:
for l in p.neighbors(Line):
line2count[l] += 1
return [l for l, count in line2count.items() if count >= 2]
def get_circle_thru_triplet(self, p1: Point, p2: Point, p3: Point) -> Circle:
p1, p2, p3 = sorted([p1, p2, p3], key=lambda x: x.name)
if (p1, p2, p3) in self._triplet2circle:
return self._triplet2circle[(p1, p2, p3)]
return self.get_new_circle_thru_triplet(p1, p2, p3)
def get_new_circle_thru_triplet(
self, p1: Point, p2: Point, p3: Point
) -> Circle:
"""Get a new Circle that goes thru three given Points."""
p1, p2, p3 = sorted([p1, p2, p3], key=lambda x: x.name)
name = p1.name.lower() + p2.name.lower() + p3.name.lower()
circle = self.new_node(Circle, f'({name})')
circle.num = nm.Circle(p1=p1.num, p2=p2.num, p3=p3.num)
circle.points = p1, p2, p3
self.connect(p1, circle, deps=None)
self.connect(p2, circle, deps=None)
self.connect(p3, circle, deps=None)
self._triplet2circle[(p1, p2, p3)] = circle
return circle
def get_line_thru_pair(self, p1: Point, p2: Point) -> Line:
if (p1, p2) in self._pair2line:
return self._pair2line[(p1, p2)]
if (p2, p1) in self._pair2line:
return self._pair2line[(p2, p1)]
return self.get_new_line_thru_pair(p1, p2)
def get_new_line_thru_pair(self, p1: Point, p2: Point) -> Line:
if p1.name.lower() > p2.name.lower():
p1, p2 = p2, p1
name = p1.name.lower() + p2.name.lower()
line = self.new_node(Line, name)
line.num = nm.Line(p1.num, p2.num)
line.points = p1, p2
self.connect(p1, line, deps=None)
self.connect(p2, line, deps=None)
self._pair2line[(p1, p2)] = line
return line
def get_line_thru_pair_why(
self, p1: Point, p2: Point
) -> tuple[Line, list[Dependency]]:
"""Get one line thru two given points and the corresponding dependency list."""
if p1.name.lower() > p2.name.lower():
p1, p2 = p2, p1
if (p1, p2) in self._pair2line:
return self._pair2line[(p1, p2)].rep_and_why()
l, why = gm.line_of_and_why([p1, p2])
if l is None:
l = self.get_new_line_thru_pair(p1, p2)
why = []
return l, why
def coll_dep(self, points: list[Point], p: Point) -> list[Dependency]:
"""Return the dep(.why) explaining why p is coll with points."""
for p1, p2 in utils.comb2(points):
if self.check_coll([p1, p2, p]):
dep = Dependency('coll', [p1, p2, p], None, None)
return dep.why_me_or_cache(self, None)
def add_coll(
self, points: list[Point], deps: EmptyDependency
) -> list[Dependency]:
"""Add a predicate that `points` are collinear."""
points = list(set(points))
og_points = list(points)
all_lines = []
for p1, p2 in utils.comb2(points):
all_lines.append(self.get_line_thru_pair(p1, p2))
points = sum([l.neighbors(Point) for l in all_lines], [])
points = list(set(points))
existed = set()
new = set()
for p1, p2 in utils.comb2(points):
if p1.name > p2.name:
p1, p2 = p2, p1
if (p1, p2) in self._pair2line:
line = self._pair2line[(p1, p2)]
existed.add(line)
else:
line = self.get_new_line_thru_pair(p1, p2)
new.add(line)
existed = sorted(existed, key=lambda l: l.name)
new = sorted(new, key=lambda l: l.name)
existed, new = list(existed), list(new)
if not existed:
line0, *lines = new
else:
line0, lines = existed[0], existed[1:] + new
add = []
line0, why0 = line0.rep_and_why()
a, b = line0.points
for line in lines:
c, d = line.points
args = list({a, b, c, d})
if len(args) < 3:
continue
whys = []
for x in args:
if x not in og_points:
whys.append(self.coll_dep(og_points, x))
abcd_deps = deps
if whys + why0:
dep0 = deps.populate('coll', og_points)
abcd_deps = EmptyDependency(level=deps.level, rule_name=None)
abcd_deps.why = [dep0] + whys
is_coll = self.check_coll(args)
dep = abcd_deps.populate('coll', args)
self.cache_dep('coll', args, dep)
self.merge_into(line0, [line], dep)
if not is_coll:
add += [dep]
return add
def check_coll(self, points: list[Point]) -> bool:
points = list(set(points))
if len(points) < 3:
return True
line2count = defaultdict(lambda: 0)
for p in points:
for l in p.neighbors(Line):
line2count[l] += 1
return any([count == len(points) for _, count in line2count.items()])
def why_coll(self, args: tuple[Line, list[Point]]) -> list[Dependency]:
line, points = args
return line.why_coll(points)
def check_ncoll(self, points: list[Point]) -> bool:
if self.check_coll(points):
return False
return not nm.check_coll([p.num for p in points])