Repository navigation
Expand file tree
/
Copy pathproofs_common.py
More file actions
7693 lines (6916 loc) · 291 KB
/
Copy pathproofs_common.py
File metadata and controls
7693 lines (6916 loc) · 291 KB
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
"""Shared machinery for the QuixiProofs program (plans/proofs_plan.md).
The math program's generators are solvers whose traces fall out of
computing the answer; proof generators are provers whose derivations fall
out of constructing the theorem. This module holds the pieces every proof
family shares:
- a small exact expression form (integer coefficients, one variable
``x``) whose renderer and parser round-trip exactly,
- the rewrite rules behind the warrant registry,
- ``WARRANTS`` — the closed registry. Unlike scratchpad op-codes (organic,
model-owned), a warrant name is only legal if a checker function backs
it; WARRANTS.md is generated from this table as an authoritative doc.
- ``check_proof`` — the validity oracle: replays a record's derivation and
verifies every STEP follows from its referenced line by exactly one
application of its named warrant.
Proof-record line grammar (shape-validated by the proofs CLI, semantics
by ``check_proof``):
PREMISE|<k>|<statement>
IH|<k>|<assumption>
STEP|<k>|<claim>|<warrant>|<refs>
QED|<final_answer>
An ``IH`` line opens an induction scope: it and every later line belong
to the block until a STEP warranted ``induction_conclusion`` discharges
it, after which the block's lines may no longer be cited (the
assumption is gone, so everything conditional on it is too). A record
must not end with an open block, and blocks do not nest (plan §8).
``refs`` is a comma-separated list of earlier line numbers; its length
must equal the warrant's declared arity (``nrefs``, default 1; the
value ``"any"`` accepts any count — certificate conclusions fan in). Two
warrant kinds share the registry (plan §8): **rewrite** warrants declare
``apply`` and validate by membership — ``claim in apply(prev)``, or
``prev in apply(claim)`` for an ``inverse_of`` entry; **judgment**
warrants declare ``check(claim, prevs)`` and validate by direct
verification over the parsed claim and cited lines. A language's
``parse`` may return any comparable form (the sum languages return node
lists; the Euclid language returns a single statement tuple).
Expression form: a sum is a list of nodes; a node is ``("num", n)``,
``("term", c)`` for ``c*x``, ``("pterm", c, e)`` for ``c*x^e`` (e >= 2),
``("group", c, [nodes])`` for ``c*( ... )``, or
``("prodg", c, [sumA, sumB])`` for ``c*(A)(B)``. Coefficients are
nonzero ints (a vanished sum renders as ``0`` via the single node
``("num", 0)``).
"""
import re
from fractions import Fraction
from math import gcd, isqrt
from helpers import DELIM
# ---------------------------------------------------------------------------
# Rendering (canonical) and parsing — must round-trip exactly.
# ---------------------------------------------------------------------------
def _node_sign(node):
return -1 if node[1] < 0 else 1
def _render_abs(node):
"""Node rendered without its sign (the sign joins the sum)."""
kind = node[0]
mag = abs(node[1])
if kind == "num":
return str(mag)
if kind == "term":
return "x" if mag == 1 else f"{mag}x"
if kind == "pterm":
base = f"x^{node[2]}"
return base if mag == 1 else f"{mag}{base}"
if kind == "prodg":
factors = f"({render(node[2][0])})({render(node[2][1])})"
return factors if mag == 1 else f"{mag}{factors}"
inner = render(node[2])
return f"({inner})" if mag == 1 else f"{mag}({inner})"
def render(nodes):
"""Canonical string for a sum: ``6(2x - 3) + 4x - 7``."""
out = []
for i, node in enumerate(nodes):
if i == 0:
prefix = "-" if _node_sign(node) < 0 else ""
else:
prefix = " - " if _node_sign(node) < 0 else " + "
out.append(prefix + _render_abs(node))
return "".join(out)
_TOKEN = re.compile(r"\s*(\d+|[x()+\-^·])")
def _tokenize(text):
tokens, pos = [], 0
while pos < len(text):
m = _TOKEN.match(text, pos)
if not m:
raise ValueError(f"cannot tokenize expression at {text[pos:]!r}")
tokens.append(m.group(1))
pos = m.end()
return tokens
def parse(text):
"""Parses a rendered sum back to the node-list form (round-trips)."""
tokens = _tokenize(text)
idx = 0
def peek():
return tokens[idx] if idx < len(tokens) else None
def parse_sum():
nonlocal idx
nodes = []
sign = 1
if peek() == "-":
sign, idx = -1, idx + 1
elif peek() == "+":
idx += 1
while True:
nodes.append(parse_item(sign))
tok = peek()
if tok == "+":
sign, idx = 1, idx + 1
elif tok == "-":
sign, idx = -1, idx + 1
else:
return nodes
def parse_item(sign):
nonlocal idx
tok = peek()
if tok is None:
raise ValueError("unexpected end of expression")
coef = None
if tok.isdigit():
coef, idx = int(tok), idx + 1
tok = peek()
if tok == "x":
idx += 1
c = sign * (coef if coef is not None else 1)
if peek() == "^":
idx += 1
exp = peek()
if exp is None or not exp.isdigit():
raise ValueError("exponent must be an integer")
idx += 1
return ("pterm", c, int(exp))
return ("term", c)
if tok == "(":
idx += 1
inner = parse_sum()
if peek() != ")":
raise ValueError("missing closing parenthesis")
idx += 1
c = sign * (coef if coef is not None else 1)
if peek() == "(":
idx += 1
second = parse_sum()
if peek() != ")":
raise ValueError("missing closing parenthesis")
idx += 1
return ("prodg", c, [inner, second])
return ("group", c, inner)
if coef is None:
raise ValueError(f"unexpected token {tok!r}")
return ("num", sign * coef)
nodes = parse_sum()
if idx != len(tokens):
raise ValueError(f"trailing tokens in expression: {tokens[idx:]!r}")
return nodes
# ---------------------------------------------------------------------------
# Rewrite rules. Each rule maps a sum to every sum reachable by ONE
# application, at any depth. The checker tests membership; generators
# construct chains whose forward direction is always a member.
# ---------------------------------------------------------------------------
def _scale(c, node):
return (node[0], c * node[1]) + tuple(node[2:])
def _sites(nodes, path=()):
"""Yields (path, sum) for the top-level sum and every group's inner sum."""
yield path, nodes
for i, node in enumerate(nodes):
if node[0] == "group":
yield from _sites(node[2], path + (i,))
def _replace_sum(nodes, path, new_sum):
if not path:
return new_sum
i = path[0]
node = nodes[i]
inner = _replace_sum(node[2], path[1:], new_sum)
return nodes[:i] + [("group", node[1], inner)] + nodes[i + 1:]
def apply_distribute(nodes):
"""Every result of expanding one group: c(d + e) -> cd + ce."""
results = []
for path, s in _sites(nodes):
for i, node in enumerate(s):
if node[0] != "group":
continue
expanded = [_scale(node[1], t) for t in node[2]]
results.append(_replace_sum(nodes, path, s[:i] + expanded + s[i + 1:]))
return results
def apply_combine(nodes):
"""Every result of merging one pair of like nodes in one sum.
Merges two like non-group nodes — two ``num``s, two ``term``s, or two
``pterm``s of the same exponent — anywhere within one sum; the merged
node takes the first node's position. A pair summing to zero drops
out (an emptied sum becomes ``0``).
"""
results = []
for path, s in _sites(nodes):
for i in range(len(s)):
if s[i][0] in ("group", "prodg"):
continue
for j in range(i + 1, len(s)):
if s[j][0] != s[i][0] or s[j][2:] != s[i][2:]:
continue
total = s[i][1] + s[j][1]
merged = [(s[i][0], total) + tuple(s[i][2:])] if total else []
rest = s[:i] + merged + s[i + 1:j] + s[j + 1:]
if not rest:
rest = [("num", 0)]
results.append(_replace_sum(nodes, path, rest))
return results
# ---------------------------------------------------------------------------
# Power expressions — the exponent-law family's language. A product is a
# list of nodes: ("xp", e) for x^e, or ("pg", [nodes], b) for
# (product)^b. Rendered with " · " separators; parsed by parse_pow. The
# warrant registry carries per-warrant parsers so one checker serves both
# expression languages.
# ---------------------------------------------------------------------------
def render_pow(nodes):
out = []
for node in nodes:
if node[0] == "xp":
out.append("x" if node[1] == 1 else f"x^{node[1]}")
else:
out.append(f"({render_pow(node[1])})^{node[2]}")
return " · ".join(out)
def parse_pow(text):
"""Parses a rendered power product back to node-list form."""
tokens = _tokenize(text)
idx = 0
def peek():
return tokens[idx] if idx < len(tokens) else None
def expect(tok):
nonlocal idx
if peek() != tok:
raise ValueError(f"expected {tok!r}, got {peek()!r}")
idx += 1
def parse_product():
nonlocal idx
nodes = [parse_factor()]
while peek() == "·":
idx += 1
nodes.append(parse_factor())
return nodes
def parse_factor():
nonlocal idx
tok = peek()
if tok == "x":
idx += 1
if peek() == "^":
idx += 1
exp = peek()
if exp is None or not exp.isdigit():
raise ValueError("exponent must be an integer")
idx += 1
return ("xp", int(exp))
return ("xp", 1)
if tok == "(":
idx += 1
inner = parse_product()
expect(")")
expect("^")
exp = peek()
if exp is None or not exp.isdigit():
raise ValueError("exponent must be an integer")
idx += 1
return ("pg", inner, int(exp))
raise ValueError(f"unexpected token {tok!r} in power expression")
nodes = parse_product()
if idx != len(tokens):
raise ValueError(f"trailing tokens in power expression: {tokens[idx:]!r}")
return nodes
def _pow_sites(nodes, path=()):
yield path, nodes
for i, node in enumerate(nodes):
if node[0] == "pg":
yield from _pow_sites(node[1], path + (i,))
def _replace_pow(nodes, path, new_product):
if not path:
return new_product
i = path[0]
node = nodes[i]
inner = _replace_pow(node[1], path[1:], new_product)
return nodes[:i] + [("pg", inner, node[2])] + nodes[i + 1:]
def apply_product_of_powers(nodes):
"""Every result of merging one pair of bare powers: x^a · x^b -> x^(a+b)."""
results = []
for path, s in _pow_sites(nodes):
for i in range(len(s)):
if s[i][0] != "xp":
continue
for j in range(i + 1, len(s)):
if s[j][0] != "xp":
continue
merged = ("xp", s[i][1] + s[j][1])
results.append(_replace_pow(
nodes, path, s[:i] + [merged] + s[i + 1:j] + s[j + 1:]))
return results
def apply_power_of_power(nodes):
"""Every result of collapsing one (x^a)^b -> x^(a*b)."""
results = []
for path, s in _pow_sites(nodes):
for i, node in enumerate(s):
if node[0] == "pg" and len(node[1]) == 1 and node[1][0][0] == "xp":
collapsed = ("xp", node[1][0][1] * node[2])
results.append(_replace_pow(
nodes, path, s[:i] + [collapsed] + s[i + 1:]))
return results
# ---------------------------------------------------------------------------
# Fraction expressions — the telescoping family's language. A sum is a
# list of ("fr", p, q) nodes (a reduced signed fraction p/q, q >= 1;
# integers render plain) and ("pf", a, b) nodes (the positive
# product-form unit fraction 1/(a·b)). No nesting: partial-fraction
# splits splice their two terms directly into the sum, paper-style.
# ---------------------------------------------------------------------------
_FRAC_TOKEN = re.compile(r"\s*(\d+|[/()+\-·])")
def _frac_sign(node):
return -1 if (node[0] == "fr" and node[1] < 0) else 1
def _render_frac_abs(node):
if node[0] == "pf":
return f"1/({node[1]}·{node[2]})"
p, q = abs(node[1]), node[2]
return str(p) if q == 1 else f"{p}/{q}"
def render_frac(nodes):
out = []
for i, node in enumerate(nodes):
if i == 0:
prefix = "-" if _frac_sign(node) < 0 else ""
else:
prefix = " - " if _frac_sign(node) < 0 else " + "
out.append(prefix + _render_frac_abs(node))
return "".join(out)
def parse_frac(text):
"""Parses a rendered fraction sum back to node-list form."""
tokens, pos = [], 0
while pos < len(text):
m = _FRAC_TOKEN.match(text, pos)
if not m:
raise ValueError(
f"cannot tokenize fraction expression at {text[pos:]!r}")
tokens.append(m.group(1))
pos = m.end()
idx = 0
def peek(offset=0):
return tokens[idx + offset] if idx + offset < len(tokens) else None
def expect(tok):
nonlocal idx
if peek() != tok:
raise ValueError(f"expected {tok!r}, got {peek()!r}")
idx += 1
def parse_item(sign):
nonlocal idx
tok = peek()
if tok is None or not tok.isdigit():
raise ValueError(f"expected a number, got {tok!r}")
idx += 1
p = int(tok)
if peek() != "/":
return ("fr", sign * p, 1)
idx += 1
if peek() == "(":
if p != 1 or sign < 0:
raise ValueError("product-form fractions must be +1/(a·b)")
idx += 1
a = peek()
if a is None or not a.isdigit():
raise ValueError("expected a number in 1/(a·b)")
idx += 1
expect("·")
b = peek()
if b is None or not b.isdigit():
raise ValueError("expected a number in 1/(a·b)")
idx += 1
expect(")")
return ("pf", int(a), int(b))
q = peek()
if q is None or not q.isdigit():
raise ValueError("expected a denominator")
idx += 1
return ("fr", sign * p, int(q))
nodes = []
sign = 1
if peek() == "-":
sign, idx = -1, idx + 1
while True:
nodes.append(parse_item(sign))
tok = peek()
if tok == "+":
sign, idx = 1, idx + 1
elif tok == "-":
sign, idx = -1, idx + 1
else:
break
if idx != len(tokens):
raise ValueError(
f"trailing tokens in fraction expression: {tokens[idx:]!r}")
return nodes
def apply_partial_fractions(nodes):
"""Every result of splitting one 1/(a·(a+1)) into 1/a - 1/(a+1)."""
results = []
for i, node in enumerate(nodes):
if node[0] == "pf" and node[2] == node[1] + 1:
split = [("fr", 1, node[1]), ("fr", -1, node[2])]
results.append(nodes[:i] + split + nodes[i + 1:])
return results
def apply_cancel_pair(nodes):
"""Every result of removing one exactly-opposite pair of fractions."""
results = []
for i in range(len(nodes)):
if nodes[i][0] != "fr":
continue
for j in range(i + 1, len(nodes)):
if nodes[j][0] != "fr":
continue
if nodes[j][1] == -nodes[i][1] and nodes[j][2] == nodes[i][2]:
rest = nodes[:i] + nodes[i + 1:j] + nodes[j + 1:]
results.append(rest if rest else [("fr", 0, 1)])
return results
def apply_add_fractions(nodes):
"""Every result of exactly adding one pair of fractions (nonzero sum;
a zero sum is cancel_pair's move)."""
results = []
for i in range(len(nodes)):
if nodes[i][0] != "fr":
continue
for j in range(i + 1, len(nodes)):
if nodes[j][0] != "fr":
continue
total = Fraction(nodes[i][1], nodes[i][2]) \
+ Fraction(nodes[j][1], nodes[j][2])
if total == 0:
continue
merged = ("fr", total.numerator, total.denominator)
results.append(nodes[:i] + [merged]
+ nodes[i + 1:j] + nodes[j + 1:])
return results
# ---------------------------------------------------------------------------
# Log expressions — the log-law family's language. A sum is a list of
# ("num", n) and ("klg", k, b, factors) nodes, where factors is a list of
# ("f", m, e) entries: k·log_b(m1^e1 · m2 · ...). All quantities positive
# integers; bases are exact-friendly and every evaluated log is exact.
# ---------------------------------------------------------------------------
_LOG_TOKEN = re.compile(r"\s*(\d+|log|[()+^·_])")
def render_log(nodes):
out = []
for node in nodes:
if node[0] == "num":
out.append(str(node[1]))
continue
k, b, fs = node[1], node[2], node[3]
arg = " · ".join(str(m) if e == 1 else f"{m}^{e}" for _, m, e in fs)
lg = f"log_{b}({arg})" if len(fs) > 1 or fs[0][2] > 1 \
else f"log_{b} {arg}"
out.append(lg if k == 1 else f"{k}·{lg}")
return " + ".join(out)
def parse_log(text):
"""Parses a rendered log sum back to node-list form."""
tokens, pos = [], 0
while pos < len(text):
m = _LOG_TOKEN.match(text, pos)
if not m:
raise ValueError(f"cannot tokenize log expression at {text[pos:]!r}")
tokens.append(m.group(1))
pos = m.end()
idx = 0
def peek(offset=0):
return tokens[idx + offset] if idx + offset < len(tokens) else None
def expect(tok):
nonlocal idx
if peek() != tok:
raise ValueError(f"expected {tok!r}, got {peek()!r}")
idx += 1
def parse_factor():
nonlocal idx
m_tok = peek()
if m_tok is None or not m_tok.isdigit():
raise ValueError(f"expected a number, got {m_tok!r}")
idx += 1
e = 1
if peek() == "^":
idx += 1
e_tok = peek()
if e_tok is None or not e_tok.isdigit():
raise ValueError("exponent must be an integer")
idx += 1
e = int(e_tok)
return ("f", int(m_tok), e)
def parse_item():
nonlocal idx
k = 1
if peek() is not None and peek().isdigit() and peek(1) == "·" \
and peek(2) == "log":
k = int(peek())
idx += 2
if peek() == "log":
idx += 1
expect("_")
b_tok = peek()
if b_tok is None or not b_tok.isdigit():
raise ValueError("log base must be an integer")
idx += 1
if peek() == "(":
idx += 1
factors = [parse_factor()]
while peek() == "·":
idx += 1
factors.append(parse_factor())
expect(")")
else:
factors = [parse_factor()]
return ("klg", k, int(b_tok), factors)
tok = peek()
if tok is None or not tok.isdigit():
raise ValueError(f"unexpected token {tok!r} in log expression")
idx += 1
return ("num", int(tok))
nodes = [parse_item()]
while peek() == "+":
idx += 1
nodes.append(parse_item())
if idx != len(tokens):
raise ValueError(f"trailing tokens in log expression: {tokens[idx:]!r}")
return nodes
def apply_log_of_product(nodes):
"""Every result of splitting one factor off a multi-factor log."""
results = []
for i, node in enumerate(nodes):
if node[0] == "klg" and len(node[3]) > 1:
first = ("klg", node[1], node[2], node[3][:1])
rest = ("klg", node[1], node[2], node[3][1:])
results.append(nodes[:i] + [first, rest] + nodes[i + 1:])
return results
def apply_log_of_power(nodes):
"""Every result of pulling one exponent out: k·log_b(m^e) -> (k·e)·log_b m."""
results = []
for i, node in enumerate(nodes):
if node[0] == "klg" and len(node[3]) == 1 and node[3][0][2] > 1:
_, m, e = node[3][0]
results.append(nodes[:i]
+ [("klg", node[1] * e, node[2], [("f", m, 1)])]
+ nodes[i + 1:])
return results
def _exact_log(b, m):
j, value = 0, 1
while value < m:
value *= b
j += 1
return j if value == m else None
def apply_evaluate_log(nodes):
"""Every result of evaluating one exact log: k·log_b(b^j) -> k·j."""
results = []
for i, node in enumerate(nodes):
if node[0] == "klg" and len(node[3]) == 1 and node[3][0][2] == 1:
j = _exact_log(node[2], node[3][0][1])
if j is not None:
results.append(nodes[:i] + [("num", node[1] * j)]
+ nodes[i + 1:])
return results
def apply_add_integers(nodes):
"""Every result of adding one pair of integer terms."""
results = []
for i in range(len(nodes)):
if nodes[i][0] != "num":
continue
for j in range(i + 1, len(nodes)):
if nodes[j][0] != "num":
continue
merged = ("num", nodes[i][1] + nodes[j][1])
results.append(nodes[:i] + [merged]
+ nodes[i + 1:j] + nodes[j + 1:])
return results
def _mul_linear(u, v):
"""Product of two linear nodes (num/term) from binomial factors."""
cu, cv = u[1], v[1]
if u[0] == "term" and v[0] == "term":
return ("pterm", cu * cv, 2)
if u[0] == "num" and v[0] == "num":
return ("num", cu * cv)
return ("term", cu * cv)
def apply_expand_product(nodes):
"""Every result of FOIL-expanding one binomial product.
c(A)(B) becomes c( a1·b1 + a1·b2 + a2·b1 + a2·b2 ) — the four cross
terms in FOIL order inside a group still carrying c, so a subsequent
``distribute`` clears the coefficient exactly as on paper. Factors
must be sums of ``num``/``term`` nodes.
"""
results = []
for path, s in _sites(nodes):
for i, node in enumerate(s):
if node[0] != "prodg":
continue
fa, fb = node[2]
if any(t[0] not in ("num", "term") for t in fa + fb):
continue
foil = [_mul_linear(u, v) for u in fa for v in fb]
expanded = ("group", node[1], foil)
results.append(_replace_sum(nodes, path,
s[:i] + [expanded] + s[i + 1:]))
if node[1] == 1:
# With no coefficient to carry, FOIL lands as four bare
# terms — the way it is actually written on paper.
results.append(_replace_sum(nodes, path,
s[:i] + foil + s[i + 1:]))
return results
# ---------------------------------------------------------------------------
# Euclid statements — the integer-arithmetic certificate language shared
# by the gcd/Bezout and primality families. Unlike the sum languages, a
# statement parses to a single tuple:
#
# ("gcd", a, b) gcd(a, b)
# ("int", n) n
# ("div", a, q, b, r) a = q·b + r (division identity, r >= 0)
# ("comb", g, s, u, t, v) g = s·u + t·v (integer combination; s, t
# may be negative)
# ("prod", n, a, b) n = a·b (factorization)
# ("prime", n) n is prime
# ("pcong", n, k, r, m) n^k ≡ r (mod m) (k = 1 renders without ^)
# ("xcong", a, m) x ≡ a (mod m) (a congruence condition on
# the unknown x)
# ("divides", d, n) d divides n (worded: "|" is the field
# ("ndivides", d, n) d does not divide n delimiter)
# ("dsum", n, s) digitsum(n) = s
# ("asum", n, s) altsum(n) = s (alternating from the units
# digit; s may be negative)
# ("tail", n, k, m) last<k>(n) = m (k in 1..3)
#
# The membership and judgment machinery is agnostic to the parsed form,
# so single tuples ride the same checker as node lists.
# ---------------------------------------------------------------------------
_EUCLID_TOKEN = re.compile(
r"\s*(\d+|gcd|is|prime|mod|digitsum|altsum|last1|last2|last3"
r"|divides|does|not|divide|[(),=+\-·^≡x])")
def render_euclid(node):
kind = node[0]
if kind == "gcd":
return f"gcd({node[1]}, {node[2]})"
if kind == "int":
return str(node[1])
if kind == "prime":
return f"{node[1]} is prime"
if kind == "prod":
return f"{node[1]} = {node[2]}·{node[3]}"
if kind == "pcong":
_, n, k, r, m = node
base = str(n) if k == 1 else f"{n}^{k}"
return f"{base} ≡ {r} (mod {m})"
if kind == "xcong":
return f"x ≡ {node[1]} (mod {node[2]})"
if kind == "divides":
return f"{node[1]} divides {node[2]}"
if kind == "ndivides":
return f"{node[1]} does not divide {node[2]}"
if kind == "dsum":
return f"digitsum({node[1]}) = {node[2]}"
if kind == "asum":
return f"altsum({node[1]}) = {node[2]}"
if kind == "tail":
return f"last{node[2]}({node[1]}) = {node[3]}"
if kind == "div":
_, a, q, b, r = node
return f"{a} = {q}·{b} + {r}"
_, g, s, u, t, v = node
head = f"{s}·{u}" if s >= 0 else f"-{-s}·{u}"
tail = f" + {t}·{v}" if t >= 0 else f" - {-t}·{v}"
return f"{g} = {head}{tail}"
def parse_euclid(text):
"""Parses a rendered Euclid statement back to its tuple (round-trips)."""
tokens, pos = [], 0
while pos < len(text):
m = _EUCLID_TOKEN.match(text, pos)
if not m:
raise ValueError(
f"cannot tokenize Euclid statement at {text[pos:]!r}")
tokens.append(m.group(1))
pos = m.end()
idx = 0
def peek():
return tokens[idx] if idx < len(tokens) else None
def expect(tok):
nonlocal idx
if peek() != tok:
raise ValueError(f"expected {tok!r}, got {peek()!r}")
idx += 1
def parse_int():
nonlocal idx
tok = peek()
if tok is None or not tok.isdigit():
raise ValueError(f"expected a number, got {tok!r}")
idx += 1
return int(tok)
def done():
return idx == len(tokens)
if peek() == "gcd":
idx += 1
expect("(")
a = parse_int()
expect(",")
b = parse_int()
expect(")")
if not done():
raise ValueError(f"trailing tokens: {tokens[idx:]!r}")
return ("gcd", a, b)
if peek() == "x":
idx += 1
expect("≡")
a = parse_int()
expect("(")
expect("mod")
m = parse_int()
expect(")")
if not done():
raise ValueError(f"trailing tokens: {tokens[idx:]!r}")
return ("xcong", a, m)
if peek() in ("digitsum", "altsum", "last1", "last2", "last3"):
head = peek()
idx += 1
expect("(")
n = parse_int()
expect(")")
expect("=")
neg = peek() == "-"
if neg:
if head != "altsum":
raise ValueError("only altsum may be negative")
idx += 1
s = parse_int()
if not done():
raise ValueError(f"trailing tokens: {tokens[idx:]!r}")
if head == "digitsum":
return ("dsum", n, s)
if head == "altsum":
return ("asum", n, -s if neg else s)
return ("tail", n, int(head[-1]), s)
n = parse_int()
if done():
return ("int", n)
if peek() in ("^", "≡"):
k = 1
if peek() == "^":
idx += 1
k = parse_int()
if k < 2:
raise ValueError("rendered congruence exponents are >= 2")
expect("≡")
r = parse_int()
expect("(")
expect("mod")
m = parse_int()
expect(")")
if not done():
raise ValueError(f"trailing tokens: {tokens[idx:]!r}")
return ("pcong", n, k, r, m)
if peek() == "is":
idx += 1
expect("prime")
if not done():
raise ValueError(f"trailing tokens: {tokens[idx:]!r}")
return ("prime", n)
if peek() in ("divides", "does"):
if peek() == "divides":
idx += 1
kind = "divides"
else:
idx += 1
expect("not")
expect("divide")
kind = "ndivides"
m = parse_int()
if not done():
raise ValueError(f"trailing tokens: {tokens[idx:]!r}")
return (kind, n, m)
expect("=")
s_neg = peek() == "-"
if s_neg:
idx += 1
k1 = parse_int()
expect("·")
m1 = parse_int()
if done():
if s_neg:
raise ValueError("factorization factors must be positive")
return ("prod", n, k1, m1)
op = peek()
if op not in ("+", "-"):
raise ValueError(f"expected + or -, got {op!r}")
idx += 1
n2 = parse_int()
if done():
if s_neg or op != "+":
raise ValueError("division identity must be a = q·b + r")
return ("div", n, k1, m1, n2)
expect("·")
m2 = parse_int()
if not done():
raise ValueError(f"trailing tokens: {tokens[idx:]!r}")
return ("comb", n, -k1 if s_neg else k1, m1, -n2 if op == "-" else n2, m2)
def apply_euclid_step(node):
"""The Euclidean descent step: gcd(a, b) -> gcd(b, a mod b), b >= 1."""
if node[0] == "gcd" and node[2] >= 1:
return [("gcd", node[2], node[1] % node[2])]
return []
def apply_gcd_of_zero(node):
"""Reading off a finished descent: gcd(d, 0) -> d, d >= 1."""
if node[0] == "gcd" and node[2] == 0 and node[1] >= 1:
return [("int", node[1])]
return []
def check_division_identity(claim, prevs):
"""a = q·b + r with 0 <= r < b, cited against the line gcd(a, b)."""
(ref,) = prevs
if claim[0] != "div" or ref[0] != "gcd":
return False
_, a, q, b, r = claim
return ref[1] == a and ref[2] == b and a == q * b + r and 0 <= r < b
def check_rearrange_division(claim, prevs):
"""r = 1·a - q·b, cited against the division identity a = q·b + r."""
(ref,) = prevs
if claim[0] != "comb" or ref[0] != "div":
return False
_, a, q, b, r = ref
return r >= 1 and claim[1:] == (r, 1, a, -q, b)
def check_substitute_remainder(claim, prevs):
"""From g = s·u + t·v and U = q·u + v, conclude g = t·U + (s - t·q)·u."""
comb, div = prevs
if claim[0] != "comb" or comb[0] != "comb" or div[0] != "div":
return False
_, g, s, u, t, v = comb
_, big, q, base, r = div
if base != u or r != v:
return False
return claim[1:] == (g, t, big, s - t * q, u)
def _primes_upto(k):
return [p for p in range(2, k + 1)
if all(p % d for d in range(2, isqrt(p) + 1))]
def check_trial_division(claim, prevs):
"""n = q·p + r with 0 <= r < p and p >= 2, cited against the line n."""
(ref,) = prevs
if claim[0] != "div" or ref[0] != "int":
return False
_, n, q, p, r = claim
return n == ref[1] and p >= 2 and n == q * p + r and 0 <= r < p
def check_factorization(claim, prevs):
"""n = a·b read off an exact trial division n = q·p + 0."""
(ref,) = prevs
if claim[0] != "prod" or ref[0] != "div":
return False
_, n, a, b = claim
_, n2, q, p, r = ref
return (n2 == n and r == 0 and n == q * p and a >= 2 and b >= 2
and (a, b) in ((q, p), (p, q)))
def _pcong_true(c):
"""A congruence line re-verified from scratch (guards smuggled refs)."""
if c[0] != "pcong":
return False
_, n, k, r, m = c
return m >= 2 and 0 <= r < m and k >= 1 and pow(n, k, m) == r
def check_square_congruence(claim, prevs):
"""From n^k ≡ r (mod m) conclude n^(2k) ≡ r² reduced mod m."""
(ref,) = prevs
if claim[0] != "pcong" or not _pcong_true(ref):
return False
_, n, k, r, m = ref
return claim[1:] == (n, 2 * k, r * r % m, m)
def check_multiply_congruences(claim, prevs):
"""From n^j ≡ r and n^k ≡ s (mod m) conclude n^(j+k) ≡ r·s mod m."""
a, b = prevs
if claim[0] != "pcong" or not (_pcong_true(a) and _pcong_true(b)):
return False
_, n, k1, r1, m = a