applied-ai-018 commited on
Commit
084d6b3
·
verified ·
1 Parent(s): d58dcd3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/generators.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/partitions.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/galois.py +611 -0
  4. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/group_constructs.py +61 -0
  5. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/group_numbers.py +118 -0
  6. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.py +549 -0
  7. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/perm_groups.py +0 -0
  8. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/prufer.py +436 -0
  9. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/subsets.py +619 -0
  10. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tensor_can.py +1190 -0
  11. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__init__.py +0 -0
  12. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  13. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_coset_table.cpython-310.pyc +0 -0
  14. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_fp_groups.cpython-310.pyc +0 -0
  15. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_free_groups.cpython-310.pyc +0 -0
  16. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_galois.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_generators.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_group_numbers.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_named_groups.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_partitions.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_pc_groups.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_permutations.cpython-310.pyc +0 -0
  23. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_polyhedron.cpython-310.pyc +0 -0
  24. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_rewriting.cpython-310.pyc +0 -0
  25. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_schur_number.cpython-310.pyc +0 -0
  26. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_subsets.cpython-310.pyc +0 -0
  27. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_tensor_can.cpython-310.pyc +0 -0
  28. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_testutil.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_util.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_coset_table.py +825 -0
  31. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_fp_groups.py +252 -0
  32. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_galois.py +82 -0
  33. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_graycode.py +72 -0
  34. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_numbers.py +27 -0
  35. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_homomorphisms.py +114 -0
  36. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_named_groups.py +70 -0
  37. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_partitions.py +118 -0
  38. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_perm_groups.py +1243 -0
  39. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_polyhedron.py +105 -0
  40. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_prufer.py +74 -0
  41. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_rewriting.py +49 -0
  42. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_schur_number.py +55 -0
  43. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_subsets.py +63 -0
  44. llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_testutil.py +55 -0
  45. llmeval-env/lib/python3.10/site-packages/sympy/logic/__init__.py +12 -0
  46. llmeval-env/lib/python3.10/site-packages/sympy/logic/__pycache__/__init__.cpython-310.pyc +0 -0
  47. llmeval-env/lib/python3.10/site-packages/sympy/logic/__pycache__/boolalg.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc +0 -0
  49. llmeval-env/lib/python3.10/site-packages/sympy/logic/algorithms/__init__.py +0 -0
  50. llmeval-env/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py +308 -0
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/generators.cpython-310.pyc ADDED
Binary file (8.29 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/partitions.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/galois.py ADDED
@@ -0,0 +1,611 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ Construct transitive subgroups of symmetric groups, useful in Galois theory.
3
+
4
+ Besides constructing instances of the :py:class:`~.PermutationGroup` class to
5
+ represent the transitive subgroups of $S_n$ for small $n$, this module provides
6
+ *names* for these groups.
7
+
8
+ In some applications, it may be preferable to know the name of a group,
9
+ rather than receive an instance of the :py:class:`~.PermutationGroup`
10
+ class, and then have to do extra work to determine which group it is, by
11
+ checking various properties.
12
+
13
+ Names are instances of ``Enum`` classes defined in this module. With a name in
14
+ hand, the name's ``get_perm_group`` method can then be used to retrieve a
15
+ :py:class:`~.PermutationGroup`.
16
+
17
+ The names used for groups in this module are taken from [1].
18
+
19
+ References
20
+ ==========
21
+
22
+ .. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.
23
+
24
+ """
25
+
26
+ from collections import defaultdict
27
+ from enum import Enum
28
+ import itertools
29
+
30
+ from sympy.combinatorics.named_groups import (
31
+ SymmetricGroup, AlternatingGroup, CyclicGroup, DihedralGroup,
32
+ set_symmetric_group_properties, set_alternating_group_properties,
33
+ )
34
+ from sympy.combinatorics.perm_groups import PermutationGroup
35
+ from sympy.combinatorics.permutations import Permutation
36
+
37
+
38
+ class S1TransitiveSubgroups(Enum):
39
+ """
40
+ Names for the transitive subgroups of S1.
41
+ """
42
+ S1 = "S1"
43
+
44
+ def get_perm_group(self):
45
+ return SymmetricGroup(1)
46
+
47
+
48
+ class S2TransitiveSubgroups(Enum):
49
+ """
50
+ Names for the transitive subgroups of S2.
51
+ """
52
+ S2 = "S2"
53
+
54
+ def get_perm_group(self):
55
+ return SymmetricGroup(2)
56
+
57
+
58
+ class S3TransitiveSubgroups(Enum):
59
+ """
60
+ Names for the transitive subgroups of S3.
61
+ """
62
+ A3 = "A3"
63
+ S3 = "S3"
64
+
65
+ def get_perm_group(self):
66
+ if self == S3TransitiveSubgroups.A3:
67
+ return AlternatingGroup(3)
68
+ elif self == S3TransitiveSubgroups.S3:
69
+ return SymmetricGroup(3)
70
+
71
+
72
+ class S4TransitiveSubgroups(Enum):
73
+ """
74
+ Names for the transitive subgroups of S4.
75
+ """
76
+ C4 = "C4"
77
+ V = "V"
78
+ D4 = "D4"
79
+ A4 = "A4"
80
+ S4 = "S4"
81
+
82
+ def get_perm_group(self):
83
+ if self == S4TransitiveSubgroups.C4:
84
+ return CyclicGroup(4)
85
+ elif self == S4TransitiveSubgroups.V:
86
+ return four_group()
87
+ elif self == S4TransitiveSubgroups.D4:
88
+ return DihedralGroup(4)
89
+ elif self == S4TransitiveSubgroups.A4:
90
+ return AlternatingGroup(4)
91
+ elif self == S4TransitiveSubgroups.S4:
92
+ return SymmetricGroup(4)
93
+
94
+
95
+ class S5TransitiveSubgroups(Enum):
96
+ """
97
+ Names for the transitive subgroups of S5.
98
+ """
99
+ C5 = "C5"
100
+ D5 = "D5"
101
+ M20 = "M20"
102
+ A5 = "A5"
103
+ S5 = "S5"
104
+
105
+ def get_perm_group(self):
106
+ if self == S5TransitiveSubgroups.C5:
107
+ return CyclicGroup(5)
108
+ elif self == S5TransitiveSubgroups.D5:
109
+ return DihedralGroup(5)
110
+ elif self == S5TransitiveSubgroups.M20:
111
+ return M20()
112
+ elif self == S5TransitiveSubgroups.A5:
113
+ return AlternatingGroup(5)
114
+ elif self == S5TransitiveSubgroups.S5:
115
+ return SymmetricGroup(5)
116
+
117
+
118
+ class S6TransitiveSubgroups(Enum):
119
+ """
120
+ Names for the transitive subgroups of S6.
121
+ """
122
+ C6 = "C6"
123
+ S3 = "S3"
124
+ D6 = "D6"
125
+ A4 = "A4"
126
+ G18 = "G18"
127
+ A4xC2 = "A4 x C2"
128
+ S4m = "S4-"
129
+ S4p = "S4+"
130
+ G36m = "G36-"
131
+ G36p = "G36+"
132
+ S4xC2 = "S4 x C2"
133
+ PSL2F5 = "PSL2(F5)"
134
+ G72 = "G72"
135
+ PGL2F5 = "PGL2(F5)"
136
+ A6 = "A6"
137
+ S6 = "S6"
138
+
139
+ def get_perm_group(self):
140
+ if self == S6TransitiveSubgroups.C6:
141
+ return CyclicGroup(6)
142
+ elif self == S6TransitiveSubgroups.S3:
143
+ return S3_in_S6()
144
+ elif self == S6TransitiveSubgroups.D6:
145
+ return DihedralGroup(6)
146
+ elif self == S6TransitiveSubgroups.A4:
147
+ return A4_in_S6()
148
+ elif self == S6TransitiveSubgroups.G18:
149
+ return G18()
150
+ elif self == S6TransitiveSubgroups.A4xC2:
151
+ return A4xC2()
152
+ elif self == S6TransitiveSubgroups.S4m:
153
+ return S4m()
154
+ elif self == S6TransitiveSubgroups.S4p:
155
+ return S4p()
156
+ elif self == S6TransitiveSubgroups.G36m:
157
+ return G36m()
158
+ elif self == S6TransitiveSubgroups.G36p:
159
+ return G36p()
160
+ elif self == S6TransitiveSubgroups.S4xC2:
161
+ return S4xC2()
162
+ elif self == S6TransitiveSubgroups.PSL2F5:
163
+ return PSL2F5()
164
+ elif self == S6TransitiveSubgroups.G72:
165
+ return G72()
166
+ elif self == S6TransitiveSubgroups.PGL2F5:
167
+ return PGL2F5()
168
+ elif self == S6TransitiveSubgroups.A6:
169
+ return AlternatingGroup(6)
170
+ elif self == S6TransitiveSubgroups.S6:
171
+ return SymmetricGroup(6)
172
+
173
+
174
+ def four_group():
175
+ """
176
+ Return a representation of the Klein four-group as a transitive subgroup
177
+ of S4.
178
+ """
179
+ return PermutationGroup(
180
+ Permutation(0, 1)(2, 3),
181
+ Permutation(0, 2)(1, 3)
182
+ )
183
+
184
+
185
+ def M20():
186
+ """
187
+ Return a representation of the metacyclic group M20, a transitive subgroup
188
+ of S5 that is one of the possible Galois groups for polys of degree 5.
189
+
190
+ Notes
191
+ =====
192
+
193
+ See [1], Page 323.
194
+
195
+ """
196
+ G = PermutationGroup(Permutation(0, 1, 2, 3, 4), Permutation(1, 2, 4, 3))
197
+ G._degree = 5
198
+ G._order = 20
199
+ G._is_transitive = True
200
+ G._is_sym = False
201
+ G._is_alt = False
202
+ G._is_cyclic = False
203
+ G._is_dihedral = False
204
+ return G
205
+
206
+
207
+ def S3_in_S6():
208
+ """
209
+ Return a representation of S3 as a transitive subgroup of S6.
210
+
211
+ Notes
212
+ =====
213
+
214
+ The representation is found by viewing the group as the symmetries of a
215
+ triangular prism.
216
+
217
+ """
218
+ G = PermutationGroup(Permutation(0, 1, 2)(3, 4, 5), Permutation(0, 3)(2, 4)(1, 5))
219
+ set_symmetric_group_properties(G, 3, 6)
220
+ return G
221
+
222
+
223
+ def A4_in_S6():
224
+ """
225
+ Return a representation of A4 as a transitive subgroup of S6.
226
+
227
+ Notes
228
+ =====
229
+
230
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
231
+
232
+ """
233
+ G = PermutationGroup(Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4))
234
+ set_alternating_group_properties(G, 4, 6)
235
+ return G
236
+
237
+
238
+ def S4m():
239
+ """
240
+ Return a representation of the S4- transitive subgroup of S6.
241
+
242
+ Notes
243
+ =====
244
+
245
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
246
+
247
+ """
248
+ G = PermutationGroup(Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3))
249
+ set_symmetric_group_properties(G, 4, 6)
250
+ return G
251
+
252
+
253
+ def S4p():
254
+ """
255
+ Return a representation of the S4+ transitive subgroup of S6.
256
+
257
+ Notes
258
+ =====
259
+
260
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
261
+
262
+ """
263
+ G = PermutationGroup(Permutation(0, 2, 4, 1)(3, 5), Permutation(0, 3)(4, 5))
264
+ set_symmetric_group_properties(G, 4, 6)
265
+ return G
266
+
267
+
268
+ def A4xC2():
269
+ """
270
+ Return a representation of the (A4 x C2) transitive subgroup of S6.
271
+
272
+ Notes
273
+ =====
274
+
275
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
276
+
277
+ """
278
+ return PermutationGroup(
279
+ Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4),
280
+ Permutation(5)(2, 4))
281
+
282
+
283
+ def S4xC2():
284
+ """
285
+ Return a representation of the (S4 x C2) transitive subgroup of S6.
286
+
287
+ Notes
288
+ =====
289
+
290
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
291
+
292
+ """
293
+ return PermutationGroup(
294
+ Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3),
295
+ Permutation(1, 4)(3, 5))
296
+
297
+
298
+ def G18():
299
+ """
300
+ Return a representation of the group G18, a transitive subgroup of S6
301
+ isomorphic to the semidirect product of C3^2 with C2.
302
+
303
+ Notes
304
+ =====
305
+
306
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
307
+
308
+ """
309
+ return PermutationGroup(
310
+ Permutation(5)(0, 1, 2), Permutation(3, 4, 5),
311
+ Permutation(0, 4)(1, 5)(2, 3))
312
+
313
+
314
+ def G36m():
315
+ """
316
+ Return a representation of the group G36-, a transitive subgroup of S6
317
+ isomorphic to the semidirect product of C3^2 with C2^2.
318
+
319
+ Notes
320
+ =====
321
+
322
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
323
+
324
+ """
325
+ return PermutationGroup(
326
+ Permutation(5)(0, 1, 2), Permutation(3, 4, 5),
327
+ Permutation(1, 2)(3, 5), Permutation(0, 4)(1, 5)(2, 3))
328
+
329
+
330
+ def G36p():
331
+ """
332
+ Return a representation of the group G36+, a transitive subgroup of S6
333
+ isomorphic to the semidirect product of C3^2 with C4.
334
+
335
+ Notes
336
+ =====
337
+
338
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
339
+
340
+ """
341
+ return PermutationGroup(
342
+ Permutation(5)(0, 1, 2), Permutation(3, 4, 5),
343
+ Permutation(0, 5, 2, 3)(1, 4))
344
+
345
+
346
+ def G72():
347
+ """
348
+ Return a representation of the group G72, a transitive subgroup of S6
349
+ isomorphic to the semidirect product of C3^2 with D4.
350
+
351
+ Notes
352
+ =====
353
+
354
+ See [1], Page 325.
355
+
356
+ """
357
+ return PermutationGroup(
358
+ Permutation(5)(0, 1, 2),
359
+ Permutation(0, 4, 1, 3)(2, 5), Permutation(0, 3)(1, 4)(2, 5))
360
+
361
+
362
+ def PSL2F5():
363
+ r"""
364
+ Return a representation of the group $PSL_2(\mathbb{F}_5)$, as a transitive
365
+ subgroup of S6, isomorphic to $A_5$.
366
+
367
+ Notes
368
+ =====
369
+
370
+ This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
371
+
372
+ """
373
+ G = PermutationGroup(
374
+ Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 4, 3, 1, 5))
375
+ set_alternating_group_properties(G, 5, 6)
376
+ return G
377
+
378
+
379
+ def PGL2F5():
380
+ r"""
381
+ Return a representation of the group $PGL_2(\mathbb{F}_5)$, as a transitive
382
+ subgroup of S6, isomorphic to $S_5$.
383
+
384
+ Notes
385
+ =====
386
+
387
+ See [1], Page 325.
388
+
389
+ """
390
+ G = PermutationGroup(
391
+ Permutation(0, 1, 2, 3, 4), Permutation(0, 5)(1, 2)(3, 4))
392
+ set_symmetric_group_properties(G, 5, 6)
393
+ return G
394
+
395
+
396
+ def find_transitive_subgroups_of_S6(*targets, print_report=False):
397
+ r"""
398
+ Search for certain transitive subgroups of $S_6$.
399
+
400
+ The symmetric group $S_6$ has 16 different transitive subgroups, up to
401
+ conjugacy. Some are more easily constructed than others. For example, the
402
+ dihedral group $D_6$ is immediately found, but it is not at all obvious how
403
+ to realize $S_4$ or $S_5$ *transitively* within $S_6$.
404
+
405
+ In some cases there are well-known constructions that can be used. For
406
+ example, $S_5$ is isomorphic to $PGL_2(\mathbb{F}_5)$, which acts in a
407
+ natural way on the projective line $P^1(\mathbb{F}_5)$, a set of order 6.
408
+
409
+ In absence of such special constructions however, we can simply search for
410
+ generators. For example, transitive instances of $A_4$ and $S_4$ can be
411
+ found within $S_6$ in this way.
412
+
413
+ Once we are engaged in such searches, it may then be easier (if less
414
+ elegant) to find even those groups like $S_5$ that do have special
415
+ constructions, by mere search.
416
+
417
+ This function locates generators for transitive instances in $S_6$ of the
418
+ following subgroups:
419
+
420
+ * $A_4$
421
+ * $S_4^-$ ($S_4$ not contained within $A_6$)
422
+ * $S_4^+$ ($S_4$ contained within $A_6$)
423
+ * $A_4 \times C_2$
424
+ * $S_4 \times C_2$
425
+ * $G_{18} = C_3^2 \rtimes C_2$
426
+ * $G_{36}^- = C_3^2 \rtimes C_2^2$
427
+ * $G_{36}^+ = C_3^2 \rtimes C_4$
428
+ * $G_{72} = C_3^2 \rtimes D_4$
429
+ * $A_5$
430
+ * $S_5$
431
+
432
+ Note: Each of these groups also has a dedicated function in this module
433
+ that returns the group immediately, using generators that were found by
434
+ this search procedure.
435
+
436
+ The search procedure serves as a record of how these generators were
437
+ found. Also, due to randomness in the generation of the elements of
438
+ permutation groups, it can be called again, in order to (probably) get
439
+ different generators for the same groups.
440
+
441
+ Parameters
442
+ ==========
443
+
444
+ targets : list of :py:class:`~.S6TransitiveSubgroups` values
445
+ The groups you want to find.
446
+
447
+ print_report : bool (default False)
448
+ If True, print to stdout the generators found for each group.
449
+
450
+ Returns
451
+ =======
452
+
453
+ dict
454
+ mapping each name in *targets* to the :py:class:`~.PermutationGroup`
455
+ that was found
456
+
457
+ References
458
+ ==========
459
+
460
+ .. [2] https://en.wikipedia.org/wiki/Projective_linear_group#Exceptional_isomorphisms
461
+ .. [3] https://en.wikipedia.org/wiki/Automorphisms_of_the_symmetric_and_alternating_groups#PGL(2,5)
462
+
463
+ """
464
+ def elts_by_order(G):
465
+ """Sort the elements of a group by their order. """
466
+ elts = defaultdict(list)
467
+ for g in G.elements:
468
+ elts[g.order()].append(g)
469
+ return elts
470
+
471
+ def order_profile(G, name=None):
472
+ """Determine how many elements a group has, of each order. """
473
+ elts = elts_by_order(G)
474
+ profile = {o:len(e) for o, e in elts.items()}
475
+ if name:
476
+ print(f'{name}: ' + ' '.join(f'{len(profile[r])}@{r}' for r in sorted(profile.keys())))
477
+ return profile
478
+
479
+ S6 = SymmetricGroup(6)
480
+ A6 = AlternatingGroup(6)
481
+ S6_by_order = elts_by_order(S6)
482
+
483
+ def search(existing_gens, needed_gen_orders, order, alt=None, profile=None, anti_profile=None):
484
+ """
485
+ Find a transitive subgroup of S6.
486
+
487
+ Parameters
488
+ ==========
489
+
490
+ existing_gens : list of Permutation
491
+ Optionally empty list of generators that must be in the group.
492
+
493
+ needed_gen_orders : list of positive int
494
+ Nonempty list of the orders of the additional generators that are
495
+ to be found.
496
+
497
+ order: int
498
+ The order of the group being sought.
499
+
500
+ alt: bool, None
501
+ If True, require the group to be contained in A6.
502
+ If False, require the group not to be contained in A6.
503
+
504
+ profile : dict
505
+ If given, the group's order profile must equal this.
506
+
507
+ anti_profile : dict
508
+ If given, the group's order profile must *not* equal this.
509
+
510
+ """
511
+ for gens in itertools.product(*[S6_by_order[n] for n in needed_gen_orders]):
512
+ if len(set(gens)) < len(gens):
513
+ continue
514
+ G = PermutationGroup(existing_gens + list(gens))
515
+ if G.order() == order and G.is_transitive():
516
+ if alt is not None and G.is_subgroup(A6) != alt:
517
+ continue
518
+ if profile and order_profile(G) != profile:
519
+ continue
520
+ if anti_profile and order_profile(G) == anti_profile:
521
+ continue
522
+ return G
523
+
524
+ def match_known_group(G, alt=None):
525
+ needed = [g.order() for g in G.generators]
526
+ return search([], needed, G.order(), alt=alt, profile=order_profile(G))
527
+
528
+ found = {}
529
+
530
+ def finish_up(name, G):
531
+ found[name] = G
532
+ if print_report:
533
+ print("=" * 40)
534
+ print(f"{name}:")
535
+ print(G.generators)
536
+
537
+ if S6TransitiveSubgroups.A4 in targets or S6TransitiveSubgroups.A4xC2 in targets:
538
+ A4_in_S6 = match_known_group(AlternatingGroup(4))
539
+ finish_up(S6TransitiveSubgroups.A4, A4_in_S6)
540
+
541
+ if S6TransitiveSubgroups.S4m in targets or S6TransitiveSubgroups.S4xC2 in targets:
542
+ S4m_in_S6 = match_known_group(SymmetricGroup(4), alt=False)
543
+ finish_up(S6TransitiveSubgroups.S4m, S4m_in_S6)
544
+
545
+ if S6TransitiveSubgroups.S4p in targets:
546
+ S4p_in_S6 = match_known_group(SymmetricGroup(4), alt=True)
547
+ finish_up(S6TransitiveSubgroups.S4p, S4p_in_S6)
548
+
549
+ if S6TransitiveSubgroups.A4xC2 in targets:
550
+ A4xC2_in_S6 = search(A4_in_S6.generators, [2], 24, anti_profile=order_profile(SymmetricGroup(4)))
551
+ finish_up(S6TransitiveSubgroups.A4xC2, A4xC2_in_S6)
552
+
553
+ if S6TransitiveSubgroups.S4xC2 in targets:
554
+ S4xC2_in_S6 = search(S4m_in_S6.generators, [2], 48)
555
+ finish_up(S6TransitiveSubgroups.S4xC2, S4xC2_in_S6)
556
+
557
+ # For the normal factor N = C3^2 in any of the G_n subgroups, we take one
558
+ # obvious instance of C3^2 in S6:
559
+ N_gens = [Permutation(5)(0, 1, 2), Permutation(5)(3, 4, 5)]
560
+
561
+ if S6TransitiveSubgroups.G18 in targets:
562
+ G18_in_S6 = search(N_gens, [2], 18)
563
+ finish_up(S6TransitiveSubgroups.G18, G18_in_S6)
564
+
565
+ if S6TransitiveSubgroups.G36m in targets:
566
+ G36m_in_S6 = search(N_gens, [2, 2], 36, alt=False)
567
+ finish_up(S6TransitiveSubgroups.G36m, G36m_in_S6)
568
+
569
+ if S6TransitiveSubgroups.G36p in targets:
570
+ G36p_in_S6 = search(N_gens, [4], 36, alt=True)
571
+ finish_up(S6TransitiveSubgroups.G36p, G36p_in_S6)
572
+
573
+ if S6TransitiveSubgroups.G72 in targets:
574
+ G72_in_S6 = search(N_gens, [4, 2], 72)
575
+ finish_up(S6TransitiveSubgroups.G72, G72_in_S6)
576
+
577
+ # The PSL2(F5) and PGL2(F5) subgroups are isomorphic to A5 and S5, resp.
578
+
579
+ if S6TransitiveSubgroups.PSL2F5 in targets:
580
+ PSL2F5_in_S6 = match_known_group(AlternatingGroup(5))
581
+ finish_up(S6TransitiveSubgroups.PSL2F5, PSL2F5_in_S6)
582
+
583
+ if S6TransitiveSubgroups.PGL2F5 in targets:
584
+ PGL2F5_in_S6 = match_known_group(SymmetricGroup(5))
585
+ finish_up(S6TransitiveSubgroups.PGL2F5, PGL2F5_in_S6)
586
+
587
+ # There is little need to "search" for any of the groups C6, S3, D6, A6,
588
+ # or S6, since they all have obvious realizations within S6. However, we
589
+ # support them here just in case a random representation is desired.
590
+
591
+ if S6TransitiveSubgroups.C6 in targets:
592
+ C6 = match_known_group(CyclicGroup(6))
593
+ finish_up(S6TransitiveSubgroups.C6, C6)
594
+
595
+ if S6TransitiveSubgroups.S3 in targets:
596
+ S3 = match_known_group(SymmetricGroup(3))
597
+ finish_up(S6TransitiveSubgroups.S3, S3)
598
+
599
+ if S6TransitiveSubgroups.D6 in targets:
600
+ D6 = match_known_group(DihedralGroup(6))
601
+ finish_up(S6TransitiveSubgroups.D6, D6)
602
+
603
+ if S6TransitiveSubgroups.A6 in targets:
604
+ A6 = match_known_group(A6)
605
+ finish_up(S6TransitiveSubgroups.A6, A6)
606
+
607
+ if S6TransitiveSubgroups.S6 in targets:
608
+ S6 = match_known_group(S6)
609
+ finish_up(S6TransitiveSubgroups.S6, S6)
610
+
611
+ return found
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/group_constructs.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.perm_groups import PermutationGroup
2
+ from sympy.combinatorics.permutations import Permutation
3
+ from sympy.utilities.iterables import uniq
4
+
5
+ _af_new = Permutation._af_new
6
+
7
+
8
+ def DirectProduct(*groups):
9
+ """
10
+ Returns the direct product of several groups as a permutation group.
11
+
12
+ Explanation
13
+ ===========
14
+
15
+ This is implemented much like the __mul__ procedure for taking the direct
16
+ product of two permutation groups, but the idea of shifting the
17
+ generators is realized in the case of an arbitrary number of groups.
18
+ A call to DirectProduct(G1, G2, ..., Gn) is generally expected to be faster
19
+ than a call to G1*G2*...*Gn (and thus the need for this algorithm).
20
+
21
+ Examples
22
+ ========
23
+
24
+ >>> from sympy.combinatorics.group_constructs import DirectProduct
25
+ >>> from sympy.combinatorics.named_groups import CyclicGroup
26
+ >>> C = CyclicGroup(4)
27
+ >>> G = DirectProduct(C, C, C)
28
+ >>> G.order()
29
+ 64
30
+
31
+ See Also
32
+ ========
33
+
34
+ sympy.combinatorics.perm_groups.PermutationGroup.__mul__
35
+
36
+ """
37
+ degrees = []
38
+ gens_count = []
39
+ total_degree = 0
40
+ total_gens = 0
41
+ for group in groups:
42
+ current_deg = group.degree
43
+ current_num_gens = len(group.generators)
44
+ degrees.append(current_deg)
45
+ total_degree += current_deg
46
+ gens_count.append(current_num_gens)
47
+ total_gens += current_num_gens
48
+ array_gens = []
49
+ for i in range(total_gens):
50
+ array_gens.append(list(range(total_degree)))
51
+ current_gen = 0
52
+ current_deg = 0
53
+ for i in range(len(gens_count)):
54
+ for j in range(current_gen, current_gen + gens_count[i]):
55
+ gen = ((groups[i].generators)[j - current_gen]).array_form
56
+ array_gens[j][current_deg:current_deg + degrees[i]] = \
57
+ [x + current_deg for x in gen]
58
+ current_gen += gens_count[i]
59
+ current_deg += degrees[i]
60
+ perm_gens = list(uniq([_af_new(list(a)) for a in array_gens]))
61
+ return PermutationGroup(perm_gens, dups=False)
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/group_numbers.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Integer, Pow, Mod
2
+ from sympy import factorint
3
+
4
+
5
+ def is_nilpotent_number(n):
6
+ """
7
+ Check whether `n` is a nilpotent number. A number `n` is said to be
8
+ nilpotent if and only if every finite group of order `n` is nilpotent.
9
+ For more information see [1]_.
10
+
11
+ Examples
12
+ ========
13
+
14
+ >>> from sympy.combinatorics.group_numbers import is_nilpotent_number
15
+ >>> from sympy import randprime
16
+ >>> is_nilpotent_number(21)
17
+ False
18
+ >>> is_nilpotent_number(randprime(1, 30)**12)
19
+ True
20
+
21
+ References
22
+ ==========
23
+
24
+ .. [1] Pakianathan, J., Shankar, K., *Nilpotent Numbers*,
25
+ The American Mathematical Monthly, 107(7), 631-634.
26
+
27
+
28
+ """
29
+ if n <= 0 or int(n) != n:
30
+ raise ValueError("n must be a positive integer, not %i" % n)
31
+
32
+ n = Integer(n)
33
+ prime_factors = list(factorint(n).items())
34
+ is_nilpotent = True
35
+ for p_j, a_j in prime_factors:
36
+ for p_i, a_i in prime_factors:
37
+ if any([Mod(Pow(p_i, k), p_j) == 1 for k in range(1, a_i + 1)]):
38
+ is_nilpotent = False
39
+ break
40
+ if not is_nilpotent:
41
+ break
42
+
43
+ return is_nilpotent
44
+
45
+
46
+ def is_abelian_number(n):
47
+ """
48
+ Check whether `n` is an abelian number. A number `n` is said to be abelian
49
+ if and only if every finite group of order `n` is abelian. For more
50
+ information see [1]_.
51
+
52
+ Examples
53
+ ========
54
+
55
+ >>> from sympy.combinatorics.group_numbers import is_abelian_number
56
+ >>> from sympy import randprime
57
+ >>> is_abelian_number(4)
58
+ True
59
+ >>> is_abelian_number(randprime(1, 2000)**2)
60
+ True
61
+ >>> is_abelian_number(60)
62
+ False
63
+
64
+ References
65
+ ==========
66
+
67
+ .. [1] Pakianathan, J., Shankar, K., *Nilpotent Numbers*,
68
+ The American Mathematical Monthly, 107(7), 631-634.
69
+
70
+
71
+ """
72
+ if n <= 0 or int(n) != n:
73
+ raise ValueError("n must be a positive integer, not %i" % n)
74
+
75
+ n = Integer(n)
76
+ if not is_nilpotent_number(n):
77
+ return False
78
+
79
+ prime_factors = list(factorint(n).items())
80
+ is_abelian = all(a_i < 3 for p_i, a_i in prime_factors)
81
+ return is_abelian
82
+
83
+
84
+ def is_cyclic_number(n):
85
+ """
86
+ Check whether `n` is a cyclic number. A number `n` is said to be cyclic
87
+ if and only if every finite group of order `n` is cyclic. For more
88
+ information see [1]_.
89
+
90
+ Examples
91
+ ========
92
+
93
+ >>> from sympy.combinatorics.group_numbers import is_cyclic_number
94
+ >>> from sympy import randprime
95
+ >>> is_cyclic_number(15)
96
+ True
97
+ >>> is_cyclic_number(randprime(1, 2000)**2)
98
+ False
99
+ >>> is_cyclic_number(4)
100
+ False
101
+
102
+ References
103
+ ==========
104
+
105
+ .. [1] Pakianathan, J., Shankar, K., *Nilpotent Numbers*,
106
+ The American Mathematical Monthly, 107(7), 631-634.
107
+
108
+ """
109
+ if n <= 0 or int(n) != n:
110
+ raise ValueError("n must be a positive integer, not %i" % n)
111
+
112
+ n = Integer(n)
113
+ if not is_nilpotent_number(n):
114
+ return False
115
+
116
+ prime_factors = list(factorint(n).items())
117
+ is_cyclic = all(a_i < 2 for p_i, a_i in prime_factors)
118
+ return is_cyclic
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from sympy.combinatorics.fp_groups import FpGroup, FpSubgroup, simplify_presentation
3
+ from sympy.combinatorics.free_groups import FreeGroup
4
+ from sympy.combinatorics.perm_groups import PermutationGroup
5
+ from sympy.core.numbers import igcd
6
+ from sympy.ntheory.factor_ import totient
7
+ from sympy.core.singleton import S
8
+
9
+ class GroupHomomorphism:
10
+ '''
11
+ A class representing group homomorphisms. Instantiate using `homomorphism()`.
12
+
13
+ References
14
+ ==========
15
+
16
+ .. [1] Holt, D., Eick, B. and O'Brien, E. (2005). Handbook of computational group theory.
17
+
18
+ '''
19
+
20
+ def __init__(self, domain, codomain, images):
21
+ self.domain = domain
22
+ self.codomain = codomain
23
+ self.images = images
24
+ self._inverses = None
25
+ self._kernel = None
26
+ self._image = None
27
+
28
+ def _invs(self):
29
+ '''
30
+ Return a dictionary with `{gen: inverse}` where `gen` is a rewriting
31
+ generator of `codomain` (e.g. strong generator for permutation groups)
32
+ and `inverse` is an element of its preimage
33
+
34
+ '''
35
+ image = self.image()
36
+ inverses = {}
37
+ for k in list(self.images.keys()):
38
+ v = self.images[k]
39
+ if not (v in inverses
40
+ or v.is_identity):
41
+ inverses[v] = k
42
+ if isinstance(self.codomain, PermutationGroup):
43
+ gens = image.strong_gens
44
+ else:
45
+ gens = image.generators
46
+ for g in gens:
47
+ if g in inverses or g.is_identity:
48
+ continue
49
+ w = self.domain.identity
50
+ if isinstance(self.codomain, PermutationGroup):
51
+ parts = image._strong_gens_slp[g][::-1]
52
+ else:
53
+ parts = g
54
+ for s in parts:
55
+ if s in inverses:
56
+ w = w*inverses[s]
57
+ else:
58
+ w = w*inverses[s**-1]**-1
59
+ inverses[g] = w
60
+
61
+ return inverses
62
+
63
+ def invert(self, g):
64
+ '''
65
+ Return an element of the preimage of ``g`` or of each element
66
+ of ``g`` if ``g`` is a list.
67
+
68
+ Explanation
69
+ ===========
70
+
71
+ If the codomain is an FpGroup, the inverse for equal
72
+ elements might not always be the same unless the FpGroup's
73
+ rewriting system is confluent. However, making a system
74
+ confluent can be time-consuming. If it's important, try
75
+ `self.codomain.make_confluent()` first.
76
+
77
+ '''
78
+ from sympy.combinatorics import Permutation
79
+ from sympy.combinatorics.free_groups import FreeGroupElement
80
+ if isinstance(g, (Permutation, FreeGroupElement)):
81
+ if isinstance(self.codomain, FpGroup):
82
+ g = self.codomain.reduce(g)
83
+ if self._inverses is None:
84
+ self._inverses = self._invs()
85
+ image = self.image()
86
+ w = self.domain.identity
87
+ if isinstance(self.codomain, PermutationGroup):
88
+ gens = image.generator_product(g)[::-1]
89
+ else:
90
+ gens = g
91
+ # the following can't be "for s in gens:"
92
+ # because that would be equivalent to
93
+ # "for s in gens.array_form:" when g is
94
+ # a FreeGroupElement. On the other hand,
95
+ # when you call gens by index, the generator
96
+ # (or inverse) at position i is returned.
97
+ for i in range(len(gens)):
98
+ s = gens[i]
99
+ if s.is_identity:
100
+ continue
101
+ if s in self._inverses:
102
+ w = w*self._inverses[s]
103
+ else:
104
+ w = w*self._inverses[s**-1]**-1
105
+ return w
106
+ elif isinstance(g, list):
107
+ return [self.invert(e) for e in g]
108
+
109
+ def kernel(self):
110
+ '''
111
+ Compute the kernel of `self`.
112
+
113
+ '''
114
+ if self._kernel is None:
115
+ self._kernel = self._compute_kernel()
116
+ return self._kernel
117
+
118
+ def _compute_kernel(self):
119
+ G = self.domain
120
+ G_order = G.order()
121
+ if G_order is S.Infinity:
122
+ raise NotImplementedError(
123
+ "Kernel computation is not implemented for infinite groups")
124
+ gens = []
125
+ if isinstance(G, PermutationGroup):
126
+ K = PermutationGroup(G.identity)
127
+ else:
128
+ K = FpSubgroup(G, gens, normal=True)
129
+ i = self.image().order()
130
+ while K.order()*i != G_order:
131
+ r = G.random()
132
+ k = r*self.invert(self(r))**-1
133
+ if k not in K:
134
+ gens.append(k)
135
+ if isinstance(G, PermutationGroup):
136
+ K = PermutationGroup(gens)
137
+ else:
138
+ K = FpSubgroup(G, gens, normal=True)
139
+ return K
140
+
141
+ def image(self):
142
+ '''
143
+ Compute the image of `self`.
144
+
145
+ '''
146
+ if self._image is None:
147
+ values = list(set(self.images.values()))
148
+ if isinstance(self.codomain, PermutationGroup):
149
+ self._image = self.codomain.subgroup(values)
150
+ else:
151
+ self._image = FpSubgroup(self.codomain, values)
152
+ return self._image
153
+
154
+ def _apply(self, elem):
155
+ '''
156
+ Apply `self` to `elem`.
157
+
158
+ '''
159
+ if elem not in self.domain:
160
+ if isinstance(elem, (list, tuple)):
161
+ return [self._apply(e) for e in elem]
162
+ raise ValueError("The supplied element does not belong to the domain")
163
+ if elem.is_identity:
164
+ return self.codomain.identity
165
+ else:
166
+ images = self.images
167
+ value = self.codomain.identity
168
+ if isinstance(self.domain, PermutationGroup):
169
+ gens = self.domain.generator_product(elem, original=True)
170
+ for g in gens:
171
+ if g in self.images:
172
+ value = images[g]*value
173
+ else:
174
+ value = images[g**-1]**-1*value
175
+ else:
176
+ i = 0
177
+ for _, p in elem.array_form:
178
+ if p < 0:
179
+ g = elem[i]**-1
180
+ else:
181
+ g = elem[i]
182
+ value = value*images[g]**p
183
+ i += abs(p)
184
+ return value
185
+
186
+ def __call__(self, elem):
187
+ return self._apply(elem)
188
+
189
+ def is_injective(self):
190
+ '''
191
+ Check if the homomorphism is injective
192
+
193
+ '''
194
+ return self.kernel().order() == 1
195
+
196
+ def is_surjective(self):
197
+ '''
198
+ Check if the homomorphism is surjective
199
+
200
+ '''
201
+ im = self.image().order()
202
+ oth = self.codomain.order()
203
+ if im is S.Infinity and oth is S.Infinity:
204
+ return None
205
+ else:
206
+ return im == oth
207
+
208
+ def is_isomorphism(self):
209
+ '''
210
+ Check if `self` is an isomorphism.
211
+
212
+ '''
213
+ return self.is_injective() and self.is_surjective()
214
+
215
+ def is_trivial(self):
216
+ '''
217
+ Check is `self` is a trivial homomorphism, i.e. all elements
218
+ are mapped to the identity.
219
+
220
+ '''
221
+ return self.image().order() == 1
222
+
223
+ def compose(self, other):
224
+ '''
225
+ Return the composition of `self` and `other`, i.e.
226
+ the homomorphism phi such that for all g in the domain
227
+ of `other`, phi(g) = self(other(g))
228
+
229
+ '''
230
+ if not other.image().is_subgroup(self.domain):
231
+ raise ValueError("The image of `other` must be a subgroup of "
232
+ "the domain of `self`")
233
+ images = {g: self(other(g)) for g in other.images}
234
+ return GroupHomomorphism(other.domain, self.codomain, images)
235
+
236
+ def restrict_to(self, H):
237
+ '''
238
+ Return the restriction of the homomorphism to the subgroup `H`
239
+ of the domain.
240
+
241
+ '''
242
+ if not isinstance(H, PermutationGroup) or not H.is_subgroup(self.domain):
243
+ raise ValueError("Given H is not a subgroup of the domain")
244
+ domain = H
245
+ images = {g: self(g) for g in H.generators}
246
+ return GroupHomomorphism(domain, self.codomain, images)
247
+
248
+ def invert_subgroup(self, H):
249
+ '''
250
+ Return the subgroup of the domain that is the inverse image
251
+ of the subgroup ``H`` of the homomorphism image
252
+
253
+ '''
254
+ if not H.is_subgroup(self.image()):
255
+ raise ValueError("Given H is not a subgroup of the image")
256
+ gens = []
257
+ P = PermutationGroup(self.image().identity)
258
+ for h in H.generators:
259
+ h_i = self.invert(h)
260
+ if h_i not in P:
261
+ gens.append(h_i)
262
+ P = PermutationGroup(gens)
263
+ for k in self.kernel().generators:
264
+ if k*h_i not in P:
265
+ gens.append(k*h_i)
266
+ P = PermutationGroup(gens)
267
+ return P
268
+
269
+ def homomorphism(domain, codomain, gens, images=(), check=True):
270
+ '''
271
+ Create (if possible) a group homomorphism from the group ``domain``
272
+ to the group ``codomain`` defined by the images of the domain's
273
+ generators ``gens``. ``gens`` and ``images`` can be either lists or tuples
274
+ of equal sizes. If ``gens`` is a proper subset of the group's generators,
275
+ the unspecified generators will be mapped to the identity. If the
276
+ images are not specified, a trivial homomorphism will be created.
277
+
278
+ If the given images of the generators do not define a homomorphism,
279
+ an exception is raised.
280
+
281
+ If ``check`` is ``False``, do not check whether the given images actually
282
+ define a homomorphism.
283
+
284
+ '''
285
+ if not isinstance(domain, (PermutationGroup, FpGroup, FreeGroup)):
286
+ raise TypeError("The domain must be a group")
287
+ if not isinstance(codomain, (PermutationGroup, FpGroup, FreeGroup)):
288
+ raise TypeError("The codomain must be a group")
289
+
290
+ generators = domain.generators
291
+ if not all(g in generators for g in gens):
292
+ raise ValueError("The supplied generators must be a subset of the domain's generators")
293
+ if not all(g in codomain for g in images):
294
+ raise ValueError("The images must be elements of the codomain")
295
+
296
+ if images and len(images) != len(gens):
297
+ raise ValueError("The number of images must be equal to the number of generators")
298
+
299
+ gens = list(gens)
300
+ images = list(images)
301
+
302
+ images.extend([codomain.identity]*(len(generators)-len(images)))
303
+ gens.extend([g for g in generators if g not in gens])
304
+ images = dict(zip(gens,images))
305
+
306
+ if check and not _check_homomorphism(domain, codomain, images):
307
+ raise ValueError("The given images do not define a homomorphism")
308
+ return GroupHomomorphism(domain, codomain, images)
309
+
310
+ def _check_homomorphism(domain, codomain, images):
311
+ """
312
+ Check that a given mapping of generators to images defines a homomorphism.
313
+
314
+ Parameters
315
+ ==========
316
+ domain : PermutationGroup, FpGroup, FreeGroup
317
+ codomain : PermutationGroup, FpGroup, FreeGroup
318
+ images : dict
319
+ The set of keys must be equal to domain.generators.
320
+ The values must be elements of the codomain.
321
+
322
+ """
323
+ pres = domain if hasattr(domain, 'relators') else domain.presentation()
324
+ rels = pres.relators
325
+ gens = pres.generators
326
+ symbols = [g.ext_rep[0] for g in gens]
327
+ symbols_to_domain_generators = dict(zip(symbols, domain.generators))
328
+ identity = codomain.identity
329
+
330
+ def _image(r):
331
+ w = identity
332
+ for symbol, power in r.array_form:
333
+ g = symbols_to_domain_generators[symbol]
334
+ w *= images[g]**power
335
+ return w
336
+
337
+ for r in rels:
338
+ if isinstance(codomain, FpGroup):
339
+ s = codomain.equals(_image(r), identity)
340
+ if s is None:
341
+ # only try to make the rewriting system
342
+ # confluent when it can't determine the
343
+ # truth of equality otherwise
344
+ success = codomain.make_confluent()
345
+ s = codomain.equals(_image(r), identity)
346
+ if s is None and not success:
347
+ raise RuntimeError("Can't determine if the images "
348
+ "define a homomorphism. Try increasing "
349
+ "the maximum number of rewriting rules "
350
+ "(group._rewriting_system.set_max(new_value); "
351
+ "the current value is stored in group._rewriting"
352
+ "_system.maxeqns)")
353
+ else:
354
+ s = _image(r).is_identity
355
+ if not s:
356
+ return False
357
+ return True
358
+
359
+ def orbit_homomorphism(group, omega):
360
+ '''
361
+ Return the homomorphism induced by the action of the permutation
362
+ group ``group`` on the set ``omega`` that is closed under the action.
363
+
364
+ '''
365
+ from sympy.combinatorics import Permutation
366
+ from sympy.combinatorics.named_groups import SymmetricGroup
367
+ codomain = SymmetricGroup(len(omega))
368
+ identity = codomain.identity
369
+ omega = list(omega)
370
+ images = {g: identity*Permutation([omega.index(o^g) for o in omega]) for g in group.generators}
371
+ group._schreier_sims(base=omega)
372
+ H = GroupHomomorphism(group, codomain, images)
373
+ if len(group.basic_stabilizers) > len(omega):
374
+ H._kernel = group.basic_stabilizers[len(omega)]
375
+ else:
376
+ H._kernel = PermutationGroup([group.identity])
377
+ return H
378
+
379
+ def block_homomorphism(group, blocks):
380
+ '''
381
+ Return the homomorphism induced by the action of the permutation
382
+ group ``group`` on the block system ``blocks``. The latter should be
383
+ of the same form as returned by the ``minimal_block`` method for
384
+ permutation groups, namely a list of length ``group.degree`` where
385
+ the i-th entry is a representative of the block i belongs to.
386
+
387
+ '''
388
+ from sympy.combinatorics import Permutation
389
+ from sympy.combinatorics.named_groups import SymmetricGroup
390
+
391
+ n = len(blocks)
392
+
393
+ # number the blocks; m is the total number,
394
+ # b is such that b[i] is the number of the block i belongs to,
395
+ # p is the list of length m such that p[i] is the representative
396
+ # of the i-th block
397
+ m = 0
398
+ p = []
399
+ b = [None]*n
400
+ for i in range(n):
401
+ if blocks[i] == i:
402
+ p.append(i)
403
+ b[i] = m
404
+ m += 1
405
+ for i in range(n):
406
+ b[i] = b[blocks[i]]
407
+
408
+ codomain = SymmetricGroup(m)
409
+ # the list corresponding to the identity permutation in codomain
410
+ identity = range(m)
411
+ images = {g: Permutation([b[p[i]^g] for i in identity]) for g in group.generators}
412
+ H = GroupHomomorphism(group, codomain, images)
413
+ return H
414
+
415
+ def group_isomorphism(G, H, isomorphism=True):
416
+ '''
417
+ Compute an isomorphism between 2 given groups.
418
+
419
+ Parameters
420
+ ==========
421
+
422
+ G : A finite ``FpGroup`` or a ``PermutationGroup``.
423
+ First group.
424
+
425
+ H : A finite ``FpGroup`` or a ``PermutationGroup``
426
+ Second group.
427
+
428
+ isomorphism : bool
429
+ This is used to avoid the computation of homomorphism
430
+ when the user only wants to check if there exists
431
+ an isomorphism between the groups.
432
+
433
+ Returns
434
+ =======
435
+
436
+ If isomorphism = False -- Returns a boolean.
437
+ If isomorphism = True -- Returns a boolean and an isomorphism between `G` and `H`.
438
+
439
+ Examples
440
+ ========
441
+
442
+ >>> from sympy.combinatorics import free_group, Permutation
443
+ >>> from sympy.combinatorics.perm_groups import PermutationGroup
444
+ >>> from sympy.combinatorics.fp_groups import FpGroup
445
+ >>> from sympy.combinatorics.homomorphisms import group_isomorphism
446
+ >>> from sympy.combinatorics.named_groups import DihedralGroup, AlternatingGroup
447
+
448
+ >>> D = DihedralGroup(8)
449
+ >>> p = Permutation(0, 1, 2, 3, 4, 5, 6, 7)
450
+ >>> P = PermutationGroup(p)
451
+ >>> group_isomorphism(D, P)
452
+ (False, None)
453
+
454
+ >>> F, a, b = free_group("a, b")
455
+ >>> G = FpGroup(F, [a**3, b**3, (a*b)**2])
456
+ >>> H = AlternatingGroup(4)
457
+ >>> (check, T) = group_isomorphism(G, H)
458
+ >>> check
459
+ True
460
+ >>> T(b*a*b**-1*a**-1*b**-1)
461
+ (0 2 3)
462
+
463
+ Notes
464
+ =====
465
+
466
+ Uses the approach suggested by Robert Tarjan to compute the isomorphism between two groups.
467
+ First, the generators of ``G`` are mapped to the elements of ``H`` and
468
+ we check if the mapping induces an isomorphism.
469
+
470
+ '''
471
+ if not isinstance(G, (PermutationGroup, FpGroup)):
472
+ raise TypeError("The group must be a PermutationGroup or an FpGroup")
473
+ if not isinstance(H, (PermutationGroup, FpGroup)):
474
+ raise TypeError("The group must be a PermutationGroup or an FpGroup")
475
+
476
+ if isinstance(G, FpGroup) and isinstance(H, FpGroup):
477
+ G = simplify_presentation(G)
478
+ H = simplify_presentation(H)
479
+ # Two infinite FpGroups with the same generators are isomorphic
480
+ # when the relators are same but are ordered differently.
481
+ if G.generators == H.generators and (G.relators).sort() == (H.relators).sort():
482
+ if not isomorphism:
483
+ return True
484
+ return (True, homomorphism(G, H, G.generators, H.generators))
485
+
486
+ # `_H` is the permutation group isomorphic to `H`.
487
+ _H = H
488
+ g_order = G.order()
489
+ h_order = H.order()
490
+
491
+ if g_order is S.Infinity:
492
+ raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.")
493
+
494
+ if isinstance(H, FpGroup):
495
+ if h_order is S.Infinity:
496
+ raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.")
497
+ _H, h_isomorphism = H._to_perm_group()
498
+
499
+ if (g_order != h_order) or (G.is_abelian != H.is_abelian):
500
+ if not isomorphism:
501
+ return False
502
+ return (False, None)
503
+
504
+ if not isomorphism:
505
+ # Two groups of the same cyclic numbered order
506
+ # are isomorphic to each other.
507
+ n = g_order
508
+ if (igcd(n, totient(n))) == 1:
509
+ return True
510
+
511
+ # Match the generators of `G` with subsets of `_H`
512
+ gens = list(G.generators)
513
+ for subset in itertools.permutations(_H, len(gens)):
514
+ images = list(subset)
515
+ images.extend([_H.identity]*(len(G.generators)-len(images)))
516
+ _images = dict(zip(gens,images))
517
+ if _check_homomorphism(G, _H, _images):
518
+ if isinstance(H, FpGroup):
519
+ images = h_isomorphism.invert(images)
520
+ T = homomorphism(G, H, G.generators, images, check=False)
521
+ if T.is_isomorphism():
522
+ # It is a valid isomorphism
523
+ if not isomorphism:
524
+ return True
525
+ return (True, T)
526
+
527
+ if not isomorphism:
528
+ return False
529
+ return (False, None)
530
+
531
+ def is_isomorphic(G, H):
532
+ '''
533
+ Check if the groups are isomorphic to each other
534
+
535
+ Parameters
536
+ ==========
537
+
538
+ G : A finite ``FpGroup`` or a ``PermutationGroup``
539
+ First group.
540
+
541
+ H : A finite ``FpGroup`` or a ``PermutationGroup``
542
+ Second group.
543
+
544
+ Returns
545
+ =======
546
+
547
+ boolean
548
+ '''
549
+ return group_isomorphism(G, H, isomorphism=False)
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/perm_groups.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/prufer.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Basic
2
+ from sympy.core.containers import Tuple
3
+ from sympy.tensor.array import Array
4
+ from sympy.core.sympify import _sympify
5
+ from sympy.utilities.iterables import flatten, iterable
6
+ from sympy.utilities.misc import as_int
7
+
8
+ from collections import defaultdict
9
+
10
+
11
+ class Prufer(Basic):
12
+ """
13
+ The Prufer correspondence is an algorithm that describes the
14
+ bijection between labeled trees and the Prufer code. A Prufer
15
+ code of a labeled tree is unique up to isomorphism and has
16
+ a length of n - 2.
17
+
18
+ Prufer sequences were first used by Heinz Prufer to give a
19
+ proof of Cayley's formula.
20
+
21
+ References
22
+ ==========
23
+
24
+ .. [1] https://mathworld.wolfram.com/LabeledTree.html
25
+
26
+ """
27
+ _prufer_repr = None
28
+ _tree_repr = None
29
+ _nodes = None
30
+ _rank = None
31
+
32
+ @property
33
+ def prufer_repr(self):
34
+ """Returns Prufer sequence for the Prufer object.
35
+
36
+ This sequence is found by removing the highest numbered vertex,
37
+ recording the node it was attached to, and continuing until only
38
+ two vertices remain. The Prufer sequence is the list of recorded nodes.
39
+
40
+ Examples
41
+ ========
42
+
43
+ >>> from sympy.combinatorics.prufer import Prufer
44
+ >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).prufer_repr
45
+ [3, 3, 3, 4]
46
+ >>> Prufer([1, 0, 0]).prufer_repr
47
+ [1, 0, 0]
48
+
49
+ See Also
50
+ ========
51
+
52
+ to_prufer
53
+
54
+ """
55
+ if self._prufer_repr is None:
56
+ self._prufer_repr = self.to_prufer(self._tree_repr[:], self.nodes)
57
+ return self._prufer_repr
58
+
59
+ @property
60
+ def tree_repr(self):
61
+ """Returns the tree representation of the Prufer object.
62
+
63
+ Examples
64
+ ========
65
+
66
+ >>> from sympy.combinatorics.prufer import Prufer
67
+ >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).tree_repr
68
+ [[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]
69
+ >>> Prufer([1, 0, 0]).tree_repr
70
+ [[1, 2], [0, 1], [0, 3], [0, 4]]
71
+
72
+ See Also
73
+ ========
74
+
75
+ to_tree
76
+
77
+ """
78
+ if self._tree_repr is None:
79
+ self._tree_repr = self.to_tree(self._prufer_repr[:])
80
+ return self._tree_repr
81
+
82
+ @property
83
+ def nodes(self):
84
+ """Returns the number of nodes in the tree.
85
+
86
+ Examples
87
+ ========
88
+
89
+ >>> from sympy.combinatorics.prufer import Prufer
90
+ >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).nodes
91
+ 6
92
+ >>> Prufer([1, 0, 0]).nodes
93
+ 5
94
+
95
+ """
96
+ return self._nodes
97
+
98
+ @property
99
+ def rank(self):
100
+ """Returns the rank of the Prufer sequence.
101
+
102
+ Examples
103
+ ========
104
+
105
+ >>> from sympy.combinatorics.prufer import Prufer
106
+ >>> p = Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]])
107
+ >>> p.rank
108
+ 778
109
+ >>> p.next(1).rank
110
+ 779
111
+ >>> p.prev().rank
112
+ 777
113
+
114
+ See Also
115
+ ========
116
+
117
+ prufer_rank, next, prev, size
118
+
119
+ """
120
+ if self._rank is None:
121
+ self._rank = self.prufer_rank()
122
+ return self._rank
123
+
124
+ @property
125
+ def size(self):
126
+ """Return the number of possible trees of this Prufer object.
127
+
128
+ Examples
129
+ ========
130
+
131
+ >>> from sympy.combinatorics.prufer import Prufer
132
+ >>> Prufer([0]*4).size == Prufer([6]*4).size == 1296
133
+ True
134
+
135
+ See Also
136
+ ========
137
+
138
+ prufer_rank, rank, next, prev
139
+
140
+ """
141
+ return self.prev(self.rank).prev().rank + 1
142
+
143
+ @staticmethod
144
+ def to_prufer(tree, n):
145
+ """Return the Prufer sequence for a tree given as a list of edges where
146
+ ``n`` is the number of nodes in the tree.
147
+
148
+ Examples
149
+ ========
150
+
151
+ >>> from sympy.combinatorics.prufer import Prufer
152
+ >>> a = Prufer([[0, 1], [0, 2], [0, 3]])
153
+ >>> a.prufer_repr
154
+ [0, 0]
155
+ >>> Prufer.to_prufer([[0, 1], [0, 2], [0, 3]], 4)
156
+ [0, 0]
157
+
158
+ See Also
159
+ ========
160
+ prufer_repr: returns Prufer sequence of a Prufer object.
161
+
162
+ """
163
+ d = defaultdict(int)
164
+ L = []
165
+ for edge in tree:
166
+ # Increment the value of the corresponding
167
+ # node in the degree list as we encounter an
168
+ # edge involving it.
169
+ d[edge[0]] += 1
170
+ d[edge[1]] += 1
171
+ for i in range(n - 2):
172
+ # find the smallest leaf
173
+ for x in range(n):
174
+ if d[x] == 1:
175
+ break
176
+ # find the node it was connected to
177
+ y = None
178
+ for edge in tree:
179
+ if x == edge[0]:
180
+ y = edge[1]
181
+ elif x == edge[1]:
182
+ y = edge[0]
183
+ if y is not None:
184
+ break
185
+ # record and update
186
+ L.append(y)
187
+ for j in (x, y):
188
+ d[j] -= 1
189
+ if not d[j]:
190
+ d.pop(j)
191
+ tree.remove(edge)
192
+ return L
193
+
194
+ @staticmethod
195
+ def to_tree(prufer):
196
+ """Return the tree (as a list of edges) of the given Prufer sequence.
197
+
198
+ Examples
199
+ ========
200
+
201
+ >>> from sympy.combinatorics.prufer import Prufer
202
+ >>> a = Prufer([0, 2], 4)
203
+ >>> a.tree_repr
204
+ [[0, 1], [0, 2], [2, 3]]
205
+ >>> Prufer.to_tree([0, 2])
206
+ [[0, 1], [0, 2], [2, 3]]
207
+
208
+ References
209
+ ==========
210
+
211
+ .. [1] https://hamberg.no/erlend/posts/2010-11-06-prufer-sequence-compact-tree-representation.html
212
+
213
+ See Also
214
+ ========
215
+ tree_repr: returns tree representation of a Prufer object.
216
+
217
+ """
218
+ tree = []
219
+ last = []
220
+ n = len(prufer) + 2
221
+ d = defaultdict(lambda: 1)
222
+ for p in prufer:
223
+ d[p] += 1
224
+ for i in prufer:
225
+ for j in range(n):
226
+ # find the smallest leaf (degree = 1)
227
+ if d[j] == 1:
228
+ break
229
+ # (i, j) is the new edge that we append to the tree
230
+ # and remove from the degree dictionary
231
+ d[i] -= 1
232
+ d[j] -= 1
233
+ tree.append(sorted([i, j]))
234
+ last = [i for i in range(n) if d[i] == 1] or [0, 1]
235
+ tree.append(last)
236
+
237
+ return tree
238
+
239
+ @staticmethod
240
+ def edges(*runs):
241
+ """Return a list of edges and the number of nodes from the given runs
242
+ that connect nodes in an integer-labelled tree.
243
+
244
+ All node numbers will be shifted so that the minimum node is 0. It is
245
+ not a problem if edges are repeated in the runs; only unique edges are
246
+ returned. There is no assumption made about what the range of the node
247
+ labels should be, but all nodes from the smallest through the largest
248
+ must be present.
249
+
250
+ Examples
251
+ ========
252
+
253
+ >>> from sympy.combinatorics.prufer import Prufer
254
+ >>> Prufer.edges([1, 2, 3], [2, 4, 5]) # a T
255
+ ([[0, 1], [1, 2], [1, 3], [3, 4]], 5)
256
+
257
+ Duplicate edges are removed:
258
+
259
+ >>> Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) # a K
260
+ ([[0, 1], [1, 2], [1, 4], [2, 3], [4, 5], [4, 6]], 7)
261
+
262
+ """
263
+ e = set()
264
+ nmin = runs[0][0]
265
+ for r in runs:
266
+ for i in range(len(r) - 1):
267
+ a, b = r[i: i + 2]
268
+ if b < a:
269
+ a, b = b, a
270
+ e.add((a, b))
271
+ rv = []
272
+ got = set()
273
+ nmin = nmax = None
274
+ for ei in e:
275
+ for i in ei:
276
+ got.add(i)
277
+ nmin = min(ei[0], nmin) if nmin is not None else ei[0]
278
+ nmax = max(ei[1], nmax) if nmax is not None else ei[1]
279
+ rv.append(list(ei))
280
+ missing = set(range(nmin, nmax + 1)) - got
281
+ if missing:
282
+ missing = [i + nmin for i in missing]
283
+ if len(missing) == 1:
284
+ msg = 'Node %s is missing.' % missing.pop()
285
+ else:
286
+ msg = 'Nodes %s are missing.' % sorted(missing)
287
+ raise ValueError(msg)
288
+ if nmin != 0:
289
+ for i, ei in enumerate(rv):
290
+ rv[i] = [n - nmin for n in ei]
291
+ nmax -= nmin
292
+ return sorted(rv), nmax + 1
293
+
294
+ def prufer_rank(self):
295
+ """Computes the rank of a Prufer sequence.
296
+
297
+ Examples
298
+ ========
299
+
300
+ >>> from sympy.combinatorics.prufer import Prufer
301
+ >>> a = Prufer([[0, 1], [0, 2], [0, 3]])
302
+ >>> a.prufer_rank()
303
+ 0
304
+
305
+ See Also
306
+ ========
307
+
308
+ rank, next, prev, size
309
+
310
+ """
311
+ r = 0
312
+ p = 1
313
+ for i in range(self.nodes - 3, -1, -1):
314
+ r += p*self.prufer_repr[i]
315
+ p *= self.nodes
316
+ return r
317
+
318
+ @classmethod
319
+ def unrank(self, rank, n):
320
+ """Finds the unranked Prufer sequence.
321
+
322
+ Examples
323
+ ========
324
+
325
+ >>> from sympy.combinatorics.prufer import Prufer
326
+ >>> Prufer.unrank(0, 4)
327
+ Prufer([0, 0])
328
+
329
+ """
330
+ n, rank = as_int(n), as_int(rank)
331
+ L = defaultdict(int)
332
+ for i in range(n - 3, -1, -1):
333
+ L[i] = rank % n
334
+ rank = (rank - L[i])//n
335
+ return Prufer([L[i] for i in range(len(L))])
336
+
337
+ def __new__(cls, *args, **kw_args):
338
+ """The constructor for the Prufer object.
339
+
340
+ Examples
341
+ ========
342
+
343
+ >>> from sympy.combinatorics.prufer import Prufer
344
+
345
+ A Prufer object can be constructed from a list of edges:
346
+
347
+ >>> a = Prufer([[0, 1], [0, 2], [0, 3]])
348
+ >>> a.prufer_repr
349
+ [0, 0]
350
+
351
+ If the number of nodes is given, no checking of the nodes will
352
+ be performed; it will be assumed that nodes 0 through n - 1 are
353
+ present:
354
+
355
+ >>> Prufer([[0, 1], [0, 2], [0, 3]], 4)
356
+ Prufer([[0, 1], [0, 2], [0, 3]], 4)
357
+
358
+ A Prufer object can be constructed from a Prufer sequence:
359
+
360
+ >>> b = Prufer([1, 3])
361
+ >>> b.tree_repr
362
+ [[0, 1], [1, 3], [2, 3]]
363
+
364
+ """
365
+ arg0 = Array(args[0]) if args[0] else Tuple()
366
+ args = (arg0,) + tuple(_sympify(arg) for arg in args[1:])
367
+ ret_obj = Basic.__new__(cls, *args, **kw_args)
368
+ args = [list(args[0])]
369
+ if args[0] and iterable(args[0][0]):
370
+ if not args[0][0]:
371
+ raise ValueError(
372
+ 'Prufer expects at least one edge in the tree.')
373
+ if len(args) > 1:
374
+ nnodes = args[1]
375
+ else:
376
+ nodes = set(flatten(args[0]))
377
+ nnodes = max(nodes) + 1
378
+ if nnodes != len(nodes):
379
+ missing = set(range(nnodes)) - nodes
380
+ if len(missing) == 1:
381
+ msg = 'Node %s is missing.' % missing.pop()
382
+ else:
383
+ msg = 'Nodes %s are missing.' % sorted(missing)
384
+ raise ValueError(msg)
385
+ ret_obj._tree_repr = [list(i) for i in args[0]]
386
+ ret_obj._nodes = nnodes
387
+ else:
388
+ ret_obj._prufer_repr = args[0]
389
+ ret_obj._nodes = len(ret_obj._prufer_repr) + 2
390
+ return ret_obj
391
+
392
+ def next(self, delta=1):
393
+ """Generates the Prufer sequence that is delta beyond the current one.
394
+
395
+ Examples
396
+ ========
397
+
398
+ >>> from sympy.combinatorics.prufer import Prufer
399
+ >>> a = Prufer([[0, 1], [0, 2], [0, 3]])
400
+ >>> b = a.next(1) # == a.next()
401
+ >>> b.tree_repr
402
+ [[0, 2], [0, 1], [1, 3]]
403
+ >>> b.rank
404
+ 1
405
+
406
+ See Also
407
+ ========
408
+
409
+ prufer_rank, rank, prev, size
410
+
411
+ """
412
+ return Prufer.unrank(self.rank + delta, self.nodes)
413
+
414
+ def prev(self, delta=1):
415
+ """Generates the Prufer sequence that is -delta before the current one.
416
+
417
+ Examples
418
+ ========
419
+
420
+ >>> from sympy.combinatorics.prufer import Prufer
421
+ >>> a = Prufer([[0, 1], [1, 2], [2, 3], [1, 4]])
422
+ >>> a.rank
423
+ 36
424
+ >>> b = a.prev()
425
+ >>> b
426
+ Prufer([1, 2, 0])
427
+ >>> b.rank
428
+ 35
429
+
430
+ See Also
431
+ ========
432
+
433
+ prufer_rank, rank, next, size
434
+
435
+ """
436
+ return Prufer.unrank(self.rank -delta, self.nodes)
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/subsets.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import combinations
2
+
3
+ from sympy.combinatorics.graycode import GrayCode
4
+
5
+
6
+ class Subset():
7
+ """
8
+ Represents a basic subset object.
9
+
10
+ Explanation
11
+ ===========
12
+
13
+ We generate subsets using essentially two techniques,
14
+ binary enumeration and lexicographic enumeration.
15
+ The Subset class takes two arguments, the first one
16
+ describes the initial subset to consider and the second
17
+ describes the superset.
18
+
19
+ Examples
20
+ ========
21
+
22
+ >>> from sympy.combinatorics import Subset
23
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
24
+ >>> a.next_binary().subset
25
+ ['b']
26
+ >>> a.prev_binary().subset
27
+ ['c']
28
+ """
29
+
30
+ _rank_binary = None
31
+ _rank_lex = None
32
+ _rank_graycode = None
33
+ _subset = None
34
+ _superset = None
35
+
36
+ def __new__(cls, subset, superset):
37
+ """
38
+ Default constructor.
39
+
40
+ It takes the ``subset`` and its ``superset`` as its parameters.
41
+
42
+ Examples
43
+ ========
44
+
45
+ >>> from sympy.combinatorics import Subset
46
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
47
+ >>> a.subset
48
+ ['c', 'd']
49
+ >>> a.superset
50
+ ['a', 'b', 'c', 'd']
51
+ >>> a.size
52
+ 2
53
+ """
54
+ if len(subset) > len(superset):
55
+ raise ValueError('Invalid arguments have been provided. The '
56
+ 'superset must be larger than the subset.')
57
+ for elem in subset:
58
+ if elem not in superset:
59
+ raise ValueError('The superset provided is invalid as it does '
60
+ 'not contain the element {}'.format(elem))
61
+ obj = object.__new__(cls)
62
+ obj._subset = subset
63
+ obj._superset = superset
64
+ return obj
65
+
66
+ def __eq__(self, other):
67
+ """Return a boolean indicating whether a == b on the basis of
68
+ whether both objects are of the class Subset and if the values
69
+ of the subset and superset attributes are the same.
70
+ """
71
+ if not isinstance(other, Subset):
72
+ return NotImplemented
73
+ return self.subset == other.subset and self.superset == other.superset
74
+
75
+ def iterate_binary(self, k):
76
+ """
77
+ This is a helper function. It iterates over the
78
+ binary subsets by ``k`` steps. This variable can be
79
+ both positive or negative.
80
+
81
+ Examples
82
+ ========
83
+
84
+ >>> from sympy.combinatorics import Subset
85
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
86
+ >>> a.iterate_binary(-2).subset
87
+ ['d']
88
+ >>> a = Subset(['a', 'b', 'c'], ['a', 'b', 'c', 'd'])
89
+ >>> a.iterate_binary(2).subset
90
+ []
91
+
92
+ See Also
93
+ ========
94
+
95
+ next_binary, prev_binary
96
+ """
97
+ bin_list = Subset.bitlist_from_subset(self.subset, self.superset)
98
+ n = (int(''.join(bin_list), 2) + k) % 2**self.superset_size
99
+ bits = bin(n)[2:].rjust(self.superset_size, '0')
100
+ return Subset.subset_from_bitlist(self.superset, bits)
101
+
102
+ def next_binary(self):
103
+ """
104
+ Generates the next binary ordered subset.
105
+
106
+ Examples
107
+ ========
108
+
109
+ >>> from sympy.combinatorics import Subset
110
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
111
+ >>> a.next_binary().subset
112
+ ['b']
113
+ >>> a = Subset(['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'])
114
+ >>> a.next_binary().subset
115
+ []
116
+
117
+ See Also
118
+ ========
119
+
120
+ prev_binary, iterate_binary
121
+ """
122
+ return self.iterate_binary(1)
123
+
124
+ def prev_binary(self):
125
+ """
126
+ Generates the previous binary ordered subset.
127
+
128
+ Examples
129
+ ========
130
+
131
+ >>> from sympy.combinatorics import Subset
132
+ >>> a = Subset([], ['a', 'b', 'c', 'd'])
133
+ >>> a.prev_binary().subset
134
+ ['a', 'b', 'c', 'd']
135
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
136
+ >>> a.prev_binary().subset
137
+ ['c']
138
+
139
+ See Also
140
+ ========
141
+
142
+ next_binary, iterate_binary
143
+ """
144
+ return self.iterate_binary(-1)
145
+
146
+ def next_lexicographic(self):
147
+ """
148
+ Generates the next lexicographically ordered subset.
149
+
150
+ Examples
151
+ ========
152
+
153
+ >>> from sympy.combinatorics import Subset
154
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
155
+ >>> a.next_lexicographic().subset
156
+ ['d']
157
+ >>> a = Subset(['d'], ['a', 'b', 'c', 'd'])
158
+ >>> a.next_lexicographic().subset
159
+ []
160
+
161
+ See Also
162
+ ========
163
+
164
+ prev_lexicographic
165
+ """
166
+ i = self.superset_size - 1
167
+ indices = Subset.subset_indices(self.subset, self.superset)
168
+
169
+ if i in indices:
170
+ if i - 1 in indices:
171
+ indices.remove(i - 1)
172
+ else:
173
+ indices.remove(i)
174
+ i = i - 1
175
+ while i >= 0 and i not in indices:
176
+ i = i - 1
177
+ if i >= 0:
178
+ indices.remove(i)
179
+ indices.append(i+1)
180
+ else:
181
+ while i not in indices and i >= 0:
182
+ i = i - 1
183
+ indices.append(i + 1)
184
+
185
+ ret_set = []
186
+ super_set = self.superset
187
+ for i in indices:
188
+ ret_set.append(super_set[i])
189
+ return Subset(ret_set, super_set)
190
+
191
+ def prev_lexicographic(self):
192
+ """
193
+ Generates the previous lexicographically ordered subset.
194
+
195
+ Examples
196
+ ========
197
+
198
+ >>> from sympy.combinatorics import Subset
199
+ >>> a = Subset([], ['a', 'b', 'c', 'd'])
200
+ >>> a.prev_lexicographic().subset
201
+ ['d']
202
+ >>> a = Subset(['c','d'], ['a', 'b', 'c', 'd'])
203
+ >>> a.prev_lexicographic().subset
204
+ ['c']
205
+
206
+ See Also
207
+ ========
208
+
209
+ next_lexicographic
210
+ """
211
+ i = self.superset_size - 1
212
+ indices = Subset.subset_indices(self.subset, self.superset)
213
+
214
+ while i >= 0 and i not in indices:
215
+ i = i - 1
216
+
217
+ if i == 0 or i - 1 in indices:
218
+ indices.remove(i)
219
+ else:
220
+ if i >= 0:
221
+ indices.remove(i)
222
+ indices.append(i - 1)
223
+ indices.append(self.superset_size - 1)
224
+
225
+ ret_set = []
226
+ super_set = self.superset
227
+ for i in indices:
228
+ ret_set.append(super_set[i])
229
+ return Subset(ret_set, super_set)
230
+
231
+ def iterate_graycode(self, k):
232
+ """
233
+ Helper function used for prev_gray and next_gray.
234
+ It performs ``k`` step overs to get the respective Gray codes.
235
+
236
+ Examples
237
+ ========
238
+
239
+ >>> from sympy.combinatorics import Subset
240
+ >>> a = Subset([1, 2, 3], [1, 2, 3, 4])
241
+ >>> a.iterate_graycode(3).subset
242
+ [1, 4]
243
+ >>> a.iterate_graycode(-2).subset
244
+ [1, 2, 4]
245
+
246
+ See Also
247
+ ========
248
+
249
+ next_gray, prev_gray
250
+ """
251
+ unranked_code = GrayCode.unrank(self.superset_size,
252
+ (self.rank_gray + k) % self.cardinality)
253
+ return Subset.subset_from_bitlist(self.superset,
254
+ unranked_code)
255
+
256
+ def next_gray(self):
257
+ """
258
+ Generates the next Gray code ordered subset.
259
+
260
+ Examples
261
+ ========
262
+
263
+ >>> from sympy.combinatorics import Subset
264
+ >>> a = Subset([1, 2, 3], [1, 2, 3, 4])
265
+ >>> a.next_gray().subset
266
+ [1, 3]
267
+
268
+ See Also
269
+ ========
270
+
271
+ iterate_graycode, prev_gray
272
+ """
273
+ return self.iterate_graycode(1)
274
+
275
+ def prev_gray(self):
276
+ """
277
+ Generates the previous Gray code ordered subset.
278
+
279
+ Examples
280
+ ========
281
+
282
+ >>> from sympy.combinatorics import Subset
283
+ >>> a = Subset([2, 3, 4], [1, 2, 3, 4, 5])
284
+ >>> a.prev_gray().subset
285
+ [2, 3, 4, 5]
286
+
287
+ See Also
288
+ ========
289
+
290
+ iterate_graycode, next_gray
291
+ """
292
+ return self.iterate_graycode(-1)
293
+
294
+ @property
295
+ def rank_binary(self):
296
+ """
297
+ Computes the binary ordered rank.
298
+
299
+ Examples
300
+ ========
301
+
302
+ >>> from sympy.combinatorics import Subset
303
+ >>> a = Subset([], ['a','b','c','d'])
304
+ >>> a.rank_binary
305
+ 0
306
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
307
+ >>> a.rank_binary
308
+ 3
309
+
310
+ See Also
311
+ ========
312
+
313
+ iterate_binary, unrank_binary
314
+ """
315
+ if self._rank_binary is None:
316
+ self._rank_binary = int("".join(
317
+ Subset.bitlist_from_subset(self.subset,
318
+ self.superset)), 2)
319
+ return self._rank_binary
320
+
321
+ @property
322
+ def rank_lexicographic(self):
323
+ """
324
+ Computes the lexicographic ranking of the subset.
325
+
326
+ Examples
327
+ ========
328
+
329
+ >>> from sympy.combinatorics import Subset
330
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
331
+ >>> a.rank_lexicographic
332
+ 14
333
+ >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6])
334
+ >>> a.rank_lexicographic
335
+ 43
336
+ """
337
+ if self._rank_lex is None:
338
+ def _ranklex(self, subset_index, i, n):
339
+ if subset_index == [] or i > n:
340
+ return 0
341
+ if i in subset_index:
342
+ subset_index.remove(i)
343
+ return 1 + _ranklex(self, subset_index, i + 1, n)
344
+ return 2**(n - i - 1) + _ranklex(self, subset_index, i + 1, n)
345
+ indices = Subset.subset_indices(self.subset, self.superset)
346
+ self._rank_lex = _ranklex(self, indices, 0, self.superset_size)
347
+ return self._rank_lex
348
+
349
+ @property
350
+ def rank_gray(self):
351
+ """
352
+ Computes the Gray code ranking of the subset.
353
+
354
+ Examples
355
+ ========
356
+
357
+ >>> from sympy.combinatorics import Subset
358
+ >>> a = Subset(['c','d'], ['a','b','c','d'])
359
+ >>> a.rank_gray
360
+ 2
361
+ >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6])
362
+ >>> a.rank_gray
363
+ 27
364
+
365
+ See Also
366
+ ========
367
+
368
+ iterate_graycode, unrank_gray
369
+ """
370
+ if self._rank_graycode is None:
371
+ bits = Subset.bitlist_from_subset(self.subset, self.superset)
372
+ self._rank_graycode = GrayCode(len(bits), start=bits).rank
373
+ return self._rank_graycode
374
+
375
+ @property
376
+ def subset(self):
377
+ """
378
+ Gets the subset represented by the current instance.
379
+
380
+ Examples
381
+ ========
382
+
383
+ >>> from sympy.combinatorics import Subset
384
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
385
+ >>> a.subset
386
+ ['c', 'd']
387
+
388
+ See Also
389
+ ========
390
+
391
+ superset, size, superset_size, cardinality
392
+ """
393
+ return self._subset
394
+
395
+ @property
396
+ def size(self):
397
+ """
398
+ Gets the size of the subset.
399
+
400
+ Examples
401
+ ========
402
+
403
+ >>> from sympy.combinatorics import Subset
404
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
405
+ >>> a.size
406
+ 2
407
+
408
+ See Also
409
+ ========
410
+
411
+ subset, superset, superset_size, cardinality
412
+ """
413
+ return len(self.subset)
414
+
415
+ @property
416
+ def superset(self):
417
+ """
418
+ Gets the superset of the subset.
419
+
420
+ Examples
421
+ ========
422
+
423
+ >>> from sympy.combinatorics import Subset
424
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
425
+ >>> a.superset
426
+ ['a', 'b', 'c', 'd']
427
+
428
+ See Also
429
+ ========
430
+
431
+ subset, size, superset_size, cardinality
432
+ """
433
+ return self._superset
434
+
435
+ @property
436
+ def superset_size(self):
437
+ """
438
+ Returns the size of the superset.
439
+
440
+ Examples
441
+ ========
442
+
443
+ >>> from sympy.combinatorics import Subset
444
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
445
+ >>> a.superset_size
446
+ 4
447
+
448
+ See Also
449
+ ========
450
+
451
+ subset, superset, size, cardinality
452
+ """
453
+ return len(self.superset)
454
+
455
+ @property
456
+ def cardinality(self):
457
+ """
458
+ Returns the number of all possible subsets.
459
+
460
+ Examples
461
+ ========
462
+
463
+ >>> from sympy.combinatorics import Subset
464
+ >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
465
+ >>> a.cardinality
466
+ 16
467
+
468
+ See Also
469
+ ========
470
+
471
+ subset, superset, size, superset_size
472
+ """
473
+ return 2**(self.superset_size)
474
+
475
+ @classmethod
476
+ def subset_from_bitlist(self, super_set, bitlist):
477
+ """
478
+ Gets the subset defined by the bitlist.
479
+
480
+ Examples
481
+ ========
482
+
483
+ >>> from sympy.combinatorics import Subset
484
+ >>> Subset.subset_from_bitlist(['a', 'b', 'c', 'd'], '0011').subset
485
+ ['c', 'd']
486
+
487
+ See Also
488
+ ========
489
+
490
+ bitlist_from_subset
491
+ """
492
+ if len(super_set) != len(bitlist):
493
+ raise ValueError("The sizes of the lists are not equal")
494
+ ret_set = []
495
+ for i in range(len(bitlist)):
496
+ if bitlist[i] == '1':
497
+ ret_set.append(super_set[i])
498
+ return Subset(ret_set, super_set)
499
+
500
+ @classmethod
501
+ def bitlist_from_subset(self, subset, superset):
502
+ """
503
+ Gets the bitlist corresponding to a subset.
504
+
505
+ Examples
506
+ ========
507
+
508
+ >>> from sympy.combinatorics import Subset
509
+ >>> Subset.bitlist_from_subset(['c', 'd'], ['a', 'b', 'c', 'd'])
510
+ '0011'
511
+
512
+ See Also
513
+ ========
514
+
515
+ subset_from_bitlist
516
+ """
517
+ bitlist = ['0'] * len(superset)
518
+ if isinstance(subset, Subset):
519
+ subset = subset.subset
520
+ for i in Subset.subset_indices(subset, superset):
521
+ bitlist[i] = '1'
522
+ return ''.join(bitlist)
523
+
524
+ @classmethod
525
+ def unrank_binary(self, rank, superset):
526
+ """
527
+ Gets the binary ordered subset of the specified rank.
528
+
529
+ Examples
530
+ ========
531
+
532
+ >>> from sympy.combinatorics import Subset
533
+ >>> Subset.unrank_binary(4, ['a', 'b', 'c', 'd']).subset
534
+ ['b']
535
+
536
+ See Also
537
+ ========
538
+
539
+ iterate_binary, rank_binary
540
+ """
541
+ bits = bin(rank)[2:].rjust(len(superset), '0')
542
+ return Subset.subset_from_bitlist(superset, bits)
543
+
544
+ @classmethod
545
+ def unrank_gray(self, rank, superset):
546
+ """
547
+ Gets the Gray code ordered subset of the specified rank.
548
+
549
+ Examples
550
+ ========
551
+
552
+ >>> from sympy.combinatorics import Subset
553
+ >>> Subset.unrank_gray(4, ['a', 'b', 'c']).subset
554
+ ['a', 'b']
555
+ >>> Subset.unrank_gray(0, ['a', 'b', 'c']).subset
556
+ []
557
+
558
+ See Also
559
+ ========
560
+
561
+ iterate_graycode, rank_gray
562
+ """
563
+ graycode_bitlist = GrayCode.unrank(len(superset), rank)
564
+ return Subset.subset_from_bitlist(superset, graycode_bitlist)
565
+
566
+ @classmethod
567
+ def subset_indices(self, subset, superset):
568
+ """Return indices of subset in superset in a list; the list is empty
569
+ if all elements of ``subset`` are not in ``superset``.
570
+
571
+ Examples
572
+ ========
573
+
574
+ >>> from sympy.combinatorics import Subset
575
+ >>> superset = [1, 3, 2, 5, 4]
576
+ >>> Subset.subset_indices([3, 2, 1], superset)
577
+ [1, 2, 0]
578
+ >>> Subset.subset_indices([1, 6], superset)
579
+ []
580
+ >>> Subset.subset_indices([], superset)
581
+ []
582
+
583
+ """
584
+ a, b = superset, subset
585
+ sb = set(b)
586
+ d = {}
587
+ for i, ai in enumerate(a):
588
+ if ai in sb:
589
+ d[ai] = i
590
+ sb.remove(ai)
591
+ if not sb:
592
+ break
593
+ else:
594
+ return []
595
+ return [d[bi] for bi in b]
596
+
597
+
598
+ def ksubsets(superset, k):
599
+ """
600
+ Finds the subsets of size ``k`` in lexicographic order.
601
+
602
+ This uses the itertools generator.
603
+
604
+ Examples
605
+ ========
606
+
607
+ >>> from sympy.combinatorics.subsets import ksubsets
608
+ >>> list(ksubsets([1, 2, 3], 2))
609
+ [(1, 2), (1, 3), (2, 3)]
610
+ >>> list(ksubsets([1, 2, 3, 4, 5], 2))
611
+ [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), \
612
+ (2, 5), (3, 4), (3, 5), (4, 5)]
613
+
614
+ See Also
615
+ ========
616
+
617
+ Subset
618
+ """
619
+ return combinations(superset, k)
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tensor_can.py ADDED
@@ -0,0 +1,1190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.permutations import Permutation, _af_rmul, \
2
+ _af_invert, _af_new
3
+ from sympy.combinatorics.perm_groups import PermutationGroup, _orbit, \
4
+ _orbit_transversal
5
+ from sympy.combinatorics.util import _distribute_gens_by_base, \
6
+ _orbits_transversals_from_bsgs
7
+
8
+ """
9
+ References for tensor canonicalization:
10
+
11
+ [1] R. Portugal "Algorithmic simplification of tensor expressions",
12
+ J. Phys. A 32 (1999) 7779-7789
13
+
14
+ [2] R. Portugal, B.F. Svaiter "Group-theoretic Approach for Symbolic
15
+ Tensor Manipulation: I. Free Indices"
16
+ arXiv:math-ph/0107031v1
17
+
18
+ [3] L.R.U. Manssur, R. Portugal "Group-theoretic Approach for Symbolic
19
+ Tensor Manipulation: II. Dummy Indices"
20
+ arXiv:math-ph/0107032v1
21
+
22
+ [4] xperm.c part of XPerm written by J. M. Martin-Garcia
23
+ http://www.xact.es/index.html
24
+ """
25
+
26
+
27
+ def dummy_sgs(dummies, sym, n):
28
+ """
29
+ Return the strong generators for dummy indices.
30
+
31
+ Parameters
32
+ ==========
33
+
34
+ dummies : List of dummy indices.
35
+ `dummies[2k], dummies[2k+1]` are paired indices.
36
+ In base form, the dummy indices are always in
37
+ consecutive positions.
38
+ sym : symmetry under interchange of contracted dummies::
39
+ * None no symmetry
40
+ * 0 commuting
41
+ * 1 anticommuting
42
+
43
+ n : number of indices
44
+
45
+ Examples
46
+ ========
47
+
48
+ >>> from sympy.combinatorics.tensor_can import dummy_sgs
49
+ >>> dummy_sgs(list(range(2, 8)), 0, 8)
50
+ [[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9],
51
+ [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9],
52
+ [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]]
53
+ """
54
+ if len(dummies) > n:
55
+ raise ValueError("List too large")
56
+ res = []
57
+ # exchange of contravariant and covariant indices
58
+ if sym is not None:
59
+ for j in dummies[::2]:
60
+ a = list(range(n + 2))
61
+ if sym == 1:
62
+ a[n] = n + 1
63
+ a[n + 1] = n
64
+ a[j], a[j + 1] = a[j + 1], a[j]
65
+ res.append(a)
66
+ # rename dummy indices
67
+ for j in dummies[:-3:2]:
68
+ a = list(range(n + 2))
69
+ a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1]
70
+ res.append(a)
71
+ return res
72
+
73
+
74
+ def _min_dummies(dummies, sym, indices):
75
+ """
76
+ Return list of minima of the orbits of indices in group of dummies.
77
+ See ``double_coset_can_rep`` for the description of ``dummies`` and ``sym``.
78
+ ``indices`` is the initial list of dummy indices.
79
+
80
+ Examples
81
+ ========
82
+
83
+ >>> from sympy.combinatorics.tensor_can import _min_dummies
84
+ >>> _min_dummies([list(range(2, 8))], [0], list(range(10)))
85
+ [0, 1, 2, 2, 2, 2, 2, 2, 8, 9]
86
+ """
87
+ num_types = len(sym)
88
+ m = [min(dx) if dx else None for dx in dummies]
89
+ res = indices[:]
90
+ for i in range(num_types):
91
+ for c, i in enumerate(indices):
92
+ for j in range(num_types):
93
+ if i in dummies[j]:
94
+ res[c] = m[j]
95
+ break
96
+ return res
97
+
98
+
99
+ def _trace_S(s, j, b, S_cosets):
100
+ """
101
+ Return the representative h satisfying s[h[b]] == j
102
+
103
+ If there is not such a representative return None
104
+ """
105
+ for h in S_cosets[b]:
106
+ if s[h[b]] == j:
107
+ return h
108
+ return None
109
+
110
+
111
+ def _trace_D(gj, p_i, Dxtrav):
112
+ """
113
+ Return the representative h satisfying h[gj] == p_i
114
+
115
+ If there is not such a representative return None
116
+ """
117
+ for h in Dxtrav:
118
+ if h[gj] == p_i:
119
+ return h
120
+ return None
121
+
122
+
123
+ def _dumx_remove(dumx, dumx_flat, p0):
124
+ """
125
+ remove p0 from dumx
126
+ """
127
+ res = []
128
+ for dx in dumx:
129
+ if p0 not in dx:
130
+ res.append(dx)
131
+ continue
132
+ k = dx.index(p0)
133
+ if k % 2 == 0:
134
+ p0_paired = dx[k + 1]
135
+ else:
136
+ p0_paired = dx[k - 1]
137
+ dx.remove(p0)
138
+ dx.remove(p0_paired)
139
+ dumx_flat.remove(p0)
140
+ dumx_flat.remove(p0_paired)
141
+ res.append(dx)
142
+
143
+
144
+ def transversal2coset(size, base, transversal):
145
+ a = []
146
+ j = 0
147
+ for i in range(size):
148
+ if i in base:
149
+ a.append(sorted(transversal[j].values()))
150
+ j += 1
151
+ else:
152
+ a.append([list(range(size))])
153
+ j = len(a) - 1
154
+ while a[j] == [list(range(size))]:
155
+ j -= 1
156
+ return a[:j + 1]
157
+
158
+
159
+ def double_coset_can_rep(dummies, sym, b_S, sgens, S_transversals, g):
160
+ r"""
161
+ Butler-Portugal algorithm for tensor canonicalization with dummy indices.
162
+
163
+ Parameters
164
+ ==========
165
+
166
+ dummies
167
+ list of lists of dummy indices,
168
+ one list for each type of index;
169
+ the dummy indices are put in order contravariant, covariant
170
+ [d0, -d0, d1, -d1, ...].
171
+
172
+ sym
173
+ list of the symmetries of the index metric for each type.
174
+
175
+ possible symmetries of the metrics
176
+ * 0 symmetric
177
+ * 1 antisymmetric
178
+ * None no symmetry
179
+
180
+ b_S
181
+ base of a minimal slot symmetry BSGS.
182
+
183
+ sgens
184
+ generators of the slot symmetry BSGS.
185
+
186
+ S_transversals
187
+ transversals for the slot BSGS.
188
+
189
+ g
190
+ permutation representing the tensor.
191
+
192
+ Returns
193
+ =======
194
+
195
+ Return 0 if the tensor is zero, else return the array form of
196
+ the permutation representing the canonical form of the tensor.
197
+
198
+ Notes
199
+ =====
200
+
201
+ A tensor with dummy indices can be represented in a number
202
+ of equivalent ways which typically grows exponentially with
203
+ the number of indices. To be able to establish if two tensors
204
+ with many indices are equal becomes computationally very slow
205
+ in absence of an efficient algorithm.
206
+
207
+ The Butler-Portugal algorithm [3] is an efficient algorithm to
208
+ put tensors in canonical form, solving the above problem.
209
+
210
+ Portugal observed that a tensor can be represented by a permutation,
211
+ and that the class of tensors equivalent to it under slot and dummy
212
+ symmetries is equivalent to the double coset `D*g*S`
213
+ (Note: in this documentation we use the conventions for multiplication
214
+ of permutations p, q with (p*q)(i) = p[q[i]] which is opposite
215
+ to the one used in the Permutation class)
216
+
217
+ Using the algorithm by Butler to find a representative of the
218
+ double coset one can find a canonical form for the tensor.
219
+
220
+ To see this correspondence,
221
+ let `g` be a permutation in array form; a tensor with indices `ind`
222
+ (the indices including both the contravariant and the covariant ones)
223
+ can be written as
224
+
225
+ `t = T(ind[g[0]], \dots, ind[g[n-1]])`,
226
+
227
+ where `n = len(ind)`;
228
+ `g` has size `n + 2`, the last two indices for the sign of the tensor
229
+ (trick introduced in [4]).
230
+
231
+ A slot symmetry transformation `s` is a permutation acting on the slots
232
+ `t \rightarrow T(ind[(g*s)[0]], \dots, ind[(g*s)[n-1]])`
233
+
234
+ A dummy symmetry transformation acts on `ind`
235
+ `t \rightarrow T(ind[(d*g)[0]], \dots, ind[(d*g)[n-1]])`
236
+
237
+ Being interested only in the transformations of the tensor under
238
+ these symmetries, one can represent the tensor by `g`, which transforms
239
+ as
240
+
241
+ `g -> d*g*s`, so it belongs to the coset `D*g*S`, or in other words
242
+ to the set of all permutations allowed by the slot and dummy symmetries.
243
+
244
+ Let us explain the conventions by an example.
245
+
246
+ Given a tensor `T^{d3 d2 d1}{}_{d1 d2 d3}` with the slot symmetries
247
+ `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`
248
+
249
+ `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}`
250
+
251
+ and symmetric metric, find the tensor equivalent to it which
252
+ is the lowest under the ordering of indices:
253
+ lexicographic ordering `d1, d2, d3` and then contravariant
254
+ before covariant index; that is the canonical form of the tensor.
255
+
256
+ The canonical form is `-T^{d1 d2 d3}{}_{d1 d2 d3}`
257
+ obtained using `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`.
258
+
259
+ To convert this problem in the input for this function,
260
+ use the following ordering of the index names
261
+ (- for covariant for short) `d1, -d1, d2, -d2, d3, -d3`
262
+
263
+ `T^{d3 d2 d1}{}_{d1 d2 d3}` corresponds to `g = [4, 2, 0, 1, 3, 5, 6, 7]`
264
+ where the last two indices are for the sign
265
+
266
+ `sgens = [Permutation(0, 2)(6, 7), Permutation(0, 4)(6, 7)]`
267
+
268
+ sgens[0] is the slot symmetry `-(0, 2)`
269
+ `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`
270
+
271
+ sgens[1] is the slot symmetry `-(0, 4)`
272
+ `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}`
273
+
274
+ The dummy symmetry group D is generated by the strong base generators
275
+ `[(0, 1), (2, 3), (4, 5), (0, 2)(1, 3), (0, 4)(1, 5)]`
276
+ where the first three interchange covariant and contravariant
277
+ positions of the same index (d1 <-> -d1) and the last two interchange
278
+ the dummy indices themselves (d1 <-> d2).
279
+
280
+ The dummy symmetry acts from the left
281
+ `d = [1, 0, 2, 3, 4, 5, 6, 7]` exchange `d1 \leftrightarrow -d1`
282
+ `T^{d3 d2 d1}{}_{d1 d2 d3} == T^{d3 d2}{}_{d1}{}^{d1}{}_{d2 d3}`
283
+
284
+ `g=[4, 2, 0, 1, 3, 5, 6, 7] -> [4, 2, 1, 0, 3, 5, 6, 7] = _af_rmul(d, g)`
285
+ which differs from `_af_rmul(g, d)`.
286
+
287
+ The slot symmetry acts from the right
288
+ `s = [2, 1, 0, 3, 4, 5, 7, 6]` exchanges slots 0 and 2 and changes sign
289
+ `T^{d3 d2 d1}{}_{d1 d2 d3} == -T^{d1 d2 d3}{}_{d1 d2 d3}`
290
+
291
+ `g=[4,2,0,1,3,5,6,7] -> [0, 2, 4, 1, 3, 5, 7, 6] = _af_rmul(g, s)`
292
+
293
+ Example in which the tensor is zero, same slot symmetries as above:
294
+ `T^{d2}{}_{d1 d3}{}^{d1 d3}{}_{d2}`
295
+
296
+ `= -T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,4)`;
297
+
298
+ `= T_{d3 d1}{}^{d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,2)`;
299
+
300
+ `= T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` symmetric metric;
301
+
302
+ `= 0` since two of these lines have tensors differ only for the sign.
303
+
304
+ The double coset D*g*S consists of permutations `h = d*g*s` corresponding
305
+ to equivalent tensors; if there are two `h` which are the same apart
306
+ from the sign, return zero; otherwise
307
+ choose as representative the tensor with indices
308
+ ordered lexicographically according to `[d1, -d1, d2, -d2, d3, -d3]`
309
+ that is ``rep = min(D*g*S) = min([d*g*s for d in D for s in S])``
310
+
311
+ The indices are fixed one by one; first choose the lowest index
312
+ for slot 0, then the lowest remaining index for slot 1, etc.
313
+ Doing this one obtains a chain of stabilizers
314
+
315
+ `S \rightarrow S_{b0} \rightarrow S_{b0,b1} \rightarrow \dots` and
316
+ `D \rightarrow D_{p0} \rightarrow D_{p0,p1} \rightarrow \dots`
317
+
318
+ where ``[b0, b1, ...] = range(b)`` is a base of the symmetric group;
319
+ the strong base `b_S` of S is an ordered sublist of it;
320
+ therefore it is sufficient to compute once the
321
+ strong base generators of S using the Schreier-Sims algorithm;
322
+ the stabilizers of the strong base generators are the
323
+ strong base generators of the stabilizer subgroup.
324
+
325
+ ``dbase = [p0, p1, ...]`` is not in general in lexicographic order,
326
+ so that one must recompute the strong base generators each time;
327
+ however this is trivial, there is no need to use the Schreier-Sims
328
+ algorithm for D.
329
+
330
+ The algorithm keeps a TAB of elements `(s_i, d_i, h_i)`
331
+ where `h_i = d_i \times g \times s_i` satisfying `h_i[j] = p_j` for `0 \le j < i`
332
+ starting from `s_0 = id, d_0 = id, h_0 = g`.
333
+
334
+ The equations `h_0[0] = p_0, h_1[1] = p_1, \dots` are solved in this order,
335
+ choosing each time the lowest possible value of p_i
336
+
337
+ For `j < i`
338
+ `d_i*g*s_i*S_{b_0, \dots, b_{i-1}}*b_j = D_{p_0, \dots, p_{i-1}}*p_j`
339
+ so that for dx in `D_{p_0,\dots,p_{i-1}}` and sx in
340
+ `S_{base[0], \dots, base[i-1]}` one has `dx*d_i*g*s_i*sx*b_j = p_j`
341
+
342
+ Search for dx, sx such that this equation holds for `j = i`;
343
+ it can be written as `s_i*sx*b_j = J, dx*d_i*g*J = p_j`
344
+ `sx*b_j = s_i**-1*J; sx = trace(s_i**-1, S_{b_0,...,b_{i-1}})`
345
+ `dx**-1*p_j = d_i*g*J; dx = trace(d_i*g*J, D_{p_0,...,p_{i-1}})`
346
+
347
+ `s_{i+1} = s_i*trace(s_i**-1*J, S_{b_0,...,b_{i-1}})`
348
+ `d_{i+1} = trace(d_i*g*J, D_{p_0,...,p_{i-1}})**-1*d_i`
349
+ `h_{i+1}*b_i = d_{i+1}*g*s_{i+1}*b_i = p_i`
350
+
351
+ `h_n*b_j = p_j` for all j, so that `h_n` is the solution.
352
+
353
+ Add the found `(s, d, h)` to TAB1.
354
+
355
+ At the end of the iteration sort TAB1 with respect to the `h`;
356
+ if there are two consecutive `h` in TAB1 which differ only for the
357
+ sign, the tensor is zero, so return 0;
358
+ if there are two consecutive `h` which are equal, keep only one.
359
+
360
+ Then stabilize the slot generators under `i` and the dummy generators
361
+ under `p_i`.
362
+
363
+ Assign `TAB = TAB1` at the end of the iteration step.
364
+
365
+ At the end `TAB` contains a unique `(s, d, h)`, since all the slots
366
+ of the tensor `h` have been fixed to have the minimum value according
367
+ to the symmetries. The algorithm returns `h`.
368
+
369
+ It is important that the slot BSGS has lexicographic minimal base,
370
+ otherwise there is an `i` which does not belong to the slot base
371
+ for which `p_i` is fixed by the dummy symmetry only, while `i`
372
+ is not invariant from the slot stabilizer, so `p_i` is not in
373
+ general the minimal value.
374
+
375
+ This algorithm differs slightly from the original algorithm [3]:
376
+ the canonical form is minimal lexicographically, and
377
+ the BSGS has minimal base under lexicographic order.
378
+ Equal tensors `h` are eliminated from TAB.
379
+
380
+
381
+ Examples
382
+ ========
383
+
384
+ >>> from sympy.combinatorics.permutations import Permutation
385
+ >>> from sympy.combinatorics.tensor_can import double_coset_can_rep, get_transversals
386
+ >>> gens = [Permutation(x) for x in [[2, 1, 0, 3, 4, 5, 7, 6], [4, 1, 2, 3, 0, 5, 7, 6]]]
387
+ >>> base = [0, 2]
388
+ >>> g = Permutation([4, 2, 0, 1, 3, 5, 6, 7])
389
+ >>> transversals = get_transversals(base, gens)
390
+ >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g)
391
+ [0, 1, 2, 3, 4, 5, 7, 6]
392
+
393
+ >>> g = Permutation([4, 1, 3, 0, 5, 2, 6, 7])
394
+ >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g)
395
+ 0
396
+ """
397
+ size = g.size
398
+ g = g.array_form
399
+ num_dummies = size - 2
400
+ indices = list(range(num_dummies))
401
+ all_metrics_with_sym = not any(_ is None for _ in sym)
402
+ num_types = len(sym)
403
+ dumx = dummies[:]
404
+ dumx_flat = []
405
+ for dx in dumx:
406
+ dumx_flat.extend(dx)
407
+ b_S = b_S[:]
408
+ sgensx = [h._array_form for h in sgens]
409
+ if b_S:
410
+ S_transversals = transversal2coset(size, b_S, S_transversals)
411
+ # strong generating set for D
412
+ dsgsx = []
413
+ for i in range(num_types):
414
+ dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies))
415
+ idn = list(range(size))
416
+ # TAB = list of entries (s, d, h) where h = _af_rmuln(d,g,s)
417
+ # for short, in the following d*g*s means _af_rmuln(d,g,s)
418
+ TAB = [(idn, idn, g)]
419
+ for i in range(size - 2):
420
+ b = i
421
+ testb = b in b_S and sgensx
422
+ if testb:
423
+ sgensx1 = [_af_new(_) for _ in sgensx]
424
+ deltab = _orbit(size, sgensx1, b)
425
+ else:
426
+ deltab = {b}
427
+ # p1 = min(IMAGES) = min(Union D_p*h*deltab for h in TAB)
428
+ if all_metrics_with_sym:
429
+ md = _min_dummies(dumx, sym, indices)
430
+ else:
431
+ md = [min(_orbit(size, [_af_new(
432
+ ddx) for ddx in dsgsx], ii)) for ii in range(size - 2)]
433
+
434
+ p_i = min([min([md[h[x]] for x in deltab]) for s, d, h in TAB])
435
+ dsgsx1 = [_af_new(_) for _ in dsgsx]
436
+ Dxtrav = _orbit_transversal(size, dsgsx1, p_i, False, af=True) \
437
+ if dsgsx else None
438
+ if Dxtrav:
439
+ Dxtrav = [_af_invert(x) for x in Dxtrav]
440
+ # compute the orbit of p_i
441
+ for ii in range(num_types):
442
+ if p_i in dumx[ii]:
443
+ # the orbit is made by all the indices in dum[ii]
444
+ if sym[ii] is not None:
445
+ deltap = dumx[ii]
446
+ else:
447
+ # the orbit is made by all the even indices if p_i
448
+ # is even, by all the odd indices if p_i is odd
449
+ p_i_index = dumx[ii].index(p_i) % 2
450
+ deltap = dumx[ii][p_i_index::2]
451
+ break
452
+ else:
453
+ deltap = [p_i]
454
+ TAB1 = []
455
+ while TAB:
456
+ s, d, h = TAB.pop()
457
+ if min([md[h[x]] for x in deltab]) != p_i:
458
+ continue
459
+ deltab1 = [x for x in deltab if md[h[x]] == p_i]
460
+ # NEXT = s*deltab1 intersection (d*g)**-1*deltap
461
+ dg = _af_rmul(d, g)
462
+ dginv = _af_invert(dg)
463
+ sdeltab = [s[x] for x in deltab1]
464
+ gdeltap = [dginv[x] for x in deltap]
465
+ NEXT = [x for x in sdeltab if x in gdeltap]
466
+ # d, s satisfy
467
+ # d*g*s*base[i-1] = p_{i-1}; using the stabilizers
468
+ # d*g*s*S_{base[0],...,base[i-1]}*base[i-1] =
469
+ # D_{p_0,...,p_{i-1}}*p_{i-1}
470
+ # so that to find d1, s1 satisfying d1*g*s1*b = p_i
471
+ # one can look for dx in D_{p_0,...,p_{i-1}} and
472
+ # sx in S_{base[0],...,base[i-1]}
473
+ # d1 = dx*d; s1 = s*sx
474
+ # d1*g*s1*b = dx*d*g*s*sx*b = p_i
475
+ for j in NEXT:
476
+ if testb:
477
+ # solve s1*b = j with s1 = s*sx for some element sx
478
+ # of the stabilizer of ..., base[i-1]
479
+ # sx*b = s**-1*j; sx = _trace_S(s, j,...)
480
+ # s1 = s*trace_S(s**-1*j,...)
481
+ s1 = _trace_S(s, j, b, S_transversals)
482
+ if not s1:
483
+ continue
484
+ else:
485
+ s1 = [s[ix] for ix in s1]
486
+ else:
487
+ s1 = s
488
+ # assert s1[b] == j # invariant
489
+ # solve d1*g*j = p_i with d1 = dx*d for some element dg
490
+ # of the stabilizer of ..., p_{i-1}
491
+ # dx**-1*p_i = d*g*j; dx**-1 = trace_D(d*g*j,...)
492
+ # d1 = trace_D(d*g*j,...)**-1*d
493
+ # to save an inversion in the inner loop; notice we did
494
+ # Dxtrav = [perm_af_invert(x) for x in Dxtrav] out of the loop
495
+ if Dxtrav:
496
+ d1 = _trace_D(dg[j], p_i, Dxtrav)
497
+ if not d1:
498
+ continue
499
+ else:
500
+ if p_i != dg[j]:
501
+ continue
502
+ d1 = idn
503
+ assert d1[dg[j]] == p_i # invariant
504
+ d1 = [d1[ix] for ix in d]
505
+ h1 = [d1[g[ix]] for ix in s1]
506
+ # assert h1[b] == p_i # invariant
507
+ TAB1.append((s1, d1, h1))
508
+
509
+ # if TAB contains equal permutations, keep only one of them;
510
+ # if TAB contains equal permutations up to the sign, return 0
511
+ TAB1.sort(key=lambda x: x[-1])
512
+ prev = [0] * size
513
+ while TAB1:
514
+ s, d, h = TAB1.pop()
515
+ if h[:-2] == prev[:-2]:
516
+ if h[-1] != prev[-1]:
517
+ return 0
518
+ else:
519
+ TAB.append((s, d, h))
520
+ prev = h
521
+
522
+ # stabilize the SGS
523
+ sgensx = [h for h in sgensx if h[b] == b]
524
+ if b in b_S:
525
+ b_S.remove(b)
526
+ _dumx_remove(dumx, dumx_flat, p_i)
527
+ dsgsx = []
528
+ for i in range(num_types):
529
+ dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies))
530
+ return TAB[0][-1]
531
+
532
+
533
+ def canonical_free(base, gens, g, num_free):
534
+ """
535
+ Canonicalization of a tensor with respect to free indices
536
+ choosing the minimum with respect to lexicographical ordering
537
+ in the free indices.
538
+
539
+ Explanation
540
+ ===========
541
+
542
+ ``base``, ``gens`` BSGS for slot permutation group
543
+ ``g`` permutation representing the tensor
544
+ ``num_free`` number of free indices
545
+ The indices must be ordered with first the free indices
546
+
547
+ See explanation in double_coset_can_rep
548
+ The algorithm is a variation of the one given in [2].
549
+
550
+ Examples
551
+ ========
552
+
553
+ >>> from sympy.combinatorics import Permutation
554
+ >>> from sympy.combinatorics.tensor_can import canonical_free
555
+ >>> gens = [[1, 0, 2, 3, 5, 4], [2, 3, 0, 1, 4, 5],[0, 1, 3, 2, 5, 4]]
556
+ >>> gens = [Permutation(h) for h in gens]
557
+ >>> base = [0, 2]
558
+ >>> g = Permutation([2, 1, 0, 3, 4, 5])
559
+ >>> canonical_free(base, gens, g, 4)
560
+ [0, 3, 1, 2, 5, 4]
561
+
562
+ Consider the product of Riemann tensors
563
+ ``T = R^{a}_{d0}^{d1,d2}*R_{d2,d1}^{d0,b}``
564
+ The order of the indices is ``[a, b, d0, -d0, d1, -d1, d2, -d2]``
565
+ The permutation corresponding to the tensor is
566
+ ``g = [0, 3, 4, 6, 7, 5, 2, 1, 8, 9]``
567
+
568
+ In particular ``a`` is position ``0``, ``b`` is in position ``9``.
569
+ Use the slot symmetries to get `T` is a form which is the minimal
570
+ in lexicographic order in the free indices ``a`` and ``b``, e.g.
571
+ ``-R^{a}_{d0}^{d1,d2}*R^{b,d0}_{d2,d1}`` corresponding to
572
+ ``[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]``
573
+
574
+ >>> from sympy.combinatorics.tensor_can import riemann_bsgs, tensor_gens
575
+ >>> base, gens = riemann_bsgs
576
+ >>> size, sbase, sgens = tensor_gens(base, gens, [[], []], 0)
577
+ >>> g = Permutation([0, 3, 4, 6, 7, 5, 2, 1, 8, 9])
578
+ >>> canonical_free(sbase, [Permutation(h) for h in sgens], g, 2)
579
+ [0, 3, 4, 6, 1, 2, 7, 5, 9, 8]
580
+ """
581
+ g = g.array_form
582
+ size = len(g)
583
+ if not base:
584
+ return g[:]
585
+
586
+ transversals = get_transversals(base, gens)
587
+ for x in sorted(g[:-2]):
588
+ if x not in base:
589
+ base.append(x)
590
+ h = g
591
+ for i, transv in enumerate(transversals):
592
+ h_i = [size]*num_free
593
+ # find the element s in transversals[i] such that
594
+ # _af_rmul(h, s) has its free elements with the lowest position in h
595
+ s = None
596
+ for sk in transv.values():
597
+ h1 = _af_rmul(h, sk)
598
+ hi = [h1.index(ix) for ix in range(num_free)]
599
+ if hi < h_i:
600
+ h_i = hi
601
+ s = sk
602
+ if s:
603
+ h = _af_rmul(h, s)
604
+ return h
605
+
606
+
607
+ def _get_map_slots(size, fixed_slots):
608
+ res = list(range(size))
609
+ pos = 0
610
+ for i in range(size):
611
+ if i in fixed_slots:
612
+ continue
613
+ res[i] = pos
614
+ pos += 1
615
+ return res
616
+
617
+
618
+ def _lift_sgens(size, fixed_slots, free, s):
619
+ a = []
620
+ j = k = 0
621
+ fd = list(zip(fixed_slots, free))
622
+ fd = [y for x, y in sorted(fd)]
623
+ num_free = len(free)
624
+ for i in range(size):
625
+ if i in fixed_slots:
626
+ a.append(fd[k])
627
+ k += 1
628
+ else:
629
+ a.append(s[j] + num_free)
630
+ j += 1
631
+ return a
632
+
633
+
634
+ def canonicalize(g, dummies, msym, *v):
635
+ """
636
+ canonicalize tensor formed by tensors
637
+
638
+ Parameters
639
+ ==========
640
+
641
+ g : permutation representing the tensor
642
+
643
+ dummies : list representing the dummy indices
644
+ it can be a list of dummy indices of the same type
645
+ or a list of lists of dummy indices, one list for each
646
+ type of index;
647
+ the dummy indices must come after the free indices,
648
+ and put in order contravariant, covariant
649
+ [d0, -d0, d1,-d1,...]
650
+
651
+ msym : symmetry of the metric(s)
652
+ it can be an integer or a list;
653
+ in the first case it is the symmetry of the dummy index metric;
654
+ in the second case it is the list of the symmetries of the
655
+ index metric for each type
656
+
657
+ v : list, (base_i, gens_i, n_i, sym_i) for tensors of type `i`
658
+
659
+ base_i, gens_i : BSGS for tensors of this type.
660
+ The BSGS should have minimal base under lexicographic ordering;
661
+ if not, an attempt is made do get the minimal BSGS;
662
+ in case of failure,
663
+ canonicalize_naive is used, which is much slower.
664
+
665
+ n_i : number of tensors of type `i`.
666
+
667
+ sym_i : symmetry under exchange of component tensors of type `i`.
668
+
669
+ Both for msym and sym_i the cases are
670
+ * None no symmetry
671
+ * 0 commuting
672
+ * 1 anticommuting
673
+
674
+ Returns
675
+ =======
676
+
677
+ 0 if the tensor is zero, else return the array form of
678
+ the permutation representing the canonical form of the tensor.
679
+
680
+ Algorithm
681
+ =========
682
+
683
+ First one uses canonical_free to get the minimum tensor under
684
+ lexicographic order, using only the slot symmetries.
685
+ If the component tensors have not minimal BSGS, it is attempted
686
+ to find it; if the attempt fails canonicalize_naive
687
+ is used instead.
688
+
689
+ Compute the residual slot symmetry keeping fixed the free indices
690
+ using tensor_gens(base, gens, list_free_indices, sym).
691
+
692
+ Reduce the problem eliminating the free indices.
693
+
694
+ Then use double_coset_can_rep and lift back the result reintroducing
695
+ the free indices.
696
+
697
+ Examples
698
+ ========
699
+
700
+ one type of index with commuting metric;
701
+
702
+ `A_{a b}` and `B_{a b}` antisymmetric and commuting
703
+
704
+ `T = A_{d0 d1} * B^{d0}{}_{d2} * B^{d2 d1}`
705
+
706
+ `ord = [d0,-d0,d1,-d1,d2,-d2]` order of the indices
707
+
708
+ g = [1, 3, 0, 5, 4, 2, 6, 7]
709
+
710
+ `T_c = 0`
711
+
712
+ >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize, bsgs_direct_product
713
+ >>> from sympy.combinatorics import Permutation
714
+ >>> base2a, gens2a = get_symmetric_group_sgs(2, 1)
715
+ >>> t0 = (base2a, gens2a, 1, 0)
716
+ >>> t1 = (base2a, gens2a, 2, 0)
717
+ >>> g = Permutation([1, 3, 0, 5, 4, 2, 6, 7])
718
+ >>> canonicalize(g, range(6), 0, t0, t1)
719
+ 0
720
+
721
+ same as above, but with `B_{a b}` anticommuting
722
+
723
+ `T_c = -A^{d0 d1} * B_{d0}{}^{d2} * B_{d1 d2}`
724
+
725
+ can = [0,2,1,4,3,5,7,6]
726
+
727
+ >>> t1 = (base2a, gens2a, 2, 1)
728
+ >>> canonicalize(g, range(6), 0, t0, t1)
729
+ [0, 2, 1, 4, 3, 5, 7, 6]
730
+
731
+ two types of indices `[a,b,c,d,e,f]` and `[m,n]`, in this order,
732
+ both with commuting metric
733
+
734
+ `f^{a b c}` antisymmetric, commuting
735
+
736
+ `A_{m a}` no symmetry, commuting
737
+
738
+ `T = f^c{}_{d a} * f^f{}_{e b} * A_m{}^d * A^{m b} * A_n{}^a * A^{n e}`
739
+
740
+ ord = [c,f,a,-a,b,-b,d,-d,e,-e,m,-m,n,-n]
741
+
742
+ g = [0,7,3, 1,9,5, 11,6, 10,4, 13,2, 12,8, 14,15]
743
+
744
+ The canonical tensor is
745
+ `T_c = -f^{c a b} * f^{f d e} * A^m{}_a * A_{m d} * A^n{}_b * A_{n e}`
746
+
747
+ can = [0,2,4, 1,6,8, 10,3, 11,7, 12,5, 13,9, 15,14]
748
+
749
+ >>> base_f, gens_f = get_symmetric_group_sgs(3, 1)
750
+ >>> base1, gens1 = get_symmetric_group_sgs(1)
751
+ >>> base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1)
752
+ >>> t0 = (base_f, gens_f, 2, 0)
753
+ >>> t1 = (base_A, gens_A, 4, 0)
754
+ >>> dummies = [range(2, 10), range(10, 14)]
755
+ >>> g = Permutation([0, 7, 3, 1, 9, 5, 11, 6, 10, 4, 13, 2, 12, 8, 14, 15])
756
+ >>> canonicalize(g, dummies, [0, 0], t0, t1)
757
+ [0, 2, 4, 1, 6, 8, 10, 3, 11, 7, 12, 5, 13, 9, 15, 14]
758
+ """
759
+ from sympy.combinatorics.testutil import canonicalize_naive
760
+ if not isinstance(msym, list):
761
+ if msym not in (0, 1, None):
762
+ raise ValueError('msym must be 0, 1 or None')
763
+ num_types = 1
764
+ else:
765
+ num_types = len(msym)
766
+ if not all(msymx in (0, 1, None) for msymx in msym):
767
+ raise ValueError('msym entries must be 0, 1 or None')
768
+ if len(dummies) != num_types:
769
+ raise ValueError(
770
+ 'dummies and msym must have the same number of elements')
771
+ size = g.size
772
+ num_tensors = 0
773
+ v1 = []
774
+ for base_i, gens_i, n_i, sym_i in v:
775
+ # check that the BSGS is minimal;
776
+ # this property is used in double_coset_can_rep;
777
+ # if it is not minimal use canonicalize_naive
778
+ if not _is_minimal_bsgs(base_i, gens_i):
779
+ mbsgs = get_minimal_bsgs(base_i, gens_i)
780
+ if not mbsgs:
781
+ can = canonicalize_naive(g, dummies, msym, *v)
782
+ return can
783
+ base_i, gens_i = mbsgs
784
+ v1.append((base_i, gens_i, [[]] * n_i, sym_i))
785
+ num_tensors += n_i
786
+
787
+ if num_types == 1 and not isinstance(msym, list):
788
+ dummies = [dummies]
789
+ msym = [msym]
790
+ flat_dummies = []
791
+ for dumx in dummies:
792
+ flat_dummies.extend(dumx)
793
+
794
+ if flat_dummies and flat_dummies != list(range(flat_dummies[0], flat_dummies[-1] + 1)):
795
+ raise ValueError('dummies is not valid')
796
+
797
+ # slot symmetry of the tensor
798
+ size1, sbase, sgens = gens_products(*v1)
799
+ if size != size1:
800
+ raise ValueError(
801
+ 'g has size %d, generators have size %d' % (size, size1))
802
+ free = [i for i in range(size - 2) if i not in flat_dummies]
803
+ num_free = len(free)
804
+
805
+ # g1 minimal tensor under slot symmetry
806
+ g1 = canonical_free(sbase, sgens, g, num_free)
807
+ if not flat_dummies:
808
+ return g1
809
+ # save the sign of g1
810
+ sign = 0 if g1[-1] == size - 1 else 1
811
+
812
+ # the free indices are kept fixed.
813
+ # Determine free_i, the list of slots of tensors which are fixed
814
+ # since they are occupied by free indices, which are fixed.
815
+ start = 0
816
+ for i, (base_i, gens_i, n_i, sym_i) in enumerate(v):
817
+ free_i = []
818
+ len_tens = gens_i[0].size - 2
819
+ # for each component tensor get a list od fixed islots
820
+ for j in range(n_i):
821
+ # get the elements corresponding to the component tensor
822
+ h = g1[start:(start + len_tens)]
823
+ fr = []
824
+ # get the positions of the fixed elements in h
825
+ for k in free:
826
+ if k in h:
827
+ fr.append(h.index(k))
828
+ free_i.append(fr)
829
+ start += len_tens
830
+ v1[i] = (base_i, gens_i, free_i, sym_i)
831
+ # BSGS of the tensor with fixed free indices
832
+ # if tensor_gens fails in gens_product, use canonicalize_naive
833
+ size, sbase, sgens = gens_products(*v1)
834
+
835
+ # reduce the permutations getting rid of the free indices
836
+ pos_free = [g1.index(x) for x in range(num_free)]
837
+ size_red = size - num_free
838
+ g1_red = [x - num_free for x in g1 if x in flat_dummies]
839
+ if sign:
840
+ g1_red.extend([size_red - 1, size_red - 2])
841
+ else:
842
+ g1_red.extend([size_red - 2, size_red - 1])
843
+ map_slots = _get_map_slots(size, pos_free)
844
+ sbase_red = [map_slots[i] for i in sbase if i not in pos_free]
845
+ sgens_red = [_af_new([map_slots[i] for i in y._array_form if i not in pos_free]) for y in sgens]
846
+ dummies_red = [[x - num_free for x in y] for y in dummies]
847
+ transv_red = get_transversals(sbase_red, sgens_red)
848
+ g1_red = _af_new(g1_red)
849
+ g2 = double_coset_can_rep(
850
+ dummies_red, msym, sbase_red, sgens_red, transv_red, g1_red)
851
+ if g2 == 0:
852
+ return 0
853
+ # lift to the case with the free indices
854
+ g3 = _lift_sgens(size, pos_free, free, g2)
855
+ return g3
856
+
857
+
858
+ def perm_af_direct_product(gens1, gens2, signed=True):
859
+ """
860
+ Direct products of the generators gens1 and gens2.
861
+
862
+ Examples
863
+ ========
864
+
865
+ >>> from sympy.combinatorics.tensor_can import perm_af_direct_product
866
+ >>> gens1 = [[1, 0, 2, 3], [0, 1, 3, 2]]
867
+ >>> gens2 = [[1, 0]]
868
+ >>> perm_af_direct_product(gens1, gens2, False)
869
+ [[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]]
870
+ >>> gens1 = [[1, 0, 2, 3, 5, 4], [0, 1, 3, 2, 4, 5]]
871
+ >>> gens2 = [[1, 0, 2, 3]]
872
+ >>> perm_af_direct_product(gens1, gens2, True)
873
+ [[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]]
874
+ """
875
+ gens1 = [list(x) for x in gens1]
876
+ gens2 = [list(x) for x in gens2]
877
+ s = 2 if signed else 0
878
+ n1 = len(gens1[0]) - s
879
+ n2 = len(gens2[0]) - s
880
+ start = list(range(n1))
881
+ end = list(range(n1, n1 + n2))
882
+ if signed:
883
+ gens1 = [gen[:-2] + end + [gen[-2] + n2, gen[-1] + n2]
884
+ for gen in gens1]
885
+ gens2 = [start + [x + n1 for x in gen] for gen in gens2]
886
+ else:
887
+ gens1 = [gen + end for gen in gens1]
888
+ gens2 = [start + [x + n1 for x in gen] for gen in gens2]
889
+
890
+ res = gens1 + gens2
891
+
892
+ return res
893
+
894
+
895
+ def bsgs_direct_product(base1, gens1, base2, gens2, signed=True):
896
+ """
897
+ Direct product of two BSGS.
898
+
899
+ Parameters
900
+ ==========
901
+
902
+ base1 : base of the first BSGS.
903
+
904
+ gens1 : strong generating sequence of the first BSGS.
905
+
906
+ base2, gens2 : similarly for the second BSGS.
907
+
908
+ signed : flag for signed permutations.
909
+
910
+ Examples
911
+ ========
912
+
913
+ >>> from sympy.combinatorics.tensor_can import (get_symmetric_group_sgs, bsgs_direct_product)
914
+ >>> base1, gens1 = get_symmetric_group_sgs(1)
915
+ >>> base2, gens2 = get_symmetric_group_sgs(2)
916
+ >>> bsgs_direct_product(base1, gens1, base2, gens2)
917
+ ([1], [(4)(1 2)])
918
+ """
919
+ s = 2 if signed else 0
920
+ n1 = gens1[0].size - s
921
+ base = list(base1)
922
+ base += [x + n1 for x in base2]
923
+ gens1 = [h._array_form for h in gens1]
924
+ gens2 = [h._array_form for h in gens2]
925
+ gens = perm_af_direct_product(gens1, gens2, signed)
926
+ size = len(gens[0])
927
+ id_af = list(range(size))
928
+ gens = [h for h in gens if h != id_af]
929
+ if not gens:
930
+ gens = [id_af]
931
+ return base, [_af_new(h) for h in gens]
932
+
933
+
934
+ def get_symmetric_group_sgs(n, antisym=False):
935
+ """
936
+ Return base, gens of the minimal BSGS for (anti)symmetric tensor
937
+
938
+ Parameters
939
+ ==========
940
+
941
+ n : rank of the tensor
942
+ antisym : bool
943
+ ``antisym = False`` symmetric tensor
944
+ ``antisym = True`` antisymmetric tensor
945
+
946
+ Examples
947
+ ========
948
+
949
+ >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs
950
+ >>> get_symmetric_group_sgs(3)
951
+ ([0, 1], [(4)(0 1), (4)(1 2)])
952
+ """
953
+ if n == 1:
954
+ return [], [_af_new(list(range(3)))]
955
+ gens = [Permutation(n - 1)(i, i + 1)._array_form for i in range(n - 1)]
956
+ if antisym == 0:
957
+ gens = [x + [n, n + 1] for x in gens]
958
+ else:
959
+ gens = [x + [n + 1, n] for x in gens]
960
+ base = list(range(n - 1))
961
+ return base, [_af_new(h) for h in gens]
962
+
963
+ riemann_bsgs = [0, 2], [Permutation(0, 1)(4, 5), Permutation(2, 3)(4, 5),
964
+ Permutation(5)(0, 2)(1, 3)]
965
+
966
+
967
+ def get_transversals(base, gens):
968
+ """
969
+ Return transversals for the group with BSGS base, gens
970
+ """
971
+ if not base:
972
+ return []
973
+ stabs = _distribute_gens_by_base(base, gens)
974
+ orbits, transversals = _orbits_transversals_from_bsgs(base, stabs)
975
+ transversals = [{x: h._array_form for x, h in y.items()} for y in
976
+ transversals]
977
+ return transversals
978
+
979
+
980
+ def _is_minimal_bsgs(base, gens):
981
+ """
982
+ Check if the BSGS has minimal base under lexigographic order.
983
+
984
+ base, gens BSGS
985
+
986
+ Examples
987
+ ========
988
+
989
+ >>> from sympy.combinatorics import Permutation
990
+ >>> from sympy.combinatorics.tensor_can import riemann_bsgs, _is_minimal_bsgs
991
+ >>> _is_minimal_bsgs(*riemann_bsgs)
992
+ True
993
+ >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)]))
994
+ >>> _is_minimal_bsgs(*riemann_bsgs1)
995
+ False
996
+ """
997
+ base1 = []
998
+ sgs1 = gens[:]
999
+ size = gens[0].size
1000
+ for i in range(size):
1001
+ if not all(h._array_form[i] == i for h in sgs1):
1002
+ base1.append(i)
1003
+ sgs1 = [h for h in sgs1 if h._array_form[i] == i]
1004
+ return base1 == base
1005
+
1006
+
1007
+ def get_minimal_bsgs(base, gens):
1008
+ """
1009
+ Compute a minimal GSGS
1010
+
1011
+ base, gens BSGS
1012
+
1013
+ If base, gens is a minimal BSGS return it; else return a minimal BSGS
1014
+ if it fails in finding one, it returns None
1015
+
1016
+ TODO: use baseswap in the case in which if it fails in finding a
1017
+ minimal BSGS
1018
+
1019
+ Examples
1020
+ ========
1021
+
1022
+ >>> from sympy.combinatorics import Permutation
1023
+ >>> from sympy.combinatorics.tensor_can import get_minimal_bsgs
1024
+ >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)]))
1025
+ >>> get_minimal_bsgs(*riemann_bsgs1)
1026
+ ([0, 2], [(0 1)(4 5), (5)(0 2)(1 3), (2 3)(4 5)])
1027
+ """
1028
+ G = PermutationGroup(gens)
1029
+ base, gens = G.schreier_sims_incremental()
1030
+ if not _is_minimal_bsgs(base, gens):
1031
+ return None
1032
+ return base, gens
1033
+
1034
+
1035
+ def tensor_gens(base, gens, list_free_indices, sym=0):
1036
+ """
1037
+ Returns size, res_base, res_gens BSGS for n tensors of the
1038
+ same type.
1039
+
1040
+ Explanation
1041
+ ===========
1042
+
1043
+ base, gens BSGS for tensors of this type
1044
+ list_free_indices list of the slots occupied by fixed indices
1045
+ for each of the tensors
1046
+
1047
+ sym symmetry under commutation of two tensors
1048
+ sym None no symmetry
1049
+ sym 0 commuting
1050
+ sym 1 anticommuting
1051
+
1052
+ Examples
1053
+ ========
1054
+
1055
+ >>> from sympy.combinatorics.tensor_can import tensor_gens, get_symmetric_group_sgs
1056
+
1057
+ two symmetric tensors with 3 indices without free indices
1058
+
1059
+ >>> base, gens = get_symmetric_group_sgs(3)
1060
+ >>> tensor_gens(base, gens, [[], []])
1061
+ (8, [0, 1, 3, 4], [(7)(0 1), (7)(1 2), (7)(3 4), (7)(4 5), (7)(0 3)(1 4)(2 5)])
1062
+
1063
+ two symmetric tensors with 3 indices with free indices in slot 1 and 0
1064
+
1065
+ >>> tensor_gens(base, gens, [[1], [0]])
1066
+ (8, [0, 4], [(7)(0 2), (7)(4 5)])
1067
+
1068
+ four symmetric tensors with 3 indices, two of which with free indices
1069
+
1070
+ """
1071
+ def _get_bsgs(G, base, gens, free_indices):
1072
+ """
1073
+ return the BSGS for G.pointwise_stabilizer(free_indices)
1074
+ """
1075
+ if not free_indices:
1076
+ return base[:], gens[:]
1077
+ else:
1078
+ H = G.pointwise_stabilizer(free_indices)
1079
+ base, sgs = H.schreier_sims_incremental()
1080
+ return base, sgs
1081
+
1082
+ # if not base there is no slot symmetry for the component tensors
1083
+ # if list_free_indices.count([]) < 2 there is no commutation symmetry
1084
+ # so there is no resulting slot symmetry
1085
+ if not base and list_free_indices.count([]) < 2:
1086
+ n = len(list_free_indices)
1087
+ size = gens[0].size
1088
+ size = n * (size - 2) + 2
1089
+ return size, [], [_af_new(list(range(size)))]
1090
+
1091
+ # if any(list_free_indices) one needs to compute the pointwise
1092
+ # stabilizer, so G is needed
1093
+ if any(list_free_indices):
1094
+ G = PermutationGroup(gens)
1095
+ else:
1096
+ G = None
1097
+
1098
+ # no_free list of lists of indices for component tensors without fixed
1099
+ # indices
1100
+ no_free = []
1101
+ size = gens[0].size
1102
+ id_af = list(range(size))
1103
+ num_indices = size - 2
1104
+ if not list_free_indices[0]:
1105
+ no_free.append(list(range(num_indices)))
1106
+ res_base, res_gens = _get_bsgs(G, base, gens, list_free_indices[0])
1107
+ for i in range(1, len(list_free_indices)):
1108
+ base1, gens1 = _get_bsgs(G, base, gens, list_free_indices[i])
1109
+ res_base, res_gens = bsgs_direct_product(res_base, res_gens,
1110
+ base1, gens1, 1)
1111
+ if not list_free_indices[i]:
1112
+ no_free.append(list(range(size - 2, size - 2 + num_indices)))
1113
+ size += num_indices
1114
+ nr = size - 2
1115
+ res_gens = [h for h in res_gens if h._array_form != id_af]
1116
+ # if sym there are no commuting tensors stop here
1117
+ if sym is None or not no_free:
1118
+ if not res_gens:
1119
+ res_gens = [_af_new(id_af)]
1120
+ return size, res_base, res_gens
1121
+
1122
+ # if the component tensors have moinimal BSGS, so is their direct
1123
+ # product P; the slot symmetry group is S = P*C, where C is the group
1124
+ # to (anti)commute the component tensors with no free indices
1125
+ # a stabilizer has the property S_i = P_i*C_i;
1126
+ # the BSGS of P*C has SGS_P + SGS_C and the base is
1127
+ # the ordered union of the bases of P and C.
1128
+ # If P has minimal BSGS, so has S with this base.
1129
+ base_comm = []
1130
+ for i in range(len(no_free) - 1):
1131
+ ind1 = no_free[i]
1132
+ ind2 = no_free[i + 1]
1133
+ a = list(range(ind1[0]))
1134
+ a.extend(ind2)
1135
+ a.extend(ind1)
1136
+ base_comm.append(ind1[0])
1137
+ a.extend(list(range(ind2[-1] + 1, nr)))
1138
+ if sym == 0:
1139
+ a.extend([nr, nr + 1])
1140
+ else:
1141
+ a.extend([nr + 1, nr])
1142
+ res_gens.append(_af_new(a))
1143
+ res_base = list(res_base)
1144
+ # each base is ordered; order the union of the two bases
1145
+ for i in base_comm:
1146
+ if i not in res_base:
1147
+ res_base.append(i)
1148
+ res_base.sort()
1149
+ if not res_gens:
1150
+ res_gens = [_af_new(id_af)]
1151
+
1152
+ return size, res_base, res_gens
1153
+
1154
+
1155
+ def gens_products(*v):
1156
+ """
1157
+ Returns size, res_base, res_gens BSGS for n tensors of different types.
1158
+
1159
+ Explanation
1160
+ ===========
1161
+
1162
+ v is a sequence of (base_i, gens_i, free_i, sym_i)
1163
+ where
1164
+ base_i, gens_i BSGS of tensor of type `i`
1165
+ free_i list of the fixed slots for each of the tensors
1166
+ of type `i`; if there are `n_i` tensors of type `i`
1167
+ and none of them have fixed slots, `free = [[]]*n_i`
1168
+ sym 0 (1) if the tensors of type `i` (anti)commute among themselves
1169
+
1170
+ Examples
1171
+ ========
1172
+
1173
+ >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, gens_products
1174
+ >>> base, gens = get_symmetric_group_sgs(2)
1175
+ >>> gens_products((base, gens, [[], []], 0))
1176
+ (6, [0, 2], [(5)(0 1), (5)(2 3), (5)(0 2)(1 3)])
1177
+ >>> gens_products((base, gens, [[1], []], 0))
1178
+ (6, [2], [(5)(2 3)])
1179
+ """
1180
+ res_size, res_base, res_gens = tensor_gens(*v[0])
1181
+ for i in range(1, len(v)):
1182
+ size, base, gens = tensor_gens(*v[i])
1183
+ res_base, res_gens = bsgs_direct_product(res_base, res_gens, base,
1184
+ gens, 1)
1185
+ res_size = res_gens[0].size
1186
+ id_af = list(range(res_size))
1187
+ res_gens = [h for h in res_gens if h != id_af]
1188
+ if not res_gens:
1189
+ res_gens = [id_af]
1190
+ return res_size, res_base, res_gens
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (198 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_coset_table.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_fp_groups.cpython-310.pyc ADDED
Binary file (9.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_free_groups.cpython-310.pyc ADDED
Binary file (8.11 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_galois.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_generators.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_group_numbers.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_named_groups.cpython-310.pyc ADDED
Binary file (2.5 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_partitions.cpython-310.pyc ADDED
Binary file (5.28 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_pc_groups.cpython-310.pyc ADDED
Binary file (2.24 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_permutations.cpython-310.pyc ADDED
Binary file (21.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_polyhedron.cpython-310.pyc ADDED
Binary file (4.45 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_rewriting.cpython-310.pyc ADDED
Binary file (1.92 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_schur_number.cpython-310.pyc ADDED
Binary file (2.25 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_subsets.cpython-310.pyc ADDED
Binary file (2.71 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_tensor_can.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_testutil.cpython-310.pyc ADDED
Binary file (2.02 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_util.cpython-310.pyc ADDED
Binary file (4.13 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_coset_table.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.fp_groups import FpGroup
2
+ from sympy.combinatorics.coset_table import (CosetTable,
3
+ coset_enumeration_r, coset_enumeration_c)
4
+ from sympy.combinatorics.coset_table import modified_coset_enumeration_r
5
+ from sympy.combinatorics.free_groups import free_group
6
+
7
+ from sympy.testing.pytest import slow
8
+
9
+ """
10
+ References
11
+ ==========
12
+
13
+ [1] Holt, D., Eick, B., O'Brien, E.
14
+ "Handbook of Computational Group Theory"
15
+
16
+ [2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson
17
+ Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490.
18
+ "Implementation and Analysis of the Todd-Coxeter Algorithm"
19
+
20
+ """
21
+
22
+ def test_scan_1():
23
+ # Example 5.1 from [1]
24
+ F, x, y = free_group("x, y")
25
+ f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
26
+ c = CosetTable(f, [x])
27
+
28
+ c.scan_and_fill(0, x)
29
+ assert c.table == [[0, 0, None, None]]
30
+ assert c.p == [0]
31
+ assert c.n == 1
32
+ assert c.omega == [0]
33
+
34
+ c.scan_and_fill(0, x**3)
35
+ assert c.table == [[0, 0, None, None]]
36
+ assert c.p == [0]
37
+ assert c.n == 1
38
+ assert c.omega == [0]
39
+
40
+ c.scan_and_fill(0, y**3)
41
+ assert c.table == [[0, 0, 1, 2], [None, None, 2, 0], [None, None, 0, 1]]
42
+ assert c.p == [0, 1, 2]
43
+ assert c.n == 3
44
+ assert c.omega == [0, 1, 2]
45
+
46
+ c.scan_and_fill(0, x**-1*y**-1*x*y)
47
+ assert c.table == [[0, 0, 1, 2], [None, None, 2, 0], [2, 2, 0, 1]]
48
+ assert c.p == [0, 1, 2]
49
+ assert c.n == 3
50
+ assert c.omega == [0, 1, 2]
51
+
52
+ c.scan_and_fill(1, x**3)
53
+ assert c.table == [[0, 0, 1, 2], [3, 4, 2, 0], [2, 2, 0, 1], \
54
+ [4, 1, None, None], [1, 3, None, None]]
55
+ assert c.p == [0, 1, 2, 3, 4]
56
+ assert c.n == 5
57
+ assert c.omega == [0, 1, 2, 3, 4]
58
+
59
+ c.scan_and_fill(1, y**3)
60
+ assert c.table == [[0, 0, 1, 2], [3, 4, 2, 0], [2, 2, 0, 1], \
61
+ [4, 1, None, None], [1, 3, None, None]]
62
+ assert c.p == [0, 1, 2, 3, 4]
63
+ assert c.n == 5
64
+ assert c.omega == [0, 1, 2, 3, 4]
65
+
66
+ c.scan_and_fill(1, x**-1*y**-1*x*y)
67
+ assert c.table == [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1], \
68
+ [None, 1, None, None], [1, 3, None, None]]
69
+ assert c.p == [0, 1, 2, 1, 1]
70
+ assert c.n == 3
71
+ assert c.omega == [0, 1, 2]
72
+
73
+ # Example 5.2 from [1]
74
+ f = FpGroup(F, [x**2, y**3, (x*y)**3])
75
+ c = CosetTable(f, [x*y])
76
+
77
+ c.scan_and_fill(0, x*y)
78
+ assert c.table == [[1, None, None, 1], [None, 0, 0, None]]
79
+ assert c.p == [0, 1]
80
+ assert c.n == 2
81
+ assert c.omega == [0, 1]
82
+
83
+ c.scan_and_fill(0, x**2)
84
+ assert c.table == [[1, 1, None, 1], [0, 0, 0, None]]
85
+ assert c.p == [0, 1]
86
+ assert c.n == 2
87
+ assert c.omega == [0, 1]
88
+
89
+ c.scan_and_fill(0, y**3)
90
+ assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [None, None, 1, 0]]
91
+ assert c.p == [0, 1, 2]
92
+ assert c.n == 3
93
+ assert c.omega == [0, 1, 2]
94
+
95
+ c.scan_and_fill(0, (x*y)**3)
96
+ assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [None, None, 1, 0]]
97
+ assert c.p == [0, 1, 2]
98
+ assert c.n == 3
99
+ assert c.omega == [0, 1, 2]
100
+
101
+ c.scan_and_fill(1, x**2)
102
+ assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [None, None, 1, 0]]
103
+ assert c.p == [0, 1, 2]
104
+ assert c.n == 3
105
+ assert c.omega == [0, 1, 2]
106
+
107
+ c.scan_and_fill(1, y**3)
108
+ assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [None, None, 1, 0]]
109
+ assert c.p == [0, 1, 2]
110
+ assert c.n == 3
111
+ assert c.omega == [0, 1, 2]
112
+
113
+ c.scan_and_fill(1, (x*y)**3)
114
+ assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [3, 4, 1, 0], [None, 2, 4, None], [2, None, None, 3]]
115
+ assert c.p == [0, 1, 2, 3, 4]
116
+ assert c.n == 5
117
+ assert c.omega == [0, 1, 2, 3, 4]
118
+
119
+ c.scan_and_fill(2, x**2)
120
+ assert c.table == [[1, 1, 2, 1], [0, 0, 0, 2], [3, 3, 1, 0], [2, 2, 3, 3], [2, None, None, 3]]
121
+ assert c.p == [0, 1, 2, 3, 3]
122
+ assert c.n == 4
123
+ assert c.omega == [0, 1, 2, 3]
124
+
125
+
126
+ @slow
127
+ def test_coset_enumeration():
128
+ # this test function contains the combined tests for the two strategies
129
+ # i.e. HLT and Felsch strategies.
130
+
131
+ # Example 5.1 from [1]
132
+ F, x, y = free_group("x, y")
133
+ f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
134
+ C_r = coset_enumeration_r(f, [x])
135
+ C_r.compress(); C_r.standardize()
136
+ C_c = coset_enumeration_c(f, [x])
137
+ C_c.compress(); C_c.standardize()
138
+ table1 = [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]]
139
+ assert C_r.table == table1
140
+ assert C_c.table == table1
141
+
142
+ # E1 from [2] Pg. 474
143
+ F, r, s, t = free_group("r, s, t")
144
+ E1 = FpGroup(F, [t**-1*r*t*r**-2, r**-1*s*r*s**-2, s**-1*t*s*t**-2])
145
+ C_r = coset_enumeration_r(E1, [])
146
+ C_r.compress()
147
+ C_c = coset_enumeration_c(E1, [])
148
+ C_c.compress()
149
+ table2 = [[0, 0, 0, 0, 0, 0]]
150
+ assert C_r.table == table2
151
+ # test for issue #11449
152
+ assert C_c.table == table2
153
+
154
+ # Cox group from [2] Pg. 474
155
+ F, a, b = free_group("a, b")
156
+ Cox = FpGroup(F, [a**6, b**6, (a*b)**2, (a**2*b**2)**2, (a**3*b**3)**5])
157
+ C_r = coset_enumeration_r(Cox, [a])
158
+ C_r.compress(); C_r.standardize()
159
+ C_c = coset_enumeration_c(Cox, [a])
160
+ C_c.compress(); C_c.standardize()
161
+ table3 = [[0, 0, 1, 2],
162
+ [2, 3, 4, 0],
163
+ [5, 1, 0, 6],
164
+ [1, 7, 8, 9],
165
+ [9, 10, 11, 1],
166
+ [12, 2, 9, 13],
167
+ [14, 9, 2, 11],
168
+ [3, 12, 15, 16],
169
+ [16, 17, 18, 3],
170
+ [6, 4, 3, 5],
171
+ [4, 19, 20, 21],
172
+ [21, 22, 6, 4],
173
+ [7, 5, 23, 24],
174
+ [25, 23, 5, 18],
175
+ [19, 6, 22, 26],
176
+ [24, 27, 28, 7],
177
+ [29, 8, 7, 30],
178
+ [8, 31, 32, 33],
179
+ [33, 34, 13, 8],
180
+ [10, 14, 35, 35],
181
+ [35, 36, 37, 10],
182
+ [30, 11, 10, 29],
183
+ [11, 38, 39, 14],
184
+ [13, 39, 38, 12],
185
+ [40, 15, 12, 41],
186
+ [42, 13, 34, 43],
187
+ [44, 35, 14, 45],
188
+ [15, 46, 47, 34],
189
+ [34, 48, 49, 15],
190
+ [50, 16, 21, 51],
191
+ [52, 21, 16, 49],
192
+ [17, 50, 53, 54],
193
+ [54, 55, 56, 17],
194
+ [41, 18, 17, 40],
195
+ [18, 28, 27, 25],
196
+ [26, 20, 19, 19],
197
+ [20, 57, 58, 59],
198
+ [59, 60, 51, 20],
199
+ [22, 52, 61, 23],
200
+ [23, 62, 63, 22],
201
+ [64, 24, 33, 65],
202
+ [48, 33, 24, 61],
203
+ [62, 25, 54, 66],
204
+ [67, 54, 25, 68],
205
+ [57, 26, 59, 69],
206
+ [70, 59, 26, 63],
207
+ [27, 64, 71, 72],
208
+ [72, 73, 68, 27],
209
+ [28, 41, 74, 75],
210
+ [75, 76, 30, 28],
211
+ [31, 29, 77, 78],
212
+ [79, 77, 29, 37],
213
+ [38, 30, 76, 80],
214
+ [78, 81, 82, 31],
215
+ [43, 32, 31, 42],
216
+ [32, 83, 84, 85],
217
+ [85, 86, 65, 32],
218
+ [36, 44, 87, 88],
219
+ [88, 89, 90, 36],
220
+ [45, 37, 36, 44],
221
+ [37, 82, 81, 79],
222
+ [80, 74, 41, 38],
223
+ [39, 42, 91, 92],
224
+ [92, 93, 45, 39],
225
+ [46, 40, 94, 95],
226
+ [96, 94, 40, 56],
227
+ [97, 91, 42, 82],
228
+ [83, 43, 98, 99],
229
+ [100, 98, 43, 47],
230
+ [101, 87, 44, 90],
231
+ [82, 45, 93, 97],
232
+ [95, 102, 103, 46],
233
+ [104, 47, 46, 105],
234
+ [47, 106, 107, 100],
235
+ [61, 108, 109, 48],
236
+ [105, 49, 48, 104],
237
+ [49, 110, 111, 52],
238
+ [51, 111, 110, 50],
239
+ [112, 53, 50, 113],
240
+ [114, 51, 60, 115],
241
+ [116, 61, 52, 117],
242
+ [53, 118, 119, 60],
243
+ [60, 70, 66, 53],
244
+ [55, 67, 120, 121],
245
+ [121, 122, 123, 55],
246
+ [113, 56, 55, 112],
247
+ [56, 103, 102, 96],
248
+ [69, 124, 125, 57],
249
+ [115, 58, 57, 114],
250
+ [58, 126, 127, 128],
251
+ [128, 128, 69, 58],
252
+ [66, 129, 130, 62],
253
+ [117, 63, 62, 116],
254
+ [63, 125, 124, 70],
255
+ [65, 109, 108, 64],
256
+ [131, 71, 64, 132],
257
+ [133, 65, 86, 134],
258
+ [135, 66, 70, 136],
259
+ [68, 130, 129, 67],
260
+ [137, 120, 67, 138],
261
+ [132, 68, 73, 131],
262
+ [139, 69, 128, 140],
263
+ [71, 141, 142, 86],
264
+ [86, 143, 144, 71],
265
+ [145, 72, 75, 146],
266
+ [147, 75, 72, 144],
267
+ [73, 145, 148, 120],
268
+ [120, 149, 150, 73],
269
+ [74, 151, 152, 94],
270
+ [94, 153, 146, 74],
271
+ [76, 147, 154, 77],
272
+ [77, 155, 156, 76],
273
+ [157, 78, 85, 158],
274
+ [143, 85, 78, 154],
275
+ [155, 79, 88, 159],
276
+ [160, 88, 79, 161],
277
+ [151, 80, 92, 162],
278
+ [163, 92, 80, 156],
279
+ [81, 157, 164, 165],
280
+ [165, 166, 161, 81],
281
+ [99, 107, 106, 83],
282
+ [134, 84, 83, 133],
283
+ [84, 167, 168, 169],
284
+ [169, 170, 158, 84],
285
+ [87, 171, 172, 93],
286
+ [93, 163, 159, 87],
287
+ [89, 160, 173, 174],
288
+ [174, 175, 176, 89],
289
+ [90, 90, 89, 101],
290
+ [91, 177, 178, 98],
291
+ [98, 179, 162, 91],
292
+ [180, 95, 100, 181],
293
+ [179, 100, 95, 152],
294
+ [153, 96, 121, 148],
295
+ [182, 121, 96, 183],
296
+ [177, 97, 165, 184],
297
+ [185, 165, 97, 172],
298
+ [186, 99, 169, 187],
299
+ [188, 169, 99, 178],
300
+ [171, 101, 174, 189],
301
+ [190, 174, 101, 176],
302
+ [102, 180, 191, 192],
303
+ [192, 193, 183, 102],
304
+ [103, 113, 194, 195],
305
+ [195, 196, 105, 103],
306
+ [106, 104, 197, 198],
307
+ [199, 197, 104, 109],
308
+ [110, 105, 196, 200],
309
+ [198, 201, 133, 106],
310
+ [107, 186, 202, 203],
311
+ [203, 204, 181, 107],
312
+ [108, 116, 205, 206],
313
+ [206, 207, 132, 108],
314
+ [109, 133, 201, 199],
315
+ [200, 194, 113, 110],
316
+ [111, 114, 208, 209],
317
+ [209, 210, 117, 111],
318
+ [118, 112, 211, 212],
319
+ [213, 211, 112, 123],
320
+ [214, 208, 114, 125],
321
+ [126, 115, 215, 216],
322
+ [217, 215, 115, 119],
323
+ [218, 205, 116, 130],
324
+ [125, 117, 210, 214],
325
+ [212, 219, 220, 118],
326
+ [136, 119, 118, 135],
327
+ [119, 221, 222, 217],
328
+ [122, 182, 223, 224],
329
+ [224, 225, 226, 122],
330
+ [138, 123, 122, 137],
331
+ [123, 220, 219, 213],
332
+ [124, 139, 227, 228],
333
+ [228, 229, 136, 124],
334
+ [216, 222, 221, 126],
335
+ [140, 127, 126, 139],
336
+ [127, 230, 231, 232],
337
+ [232, 233, 140, 127],
338
+ [129, 135, 234, 235],
339
+ [235, 236, 138, 129],
340
+ [130, 132, 207, 218],
341
+ [141, 131, 237, 238],
342
+ [239, 237, 131, 150],
343
+ [167, 134, 240, 241],
344
+ [242, 240, 134, 142],
345
+ [243, 234, 135, 220],
346
+ [221, 136, 229, 244],
347
+ [149, 137, 245, 246],
348
+ [247, 245, 137, 226],
349
+ [220, 138, 236, 243],
350
+ [244, 227, 139, 221],
351
+ [230, 140, 233, 248],
352
+ [238, 249, 250, 141],
353
+ [251, 142, 141, 252],
354
+ [142, 253, 254, 242],
355
+ [154, 255, 256, 143],
356
+ [252, 144, 143, 251],
357
+ [144, 257, 258, 147],
358
+ [146, 258, 257, 145],
359
+ [259, 148, 145, 260],
360
+ [261, 146, 153, 262],
361
+ [263, 154, 147, 264],
362
+ [148, 265, 266, 153],
363
+ [246, 267, 268, 149],
364
+ [260, 150, 149, 259],
365
+ [150, 250, 249, 239],
366
+ [162, 269, 270, 151],
367
+ [262, 152, 151, 261],
368
+ [152, 271, 272, 179],
369
+ [159, 273, 274, 155],
370
+ [264, 156, 155, 263],
371
+ [156, 270, 269, 163],
372
+ [158, 256, 255, 157],
373
+ [275, 164, 157, 276],
374
+ [277, 158, 170, 278],
375
+ [279, 159, 163, 280],
376
+ [161, 274, 273, 160],
377
+ [281, 173, 160, 282],
378
+ [276, 161, 166, 275],
379
+ [283, 162, 179, 284],
380
+ [164, 285, 286, 170],
381
+ [170, 188, 184, 164],
382
+ [166, 185, 189, 173],
383
+ [173, 287, 288, 166],
384
+ [241, 254, 253, 167],
385
+ [278, 168, 167, 277],
386
+ [168, 289, 290, 291],
387
+ [291, 292, 187, 168],
388
+ [189, 293, 294, 171],
389
+ [280, 172, 171, 279],
390
+ [172, 295, 296, 185],
391
+ [175, 190, 297, 297],
392
+ [297, 298, 299, 175],
393
+ [282, 176, 175, 281],
394
+ [176, 294, 293, 190],
395
+ [184, 296, 295, 177],
396
+ [284, 178, 177, 283],
397
+ [178, 300, 301, 188],
398
+ [181, 272, 271, 180],
399
+ [302, 191, 180, 303],
400
+ [304, 181, 204, 305],
401
+ [183, 266, 265, 182],
402
+ [306, 223, 182, 307],
403
+ [303, 183, 193, 302],
404
+ [308, 184, 188, 309],
405
+ [310, 189, 185, 311],
406
+ [187, 301, 300, 186],
407
+ [305, 202, 186, 304],
408
+ [312, 187, 292, 313],
409
+ [314, 297, 190, 315],
410
+ [191, 316, 317, 204],
411
+ [204, 318, 319, 191],
412
+ [320, 192, 195, 321],
413
+ [322, 195, 192, 319],
414
+ [193, 320, 323, 223],
415
+ [223, 324, 325, 193],
416
+ [194, 326, 327, 211],
417
+ [211, 328, 321, 194],
418
+ [196, 322, 329, 197],
419
+ [197, 330, 331, 196],
420
+ [332, 198, 203, 333],
421
+ [318, 203, 198, 329],
422
+ [330, 199, 206, 334],
423
+ [335, 206, 199, 336],
424
+ [326, 200, 209, 337],
425
+ [338, 209, 200, 331],
426
+ [201, 332, 339, 240],
427
+ [240, 340, 336, 201],
428
+ [202, 341, 342, 292],
429
+ [292, 343, 333, 202],
430
+ [205, 344, 345, 210],
431
+ [210, 338, 334, 205],
432
+ [207, 335, 346, 237],
433
+ [237, 347, 348, 207],
434
+ [208, 349, 350, 215],
435
+ [215, 351, 337, 208],
436
+ [352, 212, 217, 353],
437
+ [351, 217, 212, 327],
438
+ [328, 213, 224, 323],
439
+ [354, 224, 213, 355],
440
+ [349, 214, 228, 356],
441
+ [357, 228, 214, 345],
442
+ [358, 216, 232, 359],
443
+ [360, 232, 216, 350],
444
+ [344, 218, 235, 361],
445
+ [362, 235, 218, 348],
446
+ [219, 352, 363, 364],
447
+ [364, 365, 355, 219],
448
+ [222, 358, 366, 367],
449
+ [367, 368, 353, 222],
450
+ [225, 354, 369, 370],
451
+ [370, 371, 372, 225],
452
+ [307, 226, 225, 306],
453
+ [226, 268, 267, 247],
454
+ [227, 373, 374, 233],
455
+ [233, 360, 356, 227],
456
+ [229, 357, 361, 234],
457
+ [234, 375, 376, 229],
458
+ [248, 231, 230, 230],
459
+ [231, 377, 378, 379],
460
+ [379, 380, 359, 231],
461
+ [236, 362, 381, 245],
462
+ [245, 382, 383, 236],
463
+ [384, 238, 242, 385],
464
+ [340, 242, 238, 346],
465
+ [347, 239, 246, 381],
466
+ [386, 246, 239, 387],
467
+ [388, 241, 291, 389],
468
+ [343, 291, 241, 339],
469
+ [375, 243, 364, 390],
470
+ [391, 364, 243, 383],
471
+ [373, 244, 367, 392],
472
+ [393, 367, 244, 376],
473
+ [382, 247, 370, 394],
474
+ [395, 370, 247, 396],
475
+ [377, 248, 379, 397],
476
+ [398, 379, 248, 374],
477
+ [249, 384, 399, 400],
478
+ [400, 401, 387, 249],
479
+ [250, 260, 402, 403],
480
+ [403, 404, 252, 250],
481
+ [253, 251, 405, 406],
482
+ [407, 405, 251, 256],
483
+ [257, 252, 404, 408],
484
+ [406, 409, 277, 253],
485
+ [254, 388, 410, 411],
486
+ [411, 412, 385, 254],
487
+ [255, 263, 413, 414],
488
+ [414, 415, 276, 255],
489
+ [256, 277, 409, 407],
490
+ [408, 402, 260, 257],
491
+ [258, 261, 416, 417],
492
+ [417, 418, 264, 258],
493
+ [265, 259, 419, 420],
494
+ [421, 419, 259, 268],
495
+ [422, 416, 261, 270],
496
+ [271, 262, 423, 424],
497
+ [425, 423, 262, 266],
498
+ [426, 413, 263, 274],
499
+ [270, 264, 418, 422],
500
+ [420, 427, 307, 265],
501
+ [266, 303, 428, 425],
502
+ [267, 386, 429, 430],
503
+ [430, 431, 396, 267],
504
+ [268, 307, 427, 421],
505
+ [269, 283, 432, 433],
506
+ [433, 434, 280, 269],
507
+ [424, 428, 303, 271],
508
+ [272, 304, 435, 436],
509
+ [436, 437, 284, 272],
510
+ [273, 279, 438, 439],
511
+ [439, 440, 282, 273],
512
+ [274, 276, 415, 426],
513
+ [285, 275, 441, 442],
514
+ [443, 441, 275, 288],
515
+ [289, 278, 444, 445],
516
+ [446, 444, 278, 286],
517
+ [447, 438, 279, 294],
518
+ [295, 280, 434, 448],
519
+ [287, 281, 449, 450],
520
+ [451, 449, 281, 299],
521
+ [294, 282, 440, 447],
522
+ [448, 432, 283, 295],
523
+ [300, 284, 437, 452],
524
+ [442, 453, 454, 285],
525
+ [309, 286, 285, 308],
526
+ [286, 455, 456, 446],
527
+ [450, 457, 458, 287],
528
+ [311, 288, 287, 310],
529
+ [288, 454, 453, 443],
530
+ [445, 456, 455, 289],
531
+ [313, 290, 289, 312],
532
+ [290, 459, 460, 461],
533
+ [461, 462, 389, 290],
534
+ [293, 310, 463, 464],
535
+ [464, 465, 315, 293],
536
+ [296, 308, 466, 467],
537
+ [467, 468, 311, 296],
538
+ [298, 314, 469, 470],
539
+ [470, 471, 472, 298],
540
+ [315, 299, 298, 314],
541
+ [299, 458, 457, 451],
542
+ [452, 435, 304, 300],
543
+ [301, 312, 473, 474],
544
+ [474, 475, 309, 301],
545
+ [316, 302, 476, 477],
546
+ [478, 476, 302, 325],
547
+ [341, 305, 479, 480],
548
+ [481, 479, 305, 317],
549
+ [324, 306, 482, 483],
550
+ [484, 482, 306, 372],
551
+ [485, 466, 308, 454],
552
+ [455, 309, 475, 486],
553
+ [487, 463, 310, 458],
554
+ [454, 311, 468, 485],
555
+ [486, 473, 312, 455],
556
+ [459, 313, 488, 489],
557
+ [490, 488, 313, 342],
558
+ [491, 469, 314, 472],
559
+ [458, 315, 465, 487],
560
+ [477, 492, 485, 316],
561
+ [463, 317, 316, 468],
562
+ [317, 487, 493, 481],
563
+ [329, 447, 464, 318],
564
+ [468, 319, 318, 463],
565
+ [319, 467, 448, 322],
566
+ [321, 448, 467, 320],
567
+ [475, 323, 320, 466],
568
+ [432, 321, 328, 437],
569
+ [438, 329, 322, 434],
570
+ [323, 474, 452, 328],
571
+ [483, 494, 486, 324],
572
+ [466, 325, 324, 475],
573
+ [325, 485, 492, 478],
574
+ [337, 422, 433, 326],
575
+ [437, 327, 326, 432],
576
+ [327, 436, 424, 351],
577
+ [334, 426, 439, 330],
578
+ [434, 331, 330, 438],
579
+ [331, 433, 422, 338],
580
+ [333, 464, 447, 332],
581
+ [449, 339, 332, 440],
582
+ [465, 333, 343, 469],
583
+ [413, 334, 338, 418],
584
+ [336, 439, 426, 335],
585
+ [441, 346, 335, 415],
586
+ [440, 336, 340, 449],
587
+ [416, 337, 351, 423],
588
+ [339, 451, 470, 343],
589
+ [346, 443, 450, 340],
590
+ [480, 493, 487, 341],
591
+ [469, 342, 341, 465],
592
+ [342, 491, 495, 490],
593
+ [361, 407, 414, 344],
594
+ [418, 345, 344, 413],
595
+ [345, 417, 408, 357],
596
+ [381, 446, 442, 347],
597
+ [415, 348, 347, 441],
598
+ [348, 414, 407, 362],
599
+ [356, 408, 417, 349],
600
+ [423, 350, 349, 416],
601
+ [350, 425, 420, 360],
602
+ [353, 424, 436, 352],
603
+ [479, 363, 352, 435],
604
+ [428, 353, 368, 476],
605
+ [355, 452, 474, 354],
606
+ [488, 369, 354, 473],
607
+ [435, 355, 365, 479],
608
+ [402, 356, 360, 419],
609
+ [405, 361, 357, 404],
610
+ [359, 420, 425, 358],
611
+ [476, 366, 358, 428],
612
+ [427, 359, 380, 482],
613
+ [444, 381, 362, 409],
614
+ [363, 481, 477, 368],
615
+ [368, 393, 390, 363],
616
+ [365, 391, 394, 369],
617
+ [369, 490, 480, 365],
618
+ [366, 478, 483, 380],
619
+ [380, 398, 392, 366],
620
+ [371, 395, 496, 497],
621
+ [497, 498, 489, 371],
622
+ [473, 372, 371, 488],
623
+ [372, 486, 494, 484],
624
+ [392, 400, 403, 373],
625
+ [419, 374, 373, 402],
626
+ [374, 421, 430, 398],
627
+ [390, 411, 406, 375],
628
+ [404, 376, 375, 405],
629
+ [376, 403, 400, 393],
630
+ [397, 430, 421, 377],
631
+ [482, 378, 377, 427],
632
+ [378, 484, 497, 499],
633
+ [499, 499, 397, 378],
634
+ [394, 461, 445, 382],
635
+ [409, 383, 382, 444],
636
+ [383, 406, 411, 391],
637
+ [385, 450, 443, 384],
638
+ [492, 399, 384, 453],
639
+ [457, 385, 412, 493],
640
+ [387, 442, 446, 386],
641
+ [494, 429, 386, 456],
642
+ [453, 387, 401, 492],
643
+ [389, 470, 451, 388],
644
+ [493, 410, 388, 457],
645
+ [471, 389, 462, 495],
646
+ [412, 390, 393, 399],
647
+ [462, 394, 391, 410],
648
+ [401, 392, 398, 429],
649
+ [396, 445, 461, 395],
650
+ [498, 496, 395, 460],
651
+ [456, 396, 431, 494],
652
+ [431, 397, 499, 496],
653
+ [399, 477, 481, 412],
654
+ [429, 483, 478, 401],
655
+ [410, 480, 490, 462],
656
+ [496, 497, 484, 431],
657
+ [489, 495, 491, 459],
658
+ [495, 460, 459, 471],
659
+ [460, 489, 498, 498],
660
+ [472, 472, 471, 491]]
661
+
662
+ assert C_r.table == table3
663
+ assert C_c.table == table3
664
+
665
+ # Group denoted by B2,4 from [2] Pg. 474
666
+ F, a, b = free_group("a, b")
667
+ B_2_4 = FpGroup(F, [a**4, b**4, (a*b)**4, (a**-1*b)**4, (a**2*b)**4, \
668
+ (a*b**2)**4, (a**2*b**2)**4, (a**-1*b*a*b)**4, (a*b**-1*a*b)**4])
669
+ C_r = coset_enumeration_r(B_2_4, [a])
670
+ C_c = coset_enumeration_c(B_2_4, [a])
671
+ index_r = 0
672
+ for i in range(len(C_r.p)):
673
+ if C_r.p[i] == i:
674
+ index_r += 1
675
+ assert index_r == 1024
676
+
677
+ index_c = 0
678
+ for i in range(len(C_c.p)):
679
+ if C_c.p[i] == i:
680
+ index_c += 1
681
+ assert index_c == 1024
682
+
683
+ # trivial Macdonald group G(2,2) from [2] Pg. 480
684
+ M = FpGroup(F, [b**-1*a**-1*b*a*b**-1*a*b*a**-2, a**-1*b**-1*a*b*a**-1*b*a*b**-2])
685
+ C_r = coset_enumeration_r(M, [a])
686
+ C_r.compress(); C_r.standardize()
687
+ C_c = coset_enumeration_c(M, [a])
688
+ C_c.compress(); C_c.standardize()
689
+ table4 = [[0, 0, 0, 0]]
690
+ assert C_r.table == table4
691
+ assert C_c.table == table4
692
+
693
+
694
+ def test_look_ahead():
695
+ # Section 3.2 [Test Example] Example (d) from [2]
696
+ F, a, b, c = free_group("a, b, c")
697
+ f = FpGroup(F, [a**11, b**5, c**4, (a*c)**3, b**2*c**-1*b**-1*c, a**4*b**-1*a**-1*b])
698
+ H = [c, b, c**2]
699
+ table0 = [[1, 2, 0, 0, 0, 0],
700
+ [3, 0, 4, 5, 6, 7],
701
+ [0, 8, 9, 10, 11, 12],
702
+ [5, 1, 10, 13, 14, 15],
703
+ [16, 5, 16, 1, 17, 18],
704
+ [4, 3, 1, 8, 19, 20],
705
+ [12, 21, 22, 23, 24, 1],
706
+ [25, 26, 27, 28, 1, 24],
707
+ [2, 10, 5, 16, 22, 28],
708
+ [10, 13, 13, 2, 29, 30]]
709
+ CosetTable.max_stack_size = 10
710
+ C_c = coset_enumeration_c(f, H)
711
+ C_c.compress(); C_c.standardize()
712
+ assert C_c.table[: 10] == table0
713
+
714
+ def test_modified_methods():
715
+ '''
716
+ Tests for modified coset table methods.
717
+ Example 5.7 from [1] Holt, D., Eick, B., O'Brien
718
+ "Handbook of Computational Group Theory".
719
+
720
+ '''
721
+ F, x, y = free_group("x, y")
722
+ f = FpGroup(F, [x**3, y**5, (x*y)**2])
723
+ H = [x*y, x**-1*y**-1*x*y*x]
724
+ C = CosetTable(f, H)
725
+ C.modified_define(0, x)
726
+ identity = C._grp.identity
727
+ a_0 = C._grp.generators[0]
728
+ a_1 = C._grp.generators[1]
729
+
730
+ assert C.P == [[identity, None, None, None],
731
+ [None, identity, None, None]]
732
+ assert C.table == [[1, None, None, None],
733
+ [None, 0, None, None]]
734
+
735
+ C.modified_define(1, x)
736
+ assert C.table == [[1, None, None, None],
737
+ [2, 0, None, None],
738
+ [None, 1, None, None]]
739
+ assert C.P == [[identity, None, None, None],
740
+ [identity, identity, None, None],
741
+ [None, identity, None, None]]
742
+
743
+ C.modified_scan(0, x**3, C._grp.identity, fill=False)
744
+ assert C.P == [[identity, identity, None, None],
745
+ [identity, identity, None, None],
746
+ [identity, identity, None, None]]
747
+ assert C.table == [[1, 2, None, None],
748
+ [2, 0, None, None],
749
+ [0, 1, None, None]]
750
+
751
+ C.modified_scan(0, x*y, C._grp.generators[0], fill=False)
752
+ assert C.P == [[identity, identity, None, a_0**-1],
753
+ [identity, identity, a_0, None],
754
+ [identity, identity, None, None]]
755
+ assert C.table == [[1, 2, None, 1],
756
+ [2, 0, 0, None],
757
+ [0, 1, None, None]]
758
+
759
+ C.modified_define(2, y**-1)
760
+ assert C.table == [[1, 2, None, 1],
761
+ [2, 0, 0, None],
762
+ [0, 1, None, 3],
763
+ [None, None, 2, None]]
764
+ assert C.P == [[identity, identity, None, a_0**-1],
765
+ [identity, identity, a_0, None],
766
+ [identity, identity, None, identity],
767
+ [None, None, identity, None]]
768
+
769
+ C.modified_scan(0, x**-1*y**-1*x*y*x, C._grp.generators[1])
770
+ assert C.table == [[1, 2, None, 1],
771
+ [2, 0, 0, None],
772
+ [0, 1, None, 3],
773
+ [3, 3, 2, None]]
774
+ assert C.P == [[identity, identity, None, a_0**-1],
775
+ [identity, identity, a_0, None],
776
+ [identity, identity, None, identity],
777
+ [a_1, a_1**-1, identity, None]]
778
+
779
+ C.modified_scan(2, (x*y)**2, C._grp.identity)
780
+ assert C.table == [[1, 2, 3, 1],
781
+ [2, 0, 0, None],
782
+ [0, 1, None, 3],
783
+ [3, 3, 2, 0]]
784
+ assert C.P == [[identity, identity, a_1**-1, a_0**-1],
785
+ [identity, identity, a_0, None],
786
+ [identity, identity, None, identity],
787
+ [a_1, a_1**-1, identity, a_1]]
788
+
789
+ C.modified_define(2, y)
790
+ assert C.table == [[1, 2, 3, 1],
791
+ [2, 0, 0, None],
792
+ [0, 1, 4, 3],
793
+ [3, 3, 2, 0],
794
+ [None, None, None, 2]]
795
+ assert C.P == [[identity, identity, a_1**-1, a_0**-1],
796
+ [identity, identity, a_0, None],
797
+ [identity, identity, identity, identity],
798
+ [a_1, a_1**-1, identity, a_1],
799
+ [None, None, None, identity]]
800
+
801
+ C.modified_scan(0, y**5, C._grp.identity)
802
+ assert C.table == [[1, 2, 3, 1], [2, 0, 0, 4], [0, 1, 4, 3], [3, 3, 2, 0], [None, None, 1, 2]]
803
+ assert C.P == [[identity, identity, a_1**-1, a_0**-1],
804
+ [identity, identity, a_0, a_0*a_1**-1],
805
+ [identity, identity, identity, identity],
806
+ [a_1, a_1**-1, identity, a_1],
807
+ [None, None, a_1*a_0**-1, identity]]
808
+
809
+ C.modified_scan(1, (x*y)**2, C._grp.identity)
810
+ assert C.table == [[1, 2, 3, 1],
811
+ [2, 0, 0, 4],
812
+ [0, 1, 4, 3],
813
+ [3, 3, 2, 0],
814
+ [4, 4, 1, 2]]
815
+ assert C.P == [[identity, identity, a_1**-1, a_0**-1],
816
+ [identity, identity, a_0, a_0*a_1**-1],
817
+ [identity, identity, identity, identity],
818
+ [a_1, a_1**-1, identity, a_1],
819
+ [a_0*a_1**-1, a_1*a_0**-1, a_1*a_0**-1, identity]]
820
+
821
+ # Modified coset enumeration test
822
+ f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
823
+ C = coset_enumeration_r(f, [x])
824
+ C_m = modified_coset_enumeration_r(f, [x])
825
+ assert C_m.table == C.table
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_fp_groups.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.singleton import S
2
+ from sympy.combinatorics.fp_groups import (FpGroup, low_index_subgroups,
3
+ reidemeister_presentation, FpSubgroup,
4
+ simplify_presentation)
5
+ from sympy.combinatorics.free_groups import (free_group, FreeGroup)
6
+
7
+ from sympy.testing.pytest import slow
8
+
9
+ """
10
+ References
11
+ ==========
12
+
13
+ [1] Holt, D., Eick, B., O'Brien, E.
14
+ "Handbook of Computational Group Theory"
15
+
16
+ [2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson
17
+ Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490.
18
+ "Implementation and Analysis of the Todd-Coxeter Algorithm"
19
+
20
+ [3] PROC. SECOND INTERNAT. CONF. THEORY OF GROUPS, CANBERRA 1973,
21
+ pp. 347-356. "A Reidemeister-Schreier program" by George Havas.
22
+ http://staff.itee.uq.edu.au/havas/1973cdhw.pdf
23
+
24
+ """
25
+
26
+ def test_low_index_subgroups():
27
+ F, x, y = free_group("x, y")
28
+
29
+ # Example 5.10 from [1] Pg. 194
30
+ f = FpGroup(F, [x**2, y**3, (x*y)**4])
31
+ L = low_index_subgroups(f, 4)
32
+ t1 = [[[0, 0, 0, 0]],
33
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]],
34
+ [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]],
35
+ [[1, 1, 0, 0], [0, 0, 1, 1]]]
36
+ for i in range(len(t1)):
37
+ assert L[i].table == t1[i]
38
+
39
+ f = FpGroup(F, [x**2, y**3, (x*y)**7])
40
+ L = low_index_subgroups(f, 15)
41
+ t2 = [[[0, 0, 0, 0]],
42
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5],
43
+ [4, 4, 5, 3], [6, 6, 3, 4], [5, 5, 6, 6]],
44
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5],
45
+ [6, 6, 5, 3], [5, 5, 3, 4], [4, 4, 6, 6]],
46
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5],
47
+ [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11],
48
+ [11, 11, 9, 6], [9, 9, 6, 8], [12, 12, 11, 7], [8, 8, 7, 10],
49
+ [10, 10, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]],
50
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5],
51
+ [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11],
52
+ [11, 11, 9, 6], [12, 12, 6, 8], [10, 10, 11, 7], [8, 8, 7, 10],
53
+ [9, 9, 13, 14], [14, 14, 14, 12], [13, 13, 12, 13]],
54
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5],
55
+ [6, 6, 5, 3], [7, 7, 3, 4], [4, 4, 8, 9], [5, 5, 10, 11],
56
+ [11, 11, 9, 6], [12, 12, 6, 8], [13, 13, 11, 7], [8, 8, 7, 10],
57
+ [9, 9, 12, 12], [10, 10, 13, 13]],
58
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 3, 3], [2, 2, 5, 6]
59
+ , [7, 7, 6, 4], [8, 8, 4, 5], [5, 5, 8, 9], [6, 6, 9, 7],
60
+ [10, 10, 7, 8], [9, 9, 11, 12], [11, 11, 12, 10], [13, 13, 10, 11],
61
+ [12, 12, 13, 13]],
62
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 3, 3], [2, 2, 5, 6]
63
+ , [7, 7, 6, 4], [8, 8, 4, 5], [5, 5, 8, 9], [6, 6, 9, 7],
64
+ [10, 10, 7, 8], [9, 9, 11, 12], [13, 13, 12, 10], [12, 12, 10, 11],
65
+ [11, 11, 13, 13]],
66
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 4, 4]
67
+ , [7, 7, 6, 3], [8, 8, 3, 5], [5, 5, 8, 9], [6, 6, 9, 7],
68
+ [10, 10, 7, 8], [9, 9, 11, 12], [13, 13, 12, 10], [12, 12, 10, 11],
69
+ [11, 11, 13, 13]],
70
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8]
71
+ , [5, 5, 6, 3], [9, 9, 3, 5], [10, 10, 8, 4], [8, 8, 4, 7],
72
+ [6, 6, 10, 11], [7, 7, 11, 9], [12, 12, 9, 10], [11, 11, 13, 14],
73
+ [14, 14, 14, 12], [13, 13, 12, 13]],
74
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8]
75
+ , [6, 6, 6, 3], [5, 5, 3, 5], [8, 8, 8, 4], [7, 7, 4, 7]],
76
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8]
77
+ , [9, 9, 6, 3], [6, 6, 3, 5], [10, 10, 8, 4], [11, 11, 4, 7],
78
+ [5, 5, 10, 12], [7, 7, 12, 9], [8, 8, 11, 11], [13, 13, 9, 10],
79
+ [12, 12, 13, 13]],
80
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8]
81
+ , [9, 9, 6, 3], [6, 6, 3, 5], [10, 10, 8, 4], [11, 11, 4, 7],
82
+ [5, 5, 12, 11], [7, 7, 10, 10], [8, 8, 9, 12], [13, 13, 11, 9],
83
+ [12, 12, 13, 13]],
84
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8]
85
+ , [9, 9, 6, 3], [10, 10, 3, 5], [7, 7, 8, 4], [11, 11, 4, 7],
86
+ [5, 5, 9, 9], [6, 6, 11, 12], [8, 8, 12, 10], [13, 13, 10, 11],
87
+ [12, 12, 13, 13]],
88
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8]
89
+ , [9, 9, 6, 3], [10, 10, 3, 5], [7, 7, 8, 4], [11, 11, 4, 7],
90
+ [5, 5, 12, 11], [6, 6, 10, 10], [8, 8, 9, 12], [13, 13, 11, 9],
91
+ [12, 12, 13, 13]],
92
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8]
93
+ , [9, 9, 6, 3], [10, 10, 3, 5], [11, 11, 8, 4], [12, 12, 4, 7],
94
+ [5, 5, 9, 9], [6, 6, 12, 13], [7, 7, 11, 11], [8, 8, 13, 10],
95
+ [13, 13, 10, 12]],
96
+ [[1, 1, 0, 0], [0, 0, 2, 3], [4, 4, 3, 1], [5, 5, 1, 2], [2, 2, 4, 4]
97
+ , [3, 3, 6, 7], [7, 7, 7, 5], [6, 6, 5, 6]]]
98
+ for i in range(len(t2)):
99
+ assert L[i].table == t2[i]
100
+
101
+ f = FpGroup(F, [x**2, y**3, (x*y)**7])
102
+ L = low_index_subgroups(f, 10, [x])
103
+ t3 = [[[0, 0, 0, 0]],
104
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [4, 4, 5, 3],
105
+ [6, 6, 3, 4], [5, 5, 6, 6]],
106
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 4, 5], [6, 6, 5, 3],
107
+ [5, 5, 3, 4], [4, 4, 6, 6]],
108
+ [[0, 0, 1, 2], [3, 3, 2, 0], [4, 4, 0, 1], [1, 1, 5, 6], [2, 2, 7, 8],
109
+ [6, 6, 6, 3], [5, 5, 3, 5], [8, 8, 8, 4], [7, 7, 4, 7]]]
110
+ for i in range(len(t3)):
111
+ assert L[i].table == t3[i]
112
+
113
+
114
+ def test_subgroup_presentations():
115
+ F, x, y = free_group("x, y")
116
+ f = FpGroup(F, [x**3, y**5, (x*y)**2])
117
+ H = [x*y, x**-1*y**-1*x*y*x]
118
+ p1 = reidemeister_presentation(f, H)
119
+ assert str(p1) == "((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1))"
120
+
121
+ H = f.subgroup(H)
122
+ assert (H.generators, H.relators) == p1
123
+
124
+ f = FpGroup(F, [x**3, y**3, (x*y)**3])
125
+ H = [x*y, x*y**-1]
126
+ p2 = reidemeister_presentation(f, H)
127
+ assert str(p2) == "((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0))"
128
+
129
+ f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3])
130
+ H = [x]
131
+ p3 = reidemeister_presentation(f, H)
132
+ assert str(p3) == "((x_0,), (x_0**4,))"
133
+
134
+ f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2])
135
+ H = [x]
136
+ p4 = reidemeister_presentation(f, H)
137
+ assert str(p4) == "((x_0,), (x_0**6,))"
138
+
139
+ # this presentation can be improved, the most simplified form
140
+ # of presentation is <a, b | a^11, b^2, (a*b)^3, (a^4*b*a^-5*b)^2>
141
+ # See [2] Pg 474 group PSL_2(11)
142
+ # This is the group PSL_2(11)
143
+ F, a, b, c = free_group("a, b, c")
144
+ f = FpGroup(F, [a**11, b**5, c**4, (b*c**2)**2, (a*b*c)**3, (a**4*c**2)**3, b**2*c**-1*b**-1*c, a**4*b**-1*a**-1*b])
145
+ H = [a, b, c**2]
146
+ gens, rels = reidemeister_presentation(f, H)
147
+ assert str(gens) == "(b_1, c_3)"
148
+ assert len(rels) == 18
149
+
150
+
151
+ @slow
152
+ def test_order():
153
+ F, x, y = free_group("x, y")
154
+ f = FpGroup(F, [x**4, y**2, x*y*x**-1*y])
155
+ assert f.order() == 8
156
+
157
+ f = FpGroup(F, [x*y*x**-1*y**-1, y**2])
158
+ assert f.order() is S.Infinity
159
+
160
+ F, a, b, c = free_group("a, b, c")
161
+ f = FpGroup(F, [a**250, b**2, c*b*c**-1*b, c**4, c**-1*a**-1*c*a, a**-1*b**-1*a*b])
162
+ assert f.order() == 2000
163
+
164
+ F, x = free_group("x")
165
+ f = FpGroup(F, [])
166
+ assert f.order() is S.Infinity
167
+
168
+ f = FpGroup(free_group('')[0], [])
169
+ assert f.order() == 1
170
+
171
+ def test_fp_subgroup():
172
+ def _test_subgroup(K, T, S):
173
+ _gens = T(K.generators)
174
+ assert all(elem in S for elem in _gens)
175
+ assert T.is_injective()
176
+ assert T.image().order() == S.order()
177
+ F, x, y = free_group("x, y")
178
+ f = FpGroup(F, [x**4, y**2, x*y*x**-1*y])
179
+ S = FpSubgroup(f, [x*y])
180
+ assert (x*y)**-3 in S
181
+ K, T = f.subgroup([x*y], homomorphism=True)
182
+ assert T(K.generators) == [y*x**-1]
183
+ _test_subgroup(K, T, S)
184
+
185
+ S = FpSubgroup(f, [x**-1*y*x])
186
+ assert x**-1*y**4*x in S
187
+ assert x**-1*y**4*x**2 not in S
188
+ K, T = f.subgroup([x**-1*y*x], homomorphism=True)
189
+ assert T(K.generators[0]**3) == y**3
190
+ _test_subgroup(K, T, S)
191
+
192
+ f = FpGroup(F, [x**3, y**5, (x*y)**2])
193
+ H = [x*y, x**-1*y**-1*x*y*x]
194
+ K, T = f.subgroup(H, homomorphism=True)
195
+ S = FpSubgroup(f, H)
196
+ _test_subgroup(K, T, S)
197
+
198
+ def test_permutation_methods():
199
+ F, x, y = free_group("x, y")
200
+ # DihedralGroup(8)
201
+ G = FpGroup(F, [x**2, y**8, x*y*x**-1*y])
202
+ T = G._to_perm_group()[1]
203
+ assert T.is_isomorphism()
204
+ assert G.center() == [y**4]
205
+
206
+ # DiheadralGroup(4)
207
+ G = FpGroup(F, [x**2, y**4, x*y*x**-1*y])
208
+ S = FpSubgroup(G, G.normal_closure([x]))
209
+ assert x in S
210
+ assert y**-1*x*y in S
211
+
212
+ # Z_5xZ_4
213
+ G = FpGroup(F, [x*y*x**-1*y**-1, y**5, x**4])
214
+ assert G.is_abelian
215
+ assert G.is_solvable
216
+
217
+ # AlternatingGroup(5)
218
+ G = FpGroup(F, [x**3, y**2, (x*y)**5])
219
+ assert not G.is_solvable
220
+
221
+ # AlternatingGroup(4)
222
+ G = FpGroup(F, [x**3, y**2, (x*y)**3])
223
+ assert len(G.derived_series()) == 3
224
+ S = FpSubgroup(G, G.derived_subgroup())
225
+ assert S.order() == 4
226
+
227
+
228
+ def test_simplify_presentation():
229
+ # ref #16083
230
+ G = simplify_presentation(FpGroup(FreeGroup([]), []))
231
+ assert not G.generators
232
+ assert not G.relators
233
+
234
+
235
+ def test_cyclic():
236
+ F, x, y = free_group("x, y")
237
+ f = FpGroup(F, [x*y, x**-1*y**-1*x*y*x])
238
+ assert f.is_cyclic
239
+ f = FpGroup(F, [x*y, x*y**-1])
240
+ assert f.is_cyclic
241
+ f = FpGroup(F, [x**4, y**2, x*y*x**-1*y])
242
+ assert not f.is_cyclic
243
+
244
+
245
+ def test_abelian_invariants():
246
+ F, x, y = free_group("x, y")
247
+ f = FpGroup(F, [x*y, x**-1*y**-1*x*y*x])
248
+ assert f.abelian_invariants() == []
249
+ f = FpGroup(F, [x*y, x*y**-1])
250
+ assert f.abelian_invariants() == [2]
251
+ f = FpGroup(F, [x**4, y**2, x*y*x**-1*y])
252
+ assert f.abelian_invariants() == [2, 4]
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_galois.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test groups defined by the galois module. """
2
+
3
+ from sympy.combinatorics.galois import (
4
+ S4TransitiveSubgroups, S5TransitiveSubgroups, S6TransitiveSubgroups,
5
+ find_transitive_subgroups_of_S6,
6
+ )
7
+ from sympy.combinatorics.homomorphisms import is_isomorphic
8
+ from sympy.combinatorics.named_groups import (
9
+ SymmetricGroup, AlternatingGroup, CyclicGroup,
10
+ )
11
+
12
+
13
+ def test_four_group():
14
+ G = S4TransitiveSubgroups.V.get_perm_group()
15
+ A4 = AlternatingGroup(4)
16
+ assert G.is_subgroup(A4)
17
+ assert G.degree == 4
18
+ assert G.is_transitive()
19
+ assert G.order() == 4
20
+ assert not G.is_cyclic
21
+
22
+
23
+ def test_M20():
24
+ G = S5TransitiveSubgroups.M20.get_perm_group()
25
+ S5 = SymmetricGroup(5)
26
+ A5 = AlternatingGroup(5)
27
+ assert G.is_subgroup(S5)
28
+ assert not G.is_subgroup(A5)
29
+ assert G.degree == 5
30
+ assert G.is_transitive()
31
+ assert G.order() == 20
32
+
33
+
34
+ # Setting this True means that for each of the transitive subgroups of S6,
35
+ # we run a test not only on the fixed representation, but also on one freshly
36
+ # generated by the search procedure.
37
+ INCLUDE_SEARCH_REPS = False
38
+ S6_randomized = {}
39
+ if INCLUDE_SEARCH_REPS:
40
+ S6_randomized = find_transitive_subgroups_of_S6(*list(S6TransitiveSubgroups))
41
+
42
+
43
+ def get_versions_of_S6_subgroup(name):
44
+ vers = [name.get_perm_group()]
45
+ if INCLUDE_SEARCH_REPS:
46
+ vers.append(S6_randomized[name])
47
+ return vers
48
+
49
+
50
+ def test_S6_transitive_subgroups():
51
+ """
52
+ Test enough characteristics to distinguish all 16 transitive subgroups.
53
+ """
54
+ ts = S6TransitiveSubgroups
55
+ A6 = AlternatingGroup(6)
56
+ for name, alt, order, is_isom, not_isom in [
57
+ (ts.C6, False, 6, CyclicGroup(6), None),
58
+ (ts.S3, False, 6, SymmetricGroup(3), None),
59
+ (ts.D6, False, 12, None, None),
60
+ (ts.A4, True, 12, None, None),
61
+ (ts.G18, False, 18, None, None),
62
+ (ts.A4xC2, False, 24, None, SymmetricGroup(4)),
63
+ (ts.S4m, False, 24, SymmetricGroup(4), None),
64
+ (ts.S4p, True, 24, None, None),
65
+ (ts.G36m, False, 36, None, None),
66
+ (ts.G36p, True, 36, None, None),
67
+ (ts.S4xC2, False, 48, None, None),
68
+ (ts.PSL2F5, True, 60, None, None),
69
+ (ts.G72, False, 72, None, None),
70
+ (ts.PGL2F5, False, 120, None, None),
71
+ (ts.A6, True, 360, None, None),
72
+ (ts.S6, False, 720, None, None),
73
+ ]:
74
+ for G in get_versions_of_S6_subgroup(name):
75
+ assert G.is_transitive()
76
+ assert G.degree == 6
77
+ assert G.is_subgroup(A6) is alt
78
+ assert G.order() == order
79
+ if is_isom:
80
+ assert is_isomorphic(G, is_isom)
81
+ if not_isom:
82
+ assert not is_isomorphic(G, not_isom)
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_graycode.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.graycode import (GrayCode, bin_to_gray,
2
+ random_bitstring, get_subset_from_bitstring, graycode_subsets,
3
+ gray_to_bin)
4
+ from sympy.testing.pytest import raises
5
+
6
+ def test_graycode():
7
+ g = GrayCode(2)
8
+ got = []
9
+ for i in g.generate_gray():
10
+ if i.startswith('0'):
11
+ g.skip()
12
+ got.append(i)
13
+ assert got == '00 11 10'.split()
14
+ a = GrayCode(6)
15
+ assert a.current == '0'*6
16
+ assert a.rank == 0
17
+ assert len(list(a.generate_gray())) == 64
18
+ codes = ['011001', '011011', '011010',
19
+ '011110', '011111', '011101', '011100', '010100', '010101', '010111',
20
+ '010110', '010010', '010011', '010001', '010000', '110000', '110001',
21
+ '110011', '110010', '110110', '110111', '110101', '110100', '111100',
22
+ '111101', '111111', '111110', '111010', '111011', '111001', '111000',
23
+ '101000', '101001', '101011', '101010', '101110', '101111', '101101',
24
+ '101100', '100100', '100101', '100111', '100110', '100010', '100011',
25
+ '100001', '100000']
26
+ assert list(a.generate_gray(start='011001')) == codes
27
+ assert list(
28
+ a.generate_gray(rank=GrayCode(6, start='011001').rank)) == codes
29
+ assert a.next().current == '000001'
30
+ assert a.next(2).current == '000011'
31
+ assert a.next(-1).current == '100000'
32
+
33
+ a = GrayCode(5, start='10010')
34
+ assert a.rank == 28
35
+ a = GrayCode(6, start='101000')
36
+ assert a.rank == 48
37
+
38
+ assert GrayCode(6, rank=4).current == '000110'
39
+ assert GrayCode(6, rank=4).rank == 4
40
+ assert [GrayCode(4, start=s).rank for s in
41
+ GrayCode(4).generate_gray()] == [0, 1, 2, 3, 4, 5, 6, 7, 8,
42
+ 9, 10, 11, 12, 13, 14, 15]
43
+ a = GrayCode(15, rank=15)
44
+ assert a.current == '000000000001000'
45
+
46
+ assert bin_to_gray('111') == '100'
47
+
48
+ a = random_bitstring(5)
49
+ assert type(a) is str
50
+ assert len(a) == 5
51
+ assert all(i in ['0', '1'] for i in a)
52
+
53
+ assert get_subset_from_bitstring(
54
+ ['a', 'b', 'c', 'd'], '0011') == ['c', 'd']
55
+ assert get_subset_from_bitstring('abcd', '1001') == ['a', 'd']
56
+ assert list(graycode_subsets(['a', 'b', 'c'])) == \
57
+ [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'],
58
+ ['a', 'c'], ['a']]
59
+
60
+ raises(ValueError, lambda: GrayCode(0))
61
+ raises(ValueError, lambda: GrayCode(2.2))
62
+ raises(ValueError, lambda: GrayCode(2, start=[1, 1, 0]))
63
+ raises(ValueError, lambda: GrayCode(2, rank=2.5))
64
+ raises(ValueError, lambda: get_subset_from_bitstring(['c', 'a', 'c'], '1100'))
65
+ raises(ValueError, lambda: list(GrayCode(3).generate_gray(start="1111")))
66
+
67
+
68
+ def test_live_issue_117():
69
+ assert bin_to_gray('0100') == '0110'
70
+ assert bin_to_gray('0101') == '0111'
71
+ for bits in ('0100', '0101'):
72
+ assert gray_to_bin(bin_to_gray(bits)) == bits
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_numbers.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.group_numbers import (is_nilpotent_number,
2
+ is_abelian_number, is_cyclic_number)
3
+ from sympy.testing.pytest import raises
4
+ from sympy import randprime
5
+
6
+
7
+ def test_is_nilpotent_number():
8
+ assert is_nilpotent_number(21) == False
9
+ assert is_nilpotent_number(randprime(1, 30)**12) == True
10
+ raises(ValueError, lambda: is_nilpotent_number(-5))
11
+
12
+
13
+ def test_is_abelian_number():
14
+ assert is_abelian_number(4) == True
15
+ assert is_abelian_number(randprime(1, 2000)**2) == True
16
+ assert is_abelian_number(randprime(1000, 100000)) == True
17
+ assert is_abelian_number(60) == False
18
+ assert is_abelian_number(24) == False
19
+ raises(ValueError, lambda: is_abelian_number(-5))
20
+
21
+
22
+ def test_is_cyclic_number():
23
+ assert is_cyclic_number(15) == True
24
+ assert is_cyclic_number(randprime(1, 2000)**2) == False
25
+ assert is_cyclic_number(randprime(1000, 100000)) == True
26
+ assert is_cyclic_number(4) == False
27
+ raises(ValueError, lambda: is_cyclic_number(-5))
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_homomorphisms.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics import Permutation
2
+ from sympy.combinatorics.perm_groups import PermutationGroup
3
+ from sympy.combinatorics.homomorphisms import homomorphism, group_isomorphism, is_isomorphic
4
+ from sympy.combinatorics.free_groups import free_group
5
+ from sympy.combinatorics.fp_groups import FpGroup
6
+ from sympy.combinatorics.named_groups import AlternatingGroup, DihedralGroup, CyclicGroup
7
+ from sympy.testing.pytest import raises
8
+
9
+ def test_homomorphism():
10
+ # FpGroup -> PermutationGroup
11
+ F, a, b = free_group("a, b")
12
+ G = FpGroup(F, [a**3, b**3, (a*b)**2])
13
+
14
+ c = Permutation(3)(0, 1, 2)
15
+ d = Permutation(3)(1, 2, 3)
16
+ A = AlternatingGroup(4)
17
+ T = homomorphism(G, A, [a, b], [c, d])
18
+ assert T(a*b**2*a**-1) == c*d**2*c**-1
19
+ assert T.is_isomorphism()
20
+ assert T(T.invert(Permutation(3)(0, 2, 3))) == Permutation(3)(0, 2, 3)
21
+
22
+ T = homomorphism(G, AlternatingGroup(4), G.generators)
23
+ assert T.is_trivial()
24
+ assert T.kernel().order() == G.order()
25
+
26
+ E, e = free_group("e")
27
+ G = FpGroup(E, [e**8])
28
+ P = PermutationGroup([Permutation(0, 1, 2, 3), Permutation(0, 2)])
29
+ T = homomorphism(G, P, [e], [Permutation(0, 1, 2, 3)])
30
+ assert T.image().order() == 4
31
+ assert T(T.invert(Permutation(0, 2)(1, 3))) == Permutation(0, 2)(1, 3)
32
+
33
+ T = homomorphism(E, AlternatingGroup(4), E.generators, [c])
34
+ assert T.invert(c**2) == e**-1 #order(c) == 3 so c**2 == c**-1
35
+
36
+ # FreeGroup -> FreeGroup
37
+ T = homomorphism(F, E, [a], [e])
38
+ assert T(a**-2*b**4*a**2).is_identity
39
+
40
+ # FreeGroup -> FpGroup
41
+ G = FpGroup(F, [a*b*a**-1*b**-1])
42
+ T = homomorphism(F, G, F.generators, G.generators)
43
+ assert T.invert(a**-1*b**-1*a**2) == a*b**-1
44
+
45
+ # PermutationGroup -> PermutationGroup
46
+ D = DihedralGroup(8)
47
+ p = Permutation(0, 1, 2, 3, 4, 5, 6, 7)
48
+ P = PermutationGroup(p)
49
+ T = homomorphism(P, D, [p], [p])
50
+ assert T.is_injective()
51
+ assert not T.is_isomorphism()
52
+ assert T.invert(p**3) == p**3
53
+
54
+ T2 = homomorphism(F, P, [F.generators[0]], P.generators)
55
+ T = T.compose(T2)
56
+ assert T.domain == F
57
+ assert T.codomain == D
58
+ assert T(a*b) == p
59
+
60
+ D3 = DihedralGroup(3)
61
+ T = homomorphism(D3, D3, D3.generators, D3.generators)
62
+ assert T.is_isomorphism()
63
+
64
+
65
+ def test_isomorphisms():
66
+
67
+ F, a, b = free_group("a, b")
68
+ E, c, d = free_group("c, d")
69
+ # Infinite groups with differently ordered relators.
70
+ G = FpGroup(F, [a**2, b**3])
71
+ H = FpGroup(F, [b**3, a**2])
72
+ assert is_isomorphic(G, H)
73
+
74
+ # Trivial Case
75
+ # FpGroup -> FpGroup
76
+ H = FpGroup(F, [a**3, b**3, (a*b)**2])
77
+ F, c, d = free_group("c, d")
78
+ G = FpGroup(F, [c**3, d**3, (c*d)**2])
79
+ check, T = group_isomorphism(G, H)
80
+ assert check
81
+ assert T(c**3*d**2) == a**3*b**2
82
+
83
+ # FpGroup -> PermutationGroup
84
+ # FpGroup is converted to the equivalent isomorphic group.
85
+ F, a, b = free_group("a, b")
86
+ G = FpGroup(F, [a**3, b**3, (a*b)**2])
87
+ H = AlternatingGroup(4)
88
+ check, T = group_isomorphism(G, H)
89
+ assert check
90
+ assert T(b*a*b**-1*a**-1*b**-1) == Permutation(0, 2, 3)
91
+ assert T(b*a*b*a**-1*b**-1) == Permutation(0, 3, 2)
92
+
93
+ # PermutationGroup -> PermutationGroup
94
+ D = DihedralGroup(8)
95
+ p = Permutation(0, 1, 2, 3, 4, 5, 6, 7)
96
+ P = PermutationGroup(p)
97
+ assert not is_isomorphic(D, P)
98
+
99
+ A = CyclicGroup(5)
100
+ B = CyclicGroup(7)
101
+ assert not is_isomorphic(A, B)
102
+
103
+ # Two groups of the same prime order are isomorphic to each other.
104
+ G = FpGroup(F, [a, b**5])
105
+ H = CyclicGroup(5)
106
+ assert G.order() == H.order()
107
+ assert is_isomorphic(G, H)
108
+
109
+
110
+ def test_check_homomorphism():
111
+ a = Permutation(1,2,3,4)
112
+ b = Permutation(1,3)
113
+ G = PermutationGroup([a, b])
114
+ raises(ValueError, lambda: homomorphism(G, G, [a], [a]))
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_named_groups.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.named_groups import (SymmetricGroup, CyclicGroup,
2
+ DihedralGroup, AlternatingGroup,
3
+ AbelianGroup, RubikGroup)
4
+ from sympy.testing.pytest import raises
5
+
6
+
7
+ def test_SymmetricGroup():
8
+ G = SymmetricGroup(5)
9
+ elements = list(G.generate())
10
+ assert (G.generators[0]).size == 5
11
+ assert len(elements) == 120
12
+ assert G.is_solvable is False
13
+ assert G.is_abelian is False
14
+ assert G.is_nilpotent is False
15
+ assert G.is_transitive() is True
16
+ H = SymmetricGroup(1)
17
+ assert H.order() == 1
18
+ L = SymmetricGroup(2)
19
+ assert L.order() == 2
20
+
21
+
22
+ def test_CyclicGroup():
23
+ G = CyclicGroup(10)
24
+ elements = list(G.generate())
25
+ assert len(elements) == 10
26
+ assert (G.derived_subgroup()).order() == 1
27
+ assert G.is_abelian is True
28
+ assert G.is_solvable is True
29
+ assert G.is_nilpotent is True
30
+ H = CyclicGroup(1)
31
+ assert H.order() == 1
32
+ L = CyclicGroup(2)
33
+ assert L.order() == 2
34
+
35
+
36
+ def test_DihedralGroup():
37
+ G = DihedralGroup(6)
38
+ elements = list(G.generate())
39
+ assert len(elements) == 12
40
+ assert G.is_transitive() is True
41
+ assert G.is_abelian is False
42
+ assert G.is_solvable is True
43
+ assert G.is_nilpotent is False
44
+ H = DihedralGroup(1)
45
+ assert H.order() == 2
46
+ L = DihedralGroup(2)
47
+ assert L.order() == 4
48
+ assert L.is_abelian is True
49
+ assert L.is_nilpotent is True
50
+
51
+
52
+ def test_AlternatingGroup():
53
+ G = AlternatingGroup(5)
54
+ elements = list(G.generate())
55
+ assert len(elements) == 60
56
+ assert [perm.is_even for perm in elements] == [True]*60
57
+ H = AlternatingGroup(1)
58
+ assert H.order() == 1
59
+ L = AlternatingGroup(2)
60
+ assert L.order() == 1
61
+
62
+
63
+ def test_AbelianGroup():
64
+ A = AbelianGroup(3, 3, 3)
65
+ assert A.order() == 27
66
+ assert A.is_abelian is True
67
+
68
+
69
+ def test_RubikGroup():
70
+ raises(ValueError, lambda: RubikGroup(1))
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_partitions.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.sorting import ordered, default_sort_key
2
+ from sympy.combinatorics.partitions import (Partition, IntegerPartition,
3
+ RGS_enum, RGS_unrank, RGS_rank,
4
+ random_integer_partition)
5
+ from sympy.testing.pytest import raises
6
+ from sympy.utilities.iterables import partitions
7
+ from sympy.sets.sets import Set, FiniteSet
8
+
9
+
10
+ def test_partition_constructor():
11
+ raises(ValueError, lambda: Partition([1, 1, 2]))
12
+ raises(ValueError, lambda: Partition([1, 2, 3], [2, 3, 4]))
13
+ raises(ValueError, lambda: Partition(1, 2, 3))
14
+ raises(ValueError, lambda: Partition(*list(range(3))))
15
+
16
+ assert Partition([1, 2, 3], [4, 5]) == Partition([4, 5], [1, 2, 3])
17
+ assert Partition({1, 2, 3}, {4, 5}) == Partition([1, 2, 3], [4, 5])
18
+
19
+ a = FiniteSet(1, 2, 3)
20
+ b = FiniteSet(4, 5)
21
+ assert Partition(a, b) == Partition([1, 2, 3], [4, 5])
22
+ assert Partition({a, b}) == Partition(FiniteSet(a, b))
23
+ assert Partition({a, b}) != Partition(a, b)
24
+
25
+ def test_partition():
26
+ from sympy.abc import x
27
+
28
+ a = Partition([1, 2, 3], [4])
29
+ b = Partition([1, 2], [3, 4])
30
+ c = Partition([x])
31
+ l = [a, b, c]
32
+ l.sort(key=default_sort_key)
33
+ assert l == [c, a, b]
34
+ l.sort(key=lambda w: default_sort_key(w, order='rev-lex'))
35
+ assert l == [c, a, b]
36
+
37
+ assert (a == b) is False
38
+ assert a <= b
39
+ assert (a > b) is False
40
+ assert a != b
41
+ assert a < b
42
+
43
+ assert (a + 2).partition == [[1, 2], [3, 4]]
44
+ assert (b - 1).partition == [[1, 2, 4], [3]]
45
+
46
+ assert (a - 1).partition == [[1, 2, 3, 4]]
47
+ assert (a + 1).partition == [[1, 2, 4], [3]]
48
+ assert (b + 1).partition == [[1, 2], [3], [4]]
49
+
50
+ assert a.rank == 1
51
+ assert b.rank == 3
52
+
53
+ assert a.RGS == (0, 0, 0, 1)
54
+ assert b.RGS == (0, 0, 1, 1)
55
+
56
+
57
+ def test_integer_partition():
58
+ # no zeros in partition
59
+ raises(ValueError, lambda: IntegerPartition(list(range(3))))
60
+ # check fails since 1 + 2 != 100
61
+ raises(ValueError, lambda: IntegerPartition(100, list(range(1, 3))))
62
+ a = IntegerPartition(8, [1, 3, 4])
63
+ b = a.next_lex()
64
+ c = IntegerPartition([1, 3, 4])
65
+ d = IntegerPartition(8, {1: 3, 3: 1, 2: 1})
66
+ assert a == c
67
+ assert a.integer == d.integer
68
+ assert a.conjugate == [3, 2, 2, 1]
69
+ assert (a == b) is False
70
+ assert a <= b
71
+ assert (a > b) is False
72
+ assert a != b
73
+
74
+ for i in range(1, 11):
75
+ next = set()
76
+ prev = set()
77
+ a = IntegerPartition([i])
78
+ ans = {IntegerPartition(p) for p in partitions(i)}
79
+ n = len(ans)
80
+ for j in range(n):
81
+ next.add(a)
82
+ a = a.next_lex()
83
+ IntegerPartition(i, a.partition) # check it by giving i
84
+ for j in range(n):
85
+ prev.add(a)
86
+ a = a.prev_lex()
87
+ IntegerPartition(i, a.partition) # check it by giving i
88
+ assert next == ans
89
+ assert prev == ans
90
+
91
+ assert IntegerPartition([1, 2, 3]).as_ferrers() == '###\n##\n#'
92
+ assert IntegerPartition([1, 1, 3]).as_ferrers('o') == 'ooo\no\no'
93
+ assert str(IntegerPartition([1, 1, 3])) == '[3, 1, 1]'
94
+ assert IntegerPartition([1, 1, 3]).partition == [3, 1, 1]
95
+
96
+ raises(ValueError, lambda: random_integer_partition(-1))
97
+ assert random_integer_partition(1) == [1]
98
+ assert random_integer_partition(10, seed=[1, 3, 2, 1, 5, 1]
99
+ ) == [5, 2, 1, 1, 1]
100
+
101
+
102
+ def test_rgs():
103
+ raises(ValueError, lambda: RGS_unrank(-1, 3))
104
+ raises(ValueError, lambda: RGS_unrank(3, 0))
105
+ raises(ValueError, lambda: RGS_unrank(10, 1))
106
+
107
+ raises(ValueError, lambda: Partition.from_rgs(list(range(3)), list(range(2))))
108
+ raises(ValueError, lambda: Partition.from_rgs(list(range(1, 3)), list(range(2))))
109
+ assert RGS_enum(-1) == 0
110
+ assert RGS_enum(1) == 1
111
+ assert RGS_unrank(7, 5) == [0, 0, 1, 0, 2]
112
+ assert RGS_unrank(23, 14) == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 2]
113
+ assert RGS_rank(RGS_unrank(40, 100)) == 40
114
+
115
+ def test_ordered_partition_9608():
116
+ a = Partition([1, 2, 3], [4])
117
+ b = Partition([1, 2], [3, 4])
118
+ assert list(ordered([a,b], Set._infimum_key))
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_perm_groups.py ADDED
@@ -0,0 +1,1243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.containers import Tuple
2
+ from sympy.combinatorics.generators import rubik_cube_generators
3
+ from sympy.combinatorics.homomorphisms import is_isomorphic
4
+ from sympy.combinatorics.named_groups import SymmetricGroup, CyclicGroup,\
5
+ DihedralGroup, AlternatingGroup, AbelianGroup, RubikGroup
6
+ from sympy.combinatorics.perm_groups import (PermutationGroup,
7
+ _orbit_transversal, Coset, SymmetricPermutationGroup)
8
+ from sympy.combinatorics.permutations import Permutation
9
+ from sympy.combinatorics.polyhedron import tetrahedron as Tetra, cube
10
+ from sympy.combinatorics.testutil import _verify_bsgs, _verify_centralizer,\
11
+ _verify_normal_closure
12
+ from sympy.testing.pytest import skip, XFAIL, slow
13
+
14
+ rmul = Permutation.rmul
15
+
16
+
17
+ def test_has():
18
+ a = Permutation([1, 0])
19
+ G = PermutationGroup([a])
20
+ assert G.is_abelian
21
+ a = Permutation([2, 0, 1])
22
+ b = Permutation([2, 1, 0])
23
+ G = PermutationGroup([a, b])
24
+ assert not G.is_abelian
25
+
26
+ G = PermutationGroup([a])
27
+ assert G.has(a)
28
+ assert not G.has(b)
29
+
30
+ a = Permutation([2, 0, 1, 3, 4, 5])
31
+ b = Permutation([0, 2, 1, 3, 4])
32
+ assert PermutationGroup(a, b).degree == \
33
+ PermutationGroup(a, b).degree == 6
34
+
35
+ g = PermutationGroup(Permutation(0, 2, 1))
36
+ assert Tuple(1, g).has(g)
37
+
38
+
39
+ def test_generate():
40
+ a = Permutation([1, 0])
41
+ g = list(PermutationGroup([a]).generate())
42
+ assert g == [Permutation([0, 1]), Permutation([1, 0])]
43
+ assert len(list(PermutationGroup(Permutation((0, 1))).generate())) == 1
44
+ g = PermutationGroup([a]).generate(method='dimino')
45
+ assert list(g) == [Permutation([0, 1]), Permutation([1, 0])]
46
+ a = Permutation([2, 0, 1])
47
+ b = Permutation([2, 1, 0])
48
+ G = PermutationGroup([a, b])
49
+ g = G.generate()
50
+ v1 = [p.array_form for p in list(g)]
51
+ v1.sort()
52
+ assert v1 == [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0,
53
+ 1], [2, 1, 0]]
54
+ v2 = list(G.generate(method='dimino', af=True))
55
+ assert v1 == sorted(v2)
56
+ a = Permutation([2, 0, 1, 3, 4, 5])
57
+ b = Permutation([2, 1, 3, 4, 5, 0])
58
+ g = PermutationGroup([a, b]).generate(af=True)
59
+ assert len(list(g)) == 360
60
+
61
+
62
+ def test_order():
63
+ a = Permutation([2, 0, 1, 3, 4, 5, 6, 7, 8, 9])
64
+ b = Permutation([2, 1, 3, 4, 5, 6, 7, 8, 9, 0])
65
+ g = PermutationGroup([a, b])
66
+ assert g.order() == 1814400
67
+ assert PermutationGroup().order() == 1
68
+
69
+
70
+ def test_equality():
71
+ p_1 = Permutation(0, 1, 3)
72
+ p_2 = Permutation(0, 2, 3)
73
+ p_3 = Permutation(0, 1, 2)
74
+ p_4 = Permutation(0, 1, 3)
75
+ g_1 = PermutationGroup(p_1, p_2)
76
+ g_2 = PermutationGroup(p_3, p_4)
77
+ g_3 = PermutationGroup(p_2, p_1)
78
+ g_4 = PermutationGroup(p_1, p_2)
79
+
80
+ assert g_1 != g_2
81
+ assert g_1.generators != g_2.generators
82
+ assert g_1.equals(g_2)
83
+ assert g_1 != g_3
84
+ assert g_1.equals(g_3)
85
+ assert g_1 == g_4
86
+
87
+
88
+ def test_stabilizer():
89
+ S = SymmetricGroup(2)
90
+ H = S.stabilizer(0)
91
+ assert H.generators == [Permutation(1)]
92
+ a = Permutation([2, 0, 1, 3, 4, 5])
93
+ b = Permutation([2, 1, 3, 4, 5, 0])
94
+ G = PermutationGroup([a, b])
95
+ G0 = G.stabilizer(0)
96
+ assert G0.order() == 60
97
+
98
+ gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]]
99
+ gens = [Permutation(p) for p in gens_cube]
100
+ G = PermutationGroup(gens)
101
+ G2 = G.stabilizer(2)
102
+ assert G2.order() == 6
103
+ G2_1 = G2.stabilizer(1)
104
+ v = list(G2_1.generate(af=True))
105
+ assert v == [[0, 1, 2, 3, 4, 5, 6, 7], [3, 1, 2, 0, 7, 5, 6, 4]]
106
+
107
+ gens = (
108
+ (1, 2, 0, 4, 5, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19),
109
+ (0, 1, 2, 3, 4, 5, 19, 6, 8, 9, 10, 11, 12, 13, 14,
110
+ 15, 16, 7, 17, 18),
111
+ (0, 1, 2, 3, 4, 5, 6, 7, 9, 18, 16, 11, 12, 13, 14, 15, 8, 17, 10, 19))
112
+ gens = [Permutation(p) for p in gens]
113
+ G = PermutationGroup(gens)
114
+ G2 = G.stabilizer(2)
115
+ assert G2.order() == 181440
116
+ S = SymmetricGroup(3)
117
+ assert [G.order() for G in S.basic_stabilizers] == [6, 2]
118
+
119
+
120
+ def test_center():
121
+ # the center of the dihedral group D_n is of order 2 for even n
122
+ for i in (4, 6, 10):
123
+ D = DihedralGroup(i)
124
+ assert (D.center()).order() == 2
125
+ # the center of the dihedral group D_n is of order 1 for odd n>2
126
+ for i in (3, 5, 7):
127
+ D = DihedralGroup(i)
128
+ assert (D.center()).order() == 1
129
+ # the center of an abelian group is the group itself
130
+ for i in (2, 3, 5):
131
+ for j in (1, 5, 7):
132
+ for k in (1, 1, 11):
133
+ G = AbelianGroup(i, j, k)
134
+ assert G.center().is_subgroup(G)
135
+ # the center of a nonabelian simple group is trivial
136
+ for i in(1, 5, 9):
137
+ A = AlternatingGroup(i)
138
+ assert (A.center()).order() == 1
139
+ # brute-force verifications
140
+ D = DihedralGroup(5)
141
+ A = AlternatingGroup(3)
142
+ C = CyclicGroup(4)
143
+ G.is_subgroup(D*A*C)
144
+ assert _verify_centralizer(G, G)
145
+
146
+
147
+ def test_centralizer():
148
+ # the centralizer of the trivial group is the entire group
149
+ S = SymmetricGroup(2)
150
+ assert S.centralizer(Permutation(list(range(2)))).is_subgroup(S)
151
+ A = AlternatingGroup(5)
152
+ assert A.centralizer(Permutation(list(range(5)))).is_subgroup(A)
153
+ # a centralizer in the trivial group is the trivial group itself
154
+ triv = PermutationGroup([Permutation([0, 1, 2, 3])])
155
+ D = DihedralGroup(4)
156
+ assert triv.centralizer(D).is_subgroup(triv)
157
+ # brute-force verifications for centralizers of groups
158
+ for i in (4, 5, 6):
159
+ S = SymmetricGroup(i)
160
+ A = AlternatingGroup(i)
161
+ C = CyclicGroup(i)
162
+ D = DihedralGroup(i)
163
+ for gp in (S, A, C, D):
164
+ for gp2 in (S, A, C, D):
165
+ if not gp2.is_subgroup(gp):
166
+ assert _verify_centralizer(gp, gp2)
167
+ # verify the centralizer for all elements of several groups
168
+ S = SymmetricGroup(5)
169
+ elements = list(S.generate_dimino())
170
+ for element in elements:
171
+ assert _verify_centralizer(S, element)
172
+ A = AlternatingGroup(5)
173
+ elements = list(A.generate_dimino())
174
+ for element in elements:
175
+ assert _verify_centralizer(A, element)
176
+ D = DihedralGroup(7)
177
+ elements = list(D.generate_dimino())
178
+ for element in elements:
179
+ assert _verify_centralizer(D, element)
180
+ # verify centralizers of small groups within small groups
181
+ small = []
182
+ for i in (1, 2, 3):
183
+ small.append(SymmetricGroup(i))
184
+ small.append(AlternatingGroup(i))
185
+ small.append(DihedralGroup(i))
186
+ small.append(CyclicGroup(i))
187
+ for gp in small:
188
+ for gp2 in small:
189
+ if gp.degree == gp2.degree:
190
+ assert _verify_centralizer(gp, gp2)
191
+
192
+
193
+ def test_coset_rank():
194
+ gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]]
195
+ gens = [Permutation(p) for p in gens_cube]
196
+ G = PermutationGroup(gens)
197
+ i = 0
198
+ for h in G.generate(af=True):
199
+ rk = G.coset_rank(h)
200
+ assert rk == i
201
+ h1 = G.coset_unrank(rk, af=True)
202
+ assert h == h1
203
+ i += 1
204
+ assert G.coset_unrank(48) is None
205
+ assert G.coset_unrank(G.coset_rank(gens[0])) == gens[0]
206
+
207
+
208
+ def test_coset_factor():
209
+ a = Permutation([0, 2, 1])
210
+ G = PermutationGroup([a])
211
+ c = Permutation([2, 1, 0])
212
+ assert not G.coset_factor(c)
213
+ assert G.coset_rank(c) is None
214
+
215
+ a = Permutation([2, 0, 1, 3, 4, 5])
216
+ b = Permutation([2, 1, 3, 4, 5, 0])
217
+ g = PermutationGroup([a, b])
218
+ assert g.order() == 360
219
+ d = Permutation([1, 0, 2, 3, 4, 5])
220
+ assert not g.coset_factor(d.array_form)
221
+ assert not g.contains(d)
222
+ assert Permutation(2) in G
223
+ c = Permutation([1, 0, 2, 3, 5, 4])
224
+ v = g.coset_factor(c, True)
225
+ tr = g.basic_transversals
226
+ p = Permutation.rmul(*[tr[i][v[i]] for i in range(len(g.base))])
227
+ assert p == c
228
+ v = g.coset_factor(c)
229
+ p = Permutation.rmul(*v)
230
+ assert p == c
231
+ assert g.contains(c)
232
+ G = PermutationGroup([Permutation([2, 1, 0])])
233
+ p = Permutation([1, 0, 2])
234
+ assert G.coset_factor(p) == []
235
+
236
+
237
+ def test_orbits():
238
+ a = Permutation([2, 0, 1])
239
+ b = Permutation([2, 1, 0])
240
+ g = PermutationGroup([a, b])
241
+ assert g.orbit(0) == {0, 1, 2}
242
+ assert g.orbits() == [{0, 1, 2}]
243
+ assert g.is_transitive() and g.is_transitive(strict=False)
244
+ assert g.orbit_transversal(0) == \
245
+ [Permutation(
246
+ [0, 1, 2]), Permutation([2, 0, 1]), Permutation([1, 2, 0])]
247
+ assert g.orbit_transversal(0, True) == \
248
+ [(0, Permutation([0, 1, 2])), (2, Permutation([2, 0, 1])),
249
+ (1, Permutation([1, 2, 0]))]
250
+
251
+ G = DihedralGroup(6)
252
+ transversal, slps = _orbit_transversal(G.degree, G.generators, 0, True, slp=True)
253
+ for i, t in transversal:
254
+ slp = slps[i]
255
+ w = G.identity
256
+ for s in slp:
257
+ w = G.generators[s]*w
258
+ assert w == t
259
+
260
+ a = Permutation(list(range(1, 100)) + [0])
261
+ G = PermutationGroup([a])
262
+ assert [min(o) for o in G.orbits()] == [0]
263
+ G = PermutationGroup(rubik_cube_generators())
264
+ assert [min(o) for o in G.orbits()] == [0, 1]
265
+ assert not G.is_transitive() and not G.is_transitive(strict=False)
266
+ G = PermutationGroup([Permutation(0, 1, 3), Permutation(3)(0, 1)])
267
+ assert not G.is_transitive() and G.is_transitive(strict=False)
268
+ assert PermutationGroup(
269
+ Permutation(3)).is_transitive(strict=False) is False
270
+
271
+
272
+ def test_is_normal():
273
+ gens_s5 = [Permutation(p) for p in [[1, 2, 3, 4, 0], [2, 1, 4, 0, 3]]]
274
+ G1 = PermutationGroup(gens_s5)
275
+ assert G1.order() == 120
276
+ gens_a5 = [Permutation(p) for p in [[1, 0, 3, 2, 4], [2, 1, 4, 3, 0]]]
277
+ G2 = PermutationGroup(gens_a5)
278
+ assert G2.order() == 60
279
+ assert G2.is_normal(G1)
280
+ gens3 = [Permutation(p) for p in [[2, 1, 3, 0, 4], [1, 2, 0, 3, 4]]]
281
+ G3 = PermutationGroup(gens3)
282
+ assert not G3.is_normal(G1)
283
+ assert G3.order() == 12
284
+ G4 = G1.normal_closure(G3.generators)
285
+ assert G4.order() == 60
286
+ gens5 = [Permutation(p) for p in [[1, 2, 3, 0, 4], [1, 2, 0, 3, 4]]]
287
+ G5 = PermutationGroup(gens5)
288
+ assert G5.order() == 24
289
+ G6 = G1.normal_closure(G5.generators)
290
+ assert G6.order() == 120
291
+ assert G1.is_subgroup(G6)
292
+ assert not G1.is_subgroup(G4)
293
+ assert G2.is_subgroup(G4)
294
+ I5 = PermutationGroup(Permutation(4))
295
+ assert I5.is_normal(G5)
296
+ assert I5.is_normal(G6, strict=False)
297
+ p1 = Permutation([1, 0, 2, 3, 4])
298
+ p2 = Permutation([0, 1, 2, 4, 3])
299
+ p3 = Permutation([3, 4, 2, 1, 0])
300
+ id_ = Permutation([0, 1, 2, 3, 4])
301
+ H = PermutationGroup([p1, p3])
302
+ H_n1 = PermutationGroup([p1, p2])
303
+ H_n2_1 = PermutationGroup(p1)
304
+ H_n2_2 = PermutationGroup(p2)
305
+ H_id = PermutationGroup(id_)
306
+ assert H_n1.is_normal(H)
307
+ assert H_n2_1.is_normal(H_n1)
308
+ assert H_n2_2.is_normal(H_n1)
309
+ assert H_id.is_normal(H_n2_1)
310
+ assert H_id.is_normal(H_n1)
311
+ assert H_id.is_normal(H)
312
+ assert not H_n2_1.is_normal(H)
313
+ assert not H_n2_2.is_normal(H)
314
+
315
+
316
+ def test_eq():
317
+ a = [[1, 2, 0, 3, 4, 5], [1, 0, 2, 3, 4, 5], [2, 1, 0, 3, 4, 5], [
318
+ 1, 2, 0, 3, 4, 5]]
319
+ a = [Permutation(p) for p in a + [[1, 2, 3, 4, 5, 0]]]
320
+ g = Permutation([1, 2, 3, 4, 5, 0])
321
+ G1, G2, G3 = [PermutationGroup(x) for x in [a[:2], a[2:4], [g, g**2]]]
322
+ assert G1.order() == G2.order() == G3.order() == 6
323
+ assert G1.is_subgroup(G2)
324
+ assert not G1.is_subgroup(G3)
325
+ G4 = PermutationGroup([Permutation([0, 1])])
326
+ assert not G1.is_subgroup(G4)
327
+ assert G4.is_subgroup(G1, 0)
328
+ assert PermutationGroup(g, g).is_subgroup(PermutationGroup(g))
329
+ assert SymmetricGroup(3).is_subgroup(SymmetricGroup(4), 0)
330
+ assert SymmetricGroup(3).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0)
331
+ assert not CyclicGroup(5).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0)
332
+ assert CyclicGroup(3).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0)
333
+
334
+
335
+ def test_derived_subgroup():
336
+ a = Permutation([1, 0, 2, 4, 3])
337
+ b = Permutation([0, 1, 3, 2, 4])
338
+ G = PermutationGroup([a, b])
339
+ C = G.derived_subgroup()
340
+ assert C.order() == 3
341
+ assert C.is_normal(G)
342
+ assert C.is_subgroup(G, 0)
343
+ assert not G.is_subgroup(C, 0)
344
+ gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]]
345
+ gens = [Permutation(p) for p in gens_cube]
346
+ G = PermutationGroup(gens)
347
+ C = G.derived_subgroup()
348
+ assert C.order() == 12
349
+
350
+
351
+ def test_is_solvable():
352
+ a = Permutation([1, 2, 0])
353
+ b = Permutation([1, 0, 2])
354
+ G = PermutationGroup([a, b])
355
+ assert G.is_solvable
356
+ G = PermutationGroup([a])
357
+ assert G.is_solvable
358
+ a = Permutation([1, 2, 3, 4, 0])
359
+ b = Permutation([1, 0, 2, 3, 4])
360
+ G = PermutationGroup([a, b])
361
+ assert not G.is_solvable
362
+ P = SymmetricGroup(10)
363
+ S = P.sylow_subgroup(3)
364
+ assert S.is_solvable
365
+
366
+ def test_rubik1():
367
+ gens = rubik_cube_generators()
368
+ gens1 = [gens[-1]] + [p**2 for p in gens[1:]]
369
+ G1 = PermutationGroup(gens1)
370
+ assert G1.order() == 19508428800
371
+ gens2 = [p**2 for p in gens]
372
+ G2 = PermutationGroup(gens2)
373
+ assert G2.order() == 663552
374
+ assert G2.is_subgroup(G1, 0)
375
+ C1 = G1.derived_subgroup()
376
+ assert C1.order() == 4877107200
377
+ assert C1.is_subgroup(G1, 0)
378
+ assert not G2.is_subgroup(C1, 0)
379
+
380
+ G = RubikGroup(2)
381
+ assert G.order() == 3674160
382
+
383
+
384
+ @XFAIL
385
+ def test_rubik():
386
+ skip('takes too much time')
387
+ G = PermutationGroup(rubik_cube_generators())
388
+ assert G.order() == 43252003274489856000
389
+ G1 = PermutationGroup(G[:3])
390
+ assert G1.order() == 170659735142400
391
+ assert not G1.is_normal(G)
392
+ G2 = G.normal_closure(G1.generators)
393
+ assert G2.is_subgroup(G)
394
+
395
+
396
+ def test_direct_product():
397
+ C = CyclicGroup(4)
398
+ D = DihedralGroup(4)
399
+ G = C*C*C
400
+ assert G.order() == 64
401
+ assert G.degree == 12
402
+ assert len(G.orbits()) == 3
403
+ assert G.is_abelian is True
404
+ H = D*C
405
+ assert H.order() == 32
406
+ assert H.is_abelian is False
407
+
408
+
409
+ def test_orbit_rep():
410
+ G = DihedralGroup(6)
411
+ assert G.orbit_rep(1, 3) in [Permutation([2, 3, 4, 5, 0, 1]),
412
+ Permutation([4, 3, 2, 1, 0, 5])]
413
+ H = CyclicGroup(4)*G
414
+ assert H.orbit_rep(1, 5) is False
415
+
416
+
417
+ def test_schreier_vector():
418
+ G = CyclicGroup(50)
419
+ v = [0]*50
420
+ v[23] = -1
421
+ assert G.schreier_vector(23) == v
422
+ H = DihedralGroup(8)
423
+ assert H.schreier_vector(2) == [0, 1, -1, 0, 0, 1, 0, 0]
424
+ L = SymmetricGroup(4)
425
+ assert L.schreier_vector(1) == [1, -1, 0, 0]
426
+
427
+
428
+ def test_random_pr():
429
+ D = DihedralGroup(6)
430
+ r = 11
431
+ n = 3
432
+ _random_prec_n = {}
433
+ _random_prec_n[0] = {'s': 7, 't': 3, 'x': 2, 'e': -1}
434
+ _random_prec_n[1] = {'s': 5, 't': 5, 'x': 1, 'e': -1}
435
+ _random_prec_n[2] = {'s': 3, 't': 4, 'x': 2, 'e': 1}
436
+ D._random_pr_init(r, n, _random_prec_n=_random_prec_n)
437
+ assert D._random_gens[11] == [0, 1, 2, 3, 4, 5]
438
+ _random_prec = {'s': 2, 't': 9, 'x': 1, 'e': -1}
439
+ assert D.random_pr(_random_prec=_random_prec) == \
440
+ Permutation([0, 5, 4, 3, 2, 1])
441
+
442
+
443
+ def test_is_alt_sym():
444
+ G = DihedralGroup(10)
445
+ assert G.is_alt_sym() is False
446
+ assert G._eval_is_alt_sym_naive() is False
447
+ assert G._eval_is_alt_sym_naive(only_alt=True) is False
448
+ assert G._eval_is_alt_sym_naive(only_sym=True) is False
449
+
450
+ S = SymmetricGroup(10)
451
+ assert S._eval_is_alt_sym_naive() is True
452
+ assert S._eval_is_alt_sym_naive(only_alt=True) is False
453
+ assert S._eval_is_alt_sym_naive(only_sym=True) is True
454
+
455
+ N_eps = 10
456
+ _random_prec = {'N_eps': N_eps,
457
+ 0: Permutation([[2], [1, 4], [0, 6, 7, 8, 9, 3, 5]]),
458
+ 1: Permutation([[1, 8, 7, 6, 3, 5, 2, 9], [0, 4]]),
459
+ 2: Permutation([[5, 8], [4, 7], [0, 1, 2, 3, 6, 9]]),
460
+ 3: Permutation([[3], [0, 8, 2, 7, 4, 1, 6, 9, 5]]),
461
+ 4: Permutation([[8], [4, 7, 9], [3, 6], [0, 5, 1, 2]]),
462
+ 5: Permutation([[6], [0, 2, 4, 5, 1, 8, 3, 9, 7]]),
463
+ 6: Permutation([[6, 9, 8], [4, 5], [1, 3, 7], [0, 2]]),
464
+ 7: Permutation([[4], [0, 2, 9, 1, 3, 8, 6, 5, 7]]),
465
+ 8: Permutation([[1, 5, 6, 3], [0, 2, 7, 8, 4, 9]]),
466
+ 9: Permutation([[8], [6, 7], [2, 3, 4, 5], [0, 1, 9]])}
467
+ assert S.is_alt_sym(_random_prec=_random_prec) is True
468
+
469
+ A = AlternatingGroup(10)
470
+ assert A._eval_is_alt_sym_naive() is True
471
+ assert A._eval_is_alt_sym_naive(only_alt=True) is True
472
+ assert A._eval_is_alt_sym_naive(only_sym=True) is False
473
+
474
+ _random_prec = {'N_eps': N_eps,
475
+ 0: Permutation([[1, 6, 4, 2, 7, 8, 5, 9, 3], [0]]),
476
+ 1: Permutation([[1], [0, 5, 8, 4, 9, 2, 3, 6, 7]]),
477
+ 2: Permutation([[1, 9, 8, 3, 2, 5], [0, 6, 7, 4]]),
478
+ 3: Permutation([[6, 8, 9], [4, 5], [1, 3, 7, 2], [0]]),
479
+ 4: Permutation([[8], [5], [4], [2, 6, 9, 3], [1], [0, 7]]),
480
+ 5: Permutation([[3, 6], [0, 8, 1, 7, 5, 9, 4, 2]]),
481
+ 6: Permutation([[5], [2, 9], [1, 8, 3], [0, 4, 7, 6]]),
482
+ 7: Permutation([[1, 8, 4, 7, 2, 3], [0, 6, 9, 5]]),
483
+ 8: Permutation([[5, 8, 7], [3], [1, 4, 2, 6], [0, 9]]),
484
+ 9: Permutation([[4, 9, 6], [3, 8], [1, 2], [0, 5, 7]])}
485
+ assert A.is_alt_sym(_random_prec=_random_prec) is False
486
+
487
+ G = PermutationGroup(
488
+ Permutation(1, 3, size=8)(0, 2, 4, 6),
489
+ Permutation(5, 7, size=8)(0, 2, 4, 6))
490
+ assert G.is_alt_sym() is False
491
+
492
+ # Tests for monte-carlo c_n parameter setting, and which guarantees
493
+ # to give False.
494
+ G = DihedralGroup(10)
495
+ assert G._eval_is_alt_sym_monte_carlo() is False
496
+ G = DihedralGroup(20)
497
+ assert G._eval_is_alt_sym_monte_carlo() is False
498
+
499
+ # A dry-running test to check if it looks up for the updated cache.
500
+ G = DihedralGroup(6)
501
+ G.is_alt_sym()
502
+ assert G.is_alt_sym() is False
503
+
504
+
505
+ def test_minimal_block():
506
+ D = DihedralGroup(6)
507
+ block_system = D.minimal_block([0, 3])
508
+ for i in range(3):
509
+ assert block_system[i] == block_system[i + 3]
510
+ S = SymmetricGroup(6)
511
+ assert S.minimal_block([0, 1]) == [0, 0, 0, 0, 0, 0]
512
+
513
+ assert Tetra.pgroup.minimal_block([0, 1]) == [0, 0, 0, 0]
514
+
515
+ P1 = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5))
516
+ P2 = PermutationGroup(Permutation(0, 1, 2, 3, 4, 5), Permutation(1, 5)(2, 4))
517
+ assert P1.minimal_block([0, 2]) == [0, 1, 0, 1, 0, 1]
518
+ assert P2.minimal_block([0, 2]) == [0, 1, 0, 1, 0, 1]
519
+
520
+
521
+ def test_minimal_blocks():
522
+ P = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5))
523
+ assert P.minimal_blocks() == [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]]
524
+
525
+ P = SymmetricGroup(5)
526
+ assert P.minimal_blocks() == [[0]*5]
527
+
528
+ P = PermutationGroup(Permutation(0, 3))
529
+ assert P.minimal_blocks() is False
530
+
531
+
532
+ def test_max_div():
533
+ S = SymmetricGroup(10)
534
+ assert S.max_div == 5
535
+
536
+
537
+ def test_is_primitive():
538
+ S = SymmetricGroup(5)
539
+ assert S.is_primitive() is True
540
+ C = CyclicGroup(7)
541
+ assert C.is_primitive() is True
542
+
543
+ a = Permutation(0, 1, 2, size=6)
544
+ b = Permutation(3, 4, 5, size=6)
545
+ G = PermutationGroup(a, b)
546
+ assert G.is_primitive() is False
547
+
548
+
549
+ def test_random_stab():
550
+ S = SymmetricGroup(5)
551
+ _random_el = Permutation([1, 3, 2, 0, 4])
552
+ _random_prec = {'rand': _random_el}
553
+ g = S.random_stab(2, _random_prec=_random_prec)
554
+ assert g == Permutation([1, 3, 2, 0, 4])
555
+ h = S.random_stab(1)
556
+ assert h(1) == 1
557
+
558
+
559
+ def test_transitivity_degree():
560
+ perm = Permutation([1, 2, 0])
561
+ C = PermutationGroup([perm])
562
+ assert C.transitivity_degree == 1
563
+ gen1 = Permutation([1, 2, 0, 3, 4])
564
+ gen2 = Permutation([1, 2, 3, 4, 0])
565
+ # alternating group of degree 5
566
+ Alt = PermutationGroup([gen1, gen2])
567
+ assert Alt.transitivity_degree == 3
568
+
569
+
570
+ def test_schreier_sims_random():
571
+ assert sorted(Tetra.pgroup.base) == [0, 1]
572
+
573
+ S = SymmetricGroup(3)
574
+ base = [0, 1]
575
+ strong_gens = [Permutation([1, 2, 0]), Permutation([1, 0, 2]),
576
+ Permutation([0, 2, 1])]
577
+ assert S.schreier_sims_random(base, strong_gens, 5) == (base, strong_gens)
578
+ D = DihedralGroup(3)
579
+ _random_prec = {'g': [Permutation([2, 0, 1]), Permutation([1, 2, 0]),
580
+ Permutation([1, 0, 2])]}
581
+ base = [0, 1]
582
+ strong_gens = [Permutation([1, 2, 0]), Permutation([2, 1, 0]),
583
+ Permutation([0, 2, 1])]
584
+ assert D.schreier_sims_random([], D.generators, 2,
585
+ _random_prec=_random_prec) == (base, strong_gens)
586
+
587
+
588
+ def test_baseswap():
589
+ S = SymmetricGroup(4)
590
+ S.schreier_sims()
591
+ base = S.base
592
+ strong_gens = S.strong_gens
593
+ assert base == [0, 1, 2]
594
+ deterministic = S.baseswap(base, strong_gens, 1, randomized=False)
595
+ randomized = S.baseswap(base, strong_gens, 1)
596
+ assert deterministic[0] == [0, 2, 1]
597
+ assert _verify_bsgs(S, deterministic[0], deterministic[1]) is True
598
+ assert randomized[0] == [0, 2, 1]
599
+ assert _verify_bsgs(S, randomized[0], randomized[1]) is True
600
+
601
+
602
+ def test_schreier_sims_incremental():
603
+ identity = Permutation([0, 1, 2, 3, 4])
604
+ TrivialGroup = PermutationGroup([identity])
605
+ base, strong_gens = TrivialGroup.schreier_sims_incremental(base=[0, 1, 2])
606
+ assert _verify_bsgs(TrivialGroup, base, strong_gens) is True
607
+ S = SymmetricGroup(5)
608
+ base, strong_gens = S.schreier_sims_incremental(base=[0, 1, 2])
609
+ assert _verify_bsgs(S, base, strong_gens) is True
610
+ D = DihedralGroup(2)
611
+ base, strong_gens = D.schreier_sims_incremental(base=[1])
612
+ assert _verify_bsgs(D, base, strong_gens) is True
613
+ A = AlternatingGroup(7)
614
+ gens = A.generators[:]
615
+ gen0 = gens[0]
616
+ gen1 = gens[1]
617
+ gen1 = rmul(gen1, ~gen0)
618
+ gen0 = rmul(gen0, gen1)
619
+ gen1 = rmul(gen0, gen1)
620
+ base, strong_gens = A.schreier_sims_incremental(base=[0, 1], gens=gens)
621
+ assert _verify_bsgs(A, base, strong_gens) is True
622
+ C = CyclicGroup(11)
623
+ gen = C.generators[0]
624
+ base, strong_gens = C.schreier_sims_incremental(gens=[gen**3])
625
+ assert _verify_bsgs(C, base, strong_gens) is True
626
+
627
+
628
+ def _subgroup_search(i, j, k):
629
+ prop_true = lambda x: True
630
+ prop_fix_points = lambda x: [x(point) for point in points] == points
631
+ prop_comm_g = lambda x: rmul(x, g) == rmul(g, x)
632
+ prop_even = lambda x: x.is_even
633
+ for i in range(i, j, k):
634
+ S = SymmetricGroup(i)
635
+ A = AlternatingGroup(i)
636
+ C = CyclicGroup(i)
637
+ Sym = S.subgroup_search(prop_true)
638
+ assert Sym.is_subgroup(S)
639
+ Alt = S.subgroup_search(prop_even)
640
+ assert Alt.is_subgroup(A)
641
+ Sym = S.subgroup_search(prop_true, init_subgroup=C)
642
+ assert Sym.is_subgroup(S)
643
+ points = [7]
644
+ assert S.stabilizer(7).is_subgroup(S.subgroup_search(prop_fix_points))
645
+ points = [3, 4]
646
+ assert S.stabilizer(3).stabilizer(4).is_subgroup(
647
+ S.subgroup_search(prop_fix_points))
648
+ points = [3, 5]
649
+ fix35 = A.subgroup_search(prop_fix_points)
650
+ points = [5]
651
+ fix5 = A.subgroup_search(prop_fix_points)
652
+ assert A.subgroup_search(prop_fix_points, init_subgroup=fix35
653
+ ).is_subgroup(fix5)
654
+ base, strong_gens = A.schreier_sims_incremental()
655
+ g = A.generators[0]
656
+ comm_g = \
657
+ A.subgroup_search(prop_comm_g, base=base, strong_gens=strong_gens)
658
+ assert _verify_bsgs(comm_g, base, comm_g.generators) is True
659
+ assert [prop_comm_g(gen) is True for gen in comm_g.generators]
660
+
661
+
662
+ def test_subgroup_search():
663
+ _subgroup_search(10, 15, 2)
664
+
665
+
666
+ @XFAIL
667
+ def test_subgroup_search2():
668
+ skip('takes too much time')
669
+ _subgroup_search(16, 17, 1)
670
+
671
+
672
+ def test_normal_closure():
673
+ # the normal closure of the trivial group is trivial
674
+ S = SymmetricGroup(3)
675
+ identity = Permutation([0, 1, 2])
676
+ closure = S.normal_closure(identity)
677
+ assert closure.is_trivial
678
+ # the normal closure of the entire group is the entire group
679
+ A = AlternatingGroup(4)
680
+ assert A.normal_closure(A).is_subgroup(A)
681
+ # brute-force verifications for subgroups
682
+ for i in (3, 4, 5):
683
+ S = SymmetricGroup(i)
684
+ A = AlternatingGroup(i)
685
+ D = DihedralGroup(i)
686
+ C = CyclicGroup(i)
687
+ for gp in (A, D, C):
688
+ assert _verify_normal_closure(S, gp)
689
+ # brute-force verifications for all elements of a group
690
+ S = SymmetricGroup(5)
691
+ elements = list(S.generate_dimino())
692
+ for element in elements:
693
+ assert _verify_normal_closure(S, element)
694
+ # small groups
695
+ small = []
696
+ for i in (1, 2, 3):
697
+ small.append(SymmetricGroup(i))
698
+ small.append(AlternatingGroup(i))
699
+ small.append(DihedralGroup(i))
700
+ small.append(CyclicGroup(i))
701
+ for gp in small:
702
+ for gp2 in small:
703
+ if gp2.is_subgroup(gp, 0) and gp2.degree == gp.degree:
704
+ assert _verify_normal_closure(gp, gp2)
705
+
706
+
707
+ def test_derived_series():
708
+ # the derived series of the trivial group consists only of the trivial group
709
+ triv = PermutationGroup([Permutation([0, 1, 2])])
710
+ assert triv.derived_series()[0].is_subgroup(triv)
711
+ # the derived series for a simple group consists only of the group itself
712
+ for i in (5, 6, 7):
713
+ A = AlternatingGroup(i)
714
+ assert A.derived_series()[0].is_subgroup(A)
715
+ # the derived series for S_4 is S_4 > A_4 > K_4 > triv
716
+ S = SymmetricGroup(4)
717
+ series = S.derived_series()
718
+ assert series[1].is_subgroup(AlternatingGroup(4))
719
+ assert series[2].is_subgroup(DihedralGroup(2))
720
+ assert series[3].is_trivial
721
+
722
+
723
+ def test_lower_central_series():
724
+ # the lower central series of the trivial group consists of the trivial
725
+ # group
726
+ triv = PermutationGroup([Permutation([0, 1, 2])])
727
+ assert triv.lower_central_series()[0].is_subgroup(triv)
728
+ # the lower central series of a simple group consists of the group itself
729
+ for i in (5, 6, 7):
730
+ A = AlternatingGroup(i)
731
+ assert A.lower_central_series()[0].is_subgroup(A)
732
+ # GAP-verified example
733
+ S = SymmetricGroup(6)
734
+ series = S.lower_central_series()
735
+ assert len(series) == 2
736
+ assert series[1].is_subgroup(AlternatingGroup(6))
737
+
738
+
739
+ def test_commutator():
740
+ # the commutator of the trivial group and the trivial group is trivial
741
+ S = SymmetricGroup(3)
742
+ triv = PermutationGroup([Permutation([0, 1, 2])])
743
+ assert S.commutator(triv, triv).is_subgroup(triv)
744
+ # the commutator of the trivial group and any other group is again trivial
745
+ A = AlternatingGroup(3)
746
+ assert S.commutator(triv, A).is_subgroup(triv)
747
+ # the commutator is commutative
748
+ for i in (3, 4, 5):
749
+ S = SymmetricGroup(i)
750
+ A = AlternatingGroup(i)
751
+ D = DihedralGroup(i)
752
+ assert S.commutator(A, D).is_subgroup(S.commutator(D, A))
753
+ # the commutator of an abelian group is trivial
754
+ S = SymmetricGroup(7)
755
+ A1 = AbelianGroup(2, 5)
756
+ A2 = AbelianGroup(3, 4)
757
+ triv = PermutationGroup([Permutation([0, 1, 2, 3, 4, 5, 6])])
758
+ assert S.commutator(A1, A1).is_subgroup(triv)
759
+ assert S.commutator(A2, A2).is_subgroup(triv)
760
+ # examples calculated by hand
761
+ S = SymmetricGroup(3)
762
+ A = AlternatingGroup(3)
763
+ assert S.commutator(A, S).is_subgroup(A)
764
+
765
+
766
+ def test_is_nilpotent():
767
+ # every abelian group is nilpotent
768
+ for i in (1, 2, 3):
769
+ C = CyclicGroup(i)
770
+ Ab = AbelianGroup(i, i + 2)
771
+ assert C.is_nilpotent
772
+ assert Ab.is_nilpotent
773
+ Ab = AbelianGroup(5, 7, 10)
774
+ assert Ab.is_nilpotent
775
+ # A_5 is not solvable and thus not nilpotent
776
+ assert AlternatingGroup(5).is_nilpotent is False
777
+
778
+
779
+ def test_is_trivial():
780
+ for i in range(5):
781
+ triv = PermutationGroup([Permutation(list(range(i)))])
782
+ assert triv.is_trivial
783
+
784
+
785
+ def test_pointwise_stabilizer():
786
+ S = SymmetricGroup(2)
787
+ stab = S.pointwise_stabilizer([0])
788
+ assert stab.generators == [Permutation(1)]
789
+ S = SymmetricGroup(5)
790
+ points = []
791
+ stab = S
792
+ for point in (2, 0, 3, 4, 1):
793
+ stab = stab.stabilizer(point)
794
+ points.append(point)
795
+ assert S.pointwise_stabilizer(points).is_subgroup(stab)
796
+
797
+
798
+ def test_make_perm():
799
+ assert cube.pgroup.make_perm(5, seed=list(range(5))) == \
800
+ Permutation([4, 7, 6, 5, 0, 3, 2, 1])
801
+ assert cube.pgroup.make_perm(7, seed=list(range(7))) == \
802
+ Permutation([6, 7, 3, 2, 5, 4, 0, 1])
803
+
804
+
805
+ def test_elements():
806
+ from sympy.sets.sets import FiniteSet
807
+
808
+ p = Permutation(2, 3)
809
+ assert PermutationGroup(p).elements == {Permutation(3), Permutation(2, 3)}
810
+ assert FiniteSet(*PermutationGroup(p).elements) \
811
+ == FiniteSet(Permutation(2, 3), Permutation(3))
812
+
813
+
814
+ def test_is_group():
815
+ assert PermutationGroup(Permutation(1,2), Permutation(2,4)).is_group is True
816
+ assert SymmetricGroup(4).is_group is True
817
+
818
+
819
+ def test_PermutationGroup():
820
+ assert PermutationGroup() == PermutationGroup(Permutation())
821
+ assert (PermutationGroup() == 0) is False
822
+
823
+
824
+ def test_coset_transvesal():
825
+ G = AlternatingGroup(5)
826
+ H = PermutationGroup(Permutation(0,1,2),Permutation(1,2)(3,4))
827
+ assert G.coset_transversal(H) == \
828
+ [Permutation(4), Permutation(2, 3, 4), Permutation(2, 4, 3),
829
+ Permutation(1, 2, 4), Permutation(4)(1, 2, 3), Permutation(1, 3)(2, 4),
830
+ Permutation(0, 1, 2, 3, 4), Permutation(0, 1, 2, 4, 3),
831
+ Permutation(0, 1, 3, 2, 4), Permutation(0, 2, 4, 1, 3)]
832
+
833
+
834
+ def test_coset_table():
835
+ G = PermutationGroup(Permutation(0,1,2,3), Permutation(0,1,2),
836
+ Permutation(0,4,2,7), Permutation(5,6), Permutation(0,7));
837
+ H = PermutationGroup(Permutation(0,1,2,3), Permutation(0,7))
838
+ assert G.coset_table(H) == \
839
+ [[0, 0, 0, 0, 1, 2, 3, 3, 0, 0], [4, 5, 2, 5, 6, 0, 7, 7, 1, 1],
840
+ [5, 4, 5, 1, 0, 6, 8, 8, 6, 6], [3, 3, 3, 3, 7, 8, 0, 0, 3, 3],
841
+ [2, 1, 4, 4, 4, 4, 9, 9, 4, 4], [1, 2, 1, 2, 5, 5, 10, 10, 5, 5],
842
+ [6, 6, 6, 6, 2, 1, 11, 11, 2, 2], [9, 10, 8, 10, 11, 3, 1, 1, 7, 7],
843
+ [10, 9, 10, 7, 3, 11, 2, 2, 11, 11], [8, 7, 9, 9, 9, 9, 4, 4, 9, 9],
844
+ [7, 8, 7, 8, 10, 10, 5, 5, 10, 10], [11, 11, 11, 11, 8, 7, 6, 6, 8, 8]]
845
+
846
+
847
+ def test_subgroup():
848
+ G = PermutationGroup(Permutation(0,1,2), Permutation(0,2,3))
849
+ H = G.subgroup([Permutation(0,1,3)])
850
+ assert H.is_subgroup(G)
851
+
852
+
853
+ def test_generator_product():
854
+ G = SymmetricGroup(5)
855
+ p = Permutation(0, 2, 3)(1, 4)
856
+ gens = G.generator_product(p)
857
+ assert all(g in G.strong_gens for g in gens)
858
+ w = G.identity
859
+ for g in gens:
860
+ w = g*w
861
+ assert w == p
862
+
863
+
864
+ def test_sylow_subgroup():
865
+ P = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5))
866
+ S = P.sylow_subgroup(2)
867
+ assert S.order() == 4
868
+
869
+ P = DihedralGroup(12)
870
+ S = P.sylow_subgroup(3)
871
+ assert S.order() == 3
872
+
873
+ P = PermutationGroup(
874
+ Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5), Permutation(0, 2))
875
+ S = P.sylow_subgroup(3)
876
+ assert S.order() == 9
877
+ S = P.sylow_subgroup(2)
878
+ assert S.order() == 8
879
+
880
+ P = SymmetricGroup(10)
881
+ S = P.sylow_subgroup(2)
882
+ assert S.order() == 256
883
+ S = P.sylow_subgroup(3)
884
+ assert S.order() == 81
885
+ S = P.sylow_subgroup(5)
886
+ assert S.order() == 25
887
+
888
+ # the length of the lower central series
889
+ # of a p-Sylow subgroup of Sym(n) grows with
890
+ # the highest exponent exp of p such
891
+ # that n >= p**exp
892
+ exp = 1
893
+ length = 0
894
+ for i in range(2, 9):
895
+ P = SymmetricGroup(i)
896
+ S = P.sylow_subgroup(2)
897
+ ls = S.lower_central_series()
898
+ if i // 2**exp > 0:
899
+ # length increases with exponent
900
+ assert len(ls) > length
901
+ length = len(ls)
902
+ exp += 1
903
+ else:
904
+ assert len(ls) == length
905
+
906
+ G = SymmetricGroup(100)
907
+ S = G.sylow_subgroup(3)
908
+ assert G.order() % S.order() == 0
909
+ assert G.order()/S.order() % 3 > 0
910
+
911
+ G = AlternatingGroup(100)
912
+ S = G.sylow_subgroup(2)
913
+ assert G.order() % S.order() == 0
914
+ assert G.order()/S.order() % 2 > 0
915
+
916
+ G = DihedralGroup(18)
917
+ S = G.sylow_subgroup(p=2)
918
+ assert S.order() == 4
919
+
920
+ G = DihedralGroup(50)
921
+ S = G.sylow_subgroup(p=2)
922
+ assert S.order() == 4
923
+
924
+
925
+ @slow
926
+ def test_presentation():
927
+ def _test(P):
928
+ G = P.presentation()
929
+ return G.order() == P.order()
930
+
931
+ def _strong_test(P):
932
+ G = P.strong_presentation()
933
+ chk = len(G.generators) == len(P.strong_gens)
934
+ return chk and G.order() == P.order()
935
+
936
+ P = PermutationGroup(Permutation(0,1,5,2)(3,7,4,6), Permutation(0,3,5,4)(1,6,2,7))
937
+ assert _test(P)
938
+
939
+ P = AlternatingGroup(5)
940
+ assert _test(P)
941
+
942
+ P = SymmetricGroup(5)
943
+ assert _test(P)
944
+
945
+ P = PermutationGroup(
946
+ [Permutation(0,3,1,2), Permutation(3)(0,1), Permutation(0,1)(2,3)])
947
+ assert _strong_test(P)
948
+
949
+ P = DihedralGroup(6)
950
+ assert _strong_test(P)
951
+
952
+ a = Permutation(0,1)(2,3)
953
+ b = Permutation(0,2)(3,1)
954
+ c = Permutation(4,5)
955
+ P = PermutationGroup(c, a, b)
956
+ assert _strong_test(P)
957
+
958
+
959
+ def test_polycyclic():
960
+ a = Permutation([0, 1, 2])
961
+ b = Permutation([2, 1, 0])
962
+ G = PermutationGroup([a, b])
963
+ assert G.is_polycyclic is True
964
+
965
+ a = Permutation([1, 2, 3, 4, 0])
966
+ b = Permutation([1, 0, 2, 3, 4])
967
+ G = PermutationGroup([a, b])
968
+ assert G.is_polycyclic is False
969
+
970
+
971
+ def test_elementary():
972
+ a = Permutation([1, 5, 2, 0, 3, 6, 4])
973
+ G = PermutationGroup([a])
974
+ assert G.is_elementary(7) is False
975
+
976
+ a = Permutation(0, 1)(2, 3)
977
+ b = Permutation(0, 2)(3, 1)
978
+ G = PermutationGroup([a, b])
979
+ assert G.is_elementary(2) is True
980
+ c = Permutation(4, 5, 6)
981
+ G = PermutationGroup([a, b, c])
982
+ assert G.is_elementary(2) is False
983
+
984
+ G = SymmetricGroup(4).sylow_subgroup(2)
985
+ assert G.is_elementary(2) is False
986
+ H = AlternatingGroup(4).sylow_subgroup(2)
987
+ assert H.is_elementary(2) is True
988
+
989
+
990
+ def test_perfect():
991
+ G = AlternatingGroup(3)
992
+ assert G.is_perfect is False
993
+ G = AlternatingGroup(5)
994
+ assert G.is_perfect is True
995
+
996
+
997
+ def test_index():
998
+ G = PermutationGroup(Permutation(0,1,2), Permutation(0,2,3))
999
+ H = G.subgroup([Permutation(0,1,3)])
1000
+ assert G.index(H) == 4
1001
+
1002
+
1003
+ def test_cyclic():
1004
+ G = SymmetricGroup(2)
1005
+ assert G.is_cyclic
1006
+ G = AbelianGroup(3, 7)
1007
+ assert G.is_cyclic
1008
+ G = AbelianGroup(7, 7)
1009
+ assert not G.is_cyclic
1010
+ G = AlternatingGroup(3)
1011
+ assert G.is_cyclic
1012
+ G = AlternatingGroup(4)
1013
+ assert not G.is_cyclic
1014
+
1015
+ # Order less than 6
1016
+ G = PermutationGroup(Permutation(0, 1, 2), Permutation(0, 2, 1))
1017
+ assert G.is_cyclic
1018
+ G = PermutationGroup(
1019
+ Permutation(0, 1, 2, 3),
1020
+ Permutation(0, 2)(1, 3)
1021
+ )
1022
+ assert G.is_cyclic
1023
+ G = PermutationGroup(
1024
+ Permutation(3),
1025
+ Permutation(0, 1)(2, 3),
1026
+ Permutation(0, 2)(1, 3),
1027
+ Permutation(0, 3)(1, 2)
1028
+ )
1029
+ assert G.is_cyclic is False
1030
+
1031
+ # Order 15
1032
+ G = PermutationGroup(
1033
+ Permutation(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14),
1034
+ Permutation(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13)
1035
+ )
1036
+ assert G.is_cyclic
1037
+
1038
+ # Distinct prime orders
1039
+ assert PermutationGroup._distinct_primes_lemma([3, 5]) is True
1040
+ assert PermutationGroup._distinct_primes_lemma([5, 7]) is True
1041
+ assert PermutationGroup._distinct_primes_lemma([2, 3]) is None
1042
+ assert PermutationGroup._distinct_primes_lemma([3, 5, 7]) is None
1043
+ assert PermutationGroup._distinct_primes_lemma([5, 7, 13]) is True
1044
+
1045
+ G = PermutationGroup(
1046
+ Permutation(0, 1, 2, 3),
1047
+ Permutation(0, 2)(1, 3))
1048
+ assert G.is_cyclic
1049
+ assert G._is_abelian
1050
+
1051
+ # Non-abelian and therefore not cyclic
1052
+ G = PermutationGroup(*SymmetricGroup(3).generators)
1053
+ assert G.is_cyclic is False
1054
+
1055
+ # Abelian and cyclic
1056
+ G = PermutationGroup(
1057
+ Permutation(0, 1, 2, 3),
1058
+ Permutation(4, 5, 6)
1059
+ )
1060
+ assert G.is_cyclic
1061
+
1062
+ # Abelian but not cyclic
1063
+ G = PermutationGroup(
1064
+ Permutation(0, 1),
1065
+ Permutation(2, 3),
1066
+ Permutation(4, 5, 6)
1067
+ )
1068
+ assert G.is_cyclic is False
1069
+
1070
+
1071
+ def test_dihedral():
1072
+ G = SymmetricGroup(2)
1073
+ assert G.is_dihedral
1074
+ G = SymmetricGroup(3)
1075
+ assert G.is_dihedral
1076
+
1077
+ G = AbelianGroup(2, 2)
1078
+ assert G.is_dihedral
1079
+ G = CyclicGroup(4)
1080
+ assert not G.is_dihedral
1081
+
1082
+ G = AbelianGroup(3, 5)
1083
+ assert not G.is_dihedral
1084
+ G = AbelianGroup(2)
1085
+ assert G.is_dihedral
1086
+ G = AbelianGroup(6)
1087
+ assert not G.is_dihedral
1088
+
1089
+ # D6, generated by two adjacent flips
1090
+ G = PermutationGroup(
1091
+ Permutation(1, 5)(2, 4),
1092
+ Permutation(0, 1)(3, 4)(2, 5))
1093
+ assert G.is_dihedral
1094
+
1095
+ # D7, generated by a flip and a rotation
1096
+ G = PermutationGroup(
1097
+ Permutation(1, 6)(2, 5)(3, 4),
1098
+ Permutation(0, 1, 2, 3, 4, 5, 6))
1099
+ assert G.is_dihedral
1100
+
1101
+ # S4, presented by three generators, fails due to having exactly 9
1102
+ # elements of order 2:
1103
+ G = PermutationGroup(
1104
+ Permutation(0, 1), Permutation(0, 2),
1105
+ Permutation(0, 3))
1106
+ assert not G.is_dihedral
1107
+
1108
+ # D7, given by three generators
1109
+ G = PermutationGroup(
1110
+ Permutation(1, 6)(2, 5)(3, 4),
1111
+ Permutation(2, 0)(3, 6)(4, 5),
1112
+ Permutation(0, 1, 2, 3, 4, 5, 6))
1113
+ assert G.is_dihedral
1114
+
1115
+
1116
+ def test_abelian_invariants():
1117
+ G = AbelianGroup(2, 3, 4)
1118
+ assert G.abelian_invariants() == [2, 3, 4]
1119
+ G=PermutationGroup([Permutation(1, 2, 3, 4), Permutation(1, 2), Permutation(5, 6)])
1120
+ assert G.abelian_invariants() == [2, 2]
1121
+ G = AlternatingGroup(7)
1122
+ assert G.abelian_invariants() == []
1123
+ G = AlternatingGroup(4)
1124
+ assert G.abelian_invariants() == [3]
1125
+ G = DihedralGroup(4)
1126
+ assert G.abelian_invariants() == [2, 2]
1127
+
1128
+ G = PermutationGroup([Permutation(1, 2, 3, 4, 5, 6, 7)])
1129
+ assert G.abelian_invariants() == [7]
1130
+ G = DihedralGroup(12)
1131
+ S = G.sylow_subgroup(3)
1132
+ assert S.abelian_invariants() == [3]
1133
+ G = PermutationGroup(Permutation(0, 1, 2), Permutation(0, 2, 3))
1134
+ assert G.abelian_invariants() == [3]
1135
+ G = PermutationGroup([Permutation(0, 1), Permutation(0, 2, 4, 6)(1, 3, 5, 7)])
1136
+ assert G.abelian_invariants() == [2, 4]
1137
+ G = SymmetricGroup(30)
1138
+ S = G.sylow_subgroup(2)
1139
+ assert S.abelian_invariants() == [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
1140
+ S = G.sylow_subgroup(3)
1141
+ assert S.abelian_invariants() == [3, 3, 3, 3]
1142
+ S = G.sylow_subgroup(5)
1143
+ assert S.abelian_invariants() == [5, 5, 5]
1144
+
1145
+
1146
+ def test_composition_series():
1147
+ a = Permutation(1, 2, 3)
1148
+ b = Permutation(1, 2)
1149
+ G = PermutationGroup([a, b])
1150
+ comp_series = G.composition_series()
1151
+ assert comp_series == G.derived_series()
1152
+ # The first group in the composition series is always the group itself and
1153
+ # the last group in the series is the trivial group.
1154
+ S = SymmetricGroup(4)
1155
+ assert S.composition_series()[0] == S
1156
+ assert len(S.composition_series()) == 5
1157
+ A = AlternatingGroup(4)
1158
+ assert A.composition_series()[0] == A
1159
+ assert len(A.composition_series()) == 4
1160
+
1161
+ # the composition series for C_8 is C_8 > C_4 > C_2 > triv
1162
+ G = CyclicGroup(8)
1163
+ series = G.composition_series()
1164
+ assert is_isomorphic(series[1], CyclicGroup(4))
1165
+ assert is_isomorphic(series[2], CyclicGroup(2))
1166
+ assert series[3].is_trivial
1167
+
1168
+
1169
+ def test_is_symmetric():
1170
+ a = Permutation(0, 1, 2)
1171
+ b = Permutation(0, 1, size=3)
1172
+ assert PermutationGroup(a, b).is_symmetric is True
1173
+
1174
+ a = Permutation(0, 2, 1)
1175
+ b = Permutation(1, 2, size=3)
1176
+ assert PermutationGroup(a, b).is_symmetric is True
1177
+
1178
+ a = Permutation(0, 1, 2, 3)
1179
+ b = Permutation(0, 3)(1, 2)
1180
+ assert PermutationGroup(a, b).is_symmetric is False
1181
+
1182
+ def test_conjugacy_class():
1183
+ S = SymmetricGroup(4)
1184
+ x = Permutation(1, 2, 3)
1185
+ C = {Permutation(0, 1, 2, size = 4), Permutation(0, 1, 3),
1186
+ Permutation(0, 2, 1, size = 4), Permutation(0, 2, 3),
1187
+ Permutation(0, 3, 1), Permutation(0, 3, 2),
1188
+ Permutation(1, 2, 3), Permutation(1, 3, 2)}
1189
+ assert S.conjugacy_class(x) == C
1190
+
1191
+ def test_conjugacy_classes():
1192
+ S = SymmetricGroup(3)
1193
+ expected = [{Permutation(size = 3)},
1194
+ {Permutation(0, 1, size = 3), Permutation(0, 2), Permutation(1, 2)},
1195
+ {Permutation(0, 1, 2), Permutation(0, 2, 1)}]
1196
+ computed = S.conjugacy_classes()
1197
+
1198
+ assert len(expected) == len(computed)
1199
+ assert all(e in computed for e in expected)
1200
+
1201
+ def test_coset_class():
1202
+ a = Permutation(1, 2)
1203
+ b = Permutation(0, 1)
1204
+ G = PermutationGroup([a, b])
1205
+ #Creating right coset
1206
+ rht_coset = G*a
1207
+ #Checking whether it is left coset or right coset
1208
+ assert rht_coset.is_right_coset
1209
+ assert not rht_coset.is_left_coset
1210
+ #Creating list representation of coset
1211
+ list_repr = rht_coset.as_list()
1212
+ expected = [Permutation(0, 2), Permutation(0, 2, 1), Permutation(1, 2),
1213
+ Permutation(2), Permutation(2)(0, 1), Permutation(0, 1, 2)]
1214
+ for ele in list_repr:
1215
+ assert ele in expected
1216
+ #Creating left coset
1217
+ left_coset = a*G
1218
+ #Checking whether it is left coset or right coset
1219
+ assert not left_coset.is_right_coset
1220
+ assert left_coset.is_left_coset
1221
+ #Creating list representation of Coset
1222
+ list_repr = left_coset.as_list()
1223
+ expected = [Permutation(2)(0, 1), Permutation(0, 1, 2), Permutation(1, 2),
1224
+ Permutation(2), Permutation(0, 2), Permutation(0, 2, 1)]
1225
+ for ele in list_repr:
1226
+ assert ele in expected
1227
+
1228
+ G = PermutationGroup(Permutation(1, 2, 3, 4), Permutation(2, 3, 4))
1229
+ H = PermutationGroup(Permutation(1, 2, 3, 4))
1230
+ g = Permutation(1, 3)(2, 4)
1231
+ rht_coset = Coset(g, H, G, dir='+')
1232
+ assert rht_coset.is_right_coset
1233
+ list_repr = rht_coset.as_list()
1234
+ expected = [Permutation(1, 2, 3, 4), Permutation(4), Permutation(1, 3)(2, 4),
1235
+ Permutation(1, 4, 3, 2)]
1236
+ for ele in list_repr:
1237
+ assert ele in expected
1238
+
1239
+ def test_symmetricpermutationgroup():
1240
+ a = SymmetricPermutationGroup(5)
1241
+ assert a.degree == 5
1242
+ assert a.order() == 120
1243
+ assert a.identity() == Permutation(4)
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_polyhedron.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import symbols
2
+ from sympy.sets.sets import FiniteSet
3
+ from sympy.combinatorics.polyhedron import (Polyhedron,
4
+ tetrahedron, cube as square, octahedron, dodecahedron, icosahedron,
5
+ cube_faces)
6
+ from sympy.combinatorics.permutations import Permutation
7
+ from sympy.combinatorics.perm_groups import PermutationGroup
8
+ from sympy.testing.pytest import raises
9
+
10
+ rmul = Permutation.rmul
11
+
12
+
13
+ def test_polyhedron():
14
+ raises(ValueError, lambda: Polyhedron(list('ab'),
15
+ pgroup=[Permutation([0])]))
16
+ pgroup = [Permutation([[0, 7, 2, 5], [6, 1, 4, 3]]),
17
+ Permutation([[0, 7, 1, 6], [5, 2, 4, 3]]),
18
+ Permutation([[3, 6, 0, 5], [4, 1, 7, 2]]),
19
+ Permutation([[7, 4, 5], [1, 3, 0], [2], [6]]),
20
+ Permutation([[1, 3, 2], [7, 6, 5], [4], [0]]),
21
+ Permutation([[4, 7, 6], [2, 0, 3], [1], [5]]),
22
+ Permutation([[1, 2, 0], [4, 5, 6], [3], [7]]),
23
+ Permutation([[4, 2], [0, 6], [3, 7], [1, 5]]),
24
+ Permutation([[3, 5], [7, 1], [2, 6], [0, 4]]),
25
+ Permutation([[2, 5], [1, 6], [0, 4], [3, 7]]),
26
+ Permutation([[4, 3], [7, 0], [5, 1], [6, 2]]),
27
+ Permutation([[4, 1], [0, 5], [6, 2], [7, 3]]),
28
+ Permutation([[7, 2], [3, 6], [0, 4], [1, 5]]),
29
+ Permutation([0, 1, 2, 3, 4, 5, 6, 7])]
30
+ corners = tuple(symbols('A:H'))
31
+ faces = cube_faces
32
+ cube = Polyhedron(corners, faces, pgroup)
33
+
34
+ assert cube.edges == FiniteSet(*(
35
+ (0, 1), (6, 7), (1, 2), (5, 6), (0, 3), (2, 3),
36
+ (4, 7), (4, 5), (3, 7), (1, 5), (0, 4), (2, 6)))
37
+
38
+ for i in range(3): # add 180 degree face rotations
39
+ cube.rotate(cube.pgroup[i]**2)
40
+
41
+ assert cube.corners == corners
42
+
43
+ for i in range(3, 7): # add 240 degree axial corner rotations
44
+ cube.rotate(cube.pgroup[i]**2)
45
+
46
+ assert cube.corners == corners
47
+ cube.rotate(1)
48
+ raises(ValueError, lambda: cube.rotate(Permutation([0, 1])))
49
+ assert cube.corners != corners
50
+ assert cube.array_form == [7, 6, 4, 5, 3, 2, 0, 1]
51
+ assert cube.cyclic_form == [[0, 7, 1, 6], [2, 4, 3, 5]]
52
+ cube.reset()
53
+ assert cube.corners == corners
54
+
55
+ def check(h, size, rpt, target):
56
+
57
+ assert len(h.faces) + len(h.vertices) - len(h.edges) == 2
58
+ assert h.size == size
59
+
60
+ got = set()
61
+ for p in h.pgroup:
62
+ # make sure it restores original
63
+ P = h.copy()
64
+ hit = P.corners
65
+ for i in range(rpt):
66
+ P.rotate(p)
67
+ if P.corners == hit:
68
+ break
69
+ else:
70
+ print('error in permutation', p.array_form)
71
+ for i in range(rpt):
72
+ P.rotate(p)
73
+ got.add(tuple(P.corners))
74
+ c = P.corners
75
+ f = [[c[i] for i in f] for f in P.faces]
76
+ assert h.faces == Polyhedron(c, f).faces
77
+ assert len(got) == target
78
+ assert PermutationGroup([Permutation(g) for g in got]).is_group
79
+
80
+ for h, size, rpt, target in zip(
81
+ (tetrahedron, square, octahedron, dodecahedron, icosahedron),
82
+ (4, 8, 6, 20, 12),
83
+ (3, 4, 4, 5, 5),
84
+ (12, 24, 24, 60, 60)):
85
+ check(h, size, rpt, target)
86
+
87
+
88
+ def test_pgroups():
89
+ from sympy.combinatorics.polyhedron import (cube, tetrahedron_faces,
90
+ octahedron_faces, dodecahedron_faces, icosahedron_faces)
91
+ from sympy.combinatorics.polyhedron import _pgroup_calcs
92
+ (tetrahedron2, cube2, octahedron2, dodecahedron2, icosahedron2,
93
+ tetrahedron_faces2, cube_faces2, octahedron_faces2,
94
+ dodecahedron_faces2, icosahedron_faces2) = _pgroup_calcs()
95
+
96
+ assert tetrahedron == tetrahedron2
97
+ assert cube == cube2
98
+ assert octahedron == octahedron2
99
+ assert dodecahedron == dodecahedron2
100
+ assert icosahedron == icosahedron2
101
+ assert sorted(map(sorted, tetrahedron_faces)) == sorted(map(sorted, tetrahedron_faces2))
102
+ assert sorted(cube_faces) == sorted(cube_faces2)
103
+ assert sorted(octahedron_faces) == sorted(octahedron_faces2)
104
+ assert sorted(dodecahedron_faces) == sorted(dodecahedron_faces2)
105
+ assert sorted(icosahedron_faces) == sorted(icosahedron_faces2)
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_prufer.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.prufer import Prufer
2
+ from sympy.testing.pytest import raises
3
+
4
+
5
+ def test_prufer():
6
+ # number of nodes is optional
7
+ assert Prufer([[0, 1], [0, 2], [0, 3], [0, 4]], 5).nodes == 5
8
+ assert Prufer([[0, 1], [0, 2], [0, 3], [0, 4]]).nodes == 5
9
+
10
+ a = Prufer([[0, 1], [0, 2], [0, 3], [0, 4]])
11
+ assert a.rank == 0
12
+ assert a.nodes == 5
13
+ assert a.prufer_repr == [0, 0, 0]
14
+
15
+ a = Prufer([[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]])
16
+ assert a.rank == 924
17
+ assert a.nodes == 6
18
+ assert a.tree_repr == [[2, 4], [1, 4], [1, 3], [0, 5], [0, 4]]
19
+ assert a.prufer_repr == [4, 1, 4, 0]
20
+
21
+ assert Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) == \
22
+ ([[0, 1], [1, 2], [1, 4], [2, 3], [4, 5], [4, 6]], 7)
23
+ assert Prufer([0]*4).size == Prufer([6]*4).size == 1296
24
+
25
+ # accept iterables but convert to list of lists
26
+ tree = [(0, 1), (1, 5), (0, 3), (0, 2), (2, 6), (4, 7), (2, 4)]
27
+ tree_lists = [list(t) for t in tree]
28
+ assert Prufer(tree).tree_repr == tree_lists
29
+ assert sorted(Prufer(set(tree)).tree_repr) == sorted(tree_lists)
30
+
31
+ raises(ValueError, lambda: Prufer([[1, 2], [3, 4]])) # 0 is missing
32
+ raises(ValueError, lambda: Prufer([[2, 3], [3, 4]])) # 0, 1 are missing
33
+ assert Prufer(*Prufer.edges([1, 2], [3, 4])).prufer_repr == [1, 3]
34
+ raises(ValueError, lambda: Prufer.edges(
35
+ [1, 3], [3, 4])) # a broken tree but edges doesn't care
36
+ raises(ValueError, lambda: Prufer.edges([1, 2], [5, 6]))
37
+ raises(ValueError, lambda: Prufer([[]]))
38
+
39
+ a = Prufer([[0, 1], [0, 2], [0, 3]])
40
+ b = a.next()
41
+ assert b.tree_repr == [[0, 2], [0, 1], [1, 3]]
42
+ assert b.rank == 1
43
+
44
+
45
+ def test_round_trip():
46
+ def doit(t, b):
47
+ e, n = Prufer.edges(*t)
48
+ t = Prufer(e, n)
49
+ a = sorted(t.tree_repr)
50
+ b = [i - 1 for i in b]
51
+ assert t.prufer_repr == b
52
+ assert sorted(Prufer(b).tree_repr) == a
53
+ assert Prufer.unrank(t.rank, n).prufer_repr == b
54
+
55
+ doit([[1, 2]], [])
56
+ doit([[2, 1, 3]], [1])
57
+ doit([[1, 3, 2]], [3])
58
+ doit([[1, 2, 3]], [2])
59
+ doit([[2, 1, 4], [1, 3]], [1, 1])
60
+ doit([[3, 2, 1, 4]], [2, 1])
61
+ doit([[3, 2, 1], [2, 4]], [2, 2])
62
+ doit([[1, 3, 2, 4]], [3, 2])
63
+ doit([[1, 4, 2, 3]], [4, 2])
64
+ doit([[3, 1, 4, 2]], [4, 1])
65
+ doit([[4, 2, 1, 3]], [1, 2])
66
+ doit([[1, 2, 4, 3]], [2, 4])
67
+ doit([[1, 3, 4, 2]], [3, 4])
68
+ doit([[2, 4, 1], [4, 3]], [4, 4])
69
+ doit([[1, 2, 3, 4]], [2, 3])
70
+ doit([[2, 3, 1], [3, 4]], [3, 3])
71
+ doit([[1, 4, 3, 2]], [4, 3])
72
+ doit([[2, 1, 4, 3]], [1, 4])
73
+ doit([[2, 1, 3, 4]], [1, 3])
74
+ doit([[6, 2, 1, 4], [1, 3, 5, 8], [3, 7]], [1, 2, 1, 3, 3, 5])
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_rewriting.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.fp_groups import FpGroup
2
+ from sympy.combinatorics.free_groups import free_group
3
+ from sympy.testing.pytest import raises
4
+
5
+
6
+ def test_rewriting():
7
+ F, a, b = free_group("a, b")
8
+ G = FpGroup(F, [a*b*a**-1*b**-1])
9
+ a, b = G.generators
10
+ R = G._rewriting_system
11
+ assert R.is_confluent
12
+
13
+ assert G.reduce(b**-1*a) == a*b**-1
14
+ assert G.reduce(b**3*a**4*b**-2*a) == a**5*b
15
+ assert G.equals(b**2*a**-1*b, b**4*a**-1*b**-1)
16
+
17
+ assert R.reduce_using_automaton(b*a*a**2*b**-1) == a**3
18
+ assert R.reduce_using_automaton(b**3*a**4*b**-2*a) == a**5*b
19
+ assert R.reduce_using_automaton(b**-1*a) == a*b**-1
20
+
21
+ G = FpGroup(F, [a**3, b**3, (a*b)**2])
22
+ R = G._rewriting_system
23
+ R.make_confluent()
24
+ # R._is_confluent should be set to True after
25
+ # a successful run of make_confluent
26
+ assert R.is_confluent
27
+ # but also the system should actually be confluent
28
+ assert R._check_confluence()
29
+ assert G.reduce(b*a**-1*b**-1*a**3*b**4*a**-1*b**-15) == a**-1*b**-1
30
+ # check for automaton reduction
31
+ assert R.reduce_using_automaton(b*a**-1*b**-1*a**3*b**4*a**-1*b**-15) == a**-1*b**-1
32
+
33
+ G = FpGroup(F, [a**2, b**3, (a*b)**4])
34
+ R = G._rewriting_system
35
+ assert G.reduce(a**2*b**-2*a**2*b) == b**-1
36
+ assert R.reduce_using_automaton(a**2*b**-2*a**2*b) == b**-1
37
+ assert G.reduce(a**3*b**-2*a**2*b) == a**-1*b**-1
38
+ assert R.reduce_using_automaton(a**3*b**-2*a**2*b) == a**-1*b**-1
39
+ # Check after adding a rule
40
+ R.add_rule(a**2, b)
41
+ assert R.reduce_using_automaton(a**2*b**-2*a**2*b) == b**-1
42
+ assert R.reduce_using_automaton(a**4*b**-2*a**2*b**3) == b
43
+
44
+ R.set_max(15)
45
+ raises(RuntimeError, lambda: R.add_rule(a**-3, b))
46
+ R.set_max(20)
47
+ R.add_rule(a**-3, b)
48
+
49
+ assert R.add_rule(a, a) == set()
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_schur_number.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S, Rational
2
+ from sympy.combinatorics.schur_number import schur_partition, SchurNumber
3
+ from sympy.core.random import _randint
4
+ from sympy.testing.pytest import raises
5
+ from sympy.core.symbol import symbols
6
+
7
+
8
+ def _sum_free_test(subset):
9
+ """
10
+ Checks if subset is sum-free(There are no x,y,z in the subset such that
11
+ x + y = z)
12
+ """
13
+ for i in subset:
14
+ for j in subset:
15
+ assert (i + j in subset) is False
16
+
17
+
18
+ def test_schur_partition():
19
+ raises(ValueError, lambda: schur_partition(S.Infinity))
20
+ raises(ValueError, lambda: schur_partition(-1))
21
+ raises(ValueError, lambda: schur_partition(0))
22
+ assert schur_partition(2) == [[1, 2]]
23
+
24
+ random_number_generator = _randint(1000)
25
+ for _ in range(5):
26
+ n = random_number_generator(1, 1000)
27
+ result = schur_partition(n)
28
+ t = 0
29
+ numbers = []
30
+ for item in result:
31
+ _sum_free_test(item)
32
+ """
33
+ Checks if the occurrence of all numbers is exactly one
34
+ """
35
+ t += len(item)
36
+ for l in item:
37
+ assert (l in numbers) is False
38
+ numbers.append(l)
39
+ assert n == t
40
+
41
+ x = symbols("x")
42
+ raises(ValueError, lambda: schur_partition(x))
43
+
44
+ def test_schur_number():
45
+ first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44, 5: 160}
46
+ for k in first_known_schur_numbers:
47
+ assert SchurNumber(k) == first_known_schur_numbers[k]
48
+
49
+ assert SchurNumber(S.Infinity) == S.Infinity
50
+ assert SchurNumber(0) == 0
51
+ raises(ValueError, lambda: SchurNumber(0.5))
52
+
53
+ n = symbols("n")
54
+ assert SchurNumber(n).lower_bound() == 3**n/2 - Rational(1, 2)
55
+ assert SchurNumber(8).lower_bound() == 5039
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_subsets.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.subsets import Subset, ksubsets
2
+ from sympy.testing.pytest import raises
3
+
4
+
5
+ def test_subset():
6
+ a = Subset(['c', 'd'], ['a', 'b', 'c', 'd'])
7
+ assert a.next_binary() == Subset(['b'], ['a', 'b', 'c', 'd'])
8
+ assert a.prev_binary() == Subset(['c'], ['a', 'b', 'c', 'd'])
9
+ assert a.next_lexicographic() == Subset(['d'], ['a', 'b', 'c', 'd'])
10
+ assert a.prev_lexicographic() == Subset(['c'], ['a', 'b', 'c', 'd'])
11
+ assert a.next_gray() == Subset(['c'], ['a', 'b', 'c', 'd'])
12
+ assert a.prev_gray() == Subset(['d'], ['a', 'b', 'c', 'd'])
13
+ assert a.rank_binary == 3
14
+ assert a.rank_lexicographic == 14
15
+ assert a.rank_gray == 2
16
+ assert a.cardinality == 16
17
+ assert a.size == 2
18
+ assert Subset.bitlist_from_subset(a, ['a', 'b', 'c', 'd']) == '0011'
19
+
20
+ a = Subset([2, 5, 7], [1, 2, 3, 4, 5, 6, 7])
21
+ assert a.next_binary() == Subset([2, 5, 6], [1, 2, 3, 4, 5, 6, 7])
22
+ assert a.prev_binary() == Subset([2, 5], [1, 2, 3, 4, 5, 6, 7])
23
+ assert a.next_lexicographic() == Subset([2, 6], [1, 2, 3, 4, 5, 6, 7])
24
+ assert a.prev_lexicographic() == Subset([2, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7])
25
+ assert a.next_gray() == Subset([2, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7])
26
+ assert a.prev_gray() == Subset([2, 5], [1, 2, 3, 4, 5, 6, 7])
27
+ assert a.rank_binary == 37
28
+ assert a.rank_lexicographic == 93
29
+ assert a.rank_gray == 57
30
+ assert a.cardinality == 128
31
+
32
+ superset = ['a', 'b', 'c', 'd']
33
+ assert Subset.unrank_binary(4, superset).rank_binary == 4
34
+ assert Subset.unrank_gray(10, superset).rank_gray == 10
35
+
36
+ superset = [1, 2, 3, 4, 5, 6, 7, 8, 9]
37
+ assert Subset.unrank_binary(33, superset).rank_binary == 33
38
+ assert Subset.unrank_gray(25, superset).rank_gray == 25
39
+
40
+ a = Subset([], ['a', 'b', 'c', 'd'])
41
+ i = 1
42
+ while a.subset != Subset(['d'], ['a', 'b', 'c', 'd']).subset:
43
+ a = a.next_lexicographic()
44
+ i = i + 1
45
+ assert i == 16
46
+
47
+ i = 1
48
+ while a.subset != Subset([], ['a', 'b', 'c', 'd']).subset:
49
+ a = a.prev_lexicographic()
50
+ i = i + 1
51
+ assert i == 16
52
+
53
+ raises(ValueError, lambda: Subset(['a', 'b'], ['a']))
54
+ raises(ValueError, lambda: Subset(['a'], ['b', 'c']))
55
+ raises(ValueError, lambda: Subset.subset_from_bitlist(['a', 'b'], '010'))
56
+
57
+ assert Subset(['a'], ['a', 'b']) != Subset(['b'], ['a', 'b'])
58
+ assert Subset(['a'], ['a', 'b']) != Subset(['a'], ['a', 'c'])
59
+
60
+ def test_ksubsets():
61
+ assert list(ksubsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)]
62
+ assert list(ksubsets([1, 2, 3, 4, 5], 2)) == [(1, 2), (1, 3), (1, 4),
63
+ (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
llmeval-env/lib/python3.10/site-packages/sympy/combinatorics/tests/test_testutil.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.named_groups import SymmetricGroup, AlternatingGroup,\
2
+ CyclicGroup
3
+ from sympy.combinatorics.testutil import _verify_bsgs, _cmp_perm_lists,\
4
+ _naive_list_centralizer, _verify_centralizer,\
5
+ _verify_normal_closure
6
+ from sympy.combinatorics.permutations import Permutation
7
+ from sympy.combinatorics.perm_groups import PermutationGroup
8
+ from sympy.core.random import shuffle
9
+
10
+
11
+ def test_cmp_perm_lists():
12
+ S = SymmetricGroup(4)
13
+ els = list(S.generate_dimino())
14
+ other = els[:]
15
+ shuffle(other)
16
+ assert _cmp_perm_lists(els, other) is True
17
+
18
+
19
+ def test_naive_list_centralizer():
20
+ # verified by GAP
21
+ S = SymmetricGroup(3)
22
+ A = AlternatingGroup(3)
23
+ assert _naive_list_centralizer(S, S) == [Permutation([0, 1, 2])]
24
+ assert PermutationGroup(_naive_list_centralizer(S, A)).is_subgroup(A)
25
+
26
+
27
+ def test_verify_bsgs():
28
+ S = SymmetricGroup(5)
29
+ S.schreier_sims()
30
+ base = S.base
31
+ strong_gens = S.strong_gens
32
+ assert _verify_bsgs(S, base, strong_gens) is True
33
+ assert _verify_bsgs(S, base[:-1], strong_gens) is False
34
+ assert _verify_bsgs(S, base, S.generators) is False
35
+
36
+
37
+ def test_verify_centralizer():
38
+ # verified by GAP
39
+ S = SymmetricGroup(3)
40
+ A = AlternatingGroup(3)
41
+ triv = PermutationGroup([Permutation([0, 1, 2])])
42
+ assert _verify_centralizer(S, S, centr=triv)
43
+ assert _verify_centralizer(S, A, centr=A)
44
+
45
+
46
+ def test_verify_normal_closure():
47
+ # verified by GAP
48
+ S = SymmetricGroup(3)
49
+ A = AlternatingGroup(3)
50
+ assert _verify_normal_closure(S, A, closure=A)
51
+ S = SymmetricGroup(5)
52
+ A = AlternatingGroup(5)
53
+ C = CyclicGroup(5)
54
+ assert _verify_normal_closure(S, A, closure=A)
55
+ assert _verify_normal_closure(S, C, closure=A)
llmeval-env/lib/python3.10/site-packages/sympy/logic/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .boolalg import (to_cnf, to_dnf, to_nnf, And, Or, Not, Xor, Nand, Nor, Implies,
2
+ Equivalent, ITE, POSform, SOPform, simplify_logic, bool_map, true, false,
3
+ gateinputcount)
4
+ from .inference import satisfiable
5
+
6
+ __all__ = [
7
+ 'to_cnf', 'to_dnf', 'to_nnf', 'And', 'Or', 'Not', 'Xor', 'Nand', 'Nor',
8
+ 'Implies', 'Equivalent', 'ITE', 'POSform', 'SOPform', 'simplify_logic',
9
+ 'bool_map', 'true', 'false', 'gateinputcount',
10
+
11
+ 'satisfiable',
12
+ ]
llmeval-env/lib/python3.10/site-packages/sympy/logic/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (695 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/logic/__pycache__/boolalg.cpython-310.pyc ADDED
Binary file (101 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/logic/__pycache__/inference.cpython-310.pyc ADDED
Binary file (9.01 kB). View file
 
llmeval-env/lib/python3.10/site-packages/sympy/logic/algorithms/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/sympy/logic/algorithms/dpll.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of DPLL algorithm
2
+
3
+ Further improvements: eliminate calls to pl_true, implement branching rules,
4
+ efficient unit propagation.
5
+
6
+ References:
7
+ - https://en.wikipedia.org/wiki/DPLL_algorithm
8
+ - https://www.researchgate.net/publication/242384772_Implementations_of_the_DPLL_Algorithm
9
+ """
10
+
11
+ from sympy.core.sorting import default_sort_key
12
+ from sympy.logic.boolalg import Or, Not, conjuncts, disjuncts, to_cnf, \
13
+ to_int_repr, _find_predicates
14
+ from sympy.assumptions.cnf import CNF
15
+ from sympy.logic.inference import pl_true, literal_symbol
16
+
17
+
18
+ def dpll_satisfiable(expr):
19
+ """
20
+ Check satisfiability of a propositional sentence.
21
+ It returns a model rather than True when it succeeds
22
+
23
+ >>> from sympy.abc import A, B
24
+ >>> from sympy.logic.algorithms.dpll import dpll_satisfiable
25
+ >>> dpll_satisfiable(A & ~B)
26
+ {A: True, B: False}
27
+ >>> dpll_satisfiable(A & ~A)
28
+ False
29
+
30
+ """
31
+ if not isinstance(expr, CNF):
32
+ clauses = conjuncts(to_cnf(expr))
33
+ else:
34
+ clauses = expr.clauses
35
+ if False in clauses:
36
+ return False
37
+ symbols = sorted(_find_predicates(expr), key=default_sort_key)
38
+ symbols_int_repr = set(range(1, len(symbols) + 1))
39
+ clauses_int_repr = to_int_repr(clauses, symbols)
40
+ result = dpll_int_repr(clauses_int_repr, symbols_int_repr, {})
41
+ if not result:
42
+ return result
43
+ output = {}
44
+ for key in result:
45
+ output.update({symbols[key - 1]: result[key]})
46
+ return output
47
+
48
+
49
+ def dpll(clauses, symbols, model):
50
+ """
51
+ Compute satisfiability in a partial model.
52
+ Clauses is an array of conjuncts.
53
+
54
+ >>> from sympy.abc import A, B, D
55
+ >>> from sympy.logic.algorithms.dpll import dpll
56
+ >>> dpll([A, B, D], [A, B], {D: False})
57
+ False
58
+
59
+ """
60
+ # compute DP kernel
61
+ P, value = find_unit_clause(clauses, model)
62
+ while P:
63
+ model.update({P: value})
64
+ symbols.remove(P)
65
+ if not value:
66
+ P = ~P
67
+ clauses = unit_propagate(clauses, P)
68
+ P, value = find_unit_clause(clauses, model)
69
+ P, value = find_pure_symbol(symbols, clauses)
70
+ while P:
71
+ model.update({P: value})
72
+ symbols.remove(P)
73
+ if not value:
74
+ P = ~P
75
+ clauses = unit_propagate(clauses, P)
76
+ P, value = find_pure_symbol(symbols, clauses)
77
+ # end DP kernel
78
+ unknown_clauses = []
79
+ for c in clauses:
80
+ val = pl_true(c, model)
81
+ if val is False:
82
+ return False
83
+ if val is not True:
84
+ unknown_clauses.append(c)
85
+ if not unknown_clauses:
86
+ return model
87
+ if not clauses:
88
+ return model
89
+ P = symbols.pop()
90
+ model_copy = model.copy()
91
+ model.update({P: True})
92
+ model_copy.update({P: False})
93
+ symbols_copy = symbols[:]
94
+ return (dpll(unit_propagate(unknown_clauses, P), symbols, model) or
95
+ dpll(unit_propagate(unknown_clauses, Not(P)), symbols_copy, model_copy))
96
+
97
+
98
+ def dpll_int_repr(clauses, symbols, model):
99
+ """
100
+ Compute satisfiability in a partial model.
101
+ Arguments are expected to be in integer representation
102
+
103
+ >>> from sympy.logic.algorithms.dpll import dpll_int_repr
104
+ >>> dpll_int_repr([{1}, {2}, {3}], {1, 2}, {3: False})
105
+ False
106
+
107
+ """
108
+ # compute DP kernel
109
+ P, value = find_unit_clause_int_repr(clauses, model)
110
+ while P:
111
+ model.update({P: value})
112
+ symbols.remove(P)
113
+ if not value:
114
+ P = -P
115
+ clauses = unit_propagate_int_repr(clauses, P)
116
+ P, value = find_unit_clause_int_repr(clauses, model)
117
+ P, value = find_pure_symbol_int_repr(symbols, clauses)
118
+ while P:
119
+ model.update({P: value})
120
+ symbols.remove(P)
121
+ if not value:
122
+ P = -P
123
+ clauses = unit_propagate_int_repr(clauses, P)
124
+ P, value = find_pure_symbol_int_repr(symbols, clauses)
125
+ # end DP kernel
126
+ unknown_clauses = []
127
+ for c in clauses:
128
+ val = pl_true_int_repr(c, model)
129
+ if val is False:
130
+ return False
131
+ if val is not True:
132
+ unknown_clauses.append(c)
133
+ if not unknown_clauses:
134
+ return model
135
+ P = symbols.pop()
136
+ model_copy = model.copy()
137
+ model.update({P: True})
138
+ model_copy.update({P: False})
139
+ symbols_copy = symbols.copy()
140
+ return (dpll_int_repr(unit_propagate_int_repr(unknown_clauses, P), symbols, model) or
141
+ dpll_int_repr(unit_propagate_int_repr(unknown_clauses, -P), symbols_copy, model_copy))
142
+
143
+ ### helper methods for DPLL
144
+
145
+
146
+ def pl_true_int_repr(clause, model={}):
147
+ """
148
+ Lightweight version of pl_true.
149
+ Argument clause represents the set of args of an Or clause. This is used
150
+ inside dpll_int_repr, it is not meant to be used directly.
151
+
152
+ >>> from sympy.logic.algorithms.dpll import pl_true_int_repr
153
+ >>> pl_true_int_repr({1, 2}, {1: False})
154
+ >>> pl_true_int_repr({1, 2}, {1: False, 2: False})
155
+ False
156
+
157
+ """
158
+ result = False
159
+ for lit in clause:
160
+ if lit < 0:
161
+ p = model.get(-lit)
162
+ if p is not None:
163
+ p = not p
164
+ else:
165
+ p = model.get(lit)
166
+ if p is True:
167
+ return True
168
+ elif p is None:
169
+ result = None
170
+ return result
171
+
172
+
173
+ def unit_propagate(clauses, symbol):
174
+ """
175
+ Returns an equivalent set of clauses
176
+ If a set of clauses contains the unit clause l, the other clauses are
177
+ simplified by the application of the two following rules:
178
+
179
+ 1. every clause containing l is removed
180
+ 2. in every clause that contains ~l this literal is deleted
181
+
182
+ Arguments are expected to be in CNF.
183
+
184
+ >>> from sympy.abc import A, B, D
185
+ >>> from sympy.logic.algorithms.dpll import unit_propagate
186
+ >>> unit_propagate([A | B, D | ~B, B], B)
187
+ [D, B]
188
+
189
+ """
190
+ output = []
191
+ for c in clauses:
192
+ if c.func != Or:
193
+ output.append(c)
194
+ continue
195
+ for arg in c.args:
196
+ if arg == ~symbol:
197
+ output.append(Or(*[x for x in c.args if x != ~symbol]))
198
+ break
199
+ if arg == symbol:
200
+ break
201
+ else:
202
+ output.append(c)
203
+ return output
204
+
205
+
206
+ def unit_propagate_int_repr(clauses, s):
207
+ """
208
+ Same as unit_propagate, but arguments are expected to be in integer
209
+ representation
210
+
211
+ >>> from sympy.logic.algorithms.dpll import unit_propagate_int_repr
212
+ >>> unit_propagate_int_repr([{1, 2}, {3, -2}, {2}], 2)
213
+ [{3}]
214
+
215
+ """
216
+ negated = {-s}
217
+ return [clause - negated for clause in clauses if s not in clause]
218
+
219
+
220
+ def find_pure_symbol(symbols, unknown_clauses):
221
+ """
222
+ Find a symbol and its value if it appears only as a positive literal
223
+ (or only as a negative) in clauses.
224
+
225
+ >>> from sympy.abc import A, B, D
226
+ >>> from sympy.logic.algorithms.dpll import find_pure_symbol
227
+ >>> find_pure_symbol([A, B, D], [A|~B,~B|~D,D|A])
228
+ (A, True)
229
+
230
+ """
231
+ for sym in symbols:
232
+ found_pos, found_neg = False, False
233
+ for c in unknown_clauses:
234
+ if not found_pos and sym in disjuncts(c):
235
+ found_pos = True
236
+ if not found_neg and Not(sym) in disjuncts(c):
237
+ found_neg = True
238
+ if found_pos != found_neg:
239
+ return sym, found_pos
240
+ return None, None
241
+
242
+
243
+ def find_pure_symbol_int_repr(symbols, unknown_clauses):
244
+ """
245
+ Same as find_pure_symbol, but arguments are expected
246
+ to be in integer representation
247
+
248
+ >>> from sympy.logic.algorithms.dpll import find_pure_symbol_int_repr
249
+ >>> find_pure_symbol_int_repr({1,2,3},
250
+ ... [{1, -2}, {-2, -3}, {3, 1}])
251
+ (1, True)
252
+
253
+ """
254
+ all_symbols = set().union(*unknown_clauses)
255
+ found_pos = all_symbols.intersection(symbols)
256
+ found_neg = all_symbols.intersection([-s for s in symbols])
257
+ for p in found_pos:
258
+ if -p not in found_neg:
259
+ return p, True
260
+ for p in found_neg:
261
+ if -p not in found_pos:
262
+ return -p, False
263
+ return None, None
264
+
265
+
266
+ def find_unit_clause(clauses, model):
267
+ """
268
+ A unit clause has only 1 variable that is not bound in the model.
269
+
270
+ >>> from sympy.abc import A, B, D
271
+ >>> from sympy.logic.algorithms.dpll import find_unit_clause
272
+ >>> find_unit_clause([A | B | D, B | ~D, A | ~B], {A:True})
273
+ (B, False)
274
+
275
+ """
276
+ for clause in clauses:
277
+ num_not_in_model = 0
278
+ for literal in disjuncts(clause):
279
+ sym = literal_symbol(literal)
280
+ if sym not in model:
281
+ num_not_in_model += 1
282
+ P, value = sym, not isinstance(literal, Not)
283
+ if num_not_in_model == 1:
284
+ return P, value
285
+ return None, None
286
+
287
+
288
+ def find_unit_clause_int_repr(clauses, model):
289
+ """
290
+ Same as find_unit_clause, but arguments are expected to be in
291
+ integer representation.
292
+
293
+ >>> from sympy.logic.algorithms.dpll import find_unit_clause_int_repr
294
+ >>> find_unit_clause_int_repr([{1, 2, 3},
295
+ ... {2, -3}, {1, -2}], {1: True})
296
+ (2, False)
297
+
298
+ """
299
+ bound = set(model) | {-sym for sym in model}
300
+ for clause in clauses:
301
+ unbound = clause - bound
302
+ if len(unbound) == 1:
303
+ p = unbound.pop()
304
+ if p < 0:
305
+ return -p, False
306
+ else:
307
+ return p, True
308
+ return None, None