-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_full_proof_graph.py
More file actions
2159 lines (1851 loc) · 82.3 KB
/
generate_full_proof_graph.py
File metadata and controls
2159 lines (1851 loc) · 82.3 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
# Generative Logic: A deterministic reasoning and knowledge generation engine.
# Copyright (C) 2025 Generative Logic UG (haftungsbeschränkt)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# ------------------------------------------------------------------------------
#
# This software is also available under a commercial license. For details,
# see: https://generative-logic.com/license
#
# Contributions to this project must be made under the terms of the
# Contributor License Agreement (CLA). See the project's CONTRIBUTING.md file.
# !/usr/bin/env python3
"""
generate_full_proof_graph.py
Generates a set of HTML proof pages:
- An index page with a Table of Contents
- One HTML file per theorem (with navigation links)
Each theorem tuple is now (theorem_name:str, method:str, var_name:str).
Default output directory: full_proof_graph
"""
import copy
import json
import os
import html
import re
import shutil
import expression_utils
from expression_utils import disintegrate_implication, replace_keys_in_string
from typing import Dict
from configuration_reader import configuration_reader
from parameters import debug
import visu_helpers
from visu_helpers import format_mirroring, expand_expr
from pathlib import Path
# wherever this file lives, assume the project root is its parent folder
PROJECT_ROOT = Path(__file__).resolve().parent
# global mapping from displayed theorem title → its chapter file
theorem_to_file = {}
# alpha-normalized theorem shape -> file (only unique matches)
theorem_shape_to_file = {}
# Tag descriptions for the proof graph reference page and right-click popups
TAG_DESCRIPTIONS = {
"implication": (
"Hash-table inference",
"A premise was matched against a universally quantified implication rule "
"stored in hash memory, and the conclusion was emitted. "
"The first dependency is the rule itself; the remaining dependencies are "
"the expressions that matched the rule's premises."
),
"expansion": (
"Named expression expanded",
"A named compound expression (e.g. NaturalNumbers, fXY) was expanded "
"into its compiled definition structure from the GL binary. "
"The dependency is the named expression that was expanded."
),
"disintegration": (
"Compound expression decomposed",
"A conjunction (&) or existence node was broken apart into its "
"constituent sub-expressions. For conjunctions, each element is extracted; "
"for existence nodes, the left element (with a fresh bound variable) and "
"the right element are produced."
),
"task formulation": (
"Proof premise (root assumption)",
"The starting assumption for the theorem under proof. In a direct proof, "
"this is the premise of the implication being proved. In an induction proof, "
"this includes the base case or induction hypothesis."
),
"equality1": (
"Argument substitution via equality",
"An expression's argument was replaced using an equality fact. "
"If (=[a,b]) is known and f(...,a,...) exists, then f(...,b,...) is derived."
),
"equality2": (
"Transitivity of equality",
"From (=[a,b]) and (=[b,c]), the equality (=[a,c]) is derived. "
"This is the standard transitivity rule for the equality relation."
),
"symmetry of equality": (
"Symmetry of equality",
"From (=[a,b]), the symmetric equality (=[b,a]) is derived. "
"This is the standard symmetry rule for the equality relation."
),
"recursion": (
"Induction hypothesis",
"Introduction of the induction hypothesis. In check_zero chapters, the induction "
"variable is set to i0 (zero). In check_induction_condition chapters, the "
"successor step is applied to the induction variable."
),
"theorem": (
"Previously proved theorem",
"A theorem that was proved in an earlier chapter is used as an inference "
"rule. The dependency links to the chapter where the theorem was originally proved."
),
"reformulation for integration": (
"Reformulated for reverse-disintegration",
"An expression was reformulated into a form suitable for integration "
"(reverse disintegration). This prepares the expression structure so "
"that it can be reassembled into a compound expression."
),
"expansion for integration": (
"Expanded for reverse-disintegration",
"A named expression was expanded specifically in preparation for integration. "
"The expanded form provides the structural template needed for the "
"reverse-disintegration step."
),
"premise element": (
"Implication premise consumed",
"A premise of an implication was matched during the integration process. "
"This marks one of the conditions that needed to be satisfied before "
"the implication's conclusion could be assembled."
),
"validity name": (
"Implication scope identifier",
"Ties an expression to the specific implication whose scope it belongs to "
"during the integration process. Ensures that premises and conclusions "
"are matched within the correct logical context."
),
"anchor handling": (
"Anchor variable substitution",
"An anchor variable was substituted with a concrete value from the "
"definition set. This binds abstract anchor parameters to specific "
"elements (e.g., replacing argument position 1 with an element of N)."
),
"mirrored from": (
"Mirror of source theorem",
"This theorem is a mirrored variant of another theorem — the output-variable "
"premise and the head (conclusion) are swapped. The dependency links to "
"the original source theorem."
),
"reformulated from": (
"Reformulation of source theorem",
"This theorem is a reformulation of another theorem — the head (conclusion) "
"has been rewritten using an existence-node expansion from the GL binary. "
"The dependency links to the original source theorem."
),
"necessity for equality (hypo)": (
"Equality hypothesis introduction",
"An equality is introduced as a hypothesis for collapsing duplicate "
"variables. When multiple variables must be identified as equal, this "
"tag marks the equality assumption that enables the collapse."
),
"externally provided theorem": (
"External theorem (not proved by GL)",
"A theorem injected from the externally_provided_theorems.txt file. "
"This theorem was not proved by GL's own deduction engine but is "
"accepted as a given fact for use in downstream proofs."
),
"incubator back reformulation": (
"Back-reformulated operator theorem",
"An operator-equality theorem (e.g., a+b=c) was back-reformulated from "
"the implication form into a direct operator statement. The dependency "
"links to the source proof."
),
"contradiction": (
"Proved by contradiction",
"Both an expression and its negation were derived within the same "
"logic block, establishing a contradiction. The theorem is proved "
"because the negation of the conclusion led to an inconsistency."
),
"origin": (
"Provenance tracking",
"Tracks the origin of an expression in a contradiction proof chain. "
"Links an expression to its source derivation so the full "
"dependency chain can be reconstructed."
),
"multiplied from": (
"Partition-based variable equalization",
"A theorem produced by the multiplyImplication algorithm. Bell partitions "
"of bound variables generate copies where variable groups are set equal, "
"enabling cross-expression equalization."
),
"equalize variable": (
"Variable equalization step",
"A step within a multiplied proof where specific variables are identified "
"as equal. This is part of the partition-based equalization process "
"that collapses variables across expressions."
),
}
def _alpha_normalize_theorem_expr(expr: str) -> str:
"""Normalize theorem expressions up to variable renaming (alpha-equivalence).
We replace every bracket-argument token with a stable placeholder by first occurrence.
This lets instantiated theorem schemas (e.g. broadcasted versions) match the generic theorem page.
"""
if not expr or not isinstance(expr, str):
return expr
s = expr.strip()
if not (s.startswith('(>') or s.startswith('!(')):
return s
token_pattern = re.compile(r'(?<=[\[,])([^,\[\]]+)(?=[\],])')
mapping = {}
next_idx = 0
def repl(m):
nonlocal next_idx
tok = m.group(1)
base = _strip_u_prefixes(tok)
if base not in mapping:
mapping[base] = f"@{next_idx}"
next_idx += 1
return mapping[base]
return token_pattern.sub(repl, s)
def _resolve_theorem_target(expr: str):
target = theorem_to_file.get(expr)
if target:
return target
shape = _alpha_normalize_theorem_expr(expr)
return theorem_shape_to_file.get(shape)
# Display v-variables as w-variables for applied theorems (avoids confusion with chapter's own v-variables)
def _v_to_w_display(expr: str) -> str:
"""Replace v-prefixed variables with w-prefixed ones for display only."""
args = extract_args(expr)
v_args = [a for a in args if re.fullmatch(r'v\d+', a) or re.fullmatch(r'vx\d+', a)]
if not v_args:
return expr
rmap = {a: 'w' + a[1:] for a in v_args}
return replace_keys_in_string(expr, rmap)
def _strip_i_prefix(expr: str) -> str:
"""Strip 'i' prefix from anchor element names (i0->0, i1->1) for display.
Works on both bracketed args and readable math text."""
return re.sub(r'\bi(\d+)\b', r'\1', expr)
# Extract top-level constituent expression names for GL binary display
_EXPR_NAME_RE = re.compile(r'\(([A-Za-z_][A-Za-z0-9_]*)\[')
def _extract_expr_parts(expr: str) -> str:
"""Extract unique expression names (e.g. 'in2', 'in3', 'AnchorPeano') from an expression.
Returns comma-separated string of names that exist in the GL binary map."""
names = list(dict.fromkeys(_EXPR_NAME_RE.findall(expr))) # unique, order-preserving
return ','.join(names) if names else ''
def _space_commas(s: str) -> str:
"""Add spaces after commas inside [...] brackets for display readability."""
return re.sub(r',(?=[^\s])', ', ', s)
# Utility function to wrap clickable substrings starting with '(' or '!(' and ending at space or end-of-string
def wrap_clickable(text):
def repl(m):
s = m.group(0) # the raw token, e.g. "(v7*v8)=(v8*v7)"
esc = html.escape(s, quote=True)
parts = html.escape(_extract_expr_parts(s), quote=True)
parts_attr = f' data-parts="{parts}"' if parts else ''
target = _resolve_theorem_target(s)
if target:
# Display with w-variables, keep original v-expression for link target and data-text
display = html.escape(_strip_i_prefix(_v_to_w_display(s)), quote=True)
span = f'<span class="clickable" data-text="{esc}"{parts_attr}>{display}</span>'
return f'<a href="{target}" class="theorem-link">{span}</a>'
# span for the normal "expand on right-click"
display_esc = html.escape(_strip_i_prefix(s), quote=True)
span = f'<span class="clickable" data-text="{esc}"{parts_attr}>{display_esc}</span>'
return span
pattern = r"!?\([^ ]*?\)(?= |$)"
result = re.sub(pattern, repl, text)
# Strip i-prefix from plain text segments (outside HTML tags)
result = re.sub(r'(?<![<"\w])i(\d+)(?!["\w>])', r'\1', result)
# Wrap _integration_goal suffix as a right-clickable label
result = result.replace(
'_integration_goal',
'<span class="integration-goal-label">_integration_goal</span>')
return result
def _htmlify_readable(text):
"""Convert plain-text readable title to HTML with mathematical notation."""
h = html.escape(text)
# (preorder[N,+,a,b]) -> a < b
h = re.sub(
r'\(preorder\[([^,]+),([^,]+),([^,]+),([^\]]+)\]\)',
lambda m: f'{m.group(3)} < {m.group(4)}',
h)
# (interval[N,+,start,end,set]) -> set = [start,end]
h = re.sub(
r'\(interval\[([^,]+),([^,]+),([^,]+),([^,]+),([^\]]+)\]\)',
lambda m: f'{m.group(5)} = [{m.group(3)},{m.group(4)}]',
h)
# (fXY[a,B,C]) -> a: B -> C
h = re.sub(
r'\(fXY\[([^,]+),([^,]+),([^\]]+)\]\)',
lambda m: f'{m.group(1)}: {m.group(2)} \u2192 {m.group(3)}',
h)
# (sequence[N,+,c,a,b]) -> b is a sequence (b^i)_{i in [c,a]}
h = re.sub(
r'\(sequence\[([^,]+),([^,]+),([^,]+),([^,]+),([^\]]+)\]\)',
lambda m: f'{m.group(5)} is a sequence ({m.group(5)}<sup>i</sup>)<sub>i\u2208[{m.group(3)},{m.group(4)}]</sub>',
h)
# sum(i=start..end) -> vertical sigma with bounds above/below, summing i
def _fmt_sum(m):
lo, hi, fn = m.group(1), m.group(2), m.group(3)
body = f'{fn}(i)' if fn else 'i'
sigma = (
'<span class="sm" style="display:inline-flex;flex-direction:column;'
'align-items:center;vertical-align:middle;margin:0 2px;line-height:1">'
f'<span style="font-size:0.6em">{hi}</span>'
'<span style="font-size:1.8em;line-height:0.8;margin-bottom:8px">\u2211</span>'
f'<span style="font-size:0.6em;margin-top:8px">i={lo}</span>'
'</span>'
)
return f'{sigma} {body}'
h = re.sub(r'sum\(i=([^.]+)\.\.([^)]+)\)(?: (\w+)\(i\))?', _fmt_sum, h)
# enlarge parentheses that directly wrap a sigma block
h = re.sub(
r'\(([^()]*?<span class="sm".*?</span>[^()]*?)\)',
lambda m: (
'<span style="font-size:2em;vertical-align:middle;font-weight:normal">(</span>'
+ m.group(1) +
'<span style="font-size:2em;vertical-align:middle;font-weight:normal">)</span>'
), h)
# Space around '=' in text segments only (skip HTML tags/attributes)
parts = re.split(r'(<[^>]+>)', h)
h = ''.join(
re.sub(r'(?<!=)\s*=\s*(?!=)', ' = ', p) if not p.startswith('<') else p
for p in parts
)
# vN → v<sub>N</sub> in text segments only
parts = re.split(r'(<[^>]+>)', h)
h = ''.join(
re.sub(r'v(\d+)', r'v<sub>\1</sub>', p) if not p.startswith('<') else p
for p in parts
)
# Add breathing room around scaffolding keywords
for kw in ['RULE:', 'IMPLIES:', 'from', 'follows', 'and', 'mirrored from',
'reformulated from', 'back-reformulated from', 'is a sequence']:
h = h.replace(kw, f' {kw} ')
return h
def _format_validity_tag(validity: str) -> str:
if not validity:
return ""
raw = validity.strip()
esc = html.escape(raw)
if raw.startswith("(") and raw.endswith(")"):
return f' <span class="validity-tag">{esc}</span>'
return f' <span class="validity-tag">({esc})</span>'
def format_stack_entries(stack, prefix='', cursor_index=None, reverse_entries=True, external_anchor_map=None, goal_key_norm=None):
"""
Convert a proof-stack (list of [key, validity, explanation, ing1, val1, ...]) into HTML.
New Format Structure:
0: Result Expression (Key)
1: Result Validity
2: Explanation (Method/Justification)
3, 5, 7...: Ingredient Expressions
4, 6, 8...: Ingredient Validities
"""
# Reverse so the earliest step is first in the output (legacy behavior)
rev = list(stack)[::-1] if reverse_entries else list(stack)
# Map each key (normalized) to a unique anchor ID
key_map = {}
external_anchor_map = external_anchor_map or {}
for idx, entry in enumerate(rev):
if not entry:
continue
key = entry[0]
norm = re.sub(r'\s+', '', key).lower()
key_map[norm] = f"{prefix}-entry{idx}" if prefix else f"entry{idx}"
lines = []
total = len(rev)
visible_count = sum(1 for e in rev if e and 'theorem' not in e)
step_num = 0
highlight_idx = None
if goal_key_norm:
for i, entry in enumerate(rev):
if entry and _norm_expr(entry[0]) == goal_key_norm:
highlight_idx = i
break
else:
if total > 0:
highlight_idx = total - 1
for idx, entry in enumerate(rev):
if 'theorem' in entry:
continue
if not entry:
continue
step_num += 1
step_badge = f"<span class='step-badge'>({step_num}/{visible_count})</span>"
key_expr = entry[0]
key_validity = entry[1] if len(entry) > 1 else ""
explanation = entry[2] if len(entry) > 2 else ""
norm_key = re.sub(r'\s+', '', key_expr).lower()
anchor = key_map.get(norm_key, "")
if highlight_idx is not None and idx == highlight_idx:
first, *rest = key_expr.split(' ', 1)
first_html = wrap_clickable(first)
if first_html.startswith('<a '):
first_html = first_html.replace(
'<span class="clickable"',
'<span class="clickable" style="color:#EF9F27 !important; font-weight:bold !important;"',
1
)
else:
first_html = f'<span class="clickable" style="color:#EF9F27; font-weight:bold">{first_html}</span>'
if rest:
rest_html = wrap_clickable(rest[0])
key_html = f"{first_html} {rest_html}"
else:
key_html = first_html
else:
key_html = wrap_clickable(key_expr)
# Expression diff highlight for equality1 steps
if explanation == "equality1" and len(entry) > 3:
key_html = _diff_highlight_html(key_html, key_expr, entry[3])
if key_validity:
key_html += _format_validity_tag(key_validity)
# Collect dependency anchor IDs for hover-highlighting
dep_ids = []
for di in range(3, len(entry), 2):
d_expr = entry[di]
d_norm = re.sub(r'\s+', '', d_expr).lower()
if d_norm in key_map:
dep_ids.append(key_map[d_norm])
elif d_norm in external_anchor_map:
dep_ids.append(external_anchor_map[d_norm])
deps_attr = f" data-deps=\"{' '.join(dep_ids)}\"" if dep_ids else ""
parts = [f"<span id='{anchor}'{deps_attr}>{key_html}</span>"]
if explanation:
tag_key = explanation.lower().strip()
# Normalize sub-variants of "reformulation for integration"
if tag_key.startswith("reformulation for integration"):
tag_anchor = "reformulation-for-integration"
else:
tag_anchor = tag_key.replace(" ", "-").replace("(", "").replace(")", "")
escaped = html.escape(explanation)
parts.append(
f"<a href='tags.html#{tag_anchor}' class='proof-tag' "
f"data-tag='{html.escape(tag_key, quote=True)}'>"
f"<b>{escaped}</b></a>"
)
if explanation == "validity name":
if len(entry) > 3:
rhs_html = wrap_clickable(entry[3])
if len(entry) > 4 and entry[4]:
rhs_html += _format_validity_tag(entry[4])
parts.append(rhs_html)
content_html = " ".join(parts)
if cursor_index is not None and idx == cursor_index:
content_html = (
f"<span style='background-color:#3A3520; padding:4px; "
f"border-radius:4px'>{content_html}</span>"
)
line_html = f"<div class='proof-line'>{step_badge}<span class='proof-line-content'>{content_html}</span></div>"
lines.append(line_html)
continue
for i in range(3, len(entry), 2):
ing_expr = entry[i]
ing_val = entry[i + 1] if i + 1 < len(entry) else ""
norm_ref = re.sub(r'\s+', '', ing_expr).lower()
ref_html = wrap_clickable(ing_expr)
# --- NEW: Highlight integration target ---
is_integration_target = (explanation == "expansion for integration" and i == 3)
if is_integration_target:
# 1. Strip away the clickable <span> and data attributes to get plain text
clean_text = re.sub(r'<[^>]+>', '', ref_html)
# 2. Re-wrap in magenta span, right-clickable for integration goal explanation
ref_html = f'<span class="integration-goal-label" style="color:#E879F9 !important; font-weight:bold !important;">"{clean_text}"</span>'
# -----------------------------------------
if is_integration_target:
linked_ref = ref_html
elif norm_ref in key_map:
linked_ref = f"<a href='#{key_map[norm_ref]}' style='text-decoration:none'>{ref_html}</a>"
elif norm_ref in external_anchor_map:
linked_ref = f"<a href='#{external_anchor_map[norm_ref]}' style='text-decoration:none'>{ref_html}</a>"
else:
linked_ref = ref_html
if ing_val:
linked_ref += _format_validity_tag(ing_val)
parts.append(linked_ref)
content_html = " ".join(parts)
if cursor_index is not None and idx == cursor_index:
content_html = (
f"<span style='background-color:#3A3520; padding:4px; "
f"border-radius:4px'>{content_html}</span>"
)
line_html = f"<div class='proof-line'>{step_badge}<span class='proof-line-content'>{content_html}</span></div>"
lines.append(line_html)
if len(entry) > 2 and entry[2] == 'implication':
if len(entry) > 3:
helper_list = [entry[0], "implication", entry[3]]
for k in range(5, len(entry), 2):
helper_list.append(entry[k])
impl_text = visu_helpers.format_implication(helper_list)
if impl_text:
impl_html = (
f"<div class='implication readable-grey'>"
f"{_htmlify_readable(_strip_i_prefix(impl_text))}</div>"
)
lines.append(impl_html)
if len(entry) > 2 and entry[2] == 'mirrored from':
if len(entry) > 3:
helper_list = [entry[0], "mirrored from", entry[3]]
mirrored_text = format_mirroring(helper_list)
mirrored_html = (
f"<div class='mirrored readable-grey'>"
f"{_htmlify_readable(_strip_i_prefix(mirrored_text))}</div>"
)
lines.append(mirrored_html)
if len(entry) > 2 and entry[2] == 'reformulated from':
if len(entry) > 3:
helper_list = [entry[0], "reformulated from", entry[3]]
reformulated_text = visu_helpers.format_reformulation(helper_list)
reformulated_html = (
f"<div class='reformulated readable-grey'>"
f"{_htmlify_readable(_strip_i_prefix(reformulated_text))}</div>"
)
lines.append(reformulated_html)
if len(entry) > 2 and entry[2] == 'incubator back reformulation':
if len(entry) > 3:
source_readable = visu_helpers.make_readable_title(entry[3])
back_ref_readable = visu_helpers.make_readable_title(entry[0])
back_ref_text = f"{back_ref_readable} back-reformulated from {source_readable}"
back_ref_html = (
f"<div class='readable-grey'>"
f"{_htmlify_readable(_strip_i_prefix(back_ref_text))}</div>"
)
lines.append(back_ref_html)
return "\n".join(lines)
def extract_args(s: str) -> list[str]:
# same pattern as before
pattern = r'(?<=[\[,])([^,\[\]]+)(?=[\],])'
all_subs = re.findall(pattern, s)
# remove duplicates while preserving order
return list(dict.fromkeys(all_subs))
def _diff_highlight_html(result_html: str, result_expr: str, source_expr: str) -> str:
"""Highlight arguments in result_html that differ from source_expr."""
# Extract bracket structure: name[arg1,arg2,...] from both
r_match = re.match(r'^!?\((\w+)\[([^\]]+)\]\)$', result_expr.strip())
s_match = re.match(r'^!?\((\w+)\[([^\]]+)\]\)$', source_expr.strip())
if not r_match or not s_match:
return result_html
if r_match.group(1) != s_match.group(1):
return result_html # different expression name
r_args = r_match.group(2).split(',')
s_args = s_match.group(2).split(',')
if len(r_args) != len(s_args):
return result_html
# Find changed args
changed = {r_args[i] for i in range(len(r_args)) if r_args[i] != s_args[i]}
if not changed:
return result_html
# Wrap changed arg text in highlight spans — text segments only (skip HTML tags/attributes)
# Search for both raw form (v2, i4) and i-stripped form (4) since display strips i-prefix
for arg in changed:
variants = [html.escape(arg)]
if re.match(r'^i\d+$', arg):
variants.append(html.escape(arg[1:])) # stripped form: i4 -> 4
for escaped in variants:
pat = re.compile(r'(?<=[,\[])(' + re.escape(escaped) + r')(?=[,\]])')
parts = re.split(r'(<[^>]+>)', result_html)
result_html = ''.join(
pat.sub(r'<span class="arg-changed">\1</span>', p) if not p.startswith('<') else p
for p in parts
)
return result_html
def _strip_u_prefixes(token: str) -> str:
out = token
while out.startswith("u_"):
out = out[2:]
return out
def _looks_like_internal_var_token(token: str) -> bool:
"""
Internal proof-engine variable-ish names we want to rename to v<number>.
We intentionally do NOT rename theorem/operator symbols like implication26, in2, and0, id, s, etc.
"""
if not token:
return False
base = _strip_u_prefixes(token)
if base.isdigit():
return True
if re.fullmatch(r"x\d+", base):
return True
if re.fullmatch(r"(?:int|repl)_lev_\d+_\d+", base):
return True
if re.fullmatch(r"it_\d+_lev_\d+_\d+", base):
return True
if re.fullmatch(r"it_lev_\d+_\d+", base):
return True
if base == "rec":
return True
return False
def _normalize_local_expr_vars(expr: str):
"""
Lightweight local normalization:
Leaves u_ variables COMPLETELY ALONE (u_30 stays u_30).
Only normalizes raw non-prefixed variables (7 -> v7, x7 -> vx7).
"""
args = extract_args(expr)
replacement_map = {}
for arg in args:
if arg.startswith("u_"):
continue # Do not touch u_ variables at all
if arg.isdigit():
replacement_map[arg] = "v" + arg
elif arg.startswith("x") and arg[1:].isdigit():
replacement_map[arg] = "v" + arg
return replace_keys_in_string(expr, replacement_map)
def rename_expr_peano(expr: str):
return _normalize_local_expr_vars(expr)
def rename_expr_gauss(expr: str):
return _normalize_local_expr_vars(expr)
def rename_expr(expr: str):
# generic fallback
return _normalize_local_expr_vars(expr)
def extract_natural_numbers_expression(expression: str) -> str:
"""
Extracts the substring starting at "(NaturalNumbers[" up to and including
the first ']' that follows. Returns "" if not found or malformed.
"""
needle = "(NaturalNumbers["
start = expression.find(needle)
if start == -1:
return ""
end = expression.find("]", start + len(needle))
if end == -1:
return ""
return expression[start:end + 1]
def find_one_arg_name(zero_arg: str, s_arg: str, expr: str) -> str:
"""
Find the middle argument name in a pattern like:
(in2[<zero_arg>, <NAME>, <s_arg>])
where NAME is [A-Za-z0-9_]+. Returns the first match or "" if none.
"""
pattern = (
r"\(in2\[\s*"
+ re.escape(zero_arg)
+ r"\s*,\s*([A-Za-z0-9_]+)\s*,\s*"
+ re.escape(s_arg)
+ r"\s*\]\)"
)
m = re.search(pattern, expr)
return m.group(1) if m else ""
def find_identity_arg_name(n_arg: str, expr: str) -> str:
"""Extract id from (identity[<N>, <id>])."""
pattern = (
r"\(identity\[\s*"
+ re.escape(n_arg)
+ r"\s*,\s*([A-Za-z0-9_]+)\s*\]\)"
)
m = re.search(pattern, expr)
return m.group(1) if m else ""
def _make_prefixed_token(token: str, mode: str) -> str:
if not token:
return token
if mode == 'as_is':
return token
if mode == 'vprefix':
return token if token.startswith('v') else f"v{token}"
raise ValueError(f"Unknown prefix mode: {mode}")
def infer_anchor_kind_from_expr(expr: str) -> str:
if not expr:
return ""
if "(AnchorGauss[" in expr:
return "gauss"
if "(AnchorPeano[" in expr:
return "peano"
return ""
def infer_anchor_kind_from_theorem(theorem_expr: str) -> str:
kind = infer_anchor_kind_from_expr(theorem_expr)
if kind:
return kind
temp_chain = []
try:
disintegrate_implication(theorem_expr, temp_chain)
except Exception:
return ""
for element in temp_chain:
k = infer_anchor_kind_from_expr(element[0])
if k:
return k
return ""
def build_anchor_symbol_replacement_map(anchor_expr: str, prefix_mode: str = 'as_is', anchor_kind: str = 'auto') -> dict[str, str]:
"""Build replacement map for AnchorPeano / AnchorGauss symbols."""
replacement_map: dict[str, str] = {}
detected_kind = infer_anchor_kind_from_expr(anchor_expr)
if anchor_kind == 'auto':
anchor_kind = detected_kind
if anchor_kind not in ('peano', 'gauss'):
return replacement_map
if not (anchor_expr.startswith('(AnchorPeano[') or anchor_expr.startswith('(AnchorGauss[')):
return replacement_map
expanded_anchor = expand_expr(anchor_expr)
nn_expr = extract_natural_numbers_expression(expanded_anchor)
if not nn_expr:
return replacement_map
args = expression_utils.get_args(nn_expr)
if len(args) < 5:
return replacement_map
def put_symbol(token: str, symbol: str, include_vx_alias: bool = False):
if not token:
return
key = _make_prefixed_token(token, prefix_mode)
replacement_map[key] = symbol
if include_vx_alias and key.startswith('v') and len(key) > 1:
replacement_map['vx' + key[1:]] = symbol
# NaturalNumbers[N,i0,s,+,*]
put_symbol(args[0], 'N')
put_symbol(args[1], '0', include_vx_alias=True)
put_symbol(args[2], 's')
put_symbol(args[3], '+')
put_symbol(args[4], '*')
zero_arg_name = args[1]
s_arg_name = args[2]
one_arg_name = find_one_arg_name(zero_arg_name, s_arg_name, expanded_anchor)
put_symbol(one_arg_name, '1', include_vx_alias=True)
if anchor_kind == 'gauss':
two_arg_name = find_one_arg_name(one_arg_name, s_arg_name, expanded_anchor) if one_arg_name else ''
put_symbol(two_arg_name, '2', include_vx_alias=True)
id_arg_name = find_identity_arg_name(args[0], expanded_anchor)
put_symbol(id_arg_name, 'id')
return replacement_map
def _extract_anchor_subexpressions(expr: str) -> list[str]:
"""Return all nested (AnchorPeano[...]) / (AnchorGauss[...]) subexpressions found in expr."""
if not expr:
return []
starts = ["(AnchorPeano[", "(AnchorGauss["]
out = []
i = 0
n = len(expr)
while i < n:
start = -1
start_token = ""
for token in starts:
j = expr.find(token, i)
if j != -1 and (start == -1 or j < start):
start = j
start_token = token
if start == -1:
break
# Scan until the matching ')' of the anchor expression.
bracket_depth = 0
k = start
end = -1
while k < n:
ch = expr[k]
if ch == '[':
bracket_depth += 1
elif ch == ']':
bracket_depth = max(0, bracket_depth - 1)
elif ch == ')' and bracket_depth == 0:
end = k
break
k += 1
if end != -1:
out.append(expr[start:end + 1])
i = end + 1
else:
# malformed; avoid infinite loop
i = start + len(start_token)
# preserve order, remove duplicates
return list(dict.fromkeys(out))
def _contains_u_prefixed_token(expr: str) -> bool:
for tok in extract_args(expr):
if tok.startswith('u_'):
return True
return False
def _extract_arg_tokens_in_order(s: str) -> list[str]:
"""Return all bracket/comma-delimited argument tokens in order (with duplicates)."""
return re.findall(r'(?<=[\[,])([^,\[\]]+)(?=[\],])', s)
def _build_local_w_replacement_map_for_unanchored_implication(norm_expr: str, raw_expr: str) -> dict[str, str]:
"""
Only renames the standard v<number> variables to w<number>.
Leaves u_ variables entirely untouched.
"""
norm_tokens = _extract_arg_tokens_in_order(norm_expr)
if not norm_tokens:
return {}
has_u = any(tok.startswith('u_') for tok in norm_tokens)
if not has_u:
return {}
replacement_map: dict[str, str] = {}
next_num = 1
for tok in norm_tokens:
if not tok.startswith('u_') and (re.fullmatch(r"v\d+", tok) or re.fullmatch(r"vx\d+", tok)):
if tok not in replacement_map:
replacement_map[tok] = f"w{next_num}"
next_num += 1
return replacement_map
def _collect_anchor_maps_from_expr(expr: str, prefix_mode: str, default_kind: str = "") -> dict[str, str]:
out = {}
if not expr:
return out
for anchor_expr in _extract_anchor_subexpressions(expr):
k = infer_anchor_kind_from_expr(anchor_expr) or default_kind
out.update(build_anchor_symbol_replacement_map(anchor_expr, prefix_mode=prefix_mode, anchor_kind=k or 'auto'))
return out
def _infer_row_anchor_kind(row: list[str], default_kind: str = "") -> str:
if not row:
return default_kind
expr_indices = [0] + list(range(3, len(row), 2))
for idx in expr_indices:
if idx < len(row):
k = infer_anchor_kind_from_expr(row[idx])
if k:
return k
return default_kind
def rename_theorem(theorem: str):
"""
Renaming is now fully handled by process_proof_graphs.py.
Just return the theorem exactly as it is.
"""
return theorem
def clean_stack(stack: list[list[str]]):
"""
Cleans a stack of strings by normalizing internal variable keys.
Leaves u_ variables completely untouched.
"""
# Avoid mutating while iterating
stack[:] = [entry for entry in stack if not (len(entry) > 2 and entry[2] == "anchor handling")]
token_pattern = re.compile(r'(?<=[\[,])([^,\[\]]+)(?=[\],])')
def expr_cols(row):
return [0] + list(range(3, len(row), 2))
def validity_cols(row):
cols = []
if len(row) > 1:
cols.append(1)
cols.extend(range(4, len(row), 2))
return cols
def all_norm_cols(row):
return expr_cols(row) + validity_cols(row)
# Gather already-existing v<number> indices so numbering doesn't collide.
max_index = -1
for row in stack:
if not row:
continue
for idx in all_norm_cols(row):
if idx >= len(row):
continue
for token in token_pattern.findall(row[idx]):
m = re.fullmatch(r'v(\d+)', token)
if m:
max_index = max(max_index, int(m.group(1)))
next_idx = max_index + 1 if max_index >= 0 else 0
replacement_map: dict[str, str] = {}
for row in stack:
if not row:
continue
for idx in all_norm_cols(row):
if idx >= len(row):
continue
for token in token_pattern.findall(row[idx]):
if token in replacement_map:
continue
if token.startswith("u_"):
continue # LEAVE u_ variables ALONE!
if _looks_like_internal_var_token(token):
if token.isdigit():
replacement_map[token] = f"v{token}"