-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
931 lines (737 loc) · 30.3 KB
/
Copy pathmain.py
File metadata and controls
931 lines (737 loc) · 30.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
#!/usr/bin/env python3
"""
Cayley Graph CLI Application
A production-ready command-line interface for analyzing finite groups
and visualizing their Cayley graphs.
Author: Kiavash
"""
from abc import ABC, abstractmethod
from itertools import permutations
from typing import Any, List, Set, Tuple, Optional
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
# =============================================================================
# Abstract Group Base Class
# =============================================================================
class Group(ABC):
"""Abstract base class representing a finite group."""
@property
@abstractmethod
def elements(self) -> List[Any]:
"""Return all elements of the group."""
pass
@property
@abstractmethod
def identity(self) -> Any:
"""Return the identity element of the group."""
pass
@abstractmethod
def mult(self, a: Any, b: Any) -> Any:
"""Compute the group operation a · b."""
pass
@abstractmethod
def inverse(self, a: Any) -> Any:
"""Compute the inverse of element a."""
pass
def order(self) -> int:
"""Return the order (number of elements) of the group."""
return len(self.elements)
def closure(self, generators: Set[Any]) -> Set[Any]:
"""
Compute the closure of a set of generators.
Returns the subgroup generated by the given elements.
"""
if not generators:
return {self.identity}
generated = set(generators)
generated.add(self.identity)
# Keep multiplying until no new elements are found
changed = True
while changed:
changed = False
new_elements = set()
for g in generated:
for h in generated:
product = self.mult(g, h)
if product not in generated:
new_elements.add(product)
changed = True
generated.update(new_elements)
return generated
def get_generators(self) -> List[Any]:
"""
Find a minimal generating set using a greedy algorithm.
Start with empty set, iteratively add elements not generated
by the current set until the closure equals the full group.
"""
generators: List[Any] = []
current_closure = {self.identity}
all_elements = set(self.elements)
# Prefer non-identity elements that are likely to be generators
candidates = [e for e in self.elements if e != self.identity]
while current_closure != all_elements:
# Find the element that maximizes the closure size
best_element = None
best_closure_size = len(current_closure)
for candidate in candidates:
if candidate in current_closure:
continue
new_closure = self.closure(set(generators) | {candidate})
if len(new_closure) > best_closure_size:
best_element = candidate
best_closure_size = len(new_closure)
if best_element is None:
# This shouldn't happen for a valid group
break
generators.append(best_element)
current_closure = self.closure(set(generators))
return generators
def __repr__(self) -> str:
return f"{self.__class__.__name__}(order={self.order()})"
# =============================================================================
# Cyclic Group
# =============================================================================
class CyclicGroup(Group):
"""
Cyclic group Z_n with addition modulo n.
Elements are integers 0, 1, ..., n-1.
"""
def __init__(self, n: int):
if n < 1:
raise ValueError("Order must be at least 1")
self._n = n
self._elements = list(range(n))
@property
def elements(self) -> List[int]:
return self._elements
@property
def identity(self) -> int:
return 0
def mult(self, a: int, b: int) -> int:
"""Addition modulo n."""
return (a + b) % self._n
def inverse(self, a: int) -> int:
"""Additive inverse modulo n."""
return (-a) % self._n
def get_generators(self) -> List[int]:
"""For cyclic groups, 1 always generates (if n > 1)."""
if self._n == 1:
return [0]
return [1]
# =============================================================================
# Dihedral Group
# =============================================================================
class DihedralGroup(Group):
"""
Dihedral group D_n of order n (symmetries of a regular polygon).
Convention: D8 is the dihedral group of order 8 (symmetries of a square).
Elements are tuples (r, s) where:
- r ∈ {0, 1} indicates reflection (0 = no reflection, 1 = reflection)
- s ∈ {0, 1, ..., n/2-1} indicates rotation
Group operation: (r1, s1) · (r2, s2) = (r1 ⊕ r2, s1 + (-1)^r1 * s2 mod k)
where k = n/2 and ⊕ is XOR.
"""
def __init__(self, order: int):
if order < 2 or order % 2 != 0:
raise ValueError("Dihedral group order must be an even number >= 2")
self._order = order
self._k = order // 2 # Number of rotations (polygon sides)
# Generate all elements: (reflection, rotation)
self._elements = []
for r in [0, 1]:
for s in range(self._k):
self._elements.append((r, s))
@property
def elements(self) -> List[Tuple[int, int]]:
return self._elements
@property
def identity(self) -> Tuple[int, int]:
return (0, 0)
def mult(self, a: Tuple[int, int], b: Tuple[int, int]) -> Tuple[int, int]:
"""
Dihedral group multiplication.
(r1, s1) · (r2, s2) = (r1 ⊕ r2, s1 + (-1)^r1 * s2 mod k)
"""
r1, s1 = a
r2, s2 = b
new_r = r1 ^ r2 # XOR
if r1 == 0:
new_s = (s1 + s2) % self._k
else:
new_s = (s1 - s2) % self._k
return (new_r, new_s)
def inverse(self, a: Tuple[int, int]) -> Tuple[int, int]:
"""Compute the inverse of element a."""
r, s = a
if r == 0:
return (0, (-s) % self._k)
else:
return (1, s)
def element_to_string(self, e: Tuple[int, int]) -> str:
"""Convert element tuple to readable string notation."""
r, s = e
if r == 0 and s == 0:
return "e"
elif r == 0:
return f"r^{s}" if s > 1 else "r"
elif s == 0:
return "s"
else:
return f"sr^{s}" if s > 1 else "sr"
def get_generators(self) -> List[Tuple[int, int]]:
"""Standard generators for dihedral group: rotation and reflection."""
generators = []
if self._k > 1:
generators.append((0, 1)) # Rotation r
generators.append((1, 0)) # Reflection s
return generators
# =============================================================================
# Symmetric Group
# =============================================================================
class SymmetricGroup(Group):
"""
Symmetric group S_n of all permutations of n elements.
Elements are tuples representing permutations.
A permutation p means: element i maps to p[i].
"""
def __init__(self, n: int):
if n < 1:
raise ValueError("n must be at least 1")
self._n = n
self._elements = list(permutations(range(n)))
@property
def elements(self) -> List[Tuple[int, ...]]:
return self._elements
@property
def identity(self) -> Tuple[int, ...]:
return tuple(range(self._n))
def mult(self, a: Tuple[int, ...], b: Tuple[int, ...]) -> Tuple[int, ...]:
"""
Permutation composition: (a · b)(x) = a(b(x)).
Apply b first, then a.
"""
return tuple(a[b[i]] for i in range(self._n))
def inverse(self, a: Tuple[int, ...]) -> Tuple[int, ...]:
"""Compute the inverse permutation."""
inv = [0] * self._n
for i, val in enumerate(a):
inv[val] = i
return tuple(inv)
def permutation_to_cycle_notation(self, p: Tuple[int, ...]) -> str:
"""Convert permutation to cycle notation string."""
if p == self.identity:
return "()"
visited = [False] * self._n
cycles = []
for start in range(self._n):
if visited[start]:
continue
cycle = []
i = start
while not visited[i]:
visited[i] = True
cycle.append(i + 1) # 1-indexed for readability
i = p[i]
if len(cycle) > 1:
cycles.append(f"({' '.join(map(str, cycle))})")
return ''.join(cycles) if cycles else "()"
def get_generators(self) -> List[Tuple[int, ...]]:
"""Standard generators: (1 2) and (1 2 ... n) for n >= 2."""
if self._n == 1:
return [self.identity]
generators = []
# Transposition (0 1)
trans = list(range(self._n))
trans[0], trans[1] = trans[1], trans[0]
generators.append(tuple(trans))
# n-cycle (0 1 2 ... n-1)
if self._n > 2:
cycle = tuple((i + 1) % self._n for i in range(self._n))
generators.append(cycle)
return generators
# =============================================================================
# Alternating Group
# =============================================================================
class AlternatingGroup(Group):
"""
Alternating group A_n of even permutations of n elements.
An even permutation can be written as a product of an even number of transpositions.
"""
def __init__(self, n: int):
if n < 1:
raise ValueError("n must be at least 1")
self._n = n
self._elements = [p for p in permutations(range(n)) if self._is_even_permutation(p)]
def _is_even_permutation(self, p: Tuple[int, ...]) -> bool:
"""Check if a permutation is even by counting inversions."""
inversions = 0
n = len(p)
for i in range(n):
for j in range(i + 1, n):
if p[i] > p[j]:
inversions += 1
return inversions % 2 == 0
@property
def elements(self) -> List[Tuple[int, ...]]:
return self._elements
@property
def identity(self) -> Tuple[int, ...]:
return tuple(range(self._n))
def mult(self, a: Tuple[int, ...], b: Tuple[int, ...]) -> Tuple[int, ...]:
"""Permutation composition."""
return tuple(a[b[i]] for i in range(self._n))
def inverse(self, a: Tuple[int, ...]) -> Tuple[int, ...]:
"""Compute the inverse permutation."""
inv = [0] * self._n
for i, val in enumerate(a):
inv[val] = i
return tuple(inv)
def permutation_to_cycle_notation(self, p: Tuple[int, ...]) -> str:
"""Convert permutation to cycle notation string."""
if p == self.identity:
return "()"
visited = [False] * self._n
cycles = []
for start in range(self._n):
if visited[start]:
continue
cycle = []
i = start
while not visited[i]:
visited[i] = True
cycle.append(i + 1)
i = p[i]
if len(cycle) > 1:
cycles.append(f"({' '.join(map(str, cycle))})")
return ''.join(cycles) if cycles else "()"
def get_generators(self) -> List[Tuple[int, ...]]:
"""Standard generators for A_n: 3-cycles for n >= 3."""
if self._n <= 2:
return [self.identity]
generators = []
# 3-cycle (0 1 2)
cycle3 = list(range(self._n))
cycle3[0], cycle3[1], cycle3[2] = cycle3[1], cycle3[2], cycle3[0]
generators.append(tuple(cycle3))
# n-cycle if n is odd, or (n-1)-cycle starting from 0 if n is even
if self._n >= 4:
if self._n % 2 == 1:
# n-cycle for odd n
cycle_n = tuple((i + 1) % self._n for i in range(self._n))
generators.append(cycle_n)
else:
# (1 2)(3 4 ... n) type generator
gen = list(range(self._n))
gen[0], gen[1] = gen[1], gen[0]
# Apply (2 3 ... n-1) cycle
for i in range(2, self._n):
gen[i] = ((i - 2 + 1) % (self._n - 2)) + 2
generators.append(tuple(gen))
return generators
# =============================================================================
# CSV Group
# =============================================================================
class CSVGroup(Group):
"""
Group loaded from a CSV multiplication table.
CSV format:
- First row: headers starting with * (or operation symbol), then element names
- First column: element names (same order as first row)
- Cell (i, j): result of row_element * column_element
Example:
*, e, a, b, ab
e, e, a, b, ab
a, a, e, ab, b
b, b, ab, e, a
ab, ab, b, a, e
"""
def __init__(self, filename: str):
self._filename = filename
self._load_table(filename)
self._validate()
def _load_table(self, filename: str):
"""Load and parse the CSV file."""
# Read CSV with first column as index
df = pd.read_csv(filename, index_col=0)
# Strip whitespace from headers and index
df.columns = df.columns.str.strip()
df.index = df.index.str.strip()
# Also strip whitespace from cell values
df = df.map(lambda x: x.strip() if isinstance(x, str) else x)
self._table = df
self._elements = list(df.columns)
self._identity = self._find_identity()
def _find_identity(self) -> str:
"""Find the identity element (e such that e*x = x*e = x for all x)."""
for candidate in self._elements:
is_identity = True
for elem in self._elements:
if self._table.loc[candidate, elem] != elem or self._table.loc[elem, candidate] != elem:
is_identity = False
break
if is_identity:
return candidate
raise ValueError("No identity element found in the group table")
def _validate(self):
"""Validate that the table forms a valid group."""
# Check that all products are in the group
for a in self._elements:
for b in self._elements:
product = self._table.loc[a, b]
if product not in self._elements:
raise ValueError(f"Product {a}*{b}={product} is not in the element set")
# Check that every element has an inverse
for a in self._elements:
has_inverse = False
for b in self._elements:
if self._table.loc[a, b] == self._identity and self._table.loc[b, a] == self._identity:
has_inverse = True
break
if not has_inverse:
raise ValueError(f"Element {a} has no inverse")
@property
def elements(self) -> List[str]:
return self._elements
@property
def identity(self) -> str:
return self._identity
def mult(self, a: str, b: str) -> str:
"""Look up the product in the table."""
return self._table.loc[a, b]
def inverse(self, a: str) -> str:
"""Find the inverse of element a."""
for b in self._elements:
if self._table.loc[a, b] == self._identity:
return b
raise ValueError(f"No inverse found for {a}")
# =============================================================================
# Cayley Graph Visualization
# =============================================================================
class CayleyGrapher:
"""
Visualization engine for Cayley graphs.
A Cayley graph has:
- Nodes: group elements
- Directed edges: (g, g·s) for every element g and generator s
"""
# Color palette for generators
COLORS = [
'#e41a1c', # Red
'#377eb8', # Blue
'#4daf4a', # Green
'#984ea3', # Purple
'#ff7f00', # Orange
'#ffff33', # Yellow
'#a65628', # Brown
'#f781bf', # Pink
'#999999', # Gray
]
def __init__(self, group: Group, generators: Optional[List[Any]] = None):
"""
Initialize the Cayley grapher.
Args:
group: The group to visualize
generators: Optional list of generators (auto-detected if not provided)
"""
self.group = group
self.generators = generators if generators else group.get_generators()
self.directed_graph = self._build_directed_graph()
self.graph = self.directed_graph # For compatibility
def _build_directed_graph(self) -> nx.DiGraph:
"""Build the full directed Cayley graph."""
G = nx.DiGraph()
# Add all elements as nodes
for elem in self.group.elements:
G.add_node(elem)
# Add directed edges for each generator
for gen_idx, gen in enumerate(self.generators):
for elem in self.group.elements:
target = self.group.mult(elem, gen)
G.add_edge(elem, target, generator=gen, gen_idx=gen_idx)
return G
def _classify_edges(self) -> Tuple[List[Tuple], List[Tuple]]:
"""
Classify edges into bidirectional (undirected) and one-way (directed).
Returns:
Tuple of (undirected_edges, directed_edges) with their gen_idx
"""
undirected = [] # (u, v, gen_idx) - bidirectional pairs
directed = [] # (u, v, gen_idx) - one-way only
seen_pairs = set()
for u, v, data in self.directed_graph.edges(data=True):
gen_idx = data['gen_idx']
pair = frozenset([u, v])
if pair in seen_pairs:
continue
# Check if reverse edge exists
if self.directed_graph.has_edge(v, u):
# Bidirectional - show as undirected
undirected.append((u, v, gen_idx))
seen_pairs.add(pair)
else:
# One-way - keep as directed
directed.append((u, v, gen_idx))
return undirected, directed
def _get_node_label(self, elem: Any) -> str:
"""Get a readable label for a node."""
if isinstance(self.group, DihedralGroup):
return self.group.element_to_string(elem)
elif isinstance(self.group, (SymmetricGroup, AlternatingGroup)):
return self.group.permutation_to_cycle_notation(elem)
else:
return str(elem)
def _get_generator_label(self, gen: Any) -> str:
"""Get a readable label for a generator."""
if isinstance(self.group, DihedralGroup):
return self.group.element_to_string(gen)
elif isinstance(self.group, (SymmetricGroup, AlternatingGroup)):
return self.group.permutation_to_cycle_notation(gen)
else:
return str(gen)
def draw(self, figsize: Tuple[int, int] = (12, 10), title: Optional[str] = None):
"""
Draw the Cayley graph with colored edges for each generator.
Bidirectional edges are shown as undirected (no arrows).
One-way edges are shown as directed (with arrows).
Args:
figsize: Figure size as (width, height)
title: Optional title for the plot
"""
fig, ax = plt.subplots(figsize=figsize)
# Compute layout
try:
pos = nx.kamada_kawai_layout(self.directed_graph)
except Exception:
pos = nx.spring_layout(self.directed_graph, k=2/np.sqrt(len(self.group.elements)), seed=42)
# Create node labels
labels = {elem: self._get_node_label(elem) for elem in self.group.elements}
# Draw nodes
nx.draw_networkx_nodes(
self.directed_graph, pos, ax=ax,
node_color='lightblue',
node_size=800,
edgecolors='black',
linewidths=1.5
)
# Draw node labels
nx.draw_networkx_labels(
self.directed_graph, pos, labels, ax=ax,
font_size=9,
font_weight='bold'
)
# Classify edges
undirected_edges, directed_edges = self._classify_edges()
# Draw edges for each generator with different colors
legend_patches = []
for gen_idx, gen in enumerate(self.generators):
color = self.COLORS[gen_idx % len(self.COLORS)]
# Get undirected edges for this generator
gen_undirected = [(u, v) for u, v, idx in undirected_edges if idx == gen_idx]
# Get directed edges for this generator
gen_directed = [(u, v) for u, v, idx in directed_edges if idx == gen_idx]
# Draw undirected edges (no arrows, thicker)
if gen_undirected:
nx.draw_networkx_edges(
self.directed_graph, pos, ax=ax,
edgelist=gen_undirected,
edge_color=color,
arrows=False,
width=3,
alpha=0.8
)
# Draw directed edges (with arrows)
if gen_directed:
nx.draw_networkx_edges(
self.directed_graph, pos, ax=ax,
edgelist=gen_directed,
edge_color=color,
arrows=True,
arrowsize=18,
arrowstyle='-|>',
connectionstyle='arc3,rad=0.15',
width=2,
alpha=0.8
)
# Add to legend
gen_label = self._get_generator_label(gen)
patch = mpatches.Patch(color=color, label=f'Generator: {gen_label}')
legend_patches.append(patch)
# Add legend
ax.legend(handles=legend_patches, loc='upper left', fontsize=10)
# Set title
if title:
ax.set_title(title, fontsize=14, fontweight='bold')
else:
ax.set_title(f'Cayley Graph of {self.group}', fontsize=14, fontweight='bold')
# Add project label at bottom left
fig.text(0.02, 0.02, 'Algebra I project', fontsize=10, color='red',
ha='left', va='bottom', style='italic')
ax.axis('off')
plt.tight_layout()
return fig, ax
def get_adjacency_matrix(self) -> pd.DataFrame:
"""
Get the adjacency matrix of the directed graph as a DataFrame.
Returns:
DataFrame with element labels as row/column indices
"""
# Get node list with proper labels
node_labels = [self._get_node_label(elem) for elem in self.group.elements]
# Create adjacency matrix
n = len(self.group.elements)
matrix = np.zeros((n, n), dtype=int)
elem_to_idx = {elem: i for i, elem in enumerate(self.group.elements)}
for u, v in self.directed_graph.edges():
i, j = elem_to_idx[u], elem_to_idx[v]
matrix[i][j] = 1
return pd.DataFrame(matrix, index=node_labels, columns=node_labels)
def save_adjacency_matrix(self, directory: str = ".", group_name: Optional[str] = None) -> str:
"""
Save the adjacency matrix to a CSV file with timestamp.
Args:
directory: Directory to save the file (default: current directory)
group_name: Name to use in filename (default: group repr)
Returns:
Path to the saved file
"""
from datetime import datetime
import os
# Generate filename with date, time, and group name
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
name = group_name if group_name else str(self.group).replace("(", "_").replace(")", "").replace("=", "")
# Clean up filename
name = name.replace(" ", "_").replace("/", "-")
filename = f"{timestamp}_{name}_adjacency.csv"
filepath = os.path.join(directory, filename)
# Get and save adjacency matrix
adj_matrix = self.get_adjacency_matrix()
adj_matrix.to_csv(filepath)
print(f"Adjacency matrix saved to: {filepath}")
return filepath
def is_connected(self) -> bool:
"""Check if the Cayley graph is strongly connected."""
return nx.is_strongly_connected(self.directed_graph)
def show(self, save_matrix: bool = True, output_dir: str = ".", **kwargs):
"""
Draw and display the graph, optionally saving the adjacency matrix.
Args:
save_matrix: If True, save adjacency matrix to CSV (default: True)
output_dir: Directory for saving files (default: current directory)
**kwargs: Additional arguments passed to draw()
"""
self.draw(**kwargs)
if save_matrix:
title = kwargs.get('title', None)
self.save_adjacency_matrix(directory=output_dir, group_name=title)
plt.show()
# =============================================================================
# CLI Interface
# =============================================================================
def display_menu():
"""Display the main menu."""
print("\n" + "=" * 50)
print(" CAYLEY GRAPH GENERATOR")
print("=" * 50)
print("\nSelect a group type:")
print(" 1. Cyclic Group (Z_n)")
print(" 2. Dihedral Group (e.g., D8, D10...)")
print(" 3. Symmetric Group (S_n)")
print(" 4. Alternating Group (A_n)")
print(" 5. Import from CSV")
print(" 0. Exit")
print()
def get_positive_int(prompt: str) -> int:
"""Get a positive integer from user input."""
while True:
try:
value = int(input(prompt))
if value > 0:
return value
print("Please enter a positive integer.")
except ValueError:
print("Invalid input. Please enter a number.")
def get_even_int(prompt: str) -> int:
"""Get a positive even integer from user input."""
while True:
try:
value = int(input(prompt))
if value > 0 and value % 2 == 0:
return value
print("Please enter a positive even integer.")
except ValueError:
print("Invalid input. Please enter a number.")
def main():
"""Main entry point for the CLI."""
print("\nWelcome to the Cayley Graph Generator!")
while True:
display_menu()
try:
choice = input("Enter your choice (0-5): ").strip()
except (EOFError, KeyboardInterrupt):
print("\nGoodbye!")
break
group = None
title = None
if choice == '0':
print("\nGoodbye!")
break
elif choice == '1':
# Cyclic Group
n = get_positive_int("Enter the order n for Z_n: ")
group = CyclicGroup(n)
title = f"Cayley Graph of Z_{n}"
elif choice == '2':
# Dihedral Group
print("\nNote: D8 represents the Dihedral Group of Order 8 (symmetries of a square).")
order = get_even_int("Enter the Order of the group (e.g., 8 for D8): ")
group = DihedralGroup(order)
title = f"Cayley Graph of D{order}"
elif choice == '3':
# Symmetric Group
n = get_positive_int("Enter n for S_n: ")
if n > 5:
print(f"Warning: S_{n} has {np.math.factorial(n)} elements. This may take a while.")
confirm = input("Continue? (y/n): ").strip().lower()
if confirm != 'y':
continue
group = SymmetricGroup(n)
title = f"Cayley Graph of S_{n}"
elif choice == '4':
# Alternating Group
n = get_positive_int("Enter n for A_n: ")
if n > 5:
print(f"Warning: A_{n} has {np.math.factorial(n)//2} elements. This may take a while.")
confirm = input("Continue? (y/n): ").strip().lower()
if confirm != 'y':
continue
group = AlternatingGroup(n)
title = f"Cayley Graph of A_{n}"
elif choice == '5':
# CSV Import
filename = input("Enter the path to the CSV file: ").strip()
try:
group = CSVGroup(filename)
title = f"Cayley Graph from {filename}"
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
continue
except Exception as e:
print(f"Error loading CSV: {e}")
continue
else:
print("Invalid choice. Please try again.")
continue
if group:
print(f"\nGroup: {group}")
print(f"Order: {group.order()}")
generators = group.get_generators()
print(f"Generators: {generators}")
print("\nGenerating Cayley graph...")
grapher = CayleyGrapher(group, generators)
print(f"Graph is strongly connected: {grapher.is_connected()}")
grapher.show(title=title)
if __name__ == "__main__":
main()