applied-ai-018 commited on
Commit
5768eac
·
verified ·
1 Parent(s): 97192e6

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. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.bz2 +3 -0
  2. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.xz +3 -0
  3. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz +3 -0
  4. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl +3 -0
  5. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_02.npy +3 -0
  6. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_04.npy +3 -0
  7. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy +3 -0
  8. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy +3 -0
  9. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_04.npy +3 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-310.pyc +0 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py +74 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py +103 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__init__.py +43 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/__init__.cpython-310.pyc +0 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/coset_table.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/fp_groups.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/free_groups.cpython-310.pyc +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/galois.cpython-310.pyc +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/generators.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/graycode.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/group_constructs.cpython-310.pyc +0 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/group_numbers.cpython-310.pyc +0 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/homomorphisms.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/named_groups.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/partitions.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/pc_groups.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/permutations.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/polyhedron.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/prufer.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/rewritingsystem.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/rewritingsystem_fsm.cpython-310.pyc +0 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/schur_number.cpython-310.pyc +0 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/subsets.cpython-310.pyc +0 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/tensor_can.cpython-310.pyc +0 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/testutil.cpython-310.pyc +0 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/util.cpython-310.pyc +0 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/coset_table.py +1255 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.py +1348 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/free_groups.py +1354 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/galois.py +611 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/generators.py +302 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/group_constructs.py +61 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/group_numbers.py +118 -0
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.bz2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f2af67ea667c1f5315ddcab06bfa447005863c1c0fd88bb7e04a0b8acb9a54b
3
+ size 1021
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py34_np19.pkl.xz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:04d7e68907e978b56975f9309492b8849e42a60974beb795c9e93273977f3cd3
3
+ size 752
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.10.0_pickle_py35_np19.pkl.xz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02cf30d8b196c303662b2dd035d2a58caeb762ae3a82345ffd1274961e7f5aa0
3
+ size 752
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3d4cbc690d3ce9e5323a714ea546f32c01ab1710285c420184f6cdf4b26fc25
3
+ size 691
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_02.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1
3
+ size 120
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_04.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05
3
+ size 104
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py34_np19.pkl_03.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ede9a64a52b25d7db30950956c978ec0b3932b7d14acd5abc63216e64babde7
3
+ size 307
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_02.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c1cf36cb781fbcc21b953bb0a0b45df092da0eae0e765882e5963ccd70105b1
3
+ size 120
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py35_np19.pkl_04.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3ecbe244294ba93e08479b16c1b9a9411e3569ff660ed0459dca1d241381df05
3
+ size 104
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (185 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_accumulationbounds.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_euler.cpython-310.pyc ADDED
Binary file (3.83 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_finite_diff.cpython-310.pyc ADDED
Binary file (7.47 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_singularities.cpython-310.pyc ADDED
Binary file (4.69 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/__pycache__/test_util.cpython-310.pyc ADDED
Binary file (15.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_euler.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import (Derivative as D, Function)
2
+ from sympy.core.relational import Eq
3
+ from sympy.core.symbol import (Symbol, symbols)
4
+ from sympy.functions.elementary.trigonometric import (cos, sin)
5
+ from sympy.testing.pytest import raises
6
+ from sympy.calculus.euler import euler_equations as euler
7
+
8
+
9
+ def test_euler_interface():
10
+ x = Function('x')
11
+ y = Symbol('y')
12
+ t = Symbol('t')
13
+ raises(TypeError, lambda: euler())
14
+ raises(TypeError, lambda: euler(D(x(t), t)*y(t), [x(t), y]))
15
+ raises(ValueError, lambda: euler(D(x(t), t)*x(y), [x(t), x(y)]))
16
+ raises(TypeError, lambda: euler(D(x(t), t)**2, x(0)))
17
+ raises(TypeError, lambda: euler(D(x(t), t)*y(t), [t]))
18
+ assert euler(D(x(t), t)**2/2, {x(t)}) == [Eq(-D(x(t), t, t), 0)]
19
+ assert euler(D(x(t), t)**2/2, x(t), {t}) == [Eq(-D(x(t), t, t), 0)]
20
+
21
+
22
+ def test_euler_pendulum():
23
+ x = Function('x')
24
+ t = Symbol('t')
25
+ L = D(x(t), t)**2/2 + cos(x(t))
26
+ assert euler(L, x(t), t) == [Eq(-sin(x(t)) - D(x(t), t, t), 0)]
27
+
28
+
29
+ def test_euler_henonheiles():
30
+ x = Function('x')
31
+ y = Function('y')
32
+ t = Symbol('t')
33
+ L = sum(D(z(t), t)**2/2 - z(t)**2/2 for z in [x, y])
34
+ L += -x(t)**2*y(t) + y(t)**3/3
35
+ assert euler(L, [x(t), y(t)], t) == [Eq(-2*x(t)*y(t) - x(t) -
36
+ D(x(t), t, t), 0),
37
+ Eq(-x(t)**2 + y(t)**2 -
38
+ y(t) - D(y(t), t, t), 0)]
39
+
40
+
41
+ def test_euler_sineg():
42
+ psi = Function('psi')
43
+ t = Symbol('t')
44
+ x = Symbol('x')
45
+ L = D(psi(t, x), t)**2/2 - D(psi(t, x), x)**2/2 + cos(psi(t, x))
46
+ assert euler(L, psi(t, x), [t, x]) == [Eq(-sin(psi(t, x)) -
47
+ D(psi(t, x), t, t) +
48
+ D(psi(t, x), x, x), 0)]
49
+
50
+
51
+ def test_euler_high_order():
52
+ # an example from hep-th/0309038
53
+ m = Symbol('m')
54
+ k = Symbol('k')
55
+ x = Function('x')
56
+ y = Function('y')
57
+ t = Symbol('t')
58
+ L = (m*D(x(t), t)**2/2 + m*D(y(t), t)**2/2 -
59
+ k*D(x(t), t)*D(y(t), t, t) + k*D(y(t), t)*D(x(t), t, t))
60
+ assert euler(L, [x(t), y(t)]) == [Eq(2*k*D(y(t), t, t, t) -
61
+ m*D(x(t), t, t), 0),
62
+ Eq(-2*k*D(x(t), t, t, t) -
63
+ m*D(y(t), t, t), 0)]
64
+
65
+ w = Symbol('w')
66
+ L = D(x(t, w), t, w)**2/2
67
+ assert euler(L) == [Eq(D(x(t, w), t, t, w, w), 0)]
68
+
69
+ def test_issue_18653():
70
+ x, y, z = symbols("x y z")
71
+ f, g, h = symbols("f g h", cls=Function, args=(x, y))
72
+ f, g, h = f(), g(), h()
73
+ expr2 = f.diff(x)*h.diff(z)
74
+ assert euler(expr2, (f,), (x, y)) == []
env-llmeval/lib/python3.10/site-packages/sympy/calculus/tests/test_singularities.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import (I, Rational, oo)
2
+ from sympy.core.singleton import S
3
+ from sympy.core.symbol import Symbol
4
+ from sympy.functions.elementary.exponential import (exp, log)
5
+ from sympy.functions.elementary.miscellaneous import sqrt
6
+ from sympy.calculus.singularities import (
7
+ singularities,
8
+ is_increasing,
9
+ is_strictly_increasing,
10
+ is_decreasing,
11
+ is_strictly_decreasing,
12
+ is_monotonic
13
+ )
14
+ from sympy.sets import Interval, FiniteSet
15
+ from sympy.testing.pytest import raises
16
+ from sympy.abc import x, y
17
+
18
+
19
+ def test_singularities():
20
+ x = Symbol('x')
21
+ assert singularities(x**2, x) == S.EmptySet
22
+ assert singularities(x/(x**2 + 3*x + 2), x) == FiniteSet(-2, -1)
23
+ assert singularities(1/(x**2 + 1), x) == FiniteSet(I, -I)
24
+ assert singularities(x/(x**3 + 1), x) == \
25
+ FiniteSet(-1, (1 - sqrt(3) * I) / 2, (1 + sqrt(3) * I) / 2)
26
+ assert singularities(1/(y**2 + 2*I*y + 1), y) == \
27
+ FiniteSet(-I + sqrt(2)*I, -I - sqrt(2)*I)
28
+
29
+ x = Symbol('x', real=True)
30
+ assert singularities(1/(x**2 + 1), x) == S.EmptySet
31
+ assert singularities(exp(1/x), x, S.Reals) == FiniteSet(0)
32
+ assert singularities(exp(1/x), x, Interval(1, 2)) == S.EmptySet
33
+ assert singularities(log((x - 2)**2), x, Interval(1, 3)) == FiniteSet(2)
34
+ raises(NotImplementedError, lambda: singularities(x**-oo, x))
35
+
36
+
37
+ def test_is_increasing():
38
+ """Test whether is_increasing returns correct value."""
39
+ a = Symbol('a', negative=True)
40
+
41
+ assert is_increasing(x**3 - 3*x**2 + 4*x, S.Reals)
42
+ assert is_increasing(-x**2, Interval(-oo, 0))
43
+ assert not is_increasing(-x**2, Interval(0, oo))
44
+ assert not is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3))
45
+ assert is_increasing(x**2 + y, Interval(1, oo), x)
46
+ assert is_increasing(-x**2*a, Interval(1, oo), x)
47
+ assert is_increasing(1)
48
+
49
+ assert is_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval(-2, 3)) is False
50
+
51
+
52
+ def test_is_strictly_increasing():
53
+ """Test whether is_strictly_increasing returns correct value."""
54
+ assert is_strictly_increasing(
55
+ 4*x**3 - 6*x**2 - 72*x + 30, Interval.Ropen(-oo, -2))
56
+ assert is_strictly_increasing(
57
+ 4*x**3 - 6*x**2 - 72*x + 30, Interval.Lopen(3, oo))
58
+ assert not is_strictly_increasing(
59
+ 4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3))
60
+ assert not is_strictly_increasing(-x**2, Interval(0, oo))
61
+ assert not is_strictly_decreasing(1)
62
+
63
+ assert is_strictly_increasing(4*x**3 - 6*x**2 - 72*x + 30, Interval.open(-2, 3)) is False
64
+
65
+
66
+ def test_is_decreasing():
67
+ """Test whether is_decreasing returns correct value."""
68
+ b = Symbol('b', positive=True)
69
+
70
+ assert is_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
71
+ assert is_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
72
+ assert is_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
73
+ assert not is_decreasing(1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
74
+ assert not is_decreasing(-x**2, Interval(-oo, 0))
75
+ assert not is_decreasing(-x**2*b, Interval(-oo, 0), x)
76
+
77
+
78
+ def test_is_strictly_decreasing():
79
+ """Test whether is_strictly_decreasing returns correct value."""
80
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.Lopen(3, oo))
81
+ assert not is_strictly_decreasing(
82
+ 1/(x**2 - 3*x), Interval.Ropen(-oo, Rational(3, 2)))
83
+ assert not is_strictly_decreasing(-x**2, Interval(-oo, 0))
84
+ assert not is_strictly_decreasing(1)
85
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
86
+ assert is_strictly_decreasing(1/(x**2 - 3*x), Interval.open(1.5, 3))
87
+
88
+
89
+ def test_is_monotonic():
90
+ """Test whether is_monotonic returns correct value."""
91
+ assert is_monotonic(1/(x**2 - 3*x), Interval.open(Rational(3,2), 3))
92
+ assert is_monotonic(1/(x**2 - 3*x), Interval.open(1.5, 3))
93
+ assert is_monotonic(1/(x**2 - 3*x), Interval.Lopen(3, oo))
94
+ assert is_monotonic(x**3 - 3*x**2 + 4*x, S.Reals)
95
+ assert not is_monotonic(-x**2, S.Reals)
96
+ assert is_monotonic(x**2 + y + 1, Interval(1, 2), x)
97
+ raises(NotImplementedError, lambda: is_monotonic(x**2 + y + 1))
98
+
99
+
100
+ def test_issue_23401():
101
+ x = Symbol('x')
102
+ expr = (x + 1)/(-1.0e-3*x**2 + 0.1*x + 0.1)
103
+ assert is_increasing(expr, Interval(1,2), x)
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.permutations import Permutation, Cycle
2
+ from sympy.combinatorics.prufer import Prufer
3
+ from sympy.combinatorics.generators import cyclic, alternating, symmetric, dihedral
4
+ from sympy.combinatorics.subsets import Subset
5
+ from sympy.combinatorics.partitions import (Partition, IntegerPartition,
6
+ RGS_rank, RGS_unrank, RGS_enum)
7
+ from sympy.combinatorics.polyhedron import (Polyhedron, tetrahedron, cube,
8
+ octahedron, dodecahedron, icosahedron)
9
+ from sympy.combinatorics.perm_groups import PermutationGroup, Coset, SymmetricPermutationGroup
10
+ from sympy.combinatorics.group_constructs import DirectProduct
11
+ from sympy.combinatorics.graycode import GrayCode
12
+ from sympy.combinatorics.named_groups import (SymmetricGroup, DihedralGroup,
13
+ CyclicGroup, AlternatingGroup, AbelianGroup, RubikGroup)
14
+ from sympy.combinatorics.pc_groups import PolycyclicGroup, Collector
15
+ from sympy.combinatorics.free_groups import free_group
16
+
17
+ __all__ = [
18
+ 'Permutation', 'Cycle',
19
+
20
+ 'Prufer',
21
+
22
+ 'cyclic', 'alternating', 'symmetric', 'dihedral',
23
+
24
+ 'Subset',
25
+
26
+ 'Partition', 'IntegerPartition', 'RGS_rank', 'RGS_unrank', 'RGS_enum',
27
+
28
+ 'Polyhedron', 'tetrahedron', 'cube', 'octahedron', 'dodecahedron',
29
+ 'icosahedron',
30
+
31
+ 'PermutationGroup', 'Coset', 'SymmetricPermutationGroup',
32
+
33
+ 'DirectProduct',
34
+
35
+ 'GrayCode',
36
+
37
+ 'SymmetricGroup', 'DihedralGroup', 'CyclicGroup', 'AlternatingGroup',
38
+ 'AbelianGroup', 'RubikGroup',
39
+
40
+ 'PolycyclicGroup', 'Collector',
41
+
42
+ 'free_group',
43
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.61 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/coset_table.cpython-310.pyc ADDED
Binary file (34.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/fp_groups.cpython-310.pyc ADDED
Binary file (38.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/free_groups.cpython-310.pyc ADDED
Binary file (38.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/galois.cpython-310.pyc ADDED
Binary file (17.3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/generators.cpython-310.pyc ADDED
Binary file (8.28 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/graycode.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/group_constructs.cpython-310.pyc ADDED
Binary file (2.13 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/group_numbers.cpython-310.pyc ADDED
Binary file (3.42 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/homomorphisms.cpython-310.pyc ADDED
Binary file (16.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/named_groups.cpython-310.pyc ADDED
Binary file (8.14 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/partitions.cpython-310.pyc ADDED
Binary file (21.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/pc_groups.cpython-310.pyc ADDED
Binary file (20 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc ADDED
Binary file (153 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/permutations.cpython-310.pyc ADDED
Binary file (89.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/polyhedron.cpython-310.pyc ADDED
Binary file (33.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/prufer.cpython-310.pyc ADDED
Binary file (12.1 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/rewritingsystem.cpython-310.pyc ADDED
Binary file (10.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/rewritingsystem_fsm.cpython-310.pyc ADDED
Binary file (3 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/schur_number.cpython-310.pyc ADDED
Binary file (5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/subsets.cpython-310.pyc ADDED
Binary file (15.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/tensor_can.cpython-310.pyc ADDED
Binary file (37.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/testutil.cpython-310.pyc ADDED
Binary file (9.76 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/util.cpython-310.pyc ADDED
Binary file (14.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/coset_table.py ADDED
@@ -0,0 +1,1255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.free_groups import free_group
2
+ from sympy.printing.defaults import DefaultPrinting
3
+
4
+ from itertools import chain, product
5
+ from bisect import bisect_left
6
+
7
+
8
+ ###############################################################################
9
+ # COSET TABLE #
10
+ ###############################################################################
11
+
12
+ class CosetTable(DefaultPrinting):
13
+ # coset_table: Mathematically a coset table
14
+ # represented using a list of lists
15
+ # alpha: Mathematically a coset (precisely, a live coset)
16
+ # represented by an integer between i with 1 <= i <= n
17
+ # alpha in c
18
+ # x: Mathematically an element of "A" (set of generators and
19
+ # their inverses), represented using "FpGroupElement"
20
+ # fp_grp: Finitely Presented Group with < X|R > as presentation.
21
+ # H: subgroup of fp_grp.
22
+ # NOTE: We start with H as being only a list of words in generators
23
+ # of "fp_grp". Since `.subgroup` method has not been implemented.
24
+
25
+ r"""
26
+
27
+ Properties
28
+ ==========
29
+
30
+ [1] `0 \in \Omega` and `\tau(1) = \epsilon`
31
+ [2] `\alpha^x = \beta \Leftrightarrow \beta^{x^{-1}} = \alpha`
32
+ [3] If `\alpha^x = \beta`, then `H \tau(\alpha)x = H \tau(\beta)`
33
+ [4] `\forall \alpha \in \Omega, 1^{\tau(\alpha)} = \alpha`
34
+
35
+ References
36
+ ==========
37
+
38
+ .. [1] Holt, D., Eick, B., O'Brien, E.
39
+ "Handbook of Computational Group Theory"
40
+
41
+ .. [2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson
42
+ Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490.
43
+ "Implementation and Analysis of the Todd-Coxeter Algorithm"
44
+
45
+ """
46
+ # default limit for the number of cosets allowed in a
47
+ # coset enumeration.
48
+ coset_table_max_limit = 4096000
49
+ # limit for the current instance
50
+ coset_table_limit = None
51
+ # maximum size of deduction stack above or equal to
52
+ # which it is emptied
53
+ max_stack_size = 100
54
+
55
+ def __init__(self, fp_grp, subgroup, max_cosets=None):
56
+ if not max_cosets:
57
+ max_cosets = CosetTable.coset_table_max_limit
58
+ self.fp_group = fp_grp
59
+ self.subgroup = subgroup
60
+ self.coset_table_limit = max_cosets
61
+ # "p" is setup independent of Omega and n
62
+ self.p = [0]
63
+ # a list of the form `[gen_1, gen_1^{-1}, ... , gen_k, gen_k^{-1}]`
64
+ self.A = list(chain.from_iterable((gen, gen**-1) \
65
+ for gen in self.fp_group.generators))
66
+ #P[alpha, x] Only defined when alpha^x is defined.
67
+ self.P = [[None]*len(self.A)]
68
+ # the mathematical coset table which is a list of lists
69
+ self.table = [[None]*len(self.A)]
70
+ self.A_dict = {x: self.A.index(x) for x in self.A}
71
+ self.A_dict_inv = {}
72
+ for x, index in self.A_dict.items():
73
+ if index % 2 == 0:
74
+ self.A_dict_inv[x] = self.A_dict[x] + 1
75
+ else:
76
+ self.A_dict_inv[x] = self.A_dict[x] - 1
77
+ # used in the coset-table based method of coset enumeration. Each of
78
+ # the element is called a "deduction" which is the form (alpha, x) whenever
79
+ # a value is assigned to alpha^x during a definition or "deduction process"
80
+ self.deduction_stack = []
81
+ # Attributes for modified methods.
82
+ H = self.subgroup
83
+ self._grp = free_group(', ' .join(["a_%d" % i for i in range(len(H))]))[0]
84
+ self.P = [[None]*len(self.A)]
85
+ self.p_p = {}
86
+
87
+ @property
88
+ def omega(self):
89
+ """Set of live cosets. """
90
+ return [coset for coset in range(len(self.p)) if self.p[coset] == coset]
91
+
92
+ def copy(self):
93
+ """
94
+ Return a shallow copy of Coset Table instance ``self``.
95
+
96
+ """
97
+ self_copy = self.__class__(self.fp_group, self.subgroup)
98
+ self_copy.table = [list(perm_rep) for perm_rep in self.table]
99
+ self_copy.p = list(self.p)
100
+ self_copy.deduction_stack = list(self.deduction_stack)
101
+ return self_copy
102
+
103
+ def __str__(self):
104
+ return "Coset Table on %s with %s as subgroup generators" \
105
+ % (self.fp_group, self.subgroup)
106
+
107
+ __repr__ = __str__
108
+
109
+ @property
110
+ def n(self):
111
+ """The number `n` represents the length of the sublist containing the
112
+ live cosets.
113
+
114
+ """
115
+ if not self.table:
116
+ return 0
117
+ return max(self.omega) + 1
118
+
119
+ # Pg. 152 [1]
120
+ def is_complete(self):
121
+ r"""
122
+ The coset table is called complete if it has no undefined entries
123
+ on the live cosets; that is, `\alpha^x` is defined for all
124
+ `\alpha \in \Omega` and `x \in A`.
125
+
126
+ """
127
+ return not any(None in self.table[coset] for coset in self.omega)
128
+
129
+ # Pg. 153 [1]
130
+ def define(self, alpha, x, modified=False):
131
+ r"""
132
+ This routine is used in the relator-based strategy of Todd-Coxeter
133
+ algorithm if some `\alpha^x` is undefined. We check whether there is
134
+ space available for defining a new coset. If there is enough space
135
+ then we remedy this by adjoining a new coset `\beta` to `\Omega`
136
+ (i.e to set of live cosets) and put that equal to `\alpha^x`, then
137
+ make an assignment satisfying Property[1]. If there is not enough space
138
+ then we halt the Coset Table creation. The maximum amount of space that
139
+ can be used by Coset Table can be manipulated using the class variable
140
+ ``CosetTable.coset_table_max_limit``.
141
+
142
+ See Also
143
+ ========
144
+
145
+ define_c
146
+
147
+ """
148
+ A = self.A
149
+ table = self.table
150
+ len_table = len(table)
151
+ if len_table >= self.coset_table_limit:
152
+ # abort the further generation of cosets
153
+ raise ValueError("the coset enumeration has defined more than "
154
+ "%s cosets. Try with a greater value max number of cosets "
155
+ % self.coset_table_limit)
156
+ table.append([None]*len(A))
157
+ self.P.append([None]*len(self.A))
158
+ # beta is the new coset generated
159
+ beta = len_table
160
+ self.p.append(beta)
161
+ table[alpha][self.A_dict[x]] = beta
162
+ table[beta][self.A_dict_inv[x]] = alpha
163
+ # P[alpha][x] = epsilon, P[beta][x**-1] = epsilon
164
+ if modified:
165
+ self.P[alpha][self.A_dict[x]] = self._grp.identity
166
+ self.P[beta][self.A_dict_inv[x]] = self._grp.identity
167
+ self.p_p[beta] = self._grp.identity
168
+
169
+ def define_c(self, alpha, x):
170
+ r"""
171
+ A variation of ``define`` routine, described on Pg. 165 [1], used in
172
+ the coset table-based strategy of Todd-Coxeter algorithm. It differs
173
+ from ``define`` routine in that for each definition it also adds the
174
+ tuple `(\alpha, x)` to the deduction stack.
175
+
176
+ See Also
177
+ ========
178
+
179
+ define
180
+
181
+ """
182
+ A = self.A
183
+ table = self.table
184
+ len_table = len(table)
185
+ if len_table >= self.coset_table_limit:
186
+ # abort the further generation of cosets
187
+ raise ValueError("the coset enumeration has defined more than "
188
+ "%s cosets. Try with a greater value max number of cosets "
189
+ % self.coset_table_limit)
190
+ table.append([None]*len(A))
191
+ # beta is the new coset generated
192
+ beta = len_table
193
+ self.p.append(beta)
194
+ table[alpha][self.A_dict[x]] = beta
195
+ table[beta][self.A_dict_inv[x]] = alpha
196
+ # append to deduction stack
197
+ self.deduction_stack.append((alpha, x))
198
+
199
+ def scan_c(self, alpha, word):
200
+ """
201
+ A variation of ``scan`` routine, described on pg. 165 of [1], which
202
+ puts at tuple, whenever a deduction occurs, to deduction stack.
203
+
204
+ See Also
205
+ ========
206
+
207
+ scan, scan_check, scan_and_fill, scan_and_fill_c
208
+
209
+ """
210
+ # alpha is an integer representing a "coset"
211
+ # since scanning can be in two cases
212
+ # 1. for alpha=0 and w in Y (i.e generating set of H)
213
+ # 2. alpha in Omega (set of live cosets), w in R (relators)
214
+ A_dict = self.A_dict
215
+ A_dict_inv = self.A_dict_inv
216
+ table = self.table
217
+ f = alpha
218
+ i = 0
219
+ r = len(word)
220
+ b = alpha
221
+ j = r - 1
222
+ # list of union of generators and their inverses
223
+ while i <= j and table[f][A_dict[word[i]]] is not None:
224
+ f = table[f][A_dict[word[i]]]
225
+ i += 1
226
+ if i > j:
227
+ if f != b:
228
+ self.coincidence_c(f, b)
229
+ return
230
+ while j >= i and table[b][A_dict_inv[word[j]]] is not None:
231
+ b = table[b][A_dict_inv[word[j]]]
232
+ j -= 1
233
+ if j < i:
234
+ # we have an incorrect completed scan with coincidence f ~ b
235
+ # run the "coincidence" routine
236
+ self.coincidence_c(f, b)
237
+ elif j == i:
238
+ # deduction process
239
+ table[f][A_dict[word[i]]] = b
240
+ table[b][A_dict_inv[word[i]]] = f
241
+ self.deduction_stack.append((f, word[i]))
242
+ # otherwise scan is incomplete and yields no information
243
+
244
+ # alpha, beta coincide, i.e. alpha, beta represent the pair of cosets where
245
+ # coincidence occurs
246
+ def coincidence_c(self, alpha, beta):
247
+ """
248
+ A variation of ``coincidence`` routine used in the coset-table based
249
+ method of coset enumeration. The only difference being on addition of
250
+ a new coset in coset table(i.e new coset introduction), then it is
251
+ appended to ``deduction_stack``.
252
+
253
+ See Also
254
+ ========
255
+
256
+ coincidence
257
+
258
+ """
259
+ A_dict = self.A_dict
260
+ A_dict_inv = self.A_dict_inv
261
+ table = self.table
262
+ # behaves as a queue
263
+ q = []
264
+ self.merge(alpha, beta, q)
265
+ while len(q) > 0:
266
+ gamma = q.pop(0)
267
+ for x in A_dict:
268
+ delta = table[gamma][A_dict[x]]
269
+ if delta is not None:
270
+ table[delta][A_dict_inv[x]] = None
271
+ # only line of difference from ``coincidence`` routine
272
+ self.deduction_stack.append((delta, x**-1))
273
+ mu = self.rep(gamma)
274
+ nu = self.rep(delta)
275
+ if table[mu][A_dict[x]] is not None:
276
+ self.merge(nu, table[mu][A_dict[x]], q)
277
+ elif table[nu][A_dict_inv[x]] is not None:
278
+ self.merge(mu, table[nu][A_dict_inv[x]], q)
279
+ else:
280
+ table[mu][A_dict[x]] = nu
281
+ table[nu][A_dict_inv[x]] = mu
282
+
283
+ def scan(self, alpha, word, y=None, fill=False, modified=False):
284
+ r"""
285
+ ``scan`` performs a scanning process on the input ``word``.
286
+ It first locates the largest prefix ``s`` of ``word`` for which
287
+ `\alpha^s` is defined (i.e is not ``None``), ``s`` may be empty. Let
288
+ ``word=sv``, let ``t`` be the longest suffix of ``v`` for which
289
+ `\alpha^{t^{-1}}` is defined, and let ``v=ut``. Then three
290
+ possibilities are there:
291
+
292
+ 1. If ``t=v``, then we say that the scan completes, and if, in addition
293
+ `\alpha^s = \alpha^{t^{-1}}`, then we say that the scan completes
294
+ correctly.
295
+
296
+ 2. It can also happen that scan does not complete, but `|u|=1`; that
297
+ is, the word ``u`` consists of a single generator `x \in A`. In that
298
+ case, if `\alpha^s = \beta` and `\alpha^{t^{-1}} = \gamma`, then we can
299
+ set `\beta^x = \gamma` and `\gamma^{x^{-1}} = \beta`. These assignments
300
+ are known as deductions and enable the scan to complete correctly.
301
+
302
+ 3. See ``coicidence`` routine for explanation of third condition.
303
+
304
+ Notes
305
+ =====
306
+
307
+ The code for the procedure of scanning `\alpha \in \Omega`
308
+ under `w \in A*` is defined on pg. 155 [1]
309
+
310
+ See Also
311
+ ========
312
+
313
+ scan_c, scan_check, scan_and_fill, scan_and_fill_c
314
+
315
+ Scan and Fill
316
+ =============
317
+
318
+ Performed when the default argument fill=True.
319
+
320
+ Modified Scan
321
+ =============
322
+
323
+ Performed when the default argument modified=True
324
+
325
+ """
326
+ # alpha is an integer representing a "coset"
327
+ # since scanning can be in two cases
328
+ # 1. for alpha=0 and w in Y (i.e generating set of H)
329
+ # 2. alpha in Omega (set of live cosets), w in R (relators)
330
+ A_dict = self.A_dict
331
+ A_dict_inv = self.A_dict_inv
332
+ table = self.table
333
+ f = alpha
334
+ i = 0
335
+ r = len(word)
336
+ b = alpha
337
+ j = r - 1
338
+ b_p = y
339
+ if modified:
340
+ f_p = self._grp.identity
341
+ flag = 0
342
+ while fill or flag == 0:
343
+ flag = 1
344
+ while i <= j and table[f][A_dict[word[i]]] is not None:
345
+ if modified:
346
+ f_p = f_p*self.P[f][A_dict[word[i]]]
347
+ f = table[f][A_dict[word[i]]]
348
+ i += 1
349
+ if i > j:
350
+ if f != b:
351
+ if modified:
352
+ self.modified_coincidence(f, b, f_p**-1*y)
353
+ else:
354
+ self.coincidence(f, b)
355
+ return
356
+ while j >= i and table[b][A_dict_inv[word[j]]] is not None:
357
+ if modified:
358
+ b_p = b_p*self.P[b][self.A_dict_inv[word[j]]]
359
+ b = table[b][A_dict_inv[word[j]]]
360
+ j -= 1
361
+ if j < i:
362
+ # we have an incorrect completed scan with coincidence f ~ b
363
+ # run the "coincidence" routine
364
+ if modified:
365
+ self.modified_coincidence(f, b, f_p**-1*b_p)
366
+ else:
367
+ self.coincidence(f, b)
368
+ elif j == i:
369
+ # deduction process
370
+ table[f][A_dict[word[i]]] = b
371
+ table[b][A_dict_inv[word[i]]] = f
372
+ if modified:
373
+ self.P[f][self.A_dict[word[i]]] = f_p**-1*b_p
374
+ self.P[b][self.A_dict_inv[word[i]]] = b_p**-1*f_p
375
+ return
376
+ elif fill:
377
+ self.define(f, word[i], modified=modified)
378
+ # otherwise scan is incomplete and yields no information
379
+
380
+ # used in the low-index subgroups algorithm
381
+ def scan_check(self, alpha, word):
382
+ r"""
383
+ Another version of ``scan`` routine, described on, it checks whether
384
+ `\alpha` scans correctly under `word`, it is a straightforward
385
+ modification of ``scan``. ``scan_check`` returns ``False`` (rather than
386
+ calling ``coincidence``) if the scan completes incorrectly; otherwise
387
+ it returns ``True``.
388
+
389
+ See Also
390
+ ========
391
+
392
+ scan, scan_c, scan_and_fill, scan_and_fill_c
393
+
394
+ """
395
+ # alpha is an integer representing a "coset"
396
+ # since scanning can be in two cases
397
+ # 1. for alpha=0 and w in Y (i.e generating set of H)
398
+ # 2. alpha in Omega (set of live cosets), w in R (relators)
399
+ A_dict = self.A_dict
400
+ A_dict_inv = self.A_dict_inv
401
+ table = self.table
402
+ f = alpha
403
+ i = 0
404
+ r = len(word)
405
+ b = alpha
406
+ j = r - 1
407
+ while i <= j and table[f][A_dict[word[i]]] is not None:
408
+ f = table[f][A_dict[word[i]]]
409
+ i += 1
410
+ if i > j:
411
+ return f == b
412
+ while j >= i and table[b][A_dict_inv[word[j]]] is not None:
413
+ b = table[b][A_dict_inv[word[j]]]
414
+ j -= 1
415
+ if j < i:
416
+ # we have an incorrect completed scan with coincidence f ~ b
417
+ # return False, instead of calling coincidence routine
418
+ return False
419
+ elif j == i:
420
+ # deduction process
421
+ table[f][A_dict[word[i]]] = b
422
+ table[b][A_dict_inv[word[i]]] = f
423
+ return True
424
+
425
+ def merge(self, k, lamda, q, w=None, modified=False):
426
+ """
427
+ Merge two classes with representatives ``k`` and ``lamda``, described
428
+ on Pg. 157 [1] (for pseudocode), start by putting ``p[k] = lamda``.
429
+ It is more efficient to choose the new representative from the larger
430
+ of the two classes being merged, i.e larger among ``k`` and ``lamda``.
431
+ procedure ``merge`` performs the merging operation, adds the deleted
432
+ class representative to the queue ``q``.
433
+
434
+ Parameters
435
+ ==========
436
+
437
+ 'k', 'lamda' being the two class representatives to be merged.
438
+
439
+ Notes
440
+ =====
441
+
442
+ Pg. 86-87 [1] contains a description of this method.
443
+
444
+ See Also
445
+ ========
446
+
447
+ coincidence, rep
448
+
449
+ """
450
+ p = self.p
451
+ rep = self.rep
452
+ phi = rep(k, modified=modified)
453
+ psi = rep(lamda, modified=modified)
454
+ if phi != psi:
455
+ mu = min(phi, psi)
456
+ v = max(phi, psi)
457
+ p[v] = mu
458
+ if modified:
459
+ if v == phi:
460
+ self.p_p[phi] = self.p_p[k]**-1*w*self.p_p[lamda]
461
+ else:
462
+ self.p_p[psi] = self.p_p[lamda]**-1*w**-1*self.p_p[k]
463
+ q.append(v)
464
+
465
+ def rep(self, k, modified=False):
466
+ r"""
467
+ Parameters
468
+ ==========
469
+
470
+ `k \in [0 \ldots n-1]`, as for ``self`` only array ``p`` is used
471
+
472
+ Returns
473
+ =======
474
+
475
+ Representative of the class containing ``k``.
476
+
477
+ Returns the representative of `\sim` class containing ``k``, it also
478
+ makes some modification to array ``p`` of ``self`` to ease further
479
+ computations, described on Pg. 157 [1].
480
+
481
+ The information on classes under `\sim` is stored in array `p` of
482
+ ``self`` argument, which will always satisfy the property:
483
+
484
+ `p[\alpha] \sim \alpha` and `p[\alpha]=\alpha \iff \alpha=rep(\alpha)`
485
+ `\forall \in [0 \ldots n-1]`.
486
+
487
+ So, for `\alpha \in [0 \ldots n-1]`, we find `rep(self, \alpha)` by
488
+ continually replacing `\alpha` by `p[\alpha]` until it becomes
489
+ constant (i.e satisfies `p[\alpha] = \alpha`):w
490
+
491
+ To increase the efficiency of later ``rep`` calculations, whenever we
492
+ find `rep(self, \alpha)=\beta`, we set
493
+ `p[\gamma] = \beta \forall \gamma \in p-chain` from `\alpha` to `\beta`
494
+
495
+ Notes
496
+ =====
497
+
498
+ ``rep`` routine is also described on Pg. 85-87 [1] in Atkinson's
499
+ algorithm, this results from the fact that ``coincidence`` routine
500
+ introduces functionality similar to that introduced by the
501
+ ``minimal_block`` routine on Pg. 85-87 [1].
502
+
503
+ See Also
504
+ ========
505
+
506
+ coincidence, merge
507
+
508
+ """
509
+ p = self.p
510
+ lamda = k
511
+ rho = p[lamda]
512
+ if modified:
513
+ s = p[:]
514
+ while rho != lamda:
515
+ if modified:
516
+ s[rho] = lamda
517
+ lamda = rho
518
+ rho = p[lamda]
519
+ if modified:
520
+ rho = s[lamda]
521
+ while rho != k:
522
+ mu = rho
523
+ rho = s[mu]
524
+ p[rho] = lamda
525
+ self.p_p[rho] = self.p_p[rho]*self.p_p[mu]
526
+ else:
527
+ mu = k
528
+ rho = p[mu]
529
+ while rho != lamda:
530
+ p[mu] = lamda
531
+ mu = rho
532
+ rho = p[mu]
533
+ return lamda
534
+
535
+ # alpha, beta coincide, i.e. alpha, beta represent the pair of cosets
536
+ # where coincidence occurs
537
+ def coincidence(self, alpha, beta, w=None, modified=False):
538
+ r"""
539
+ The third situation described in ``scan`` routine is handled by this
540
+ routine, described on Pg. 156-161 [1].
541
+
542
+ The unfortunate situation when the scan completes but not correctly,
543
+ then ``coincidence`` routine is run. i.e when for some `i` with
544
+ `1 \le i \le r+1`, we have `w=st` with `s = x_1 x_2 \dots x_{i-1}`,
545
+ `t = x_i x_{i+1} \dots x_r`, and `\beta = \alpha^s` and
546
+ `\gamma = \alpha^{t-1}` are defined but unequal. This means that
547
+ `\beta` and `\gamma` represent the same coset of `H` in `G`. Described
548
+ on Pg. 156 [1]. ``rep``
549
+
550
+ See Also
551
+ ========
552
+
553
+ scan
554
+
555
+ """
556
+ A_dict = self.A_dict
557
+ A_dict_inv = self.A_dict_inv
558
+ table = self.table
559
+ # behaves as a queue
560
+ q = []
561
+ if modified:
562
+ self.modified_merge(alpha, beta, w, q)
563
+ else:
564
+ self.merge(alpha, beta, q)
565
+ while len(q) > 0:
566
+ gamma = q.pop(0)
567
+ for x in A_dict:
568
+ delta = table[gamma][A_dict[x]]
569
+ if delta is not None:
570
+ table[delta][A_dict_inv[x]] = None
571
+ mu = self.rep(gamma, modified=modified)
572
+ nu = self.rep(delta, modified=modified)
573
+ if table[mu][A_dict[x]] is not None:
574
+ if modified:
575
+ v = self.p_p[delta]**-1*self.P[gamma][self.A_dict[x]]**-1
576
+ v = v*self.p_p[gamma]*self.P[mu][self.A_dict[x]]
577
+ self.modified_merge(nu, table[mu][self.A_dict[x]], v, q)
578
+ else:
579
+ self.merge(nu, table[mu][A_dict[x]], q)
580
+ elif table[nu][A_dict_inv[x]] is not None:
581
+ if modified:
582
+ v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]]
583
+ v = v*self.p_p[delta]*self.P[mu][self.A_dict_inv[x]]
584
+ self.modified_merge(mu, table[nu][self.A_dict_inv[x]], v, q)
585
+ else:
586
+ self.merge(mu, table[nu][A_dict_inv[x]], q)
587
+ else:
588
+ table[mu][A_dict[x]] = nu
589
+ table[nu][A_dict_inv[x]] = mu
590
+ if modified:
591
+ v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]]*self.p_p[delta]
592
+ self.P[mu][self.A_dict[x]] = v
593
+ self.P[nu][self.A_dict_inv[x]] = v**-1
594
+
595
+ # method used in the HLT strategy
596
+ def scan_and_fill(self, alpha, word):
597
+ """
598
+ A modified version of ``scan`` routine used in the relator-based
599
+ method of coset enumeration, described on pg. 162-163 [1], which
600
+ follows the idea that whenever the procedure is called and the scan
601
+ is incomplete then it makes new definitions to enable the scan to
602
+ complete; i.e it fills in the gaps in the scan of the relator or
603
+ subgroup generator.
604
+
605
+ """
606
+ self.scan(alpha, word, fill=True)
607
+
608
+ def scan_and_fill_c(self, alpha, word):
609
+ """
610
+ A modified version of ``scan`` routine, described on Pg. 165 second
611
+ para. [1], with modification similar to that of ``scan_anf_fill`` the
612
+ only difference being it calls the coincidence procedure used in the
613
+ coset-table based method i.e. the routine ``coincidence_c`` is used.
614
+
615
+ See Also
616
+ ========
617
+
618
+ scan, scan_and_fill
619
+
620
+ """
621
+ A_dict = self.A_dict
622
+ A_dict_inv = self.A_dict_inv
623
+ table = self.table
624
+ r = len(word)
625
+ f = alpha
626
+ i = 0
627
+ b = alpha
628
+ j = r - 1
629
+ # loop until it has filled the alpha row in the table.
630
+ while True:
631
+ # do the forward scanning
632
+ while i <= j and table[f][A_dict[word[i]]] is not None:
633
+ f = table[f][A_dict[word[i]]]
634
+ i += 1
635
+ if i > j:
636
+ if f != b:
637
+ self.coincidence_c(f, b)
638
+ return
639
+ # forward scan was incomplete, scan backwards
640
+ while j >= i and table[b][A_dict_inv[word[j]]] is not None:
641
+ b = table[b][A_dict_inv[word[j]]]
642
+ j -= 1
643
+ if j < i:
644
+ self.coincidence_c(f, b)
645
+ elif j == i:
646
+ table[f][A_dict[word[i]]] = b
647
+ table[b][A_dict_inv[word[i]]] = f
648
+ self.deduction_stack.append((f, word[i]))
649
+ else:
650
+ self.define_c(f, word[i])
651
+
652
+ # method used in the HLT strategy
653
+ def look_ahead(self):
654
+ """
655
+ When combined with the HLT method this is known as HLT+Lookahead
656
+ method of coset enumeration, described on pg. 164 [1]. Whenever
657
+ ``define`` aborts due to lack of space available this procedure is
658
+ executed. This routine helps in recovering space resulting from
659
+ "coincidence" of cosets.
660
+
661
+ """
662
+ R = self.fp_group.relators
663
+ p = self.p
664
+ # complete scan all relators under all cosets(obviously live)
665
+ # without making new definitions
666
+ for beta in self.omega:
667
+ for w in R:
668
+ self.scan(beta, w)
669
+ if p[beta] < beta:
670
+ break
671
+
672
+ # Pg. 166
673
+ def process_deductions(self, R_c_x, R_c_x_inv):
674
+ """
675
+ Processes the deductions that have been pushed onto ``deduction_stack``,
676
+ described on Pg. 166 [1] and is used in coset-table based enumeration.
677
+
678
+ See Also
679
+ ========
680
+
681
+ deduction_stack
682
+
683
+ """
684
+ p = self.p
685
+ table = self.table
686
+ while len(self.deduction_stack) > 0:
687
+ if len(self.deduction_stack) >= CosetTable.max_stack_size:
688
+ self.look_ahead()
689
+ del self.deduction_stack[:]
690
+ continue
691
+ else:
692
+ alpha, x = self.deduction_stack.pop()
693
+ if p[alpha] == alpha:
694
+ for w in R_c_x:
695
+ self.scan_c(alpha, w)
696
+ if p[alpha] < alpha:
697
+ break
698
+ beta = table[alpha][self.A_dict[x]]
699
+ if beta is not None and p[beta] == beta:
700
+ for w in R_c_x_inv:
701
+ self.scan_c(beta, w)
702
+ if p[beta] < beta:
703
+ break
704
+
705
+ def process_deductions_check(self, R_c_x, R_c_x_inv):
706
+ """
707
+ A variation of ``process_deductions``, this calls ``scan_check``
708
+ wherever ``process_deductions`` calls ``scan``, described on Pg. [1].
709
+
710
+ See Also
711
+ ========
712
+
713
+ process_deductions
714
+
715
+ """
716
+ table = self.table
717
+ while len(self.deduction_stack) > 0:
718
+ alpha, x = self.deduction_stack.pop()
719
+ for w in R_c_x:
720
+ if not self.scan_check(alpha, w):
721
+ return False
722
+ beta = table[alpha][self.A_dict[x]]
723
+ if beta is not None:
724
+ for w in R_c_x_inv:
725
+ if not self.scan_check(beta, w):
726
+ return False
727
+ return True
728
+
729
+ def switch(self, beta, gamma):
730
+ r"""Switch the elements `\beta, \gamma \in \Omega` of ``self``, used
731
+ by the ``standardize`` procedure, described on Pg. 167 [1].
732
+
733
+ See Also
734
+ ========
735
+
736
+ standardize
737
+
738
+ """
739
+ A = self.A
740
+ A_dict = self.A_dict
741
+ table = self.table
742
+ for x in A:
743
+ z = table[gamma][A_dict[x]]
744
+ table[gamma][A_dict[x]] = table[beta][A_dict[x]]
745
+ table[beta][A_dict[x]] = z
746
+ for alpha in range(len(self.p)):
747
+ if self.p[alpha] == alpha:
748
+ if table[alpha][A_dict[x]] == beta:
749
+ table[alpha][A_dict[x]] = gamma
750
+ elif table[alpha][A_dict[x]] == gamma:
751
+ table[alpha][A_dict[x]] = beta
752
+
753
+ def standardize(self):
754
+ r"""
755
+ A coset table is standardized if when running through the cosets and
756
+ within each coset through the generator images (ignoring generator
757
+ inverses), the cosets appear in order of the integers
758
+ `0, 1, \dots, n`. "Standardize" reorders the elements of `\Omega`
759
+ such that, if we scan the coset table first by elements of `\Omega`
760
+ and then by elements of A, then the cosets occur in ascending order.
761
+ ``standardize()`` is used at the end of an enumeration to permute the
762
+ cosets so that they occur in some sort of standard order.
763
+
764
+ Notes
765
+ =====
766
+
767
+ procedure is described on pg. 167-168 [1], it also makes use of the
768
+ ``switch`` routine to replace by smaller integer value.
769
+
770
+ Examples
771
+ ========
772
+
773
+ >>> from sympy.combinatorics import free_group
774
+ >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r
775
+ >>> F, x, y = free_group("x, y")
776
+
777
+ # Example 5.3 from [1]
778
+ >>> f = FpGroup(F, [x**2*y**2, x**3*y**5])
779
+ >>> C = coset_enumeration_r(f, [])
780
+ >>> C.compress()
781
+ >>> C.table
782
+ [[1, 3, 1, 3], [2, 0, 2, 0], [3, 1, 3, 1], [0, 2, 0, 2]]
783
+ >>> C.standardize()
784
+ >>> C.table
785
+ [[1, 2, 1, 2], [3, 0, 3, 0], [0, 3, 0, 3], [2, 1, 2, 1]]
786
+
787
+ """
788
+ A = self.A
789
+ A_dict = self.A_dict
790
+ gamma = 1
791
+ for alpha, x in product(range(self.n), A):
792
+ beta = self.table[alpha][A_dict[x]]
793
+ if beta >= gamma:
794
+ if beta > gamma:
795
+ self.switch(gamma, beta)
796
+ gamma += 1
797
+ if gamma == self.n:
798
+ return
799
+
800
+ # Compression of a Coset Table
801
+ def compress(self):
802
+ """Removes the non-live cosets from the coset table, described on
803
+ pg. 167 [1].
804
+
805
+ """
806
+ gamma = -1
807
+ A = self.A
808
+ A_dict = self.A_dict
809
+ A_dict_inv = self.A_dict_inv
810
+ table = self.table
811
+ chi = tuple([i for i in range(len(self.p)) if self.p[i] != i])
812
+ for alpha in self.omega:
813
+ gamma += 1
814
+ if gamma != alpha:
815
+ # replace alpha by gamma in coset table
816
+ for x in A:
817
+ beta = table[alpha][A_dict[x]]
818
+ table[gamma][A_dict[x]] = beta
819
+ table[beta][A_dict_inv[x]] == gamma
820
+ # all the cosets in the table are live cosets
821
+ self.p = list(range(gamma + 1))
822
+ # delete the useless columns
823
+ del table[len(self.p):]
824
+ # re-define values
825
+ for row in table:
826
+ for j in range(len(self.A)):
827
+ row[j] -= bisect_left(chi, row[j])
828
+
829
+ def conjugates(self, R):
830
+ R_c = list(chain.from_iterable((rel.cyclic_conjugates(), \
831
+ (rel**-1).cyclic_conjugates()) for rel in R))
832
+ R_set = set()
833
+ for conjugate in R_c:
834
+ R_set = R_set.union(conjugate)
835
+ R_c_list = []
836
+ for x in self.A:
837
+ r = {word for word in R_set if word[0] == x}
838
+ R_c_list.append(r)
839
+ R_set.difference_update(r)
840
+ return R_c_list
841
+
842
+ def coset_representative(self, coset):
843
+ '''
844
+ Compute the coset representative of a given coset.
845
+
846
+ Examples
847
+ ========
848
+
849
+ >>> from sympy.combinatorics import free_group
850
+ >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r
851
+ >>> F, x, y = free_group("x, y")
852
+ >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
853
+ >>> C = coset_enumeration_r(f, [x])
854
+ >>> C.compress()
855
+ >>> C.table
856
+ [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]]
857
+ >>> C.coset_representative(0)
858
+ <identity>
859
+ >>> C.coset_representative(1)
860
+ y
861
+ >>> C.coset_representative(2)
862
+ y**-1
863
+
864
+ '''
865
+ for x in self.A:
866
+ gamma = self.table[coset][self.A_dict[x]]
867
+ if coset == 0:
868
+ return self.fp_group.identity
869
+ if gamma < coset:
870
+ return self.coset_representative(gamma)*x**-1
871
+
872
+ ##############################
873
+ # Modified Methods #
874
+ ##############################
875
+
876
+ def modified_define(self, alpha, x):
877
+ r"""
878
+ Define a function p_p from from [1..n] to A* as
879
+ an additional component of the modified coset table.
880
+
881
+ Parameters
882
+ ==========
883
+
884
+ \alpha \in \Omega
885
+ x \in A*
886
+
887
+ See Also
888
+ ========
889
+
890
+ define
891
+
892
+ """
893
+ self.define(alpha, x, modified=True)
894
+
895
+ def modified_scan(self, alpha, w, y, fill=False):
896
+ r"""
897
+ Parameters
898
+ ==========
899
+ \alpha \in \Omega
900
+ w \in A*
901
+ y \in (YUY^-1)
902
+ fill -- `modified_scan_and_fill` when set to True.
903
+
904
+ See Also
905
+ ========
906
+
907
+ scan
908
+ """
909
+ self.scan(alpha, w, y=y, fill=fill, modified=True)
910
+
911
+ def modified_scan_and_fill(self, alpha, w, y):
912
+ self.modified_scan(alpha, w, y, fill=True)
913
+
914
+ def modified_merge(self, k, lamda, w, q):
915
+ r"""
916
+ Parameters
917
+ ==========
918
+
919
+ 'k', 'lamda' -- the two class representatives to be merged.
920
+ q -- queue of length l of elements to be deleted from `\Omega` *.
921
+ w -- Word in (YUY^-1)
922
+
923
+ See Also
924
+ ========
925
+
926
+ merge
927
+ """
928
+ self.merge(k, lamda, q, w=w, modified=True)
929
+
930
+ def modified_rep(self, k):
931
+ r"""
932
+ Parameters
933
+ ==========
934
+
935
+ `k \in [0 \ldots n-1]`
936
+
937
+ See Also
938
+ ========
939
+
940
+ rep
941
+ """
942
+ self.rep(k, modified=True)
943
+
944
+ def modified_coincidence(self, alpha, beta, w):
945
+ r"""
946
+ Parameters
947
+ ==========
948
+
949
+ A coincident pair `\alpha, \beta \in \Omega, w \in Y \cup Y^{-1}`
950
+
951
+ See Also
952
+ ========
953
+
954
+ coincidence
955
+
956
+ """
957
+ self.coincidence(alpha, beta, w=w, modified=True)
958
+
959
+ ###############################################################################
960
+ # COSET ENUMERATION #
961
+ ###############################################################################
962
+
963
+ # relator-based method
964
+ def coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None,
965
+ incomplete=False, modified=False):
966
+ """
967
+ This is easier of the two implemented methods of coset enumeration.
968
+ and is often called the HLT method, after Hazelgrove, Leech, Trotter
969
+ The idea is that we make use of ``scan_and_fill`` makes new definitions
970
+ whenever the scan is incomplete to enable the scan to complete; this way
971
+ we fill in the gaps in the scan of the relator or subgroup generator,
972
+ that's why the name relator-based method.
973
+
974
+ An instance of `CosetTable` for `fp_grp` can be passed as the keyword
975
+ argument `draft` in which case the coset enumeration will start with
976
+ that instance and attempt to complete it.
977
+
978
+ When `incomplete` is `True` and the function is unable to complete for
979
+ some reason, the partially complete table will be returned.
980
+
981
+ # TODO: complete the docstring
982
+
983
+ See Also
984
+ ========
985
+
986
+ scan_and_fill,
987
+
988
+ Examples
989
+ ========
990
+
991
+ >>> from sympy.combinatorics.free_groups import free_group
992
+ >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r
993
+ >>> F, x, y = free_group("x, y")
994
+
995
+ # Example 5.1 from [1]
996
+ >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
997
+ >>> C = coset_enumeration_r(f, [x])
998
+ >>> for i in range(len(C.p)):
999
+ ... if C.p[i] == i:
1000
+ ... print(C.table[i])
1001
+ [0, 0, 1, 2]
1002
+ [1, 1, 2, 0]
1003
+ [2, 2, 0, 1]
1004
+ >>> C.p
1005
+ [0, 1, 2, 1, 1]
1006
+
1007
+ # Example from exercises Q2 [1]
1008
+ >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3])
1009
+ >>> C = coset_enumeration_r(f, [])
1010
+ >>> C.compress(); C.standardize()
1011
+ >>> C.table
1012
+ [[1, 2, 3, 4],
1013
+ [5, 0, 6, 7],
1014
+ [0, 5, 7, 6],
1015
+ [7, 6, 5, 0],
1016
+ [6, 7, 0, 5],
1017
+ [2, 1, 4, 3],
1018
+ [3, 4, 2, 1],
1019
+ [4, 3, 1, 2]]
1020
+
1021
+ # Example 5.2
1022
+ >>> f = FpGroup(F, [x**2, y**3, (x*y)**3])
1023
+ >>> Y = [x*y]
1024
+ >>> C = coset_enumeration_r(f, Y)
1025
+ >>> for i in range(len(C.p)):
1026
+ ... if C.p[i] == i:
1027
+ ... print(C.table[i])
1028
+ [1, 1, 2, 1]
1029
+ [0, 0, 0, 2]
1030
+ [3, 3, 1, 0]
1031
+ [2, 2, 3, 3]
1032
+
1033
+ # Example 5.3
1034
+ >>> f = FpGroup(F, [x**2*y**2, x**3*y**5])
1035
+ >>> Y = []
1036
+ >>> C = coset_enumeration_r(f, Y)
1037
+ >>> for i in range(len(C.p)):
1038
+ ... if C.p[i] == i:
1039
+ ... print(C.table[i])
1040
+ [1, 3, 1, 3]
1041
+ [2, 0, 2, 0]
1042
+ [3, 1, 3, 1]
1043
+ [0, 2, 0, 2]
1044
+
1045
+ # Example 5.4
1046
+ >>> F, a, b, c, d, e = free_group("a, b, c, d, e")
1047
+ >>> f = FpGroup(F, [a*b*c**-1, b*c*d**-1, c*d*e**-1, d*e*a**-1, e*a*b**-1])
1048
+ >>> Y = [a]
1049
+ >>> C = coset_enumeration_r(f, Y)
1050
+ >>> for i in range(len(C.p)):
1051
+ ... if C.p[i] == i:
1052
+ ... print(C.table[i])
1053
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1054
+
1055
+ # example of "compress" method
1056
+ >>> C.compress()
1057
+ >>> C.table
1058
+ [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
1059
+
1060
+ # Exercises Pg. 161, Q2.
1061
+ >>> F, x, y = free_group("x, y")
1062
+ >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3])
1063
+ >>> Y = []
1064
+ >>> C = coset_enumeration_r(f, Y)
1065
+ >>> C.compress()
1066
+ >>> C.standardize()
1067
+ >>> C.table
1068
+ [[1, 2, 3, 4],
1069
+ [5, 0, 6, 7],
1070
+ [0, 5, 7, 6],
1071
+ [7, 6, 5, 0],
1072
+ [6, 7, 0, 5],
1073
+ [2, 1, 4, 3],
1074
+ [3, 4, 2, 1],
1075
+ [4, 3, 1, 2]]
1076
+
1077
+ # John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson
1078
+ # Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490
1079
+ # from 1973chwd.pdf
1080
+ # Table 1. Ex. 1
1081
+ >>> F, r, s, t = free_group("r, s, t")
1082
+ >>> E1 = FpGroup(F, [t**-1*r*t*r**-2, r**-1*s*r*s**-2, s**-1*t*s*t**-2])
1083
+ >>> C = coset_enumeration_r(E1, [r])
1084
+ >>> for i in range(len(C.p)):
1085
+ ... if C.p[i] == i:
1086
+ ... print(C.table[i])
1087
+ [0, 0, 0, 0, 0, 0]
1088
+
1089
+ Ex. 2
1090
+ >>> F, a, b = free_group("a, b")
1091
+ >>> Cox = FpGroup(F, [a**6, b**6, (a*b)**2, (a**2*b**2)**2, (a**3*b**3)**5])
1092
+ >>> C = coset_enumeration_r(Cox, [a])
1093
+ >>> index = 0
1094
+ >>> for i in range(len(C.p)):
1095
+ ... if C.p[i] == i:
1096
+ ... index += 1
1097
+ >>> index
1098
+ 500
1099
+
1100
+ # Ex. 3
1101
+ >>> F, a, b = free_group("a, b")
1102
+ >>> B_2_4 = FpGroup(F, [a**4, b**4, (a*b)**4, (a**-1*b)**4, (a**2*b)**4, \
1103
+ (a*b**2)**4, (a**2*b**2)**4, (a**-1*b*a*b)**4, (a*b**-1*a*b)**4])
1104
+ >>> C = coset_enumeration_r(B_2_4, [a])
1105
+ >>> index = 0
1106
+ >>> for i in range(len(C.p)):
1107
+ ... if C.p[i] == i:
1108
+ ... index += 1
1109
+ >>> index
1110
+ 1024
1111
+
1112
+ References
1113
+ ==========
1114
+
1115
+ .. [1] Holt, D., Eick, B., O'Brien, E.
1116
+ "Handbook of computational group theory"
1117
+
1118
+ """
1119
+ # 1. Initialize a coset table C for < X|R >
1120
+ C = CosetTable(fp_grp, Y, max_cosets=max_cosets)
1121
+ # Define coset table methods.
1122
+ if modified:
1123
+ _scan_and_fill = C.modified_scan_and_fill
1124
+ _define = C.modified_define
1125
+ else:
1126
+ _scan_and_fill = C.scan_and_fill
1127
+ _define = C.define
1128
+ if draft:
1129
+ C.table = draft.table[:]
1130
+ C.p = draft.p[:]
1131
+ R = fp_grp.relators
1132
+ A_dict = C.A_dict
1133
+ p = C.p
1134
+ for i in range(len(Y)):
1135
+ if modified:
1136
+ _scan_and_fill(0, Y[i], C._grp.generators[i])
1137
+ else:
1138
+ _scan_and_fill(0, Y[i])
1139
+ alpha = 0
1140
+ while alpha < C.n:
1141
+ if p[alpha] == alpha:
1142
+ try:
1143
+ for w in R:
1144
+ if modified:
1145
+ _scan_and_fill(alpha, w, C._grp.identity)
1146
+ else:
1147
+ _scan_and_fill(alpha, w)
1148
+ # if alpha was eliminated during the scan then break
1149
+ if p[alpha] < alpha:
1150
+ break
1151
+ if p[alpha] == alpha:
1152
+ for x in A_dict:
1153
+ if C.table[alpha][A_dict[x]] is None:
1154
+ _define(alpha, x)
1155
+ except ValueError as e:
1156
+ if incomplete:
1157
+ return C
1158
+ raise e
1159
+ alpha += 1
1160
+ return C
1161
+
1162
+ def modified_coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None,
1163
+ incomplete=False):
1164
+ r"""
1165
+ Introduce a new set of symbols y \in Y that correspond to the
1166
+ generators of the subgroup. Store the elements of Y as a
1167
+ word P[\alpha, x] and compute the coset table similar to that of
1168
+ the regular coset enumeration methods.
1169
+
1170
+ Examples
1171
+ ========
1172
+
1173
+ >>> from sympy.combinatorics.free_groups import free_group
1174
+ >>> from sympy.combinatorics.fp_groups import FpGroup
1175
+ >>> from sympy.combinatorics.coset_table import modified_coset_enumeration_r
1176
+ >>> F, x, y = free_group("x, y")
1177
+ >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
1178
+ >>> C = modified_coset_enumeration_r(f, [x])
1179
+ >>> C.table
1180
+ [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1], [None, 1, None, None], [1, 3, None, None]]
1181
+
1182
+ See Also
1183
+ ========
1184
+
1185
+ coset_enumertation_r
1186
+
1187
+ References
1188
+ ==========
1189
+
1190
+ .. [1] Holt, D., Eick, B., O'Brien, E.,
1191
+ "Handbook of Computational Group Theory",
1192
+ Section 5.3.2
1193
+ """
1194
+ return coset_enumeration_r(fp_grp, Y, max_cosets=max_cosets, draft=draft,
1195
+ incomplete=incomplete, modified=True)
1196
+
1197
+ # Pg. 166
1198
+ # coset-table based method
1199
+ def coset_enumeration_c(fp_grp, Y, max_cosets=None, draft=None,
1200
+ incomplete=False):
1201
+ """
1202
+ >>> from sympy.combinatorics.free_groups import free_group
1203
+ >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_c
1204
+ >>> F, x, y = free_group("x, y")
1205
+ >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
1206
+ >>> C = coset_enumeration_c(f, [x])
1207
+ >>> C.table
1208
+ [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]]
1209
+
1210
+ """
1211
+ # Initialize a coset table C for < X|R >
1212
+ X = fp_grp.generators
1213
+ R = fp_grp.relators
1214
+ C = CosetTable(fp_grp, Y, max_cosets=max_cosets)
1215
+ if draft:
1216
+ C.table = draft.table[:]
1217
+ C.p = draft.p[:]
1218
+ C.deduction_stack = draft.deduction_stack
1219
+ for alpha, x in product(range(len(C.table)), X):
1220
+ if C.table[alpha][C.A_dict[x]] is not None:
1221
+ C.deduction_stack.append((alpha, x))
1222
+ A = C.A
1223
+ # replace all the elements by cyclic reductions
1224
+ R_cyc_red = [rel.identity_cyclic_reduction() for rel in R]
1225
+ R_c = list(chain.from_iterable((rel.cyclic_conjugates(), (rel**-1).cyclic_conjugates()) \
1226
+ for rel in R_cyc_red))
1227
+ R_set = set()
1228
+ for conjugate in R_c:
1229
+ R_set = R_set.union(conjugate)
1230
+ # a list of subsets of R_c whose words start with "x".
1231
+ R_c_list = []
1232
+ for x in C.A:
1233
+ r = {word for word in R_set if word[0] == x}
1234
+ R_c_list.append(r)
1235
+ R_set.difference_update(r)
1236
+ for w in Y:
1237
+ C.scan_and_fill_c(0, w)
1238
+ for x in A:
1239
+ C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]])
1240
+ alpha = 0
1241
+ while alpha < len(C.table):
1242
+ if C.p[alpha] == alpha:
1243
+ try:
1244
+ for x in C.A:
1245
+ if C.p[alpha] != alpha:
1246
+ break
1247
+ if C.table[alpha][C.A_dict[x]] is None:
1248
+ C.define_c(alpha, x)
1249
+ C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]])
1250
+ except ValueError as e:
1251
+ if incomplete:
1252
+ return C
1253
+ raise e
1254
+ alpha += 1
1255
+ return C
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.py ADDED
@@ -0,0 +1,1348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Finitely Presented Groups and its algorithms. """
2
+
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import symbols
5
+ from sympy.combinatorics.free_groups import (FreeGroup, FreeGroupElement,
6
+ free_group)
7
+ from sympy.combinatorics.rewritingsystem import RewritingSystem
8
+ from sympy.combinatorics.coset_table import (CosetTable,
9
+ coset_enumeration_r,
10
+ coset_enumeration_c)
11
+ from sympy.combinatorics import PermutationGroup
12
+ from sympy.matrices.normalforms import invariant_factors
13
+ from sympy.matrices import Matrix
14
+ from sympy.polys.polytools import gcd
15
+ from sympy.printing.defaults import DefaultPrinting
16
+ from sympy.utilities import public
17
+ from sympy.utilities.magic import pollute
18
+
19
+ from itertools import product
20
+
21
+
22
+ @public
23
+ def fp_group(fr_grp, relators=()):
24
+ _fp_group = FpGroup(fr_grp, relators)
25
+ return (_fp_group,) + tuple(_fp_group._generators)
26
+
27
+ @public
28
+ def xfp_group(fr_grp, relators=()):
29
+ _fp_group = FpGroup(fr_grp, relators)
30
+ return (_fp_group, _fp_group._generators)
31
+
32
+ # Does not work. Both symbols and pollute are undefined. Never tested.
33
+ @public
34
+ def vfp_group(fr_grpm, relators):
35
+ _fp_group = FpGroup(symbols, relators)
36
+ pollute([sym.name for sym in _fp_group.symbols], _fp_group.generators)
37
+ return _fp_group
38
+
39
+
40
+ def _parse_relators(rels):
41
+ """Parse the passed relators."""
42
+ return rels
43
+
44
+
45
+ ###############################################################################
46
+ # FINITELY PRESENTED GROUPS #
47
+ ###############################################################################
48
+
49
+
50
+ class FpGroup(DefaultPrinting):
51
+ """
52
+ The FpGroup would take a FreeGroup and a list/tuple of relators, the
53
+ relators would be specified in such a way that each of them be equal to the
54
+ identity of the provided free group.
55
+
56
+ """
57
+ is_group = True
58
+ is_FpGroup = True
59
+ is_PermutationGroup = False
60
+
61
+ def __init__(self, fr_grp, relators):
62
+ relators = _parse_relators(relators)
63
+ self.free_group = fr_grp
64
+ self.relators = relators
65
+ self.generators = self._generators()
66
+ self.dtype = type("FpGroupElement", (FpGroupElement,), {"group": self})
67
+
68
+ # CosetTable instance on identity subgroup
69
+ self._coset_table = None
70
+ # returns whether coset table on identity subgroup
71
+ # has been standardized
72
+ self._is_standardized = False
73
+
74
+ self._order = None
75
+ self._center = None
76
+
77
+ self._rewriting_system = RewritingSystem(self)
78
+ self._perm_isomorphism = None
79
+ return
80
+
81
+ def _generators(self):
82
+ return self.free_group.generators
83
+
84
+ def make_confluent(self):
85
+ '''
86
+ Try to make the group's rewriting system confluent
87
+
88
+ '''
89
+ self._rewriting_system.make_confluent()
90
+ return
91
+
92
+ def reduce(self, word):
93
+ '''
94
+ Return the reduced form of `word` in `self` according to the group's
95
+ rewriting system. If it's confluent, the reduced form is the unique normal
96
+ form of the word in the group.
97
+
98
+ '''
99
+ return self._rewriting_system.reduce(word)
100
+
101
+ def equals(self, word1, word2):
102
+ '''
103
+ Compare `word1` and `word2` for equality in the group
104
+ using the group's rewriting system. If the system is
105
+ confluent, the returned answer is necessarily correct.
106
+ (If it is not, `False` could be returned in some cases
107
+ where in fact `word1 == word2`)
108
+
109
+ '''
110
+ if self.reduce(word1*word2**-1) == self.identity:
111
+ return True
112
+ elif self._rewriting_system.is_confluent:
113
+ return False
114
+ return None
115
+
116
+ @property
117
+ def identity(self):
118
+ return self.free_group.identity
119
+
120
+ def __contains__(self, g):
121
+ return g in self.free_group
122
+
123
+ def subgroup(self, gens, C=None, homomorphism=False):
124
+ '''
125
+ Return the subgroup generated by `gens` using the
126
+ Reidemeister-Schreier algorithm
127
+ homomorphism -- When set to True, return a dictionary containing the images
128
+ of the presentation generators in the original group.
129
+
130
+ Examples
131
+ ========
132
+
133
+ >>> from sympy.combinatorics.fp_groups import FpGroup
134
+ >>> from sympy.combinatorics import free_group
135
+ >>> F, x, y = free_group("x, y")
136
+ >>> f = FpGroup(F, [x**3, y**5, (x*y)**2])
137
+ >>> H = [x*y, x**-1*y**-1*x*y*x]
138
+ >>> K, T = f.subgroup(H, homomorphism=True)
139
+ >>> T(K.generators)
140
+ [x*y, x**-1*y**2*x**-1]
141
+
142
+ '''
143
+
144
+ if not all(isinstance(g, FreeGroupElement) for g in gens):
145
+ raise ValueError("Generators must be `FreeGroupElement`s")
146
+ if not all(g.group == self.free_group for g in gens):
147
+ raise ValueError("Given generators are not members of the group")
148
+ if homomorphism:
149
+ g, rels, _gens = reidemeister_presentation(self, gens, C=C, homomorphism=True)
150
+ else:
151
+ g, rels = reidemeister_presentation(self, gens, C=C)
152
+ if g:
153
+ g = FpGroup(g[0].group, rels)
154
+ else:
155
+ g = FpGroup(free_group('')[0], [])
156
+ if homomorphism:
157
+ from sympy.combinatorics.homomorphisms import homomorphism
158
+ return g, homomorphism(g, self, g.generators, _gens, check=False)
159
+ return g
160
+
161
+ def coset_enumeration(self, H, strategy="relator_based", max_cosets=None,
162
+ draft=None, incomplete=False):
163
+ """
164
+ Return an instance of ``coset table``, when Todd-Coxeter algorithm is
165
+ run over the ``self`` with ``H`` as subgroup, using ``strategy``
166
+ argument as strategy. The returned coset table is compressed but not
167
+ standardized.
168
+
169
+ An instance of `CosetTable` for `fp_grp` can be passed as the keyword
170
+ argument `draft` in which case the coset enumeration will start with
171
+ that instance and attempt to complete it.
172
+
173
+ When `incomplete` is `True` and the function is unable to complete for
174
+ some reason, the partially complete table will be returned.
175
+
176
+ """
177
+ if not max_cosets:
178
+ max_cosets = CosetTable.coset_table_max_limit
179
+ if strategy == 'relator_based':
180
+ C = coset_enumeration_r(self, H, max_cosets=max_cosets,
181
+ draft=draft, incomplete=incomplete)
182
+ else:
183
+ C = coset_enumeration_c(self, H, max_cosets=max_cosets,
184
+ draft=draft, incomplete=incomplete)
185
+ if C.is_complete():
186
+ C.compress()
187
+ return C
188
+
189
+ def standardize_coset_table(self):
190
+ """
191
+ Standardized the coset table ``self`` and makes the internal variable
192
+ ``_is_standardized`` equal to ``True``.
193
+
194
+ """
195
+ self._coset_table.standardize()
196
+ self._is_standardized = True
197
+
198
+ def coset_table(self, H, strategy="relator_based", max_cosets=None,
199
+ draft=None, incomplete=False):
200
+ """
201
+ Return the mathematical coset table of ``self`` in ``H``.
202
+
203
+ """
204
+ if not H:
205
+ if self._coset_table is not None:
206
+ if not self._is_standardized:
207
+ self.standardize_coset_table()
208
+ else:
209
+ C = self.coset_enumeration([], strategy, max_cosets=max_cosets,
210
+ draft=draft, incomplete=incomplete)
211
+ self._coset_table = C
212
+ self.standardize_coset_table()
213
+ return self._coset_table.table
214
+ else:
215
+ C = self.coset_enumeration(H, strategy, max_cosets=max_cosets,
216
+ draft=draft, incomplete=incomplete)
217
+ C.standardize()
218
+ return C.table
219
+
220
+ def order(self, strategy="relator_based"):
221
+ """
222
+ Returns the order of the finitely presented group ``self``. It uses
223
+ the coset enumeration with identity group as subgroup, i.e ``H=[]``.
224
+
225
+ Examples
226
+ ========
227
+
228
+ >>> from sympy.combinatorics import free_group
229
+ >>> from sympy.combinatorics.fp_groups import FpGroup
230
+ >>> F, x, y = free_group("x, y")
231
+ >>> f = FpGroup(F, [x, y**2])
232
+ >>> f.order(strategy="coset_table_based")
233
+ 2
234
+
235
+ """
236
+ if self._order is not None:
237
+ return self._order
238
+ if self._coset_table is not None:
239
+ self._order = len(self._coset_table.table)
240
+ elif len(self.relators) == 0:
241
+ self._order = self.free_group.order()
242
+ elif len(self.generators) == 1:
243
+ self._order = abs(gcd([r.array_form[0][1] for r in self.relators]))
244
+ elif self._is_infinite():
245
+ self._order = S.Infinity
246
+ else:
247
+ gens, C = self._finite_index_subgroup()
248
+ if C:
249
+ ind = len(C.table)
250
+ self._order = ind*self.subgroup(gens, C=C).order()
251
+ else:
252
+ self._order = self.index([])
253
+ return self._order
254
+
255
+ def _is_infinite(self):
256
+ '''
257
+ Test if the group is infinite. Return `True` if the test succeeds
258
+ and `None` otherwise
259
+
260
+ '''
261
+ used_gens = set()
262
+ for r in self.relators:
263
+ used_gens.update(r.contains_generators())
264
+ if not set(self.generators) <= used_gens:
265
+ return True
266
+ # Abelianisation test: check is the abelianisation is infinite
267
+ abelian_rels = []
268
+ for rel in self.relators:
269
+ abelian_rels.append([rel.exponent_sum(g) for g in self.generators])
270
+ m = Matrix(Matrix(abelian_rels))
271
+ if 0 in invariant_factors(m):
272
+ return True
273
+ else:
274
+ return None
275
+
276
+
277
+ def _finite_index_subgroup(self, s=None):
278
+ '''
279
+ Find the elements of `self` that generate a finite index subgroup
280
+ and, if found, return the list of elements and the coset table of `self` by
281
+ the subgroup, otherwise return `(None, None)`
282
+
283
+ '''
284
+ gen = self.most_frequent_generator()
285
+ rels = list(self.generators)
286
+ rels.extend(self.relators)
287
+ if not s:
288
+ if len(self.generators) == 2:
289
+ s = [gen] + [g for g in self.generators if g != gen]
290
+ else:
291
+ rand = self.free_group.identity
292
+ i = 0
293
+ while ((rand in rels or rand**-1 in rels or rand.is_identity)
294
+ and i<10):
295
+ rand = self.random()
296
+ i += 1
297
+ s = [gen, rand] + [g for g in self.generators if g != gen]
298
+ mid = (len(s)+1)//2
299
+ half1 = s[:mid]
300
+ half2 = s[mid:]
301
+ draft1 = None
302
+ draft2 = None
303
+ m = 200
304
+ C = None
305
+ while not C and (m/2 < CosetTable.coset_table_max_limit):
306
+ m = min(m, CosetTable.coset_table_max_limit)
307
+ draft1 = self.coset_enumeration(half1, max_cosets=m,
308
+ draft=draft1, incomplete=True)
309
+ if draft1.is_complete():
310
+ C = draft1
311
+ half = half1
312
+ else:
313
+ draft2 = self.coset_enumeration(half2, max_cosets=m,
314
+ draft=draft2, incomplete=True)
315
+ if draft2.is_complete():
316
+ C = draft2
317
+ half = half2
318
+ if not C:
319
+ m *= 2
320
+ if not C:
321
+ return None, None
322
+ C.compress()
323
+ return half, C
324
+
325
+ def most_frequent_generator(self):
326
+ gens = self.generators
327
+ rels = self.relators
328
+ freqs = [sum([r.generator_count(g) for r in rels]) for g in gens]
329
+ return gens[freqs.index(max(freqs))]
330
+
331
+ def random(self):
332
+ import random
333
+ r = self.free_group.identity
334
+ for i in range(random.randint(2,3)):
335
+ r = r*random.choice(self.generators)**random.choice([1,-1])
336
+ return r
337
+
338
+ def index(self, H, strategy="relator_based"):
339
+ """
340
+ Return the index of subgroup ``H`` in group ``self``.
341
+
342
+ Examples
343
+ ========
344
+
345
+ >>> from sympy.combinatorics import free_group
346
+ >>> from sympy.combinatorics.fp_groups import FpGroup
347
+ >>> F, x, y = free_group("x, y")
348
+ >>> f = FpGroup(F, [x**5, y**4, y*x*y**3*x**3])
349
+ >>> f.index([x])
350
+ 4
351
+
352
+ """
353
+ # TODO: use |G:H| = |G|/|H| (currently H can't be made into a group)
354
+ # when we know |G| and |H|
355
+
356
+ if H == []:
357
+ return self.order()
358
+ else:
359
+ C = self.coset_enumeration(H, strategy)
360
+ return len(C.table)
361
+
362
+ def __str__(self):
363
+ if self.free_group.rank > 30:
364
+ str_form = "<fp group with %s generators>" % self.free_group.rank
365
+ else:
366
+ str_form = "<fp group on the generators %s>" % str(self.generators)
367
+ return str_form
368
+
369
+ __repr__ = __str__
370
+
371
+ #==============================================================================
372
+ # PERMUTATION GROUP METHODS
373
+ #==============================================================================
374
+
375
+ def _to_perm_group(self):
376
+ '''
377
+ Return an isomorphic permutation group and the isomorphism.
378
+ The implementation is dependent on coset enumeration so
379
+ will only terminate for finite groups.
380
+
381
+ '''
382
+ from sympy.combinatorics import Permutation
383
+ from sympy.combinatorics.homomorphisms import homomorphism
384
+ if self.order() is S.Infinity:
385
+ raise NotImplementedError("Permutation presentation of infinite "
386
+ "groups is not implemented")
387
+ if self._perm_isomorphism:
388
+ T = self._perm_isomorphism
389
+ P = T.image()
390
+ else:
391
+ C = self.coset_table([])
392
+ gens = self.generators
393
+ images = [[C[i][2*gens.index(g)] for i in range(len(C))] for g in gens]
394
+ images = [Permutation(i) for i in images]
395
+ P = PermutationGroup(images)
396
+ T = homomorphism(self, P, gens, images, check=False)
397
+ self._perm_isomorphism = T
398
+ return P, T
399
+
400
+ def _perm_group_list(self, method_name, *args):
401
+ '''
402
+ Given the name of a `PermutationGroup` method (returning a subgroup
403
+ or a list of subgroups) and (optionally) additional arguments it takes,
404
+ return a list or a list of lists containing the generators of this (or
405
+ these) subgroups in terms of the generators of `self`.
406
+
407
+ '''
408
+ P, T = self._to_perm_group()
409
+ perm_result = getattr(P, method_name)(*args)
410
+ single = False
411
+ if isinstance(perm_result, PermutationGroup):
412
+ perm_result, single = [perm_result], True
413
+ result = []
414
+ for group in perm_result:
415
+ gens = group.generators
416
+ result.append(T.invert(gens))
417
+ return result[0] if single else result
418
+
419
+ def derived_series(self):
420
+ '''
421
+ Return the list of lists containing the generators
422
+ of the subgroups in the derived series of `self`.
423
+
424
+ '''
425
+ return self._perm_group_list('derived_series')
426
+
427
+ def lower_central_series(self):
428
+ '''
429
+ Return the list of lists containing the generators
430
+ of the subgroups in the lower central series of `self`.
431
+
432
+ '''
433
+ return self._perm_group_list('lower_central_series')
434
+
435
+ def center(self):
436
+ '''
437
+ Return the list of generators of the center of `self`.
438
+
439
+ '''
440
+ return self._perm_group_list('center')
441
+
442
+
443
+ def derived_subgroup(self):
444
+ '''
445
+ Return the list of generators of the derived subgroup of `self`.
446
+
447
+ '''
448
+ return self._perm_group_list('derived_subgroup')
449
+
450
+
451
+ def centralizer(self, other):
452
+ '''
453
+ Return the list of generators of the centralizer of `other`
454
+ (a list of elements of `self`) in `self`.
455
+
456
+ '''
457
+ T = self._to_perm_group()[1]
458
+ other = T(other)
459
+ return self._perm_group_list('centralizer', other)
460
+
461
+ def normal_closure(self, other):
462
+ '''
463
+ Return the list of generators of the normal closure of `other`
464
+ (a list of elements of `self`) in `self`.
465
+
466
+ '''
467
+ T = self._to_perm_group()[1]
468
+ other = T(other)
469
+ return self._perm_group_list('normal_closure', other)
470
+
471
+ def _perm_property(self, attr):
472
+ '''
473
+ Given an attribute of a `PermutationGroup`, return
474
+ its value for a permutation group isomorphic to `self`.
475
+
476
+ '''
477
+ P = self._to_perm_group()[0]
478
+ return getattr(P, attr)
479
+
480
+ @property
481
+ def is_abelian(self):
482
+ '''
483
+ Check if `self` is abelian.
484
+
485
+ '''
486
+ return self._perm_property("is_abelian")
487
+
488
+ @property
489
+ def is_nilpotent(self):
490
+ '''
491
+ Check if `self` is nilpotent.
492
+
493
+ '''
494
+ return self._perm_property("is_nilpotent")
495
+
496
+ @property
497
+ def is_solvable(self):
498
+ '''
499
+ Check if `self` is solvable.
500
+
501
+ '''
502
+ return self._perm_property("is_solvable")
503
+
504
+ @property
505
+ def elements(self):
506
+ '''
507
+ List the elements of `self`.
508
+
509
+ '''
510
+ P, T = self._to_perm_group()
511
+ return T.invert(P._elements)
512
+
513
+ @property
514
+ def is_cyclic(self):
515
+ """
516
+ Return ``True`` if group is Cyclic.
517
+
518
+ """
519
+ if len(self.generators) <= 1:
520
+ return True
521
+ try:
522
+ P, T = self._to_perm_group()
523
+ except NotImplementedError:
524
+ raise NotImplementedError("Check for infinite Cyclic group "
525
+ "is not implemented")
526
+ return P.is_cyclic
527
+
528
+ def abelian_invariants(self):
529
+ """
530
+ Return Abelian Invariants of a group.
531
+ """
532
+ try:
533
+ P, T = self._to_perm_group()
534
+ except NotImplementedError:
535
+ raise NotImplementedError("abelian invariants is not implemented"
536
+ "for infinite group")
537
+ return P.abelian_invariants()
538
+
539
+ def composition_series(self):
540
+ """
541
+ Return subnormal series of maximum length for a group.
542
+ """
543
+ try:
544
+ P, T = self._to_perm_group()
545
+ except NotImplementedError:
546
+ raise NotImplementedError("composition series is not implemented"
547
+ "for infinite group")
548
+ return P.composition_series()
549
+
550
+
551
+ class FpSubgroup(DefaultPrinting):
552
+ '''
553
+ The class implementing a subgroup of an FpGroup or a FreeGroup
554
+ (only finite index subgroups are supported at this point). This
555
+ is to be used if one wishes to check if an element of the original
556
+ group belongs to the subgroup
557
+
558
+ '''
559
+ def __init__(self, G, gens, normal=False):
560
+ super().__init__()
561
+ self.parent = G
562
+ self.generators = list({g for g in gens if g != G.identity})
563
+ self._min_words = None #for use in __contains__
564
+ self.C = None
565
+ self.normal = normal
566
+
567
+ def __contains__(self, g):
568
+
569
+ if isinstance(self.parent, FreeGroup):
570
+ if self._min_words is None:
571
+ # make _min_words - a list of subwords such that
572
+ # g is in the subgroup if and only if it can be
573
+ # partitioned into these subwords. Infinite families of
574
+ # subwords are presented by tuples, e.g. (r, w)
575
+ # stands for the family of subwords r*w**n*r**-1
576
+
577
+ def _process(w):
578
+ # this is to be used before adding new words
579
+ # into _min_words; if the word w is not cyclically
580
+ # reduced, it will generate an infinite family of
581
+ # subwords so should be written as a tuple;
582
+ # if it is, w**-1 should be added to the list
583
+ # as well
584
+ p, r = w.cyclic_reduction(removed=True)
585
+ if not r.is_identity:
586
+ return [(r, p)]
587
+ else:
588
+ return [w, w**-1]
589
+
590
+ # make the initial list
591
+ gens = []
592
+ for w in self.generators:
593
+ if self.normal:
594
+ w = w.cyclic_reduction()
595
+ gens.extend(_process(w))
596
+
597
+ for w1 in gens:
598
+ for w2 in gens:
599
+ # if w1 and w2 are equal or are inverses, continue
600
+ if w1 == w2 or (not isinstance(w1, tuple)
601
+ and w1**-1 == w2):
602
+ continue
603
+
604
+ # if the start of one word is the inverse of the
605
+ # end of the other, their multiple should be added
606
+ # to _min_words because of cancellation
607
+ if isinstance(w1, tuple):
608
+ # start, end
609
+ s1, s2 = w1[0][0], w1[0][0]**-1
610
+ else:
611
+ s1, s2 = w1[0], w1[len(w1)-1]
612
+
613
+ if isinstance(w2, tuple):
614
+ # start, end
615
+ r1, r2 = w2[0][0], w2[0][0]**-1
616
+ else:
617
+ r1, r2 = w2[0], w2[len(w1)-1]
618
+
619
+ # p1 and p2 are w1 and w2 or, in case when
620
+ # w1 or w2 is an infinite family, a representative
621
+ p1, p2 = w1, w2
622
+ if isinstance(w1, tuple):
623
+ p1 = w1[0]*w1[1]*w1[0]**-1
624
+ if isinstance(w2, tuple):
625
+ p2 = w2[0]*w2[1]*w2[0]**-1
626
+
627
+ # add the product of the words to the list is necessary
628
+ if r1**-1 == s2 and not (p1*p2).is_identity:
629
+ new = _process(p1*p2)
630
+ if new not in gens:
631
+ gens.extend(new)
632
+
633
+ if r2**-1 == s1 and not (p2*p1).is_identity:
634
+ new = _process(p2*p1)
635
+ if new not in gens:
636
+ gens.extend(new)
637
+
638
+ self._min_words = gens
639
+
640
+ min_words = self._min_words
641
+
642
+ def _is_subword(w):
643
+ # check if w is a word in _min_words or one of
644
+ # the infinite families in it
645
+ w, r = w.cyclic_reduction(removed=True)
646
+ if r.is_identity or self.normal:
647
+ return w in min_words
648
+ else:
649
+ t = [s[1] for s in min_words if isinstance(s, tuple)
650
+ and s[0] == r]
651
+ return [s for s in t if w.power_of(s)] != []
652
+
653
+ # store the solution of words for which the result of
654
+ # _word_break (below) is known
655
+ known = {}
656
+
657
+ def _word_break(w):
658
+ # check if w can be written as a product of words
659
+ # in min_words
660
+ if len(w) == 0:
661
+ return True
662
+ i = 0
663
+ while i < len(w):
664
+ i += 1
665
+ prefix = w.subword(0, i)
666
+ if not _is_subword(prefix):
667
+ continue
668
+ rest = w.subword(i, len(w))
669
+ if rest not in known:
670
+ known[rest] = _word_break(rest)
671
+ if known[rest]:
672
+ return True
673
+ return False
674
+
675
+ if self.normal:
676
+ g = g.cyclic_reduction()
677
+ return _word_break(g)
678
+ else:
679
+ if self.C is None:
680
+ C = self.parent.coset_enumeration(self.generators)
681
+ self.C = C
682
+ i = 0
683
+ C = self.C
684
+ for j in range(len(g)):
685
+ i = C.table[i][C.A_dict[g[j]]]
686
+ return i == 0
687
+
688
+ def order(self):
689
+ if not self.generators:
690
+ return S.One
691
+ if isinstance(self.parent, FreeGroup):
692
+ return S.Infinity
693
+ if self.C is None:
694
+ C = self.parent.coset_enumeration(self.generators)
695
+ self.C = C
696
+ # This is valid because `len(self.C.table)` (the index of the subgroup)
697
+ # will always be finite - otherwise coset enumeration doesn't terminate
698
+ return self.parent.order()/len(self.C.table)
699
+
700
+ def to_FpGroup(self):
701
+ if isinstance(self.parent, FreeGroup):
702
+ gen_syms = [('x_%d'%i) for i in range(len(self.generators))]
703
+ return free_group(', '.join(gen_syms))[0]
704
+ return self.parent.subgroup(C=self.C)
705
+
706
+ def __str__(self):
707
+ if len(self.generators) > 30:
708
+ str_form = "<fp subgroup with %s generators>" % len(self.generators)
709
+ else:
710
+ str_form = "<fp subgroup on the generators %s>" % str(self.generators)
711
+ return str_form
712
+
713
+ __repr__ = __str__
714
+
715
+
716
+ ###############################################################################
717
+ # LOW INDEX SUBGROUPS #
718
+ ###############################################################################
719
+
720
+ def low_index_subgroups(G, N, Y=()):
721
+ """
722
+ Implements the Low Index Subgroups algorithm, i.e find all subgroups of
723
+ ``G`` upto a given index ``N``. This implements the method described in
724
+ [Sim94]. This procedure involves a backtrack search over incomplete Coset
725
+ Tables, rather than over forced coincidences.
726
+
727
+ Parameters
728
+ ==========
729
+
730
+ G: An FpGroup < X|R >
731
+ N: positive integer, representing the maximum index value for subgroups
732
+ Y: (an optional argument) specifying a list of subgroup generators, such
733
+ that each of the resulting subgroup contains the subgroup generated by Y.
734
+
735
+ Examples
736
+ ========
737
+
738
+ >>> from sympy.combinatorics import free_group
739
+ >>> from sympy.combinatorics.fp_groups import FpGroup, low_index_subgroups
740
+ >>> F, x, y = free_group("x, y")
741
+ >>> f = FpGroup(F, [x**2, y**3, (x*y)**4])
742
+ >>> L = low_index_subgroups(f, 4)
743
+ >>> for coset_table in L:
744
+ ... print(coset_table.table)
745
+ [[0, 0, 0, 0]]
746
+ [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]]
747
+ [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]]
748
+ [[1, 1, 0, 0], [0, 0, 1, 1]]
749
+
750
+ References
751
+ ==========
752
+
753
+ .. [1] Holt, D., Eick, B., O'Brien, E.
754
+ "Handbook of Computational Group Theory"
755
+ Section 5.4
756
+
757
+ .. [2] Marston Conder and Peter Dobcsanyi
758
+ "Applications and Adaptions of the Low Index Subgroups Procedure"
759
+
760
+ """
761
+ C = CosetTable(G, [])
762
+ R = G.relators
763
+ # length chosen for the length of the short relators
764
+ len_short_rel = 5
765
+ # elements of R2 only checked at the last step for complete
766
+ # coset tables
767
+ R2 = {rel for rel in R if len(rel) > len_short_rel}
768
+ # elements of R1 are used in inner parts of the process to prune
769
+ # branches of the search tree,
770
+ R1 = {rel.identity_cyclic_reduction() for rel in set(R) - R2}
771
+ R1_c_list = C.conjugates(R1)
772
+ S = []
773
+ descendant_subgroups(S, C, R1_c_list, C.A[0], R2, N, Y)
774
+ return S
775
+
776
+
777
+ def descendant_subgroups(S, C, R1_c_list, x, R2, N, Y):
778
+ A_dict = C.A_dict
779
+ A_dict_inv = C.A_dict_inv
780
+ if C.is_complete():
781
+ # if C is complete then it only needs to test
782
+ # whether the relators in R2 are satisfied
783
+ for w, alpha in product(R2, C.omega):
784
+ if not C.scan_check(alpha, w):
785
+ return
786
+ # relators in R2 are satisfied, append the table to list
787
+ S.append(C)
788
+ else:
789
+ # find the first undefined entry in Coset Table
790
+ for alpha, x in product(range(len(C.table)), C.A):
791
+ if C.table[alpha][A_dict[x]] is None:
792
+ # this is "x" in pseudo-code (using "y" makes it clear)
793
+ undefined_coset, undefined_gen = alpha, x
794
+ break
795
+ # for filling up the undefine entry we try all possible values
796
+ # of beta in Omega or beta = n where beta^(undefined_gen^-1) is undefined
797
+ reach = C.omega + [C.n]
798
+ for beta in reach:
799
+ if beta < N:
800
+ if beta == C.n or C.table[beta][A_dict_inv[undefined_gen]] is None:
801
+ try_descendant(S, C, R1_c_list, R2, N, undefined_coset, \
802
+ undefined_gen, beta, Y)
803
+
804
+
805
+ def try_descendant(S, C, R1_c_list, R2, N, alpha, x, beta, Y):
806
+ r"""
807
+ Solves the problem of trying out each individual possibility
808
+ for `\alpha^x.
809
+
810
+ """
811
+ D = C.copy()
812
+ if beta == D.n and beta < N:
813
+ D.table.append([None]*len(D.A))
814
+ D.p.append(beta)
815
+ D.table[alpha][D.A_dict[x]] = beta
816
+ D.table[beta][D.A_dict_inv[x]] = alpha
817
+ D.deduction_stack.append((alpha, x))
818
+ if not D.process_deductions_check(R1_c_list[D.A_dict[x]], \
819
+ R1_c_list[D.A_dict_inv[x]]):
820
+ return
821
+ for w in Y:
822
+ if not D.scan_check(0, w):
823
+ return
824
+ if first_in_class(D, Y):
825
+ descendant_subgroups(S, D, R1_c_list, x, R2, N, Y)
826
+
827
+
828
+ def first_in_class(C, Y=()):
829
+ """
830
+ Checks whether the subgroup ``H=G1`` corresponding to the Coset Table
831
+ could possibly be the canonical representative of its conjugacy class.
832
+
833
+ Parameters
834
+ ==========
835
+
836
+ C: CosetTable
837
+
838
+ Returns
839
+ =======
840
+
841
+ bool: True/False
842
+
843
+ If this returns False, then no descendant of C can have that property, and
844
+ so we can abandon C. If it returns True, then we need to process further
845
+ the node of the search tree corresponding to C, and so we call
846
+ ``descendant_subgroups`` recursively on C.
847
+
848
+ Examples
849
+ ========
850
+
851
+ >>> from sympy.combinatorics import free_group
852
+ >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, first_in_class
853
+ >>> F, x, y = free_group("x, y")
854
+ >>> f = FpGroup(F, [x**2, y**3, (x*y)**4])
855
+ >>> C = CosetTable(f, [])
856
+ >>> C.table = [[0, 0, None, None]]
857
+ >>> first_in_class(C)
858
+ True
859
+ >>> C.table = [[1, 1, 1, None], [0, 0, None, 1]]; C.p = [0, 1]
860
+ >>> first_in_class(C)
861
+ True
862
+ >>> C.table = [[1, 1, 2, 1], [0, 0, 0, None], [None, None, None, 0]]
863
+ >>> C.p = [0, 1, 2]
864
+ >>> first_in_class(C)
865
+ False
866
+ >>> C.table = [[1, 1, 1, 2], [0, 0, 2, 0], [2, None, 0, 1]]
867
+ >>> first_in_class(C)
868
+ False
869
+
870
+ # TODO:: Sims points out in [Sim94] that performance can be improved by
871
+ # remembering some of the information computed by ``first_in_class``. If
872
+ # the ``continue alpha`` statement is executed at line 14, then the same thing
873
+ # will happen for that value of alpha in any descendant of the table C, and so
874
+ # the values the values of alpha for which this occurs could profitably be
875
+ # stored and passed through to the descendants of C. Of course this would
876
+ # make the code more complicated.
877
+
878
+ # The code below is taken directly from the function on page 208 of [Sim94]
879
+ # nu[alpha]
880
+
881
+ """
882
+ n = C.n
883
+ # lamda is the largest numbered point in Omega_c_alpha which is currently defined
884
+ lamda = -1
885
+ # for alpha in Omega_c, nu[alpha] is the point in Omega_c_alpha corresponding to alpha
886
+ nu = [None]*n
887
+ # for alpha in Omega_c_alpha, mu[alpha] is the point in Omega_c corresponding to alpha
888
+ mu = [None]*n
889
+ # mutually nu and mu are the mutually-inverse equivalence maps between
890
+ # Omega_c_alpha and Omega_c
891
+ next_alpha = False
892
+ # For each 0!=alpha in [0 .. nc-1], we start by constructing the equivalent
893
+ # standardized coset table C_alpha corresponding to H_alpha
894
+ for alpha in range(1, n):
895
+ # reset nu to "None" after previous value of alpha
896
+ for beta in range(lamda+1):
897
+ nu[mu[beta]] = None
898
+ # we only want to reject our current table in favour of a preceding
899
+ # table in the ordering in which 1 is replaced by alpha, if the subgroup
900
+ # G_alpha corresponding to this preceding table definitely contains the
901
+ # given subgroup
902
+ for w in Y:
903
+ # TODO: this should support input of a list of general words
904
+ # not just the words which are in "A" (i.e gen and gen^-1)
905
+ if C.table[alpha][C.A_dict[w]] != alpha:
906
+ # continue with alpha
907
+ next_alpha = True
908
+ break
909
+ if next_alpha:
910
+ next_alpha = False
911
+ continue
912
+ # try alpha as the new point 0 in Omega_C_alpha
913
+ mu[0] = alpha
914
+ nu[alpha] = 0
915
+ # compare corresponding entries in C and C_alpha
916
+ lamda = 0
917
+ for beta in range(n):
918
+ for x in C.A:
919
+ gamma = C.table[beta][C.A_dict[x]]
920
+ delta = C.table[mu[beta]][C.A_dict[x]]
921
+ # if either of the entries is undefined,
922
+ # we move with next alpha
923
+ if gamma is None or delta is None:
924
+ # continue with alpha
925
+ next_alpha = True
926
+ break
927
+ if nu[delta] is None:
928
+ # delta becomes the next point in Omega_C_alpha
929
+ lamda += 1
930
+ nu[delta] = lamda
931
+ mu[lamda] = delta
932
+ if nu[delta] < gamma:
933
+ return False
934
+ if nu[delta] > gamma:
935
+ # continue with alpha
936
+ next_alpha = True
937
+ break
938
+ if next_alpha:
939
+ next_alpha = False
940
+ break
941
+ return True
942
+
943
+ #========================================================================
944
+ # Simplifying Presentation
945
+ #========================================================================
946
+
947
+ def simplify_presentation(*args, change_gens=False):
948
+ '''
949
+ For an instance of `FpGroup`, return a simplified isomorphic copy of
950
+ the group (e.g. remove redundant generators or relators). Alternatively,
951
+ a list of generators and relators can be passed in which case the
952
+ simplified lists will be returned.
953
+
954
+ By default, the generators of the group are unchanged. If you would
955
+ like to remove redundant generators, set the keyword argument
956
+ `change_gens = True`.
957
+
958
+ '''
959
+ if len(args) == 1:
960
+ if not isinstance(args[0], FpGroup):
961
+ raise TypeError("The argument must be an instance of FpGroup")
962
+ G = args[0]
963
+ gens, rels = simplify_presentation(G.generators, G.relators,
964
+ change_gens=change_gens)
965
+ if gens:
966
+ return FpGroup(gens[0].group, rels)
967
+ return FpGroup(FreeGroup([]), [])
968
+ elif len(args) == 2:
969
+ gens, rels = args[0][:], args[1][:]
970
+ if not gens:
971
+ return gens, rels
972
+ identity = gens[0].group.identity
973
+ else:
974
+ if len(args) == 0:
975
+ m = "Not enough arguments"
976
+ else:
977
+ m = "Too many arguments"
978
+ raise RuntimeError(m)
979
+
980
+ prev_gens = []
981
+ prev_rels = []
982
+ while not set(prev_rels) == set(rels):
983
+ prev_rels = rels
984
+ while change_gens and not set(prev_gens) == set(gens):
985
+ prev_gens = gens
986
+ gens, rels = elimination_technique_1(gens, rels, identity)
987
+ rels = _simplify_relators(rels, identity)
988
+
989
+ if change_gens:
990
+ syms = [g.array_form[0][0] for g in gens]
991
+ F = free_group(syms)[0]
992
+ identity = F.identity
993
+ gens = F.generators
994
+ subs = dict(zip(syms, gens))
995
+ for j, r in enumerate(rels):
996
+ a = r.array_form
997
+ rel = identity
998
+ for sym, p in a:
999
+ rel = rel*subs[sym]**p
1000
+ rels[j] = rel
1001
+ return gens, rels
1002
+
1003
+ def _simplify_relators(rels, identity):
1004
+ """Relies upon ``_simplification_technique_1`` for its functioning. """
1005
+ rels = rels[:]
1006
+
1007
+ rels = list(set(_simplification_technique_1(rels)))
1008
+ rels.sort()
1009
+ rels = [r.identity_cyclic_reduction() for r in rels]
1010
+ try:
1011
+ rels.remove(identity)
1012
+ except ValueError:
1013
+ pass
1014
+ return rels
1015
+
1016
+ # Pg 350, section 2.5.1 from [2]
1017
+ def elimination_technique_1(gens, rels, identity):
1018
+ rels = rels[:]
1019
+ # the shorter relators are examined first so that generators selected for
1020
+ # elimination will have shorter strings as equivalent
1021
+ rels.sort()
1022
+ gens = gens[:]
1023
+ redundant_gens = {}
1024
+ redundant_rels = []
1025
+ used_gens = set()
1026
+ # examine each relator in relator list for any generator occurring exactly
1027
+ # once
1028
+ for rel in rels:
1029
+ # don't look for a redundant generator in a relator which
1030
+ # depends on previously found ones
1031
+ contained_gens = rel.contains_generators()
1032
+ if any(g in contained_gens for g in redundant_gens):
1033
+ continue
1034
+ contained_gens = list(contained_gens)
1035
+ contained_gens.sort(reverse = True)
1036
+ for gen in contained_gens:
1037
+ if rel.generator_count(gen) == 1 and gen not in used_gens:
1038
+ k = rel.exponent_sum(gen)
1039
+ gen_index = rel.index(gen**k)
1040
+ bk = rel.subword(gen_index + 1, len(rel))
1041
+ fw = rel.subword(0, gen_index)
1042
+ chi = bk*fw
1043
+ redundant_gens[gen] = chi**(-1*k)
1044
+ used_gens.update(chi.contains_generators())
1045
+ redundant_rels.append(rel)
1046
+ break
1047
+ rels = [r for r in rels if r not in redundant_rels]
1048
+ # eliminate the redundant generators from remaining relators
1049
+ rels = [r.eliminate_words(redundant_gens, _all = True).identity_cyclic_reduction() for r in rels]
1050
+ rels = list(set(rels))
1051
+ try:
1052
+ rels.remove(identity)
1053
+ except ValueError:
1054
+ pass
1055
+ gens = [g for g in gens if g not in redundant_gens]
1056
+ return gens, rels
1057
+
1058
+ def _simplification_technique_1(rels):
1059
+ """
1060
+ All relators are checked to see if they are of the form `gen^n`. If any
1061
+ such relators are found then all other relators are processed for strings
1062
+ in the `gen` known order.
1063
+
1064
+ Examples
1065
+ ========
1066
+
1067
+ >>> from sympy.combinatorics import free_group
1068
+ >>> from sympy.combinatorics.fp_groups import _simplification_technique_1
1069
+ >>> F, x, y = free_group("x, y")
1070
+ >>> w1 = [x**2*y**4, x**3]
1071
+ >>> _simplification_technique_1(w1)
1072
+ [x**-1*y**4, x**3]
1073
+
1074
+ >>> w2 = [x**2*y**-4*x**5, x**3, x**2*y**8, y**5]
1075
+ >>> _simplification_technique_1(w2)
1076
+ [x**-1*y*x**-1, x**3, x**-1*y**-2, y**5]
1077
+
1078
+ >>> w3 = [x**6*y**4, x**4]
1079
+ >>> _simplification_technique_1(w3)
1080
+ [x**2*y**4, x**4]
1081
+
1082
+ """
1083
+ rels = rels[:]
1084
+ # dictionary with "gen: n" where gen^n is one of the relators
1085
+ exps = {}
1086
+ for i in range(len(rels)):
1087
+ rel = rels[i]
1088
+ if rel.number_syllables() == 1:
1089
+ g = rel[0]
1090
+ exp = abs(rel.array_form[0][1])
1091
+ if rel.array_form[0][1] < 0:
1092
+ rels[i] = rels[i]**-1
1093
+ g = g**-1
1094
+ if g in exps:
1095
+ exp = gcd(exp, exps[g].array_form[0][1])
1096
+ exps[g] = g**exp
1097
+
1098
+ one_syllables_words = exps.values()
1099
+ # decrease some of the exponents in relators, making use of the single
1100
+ # syllable relators
1101
+ for i in range(len(rels)):
1102
+ rel = rels[i]
1103
+ if rel in one_syllables_words:
1104
+ continue
1105
+ rel = rel.eliminate_words(one_syllables_words, _all = True)
1106
+ # if rels[i] contains g**n where abs(n) is greater than half of the power p
1107
+ # of g in exps, g**n can be replaced by g**(n-p) (or g**(p-n) if n<0)
1108
+ for g in rel.contains_generators():
1109
+ if g in exps:
1110
+ exp = exps[g].array_form[0][1]
1111
+ max_exp = (exp + 1)//2
1112
+ rel = rel.eliminate_word(g**(max_exp), g**(max_exp-exp), _all = True)
1113
+ rel = rel.eliminate_word(g**(-max_exp), g**(-(max_exp-exp)), _all = True)
1114
+ rels[i] = rel
1115
+ rels = [r.identity_cyclic_reduction() for r in rels]
1116
+ return rels
1117
+
1118
+
1119
+ ###############################################################################
1120
+ # SUBGROUP PRESENTATIONS #
1121
+ ###############################################################################
1122
+
1123
+ # Pg 175 [1]
1124
+ def define_schreier_generators(C, homomorphism=False):
1125
+ '''
1126
+ Parameters
1127
+ ==========
1128
+
1129
+ C -- Coset table.
1130
+ homomorphism -- When set to True, return a dictionary containing the images
1131
+ of the presentation generators in the original group.
1132
+ '''
1133
+ y = []
1134
+ gamma = 1
1135
+ f = C.fp_group
1136
+ X = f.generators
1137
+ if homomorphism:
1138
+ # `_gens` stores the elements of the parent group to
1139
+ # to which the schreier generators correspond to.
1140
+ _gens = {}
1141
+ # compute the schreier Traversal
1142
+ tau = {}
1143
+ tau[0] = f.identity
1144
+ C.P = [[None]*len(C.A) for i in range(C.n)]
1145
+ for alpha, x in product(C.omega, C.A):
1146
+ beta = C.table[alpha][C.A_dict[x]]
1147
+ if beta == gamma:
1148
+ C.P[alpha][C.A_dict[x]] = "<identity>"
1149
+ C.P[beta][C.A_dict_inv[x]] = "<identity>"
1150
+ gamma += 1
1151
+ if homomorphism:
1152
+ tau[beta] = tau[alpha]*x
1153
+ elif x in X and C.P[alpha][C.A_dict[x]] is None:
1154
+ y_alpha_x = '%s_%s' % (x, alpha)
1155
+ y.append(y_alpha_x)
1156
+ C.P[alpha][C.A_dict[x]] = y_alpha_x
1157
+ if homomorphism:
1158
+ _gens[y_alpha_x] = tau[alpha]*x*tau[beta]**-1
1159
+ grp_gens = list(free_group(', '.join(y)))
1160
+ C._schreier_free_group = grp_gens.pop(0)
1161
+ C._schreier_generators = grp_gens
1162
+ if homomorphism:
1163
+ C._schreier_gen_elem = _gens
1164
+ # replace all elements of P by, free group elements
1165
+ for i, j in product(range(len(C.P)), range(len(C.A))):
1166
+ # if equals "<identity>", replace by identity element
1167
+ if C.P[i][j] == "<identity>":
1168
+ C.P[i][j] = C._schreier_free_group.identity
1169
+ elif isinstance(C.P[i][j], str):
1170
+ r = C._schreier_generators[y.index(C.P[i][j])]
1171
+ C.P[i][j] = r
1172
+ beta = C.table[i][j]
1173
+ C.P[beta][j + 1] = r**-1
1174
+
1175
+ def reidemeister_relators(C):
1176
+ R = C.fp_group.relators
1177
+ rels = [rewrite(C, coset, word) for word in R for coset in range(C.n)]
1178
+ order_1_gens = {i for i in rels if len(i) == 1}
1179
+
1180
+ # remove all the order 1 generators from relators
1181
+ rels = list(filter(lambda rel: rel not in order_1_gens, rels))
1182
+
1183
+ # replace order 1 generators by identity element in reidemeister relators
1184
+ for i in range(len(rels)):
1185
+ w = rels[i]
1186
+ w = w.eliminate_words(order_1_gens, _all=True)
1187
+ rels[i] = w
1188
+
1189
+ C._schreier_generators = [i for i in C._schreier_generators
1190
+ if not (i in order_1_gens or i**-1 in order_1_gens)]
1191
+
1192
+ # Tietze transformation 1 i.e TT_1
1193
+ # remove cyclic conjugate elements from relators
1194
+ i = 0
1195
+ while i < len(rels):
1196
+ w = rels[i]
1197
+ j = i + 1
1198
+ while j < len(rels):
1199
+ if w.is_cyclic_conjugate(rels[j]):
1200
+ del rels[j]
1201
+ else:
1202
+ j += 1
1203
+ i += 1
1204
+
1205
+ C._reidemeister_relators = rels
1206
+
1207
+
1208
+ def rewrite(C, alpha, w):
1209
+ """
1210
+ Parameters
1211
+ ==========
1212
+
1213
+ C: CosetTable
1214
+ alpha: A live coset
1215
+ w: A word in `A*`
1216
+
1217
+ Returns
1218
+ =======
1219
+
1220
+ rho(tau(alpha), w)
1221
+
1222
+ Examples
1223
+ ========
1224
+
1225
+ >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, define_schreier_generators, rewrite
1226
+ >>> from sympy.combinatorics import free_group
1227
+ >>> F, x, y = free_group("x, y")
1228
+ >>> f = FpGroup(F, [x**2, y**3, (x*y)**6])
1229
+ >>> C = CosetTable(f, [])
1230
+ >>> C.table = [[1, 1, 2, 3], [0, 0, 4, 5], [4, 4, 3, 0], [5, 5, 0, 2], [2, 2, 5, 1], [3, 3, 1, 4]]
1231
+ >>> C.p = [0, 1, 2, 3, 4, 5]
1232
+ >>> define_schreier_generators(C)
1233
+ >>> rewrite(C, 0, (x*y)**6)
1234
+ x_4*y_2*x_3*x_1*x_2*y_4*x_5
1235
+
1236
+ """
1237
+ v = C._schreier_free_group.identity
1238
+ for i in range(len(w)):
1239
+ x_i = w[i]
1240
+ v = v*C.P[alpha][C.A_dict[x_i]]
1241
+ alpha = C.table[alpha][C.A_dict[x_i]]
1242
+ return v
1243
+
1244
+ # Pg 350, section 2.5.2 from [2]
1245
+ def elimination_technique_2(C):
1246
+ """
1247
+ This technique eliminates one generator at a time. Heuristically this
1248
+ seems superior in that we may select for elimination the generator with
1249
+ shortest equivalent string at each stage.
1250
+
1251
+ >>> from sympy.combinatorics import free_group
1252
+ >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r, \
1253
+ reidemeister_relators, define_schreier_generators, elimination_technique_2
1254
+ >>> F, x, y = free_group("x, y")
1255
+ >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]); H = [x*y, x**-1*y**-1*x*y*x]
1256
+ >>> C = coset_enumeration_r(f, H)
1257
+ >>> C.compress(); C.standardize()
1258
+ >>> define_schreier_generators(C)
1259
+ >>> reidemeister_relators(C)
1260
+ >>> elimination_technique_2(C)
1261
+ ([y_1, y_2], [y_2**-3, y_2*y_1*y_2*y_1*y_2*y_1, y_1**2])
1262
+
1263
+ """
1264
+ rels = C._reidemeister_relators
1265
+ rels.sort(reverse=True)
1266
+ gens = C._schreier_generators
1267
+ for i in range(len(gens) - 1, -1, -1):
1268
+ rel = rels[i]
1269
+ for j in range(len(gens) - 1, -1, -1):
1270
+ gen = gens[j]
1271
+ if rel.generator_count(gen) == 1:
1272
+ k = rel.exponent_sum(gen)
1273
+ gen_index = rel.index(gen**k)
1274
+ bk = rel.subword(gen_index + 1, len(rel))
1275
+ fw = rel.subword(0, gen_index)
1276
+ rep_by = (bk*fw)**(-1*k)
1277
+ del rels[i]; del gens[j]
1278
+ for l in range(len(rels)):
1279
+ rels[l] = rels[l].eliminate_word(gen, rep_by)
1280
+ break
1281
+ C._reidemeister_relators = rels
1282
+ C._schreier_generators = gens
1283
+ return C._schreier_generators, C._reidemeister_relators
1284
+
1285
+ def reidemeister_presentation(fp_grp, H, C=None, homomorphism=False):
1286
+ """
1287
+ Parameters
1288
+ ==========
1289
+
1290
+ fp_group: A finitely presented group, an instance of FpGroup
1291
+ H: A subgroup whose presentation is to be found, given as a list
1292
+ of words in generators of `fp_grp`
1293
+ homomorphism: When set to True, return a homomorphism from the subgroup
1294
+ to the parent group
1295
+
1296
+ Examples
1297
+ ========
1298
+
1299
+ >>> from sympy.combinatorics import free_group
1300
+ >>> from sympy.combinatorics.fp_groups import FpGroup, reidemeister_presentation
1301
+ >>> F, x, y = free_group("x, y")
1302
+
1303
+ Example 5.6 Pg. 177 from [1]
1304
+ >>> f = FpGroup(F, [x**3, y**5, (x*y)**2])
1305
+ >>> H = [x*y, x**-1*y**-1*x*y*x]
1306
+ >>> reidemeister_presentation(f, H)
1307
+ ((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1))
1308
+
1309
+ Example 5.8 Pg. 183 from [1]
1310
+ >>> f = FpGroup(F, [x**3, y**3, (x*y)**3])
1311
+ >>> H = [x*y, x*y**-1]
1312
+ >>> reidemeister_presentation(f, H)
1313
+ ((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0))
1314
+
1315
+ Exercises Q2. Pg 187 from [1]
1316
+ >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3])
1317
+ >>> H = [x]
1318
+ >>> reidemeister_presentation(f, H)
1319
+ ((x_0,), (x_0**4,))
1320
+
1321
+ Example 5.9 Pg. 183 from [1]
1322
+ >>> f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2])
1323
+ >>> H = [x]
1324
+ >>> reidemeister_presentation(f, H)
1325
+ ((x_0,), (x_0**6,))
1326
+
1327
+ """
1328
+ if not C:
1329
+ C = coset_enumeration_r(fp_grp, H)
1330
+ C.compress(); C.standardize()
1331
+ define_schreier_generators(C, homomorphism=homomorphism)
1332
+ reidemeister_relators(C)
1333
+ gens, rels = C._schreier_generators, C._reidemeister_relators
1334
+ gens, rels = simplify_presentation(gens, rels, change_gens=True)
1335
+
1336
+ C.schreier_generators = tuple(gens)
1337
+ C.reidemeister_relators = tuple(rels)
1338
+
1339
+ if homomorphism:
1340
+ _gens = []
1341
+ for gen in gens:
1342
+ _gens.append(C._schreier_gen_elem[str(gen)])
1343
+ return C.schreier_generators, C.reidemeister_relators, _gens
1344
+
1345
+ return C.schreier_generators, C.reidemeister_relators
1346
+
1347
+
1348
+ FpGroupElement = FreeGroupElement
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/free_groups.py ADDED
@@ -0,0 +1,1354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from sympy.core import S
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.symbol import Symbol, symbols as _symbols
6
+ from sympy.core.sympify import CantSympify
7
+ from sympy.printing.defaults import DefaultPrinting
8
+ from sympy.utilities import public
9
+ from sympy.utilities.iterables import flatten, is_sequence
10
+ from sympy.utilities.magic import pollute
11
+ from sympy.utilities.misc import as_int
12
+
13
+
14
+ @public
15
+ def free_group(symbols):
16
+ """Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1))``.
17
+
18
+ Parameters
19
+ ==========
20
+
21
+ symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty)
22
+
23
+ Examples
24
+ ========
25
+
26
+ >>> from sympy.combinatorics import free_group
27
+ >>> F, x, y, z = free_group("x, y, z")
28
+ >>> F
29
+ <free group on the generators (x, y, z)>
30
+ >>> x**2*y**-1
31
+ x**2*y**-1
32
+ >>> type(_)
33
+ <class 'sympy.combinatorics.free_groups.FreeGroupElement'>
34
+
35
+ """
36
+ _free_group = FreeGroup(symbols)
37
+ return (_free_group,) + tuple(_free_group.generators)
38
+
39
+ @public
40
+ def xfree_group(symbols):
41
+ """Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1)))``.
42
+
43
+ Parameters
44
+ ==========
45
+
46
+ symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty)
47
+
48
+ Examples
49
+ ========
50
+
51
+ >>> from sympy.combinatorics.free_groups import xfree_group
52
+ >>> F, (x, y, z) = xfree_group("x, y, z")
53
+ >>> F
54
+ <free group on the generators (x, y, z)>
55
+ >>> y**2*x**-2*z**-1
56
+ y**2*x**-2*z**-1
57
+ >>> type(_)
58
+ <class 'sympy.combinatorics.free_groups.FreeGroupElement'>
59
+
60
+ """
61
+ _free_group = FreeGroup(symbols)
62
+ return (_free_group, _free_group.generators)
63
+
64
+ @public
65
+ def vfree_group(symbols):
66
+ """Construct a free group and inject ``f_0, f_1, ..., f_(n-1)`` as symbols
67
+ into the global namespace.
68
+
69
+ Parameters
70
+ ==========
71
+
72
+ symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty)
73
+
74
+ Examples
75
+ ========
76
+
77
+ >>> from sympy.combinatorics.free_groups import vfree_group
78
+ >>> vfree_group("x, y, z")
79
+ <free group on the generators (x, y, z)>
80
+ >>> x**2*y**-2*z # noqa: F821
81
+ x**2*y**-2*z
82
+ >>> type(_)
83
+ <class 'sympy.combinatorics.free_groups.FreeGroupElement'>
84
+
85
+ """
86
+ _free_group = FreeGroup(symbols)
87
+ pollute([sym.name for sym in _free_group.symbols], _free_group.generators)
88
+ return _free_group
89
+
90
+
91
+ def _parse_symbols(symbols):
92
+ if not symbols:
93
+ return ()
94
+ if isinstance(symbols, str):
95
+ return _symbols(symbols, seq=True)
96
+ elif isinstance(symbols, (Expr, FreeGroupElement)):
97
+ return (symbols,)
98
+ elif is_sequence(symbols):
99
+ if all(isinstance(s, str) for s in symbols):
100
+ return _symbols(symbols)
101
+ elif all(isinstance(s, Expr) for s in symbols):
102
+ return symbols
103
+ raise ValueError("The type of `symbols` must be one of the following: "
104
+ "a str, Symbol/Expr or a sequence of "
105
+ "one of these types")
106
+
107
+
108
+ ##############################################################################
109
+ # FREE GROUP #
110
+ ##############################################################################
111
+
112
+ _free_group_cache: dict[int, FreeGroup] = {}
113
+
114
+ class FreeGroup(DefaultPrinting):
115
+ """
116
+ Free group with finite or infinite number of generators. Its input API
117
+ is that of a str, Symbol/Expr or a sequence of one of
118
+ these types (which may be empty)
119
+
120
+ See Also
121
+ ========
122
+
123
+ sympy.polys.rings.PolyRing
124
+
125
+ References
126
+ ==========
127
+
128
+ .. [1] https://www.gap-system.org/Manuals/doc/ref/chap37.html
129
+
130
+ .. [2] https://en.wikipedia.org/wiki/Free_group
131
+
132
+ """
133
+ is_associative = True
134
+ is_group = True
135
+ is_FreeGroup = True
136
+ is_PermutationGroup = False
137
+ relators: list[Expr] = []
138
+
139
+ def __new__(cls, symbols):
140
+ symbols = tuple(_parse_symbols(symbols))
141
+ rank = len(symbols)
142
+ _hash = hash((cls.__name__, symbols, rank))
143
+ obj = _free_group_cache.get(_hash)
144
+
145
+ if obj is None:
146
+ obj = object.__new__(cls)
147
+ obj._hash = _hash
148
+ obj._rank = rank
149
+ # dtype method is used to create new instances of FreeGroupElement
150
+ obj.dtype = type("FreeGroupElement", (FreeGroupElement,), {"group": obj})
151
+ obj.symbols = symbols
152
+ obj.generators = obj._generators()
153
+ obj._gens_set = set(obj.generators)
154
+ for symbol, generator in zip(obj.symbols, obj.generators):
155
+ if isinstance(symbol, Symbol):
156
+ name = symbol.name
157
+ if hasattr(obj, name):
158
+ setattr(obj, name, generator)
159
+
160
+ _free_group_cache[_hash] = obj
161
+
162
+ return obj
163
+
164
+ def _generators(group):
165
+ """Returns the generators of the FreeGroup.
166
+
167
+ Examples
168
+ ========
169
+
170
+ >>> from sympy.combinatorics import free_group
171
+ >>> F, x, y, z = free_group("x, y, z")
172
+ >>> F.generators
173
+ (x, y, z)
174
+
175
+ """
176
+ gens = []
177
+ for sym in group.symbols:
178
+ elm = ((sym, 1),)
179
+ gens.append(group.dtype(elm))
180
+ return tuple(gens)
181
+
182
+ def clone(self, symbols=None):
183
+ return self.__class__(symbols or self.symbols)
184
+
185
+ def __contains__(self, i):
186
+ """Return True if ``i`` is contained in FreeGroup."""
187
+ if not isinstance(i, FreeGroupElement):
188
+ return False
189
+ group = i.group
190
+ return self == group
191
+
192
+ def __hash__(self):
193
+ return self._hash
194
+
195
+ def __len__(self):
196
+ return self.rank
197
+
198
+ def __str__(self):
199
+ if self.rank > 30:
200
+ str_form = "<free group with %s generators>" % self.rank
201
+ else:
202
+ str_form = "<free group on the generators "
203
+ gens = self.generators
204
+ str_form += str(gens) + ">"
205
+ return str_form
206
+
207
+ __repr__ = __str__
208
+
209
+ def __getitem__(self, index):
210
+ symbols = self.symbols[index]
211
+ return self.clone(symbols=symbols)
212
+
213
+ def __eq__(self, other):
214
+ """No ``FreeGroup`` is equal to any "other" ``FreeGroup``.
215
+ """
216
+ return self is other
217
+
218
+ def index(self, gen):
219
+ """Return the index of the generator `gen` from ``(f_0, ..., f_(n-1))``.
220
+
221
+ Examples
222
+ ========
223
+
224
+ >>> from sympy.combinatorics import free_group
225
+ >>> F, x, y = free_group("x, y")
226
+ >>> F.index(y)
227
+ 1
228
+ >>> F.index(x)
229
+ 0
230
+
231
+ """
232
+ if isinstance(gen, self.dtype):
233
+ return self.generators.index(gen)
234
+ else:
235
+ raise ValueError("expected a generator of Free Group %s, got %s" % (self, gen))
236
+
237
+ def order(self):
238
+ """Return the order of the free group.
239
+
240
+ Examples
241
+ ========
242
+
243
+ >>> from sympy.combinatorics import free_group
244
+ >>> F, x, y = free_group("x, y")
245
+ >>> F.order()
246
+ oo
247
+
248
+ >>> free_group("")[0].order()
249
+ 1
250
+
251
+ """
252
+ if self.rank == 0:
253
+ return S.One
254
+ else:
255
+ return S.Infinity
256
+
257
+ @property
258
+ def elements(self):
259
+ """
260
+ Return the elements of the free group.
261
+
262
+ Examples
263
+ ========
264
+
265
+ >>> from sympy.combinatorics import free_group
266
+ >>> (z,) = free_group("")
267
+ >>> z.elements
268
+ {<identity>}
269
+
270
+ """
271
+ if self.rank == 0:
272
+ # A set containing Identity element of `FreeGroup` self is returned
273
+ return {self.identity}
274
+ else:
275
+ raise ValueError("Group contains infinitely many elements"
276
+ ", hence cannot be represented")
277
+
278
+ @property
279
+ def rank(self):
280
+ r"""
281
+ In group theory, the `rank` of a group `G`, denoted `G.rank`,
282
+ can refer to the smallest cardinality of a generating set
283
+ for G, that is
284
+
285
+ \operatorname{rank}(G)=\min\{ |X|: X\subseteq G, \left\langle X\right\rangle =G\}.
286
+
287
+ """
288
+ return self._rank
289
+
290
+ @property
291
+ def is_abelian(self):
292
+ """Returns if the group is Abelian.
293
+
294
+ Examples
295
+ ========
296
+
297
+ >>> from sympy.combinatorics import free_group
298
+ >>> f, x, y, z = free_group("x y z")
299
+ >>> f.is_abelian
300
+ False
301
+
302
+ """
303
+ return self.rank in (0, 1)
304
+
305
+ @property
306
+ def identity(self):
307
+ """Returns the identity element of free group."""
308
+ return self.dtype()
309
+
310
+ def contains(self, g):
311
+ """Tests if Free Group element ``g`` belong to self, ``G``.
312
+
313
+ In mathematical terms any linear combination of generators
314
+ of a Free Group is contained in it.
315
+
316
+ Examples
317
+ ========
318
+
319
+ >>> from sympy.combinatorics import free_group
320
+ >>> f, x, y, z = free_group("x y z")
321
+ >>> f.contains(x**3*y**2)
322
+ True
323
+
324
+ """
325
+ if not isinstance(g, FreeGroupElement):
326
+ return False
327
+ elif self != g.group:
328
+ return False
329
+ else:
330
+ return True
331
+
332
+ def center(self):
333
+ """Returns the center of the free group `self`."""
334
+ return {self.identity}
335
+
336
+
337
+ ############################################################################
338
+ # FreeGroupElement #
339
+ ############################################################################
340
+
341
+
342
+ class FreeGroupElement(CantSympify, DefaultPrinting, tuple):
343
+ """Used to create elements of FreeGroup. It cannot be used directly to
344
+ create a free group element. It is called by the `dtype` method of the
345
+ `FreeGroup` class.
346
+
347
+ """
348
+ is_assoc_word = True
349
+
350
+ def new(self, init):
351
+ return self.__class__(init)
352
+
353
+ _hash = None
354
+
355
+ def __hash__(self):
356
+ _hash = self._hash
357
+ if _hash is None:
358
+ self._hash = _hash = hash((self.group, frozenset(tuple(self))))
359
+ return _hash
360
+
361
+ def copy(self):
362
+ return self.new(self)
363
+
364
+ @property
365
+ def is_identity(self):
366
+ if self.array_form == ():
367
+ return True
368
+ else:
369
+ return False
370
+
371
+ @property
372
+ def array_form(self):
373
+ """
374
+ SymPy provides two different internal kinds of representation
375
+ of associative words. The first one is called the `array_form`
376
+ which is a tuple containing `tuples` as its elements, where the
377
+ size of each tuple is two. At the first position the tuple
378
+ contains the `symbol-generator`, while at the second position
379
+ of tuple contains the exponent of that generator at the position.
380
+ Since elements (i.e. words) do not commute, the indexing of tuple
381
+ makes that property to stay.
382
+
383
+ The structure in ``array_form`` of ``FreeGroupElement`` is of form:
384
+
385
+ ``( ( symbol_of_gen, exponent ), ( , ), ... ( , ) )``
386
+
387
+ Examples
388
+ ========
389
+
390
+ >>> from sympy.combinatorics import free_group
391
+ >>> f, x, y, z = free_group("x y z")
392
+ >>> (x*z).array_form
393
+ ((x, 1), (z, 1))
394
+ >>> (x**2*z*y*x**2).array_form
395
+ ((x, 2), (z, 1), (y, 1), (x, 2))
396
+
397
+ See Also
398
+ ========
399
+
400
+ letter_repr
401
+
402
+ """
403
+ return tuple(self)
404
+
405
+ @property
406
+ def letter_form(self):
407
+ """
408
+ The letter representation of a ``FreeGroupElement`` is a tuple
409
+ of generator symbols, with each entry corresponding to a group
410
+ generator. Inverses of the generators are represented by
411
+ negative generator symbols.
412
+
413
+ Examples
414
+ ========
415
+
416
+ >>> from sympy.combinatorics import free_group
417
+ >>> f, a, b, c, d = free_group("a b c d")
418
+ >>> (a**3).letter_form
419
+ (a, a, a)
420
+ >>> (a**2*d**-2*a*b**-4).letter_form
421
+ (a, a, -d, -d, a, -b, -b, -b, -b)
422
+ >>> (a**-2*b**3*d).letter_form
423
+ (-a, -a, b, b, b, d)
424
+
425
+ See Also
426
+ ========
427
+
428
+ array_form
429
+
430
+ """
431
+ return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j)
432
+ for i, j in self.array_form]))
433
+
434
+ def __getitem__(self, i):
435
+ group = self.group
436
+ r = self.letter_form[i]
437
+ if r.is_Symbol:
438
+ return group.dtype(((r, 1),))
439
+ else:
440
+ return group.dtype(((-r, -1),))
441
+
442
+ def index(self, gen):
443
+ if len(gen) != 1:
444
+ raise ValueError()
445
+ return (self.letter_form).index(gen.letter_form[0])
446
+
447
+ @property
448
+ def letter_form_elm(self):
449
+ """
450
+ """
451
+ group = self.group
452
+ r = self.letter_form
453
+ return [group.dtype(((elm,1),)) if elm.is_Symbol \
454
+ else group.dtype(((-elm,-1),)) for elm in r]
455
+
456
+ @property
457
+ def ext_rep(self):
458
+ """This is called the External Representation of ``FreeGroupElement``
459
+ """
460
+ return tuple(flatten(self.array_form))
461
+
462
+ def __contains__(self, gen):
463
+ return gen.array_form[0][0] in tuple([r[0] for r in self.array_form])
464
+
465
+ def __str__(self):
466
+ if self.is_identity:
467
+ return "<identity>"
468
+
469
+ str_form = ""
470
+ array_form = self.array_form
471
+ for i in range(len(array_form)):
472
+ if i == len(array_form) - 1:
473
+ if array_form[i][1] == 1:
474
+ str_form += str(array_form[i][0])
475
+ else:
476
+ str_form += str(array_form[i][0]) + \
477
+ "**" + str(array_form[i][1])
478
+ else:
479
+ if array_form[i][1] == 1:
480
+ str_form += str(array_form[i][0]) + "*"
481
+ else:
482
+ str_form += str(array_form[i][0]) + \
483
+ "**" + str(array_form[i][1]) + "*"
484
+ return str_form
485
+
486
+ __repr__ = __str__
487
+
488
+ def __pow__(self, n):
489
+ n = as_int(n)
490
+ group = self.group
491
+ if n == 0:
492
+ return group.identity
493
+
494
+ if n < 0:
495
+ n = -n
496
+ return (self.inverse())**n
497
+
498
+ result = self
499
+ for i in range(n - 1):
500
+ result = result*self
501
+ # this method can be improved instead of just returning the
502
+ # multiplication of elements
503
+ return result
504
+
505
+ def __mul__(self, other):
506
+ """Returns the product of elements belonging to the same ``FreeGroup``.
507
+
508
+ Examples
509
+ ========
510
+
511
+ >>> from sympy.combinatorics import free_group
512
+ >>> f, x, y, z = free_group("x y z")
513
+ >>> x*y**2*y**-4
514
+ x*y**-2
515
+ >>> z*y**-2
516
+ z*y**-2
517
+ >>> x**2*y*y**-1*x**-2
518
+ <identity>
519
+
520
+ """
521
+ group = self.group
522
+ if not isinstance(other, group.dtype):
523
+ raise TypeError("only FreeGroup elements of same FreeGroup can "
524
+ "be multiplied")
525
+ if self.is_identity:
526
+ return other
527
+ if other.is_identity:
528
+ return self
529
+ r = list(self.array_form + other.array_form)
530
+ zero_mul_simp(r, len(self.array_form) - 1)
531
+ return group.dtype(tuple(r))
532
+
533
+ def __truediv__(self, other):
534
+ group = self.group
535
+ if not isinstance(other, group.dtype):
536
+ raise TypeError("only FreeGroup elements of same FreeGroup can "
537
+ "be multiplied")
538
+ return self*(other.inverse())
539
+
540
+ def __rtruediv__(self, other):
541
+ group = self.group
542
+ if not isinstance(other, group.dtype):
543
+ raise TypeError("only FreeGroup elements of same FreeGroup can "
544
+ "be multiplied")
545
+ return other*(self.inverse())
546
+
547
+ def __add__(self, other):
548
+ return NotImplemented
549
+
550
+ def inverse(self):
551
+ """
552
+ Returns the inverse of a ``FreeGroupElement`` element
553
+
554
+ Examples
555
+ ========
556
+
557
+ >>> from sympy.combinatorics import free_group
558
+ >>> f, x, y, z = free_group("x y z")
559
+ >>> x.inverse()
560
+ x**-1
561
+ >>> (x*y).inverse()
562
+ y**-1*x**-1
563
+
564
+ """
565
+ group = self.group
566
+ r = tuple([(i, -j) for i, j in self.array_form[::-1]])
567
+ return group.dtype(r)
568
+
569
+ def order(self):
570
+ """Find the order of a ``FreeGroupElement``.
571
+
572
+ Examples
573
+ ========
574
+
575
+ >>> from sympy.combinatorics import free_group
576
+ >>> f, x, y = free_group("x y")
577
+ >>> (x**2*y*y**-1*x**-2).order()
578
+ 1
579
+
580
+ """
581
+ if self.is_identity:
582
+ return S.One
583
+ else:
584
+ return S.Infinity
585
+
586
+ def commutator(self, other):
587
+ """
588
+ Return the commutator of `self` and `x`: ``~x*~self*x*self``
589
+
590
+ """
591
+ group = self.group
592
+ if not isinstance(other, group.dtype):
593
+ raise ValueError("commutator of only FreeGroupElement of the same "
594
+ "FreeGroup exists")
595
+ else:
596
+ return self.inverse()*other.inverse()*self*other
597
+
598
+ def eliminate_words(self, words, _all=False, inverse=True):
599
+ '''
600
+ Replace each subword from the dictionary `words` by words[subword].
601
+ If words is a list, replace the words by the identity.
602
+
603
+ '''
604
+ again = True
605
+ new = self
606
+ if isinstance(words, dict):
607
+ while again:
608
+ again = False
609
+ for sub in words:
610
+ prev = new
611
+ new = new.eliminate_word(sub, words[sub], _all=_all, inverse=inverse)
612
+ if new != prev:
613
+ again = True
614
+ else:
615
+ while again:
616
+ again = False
617
+ for sub in words:
618
+ prev = new
619
+ new = new.eliminate_word(sub, _all=_all, inverse=inverse)
620
+ if new != prev:
621
+ again = True
622
+ return new
623
+
624
+ def eliminate_word(self, gen, by=None, _all=False, inverse=True):
625
+ """
626
+ For an associative word `self`, a subword `gen`, and an associative
627
+ word `by` (identity by default), return the associative word obtained by
628
+ replacing each occurrence of `gen` in `self` by `by`. If `_all = True`,
629
+ the occurrences of `gen` that may appear after the first substitution will
630
+ also be replaced and so on until no occurrences are found. This might not
631
+ always terminate (e.g. `(x).eliminate_word(x, x**2, _all=True)`).
632
+
633
+ Examples
634
+ ========
635
+
636
+ >>> from sympy.combinatorics import free_group
637
+ >>> f, x, y = free_group("x y")
638
+ >>> w = x**5*y*x**2*y**-4*x
639
+ >>> w.eliminate_word( x, x**2 )
640
+ x**10*y*x**4*y**-4*x**2
641
+ >>> w.eliminate_word( x, y**-1 )
642
+ y**-11
643
+ >>> w.eliminate_word(x**5)
644
+ y*x**2*y**-4*x
645
+ >>> w.eliminate_word(x*y, y)
646
+ x**4*y*x**2*y**-4*x
647
+
648
+ See Also
649
+ ========
650
+ substituted_word
651
+
652
+ """
653
+ if by is None:
654
+ by = self.group.identity
655
+ if self.is_independent(gen) or gen == by:
656
+ return self
657
+ if gen == self:
658
+ return by
659
+ if gen**-1 == by:
660
+ _all = False
661
+ word = self
662
+ l = len(gen)
663
+
664
+ try:
665
+ i = word.subword_index(gen)
666
+ k = 1
667
+ except ValueError:
668
+ if not inverse:
669
+ return word
670
+ try:
671
+ i = word.subword_index(gen**-1)
672
+ k = -1
673
+ except ValueError:
674
+ return word
675
+
676
+ word = word.subword(0, i)*by**k*word.subword(i+l, len(word)).eliminate_word(gen, by)
677
+
678
+ if _all:
679
+ return word.eliminate_word(gen, by, _all=True, inverse=inverse)
680
+ else:
681
+ return word
682
+
683
+ def __len__(self):
684
+ """
685
+ For an associative word `self`, returns the number of letters in it.
686
+
687
+ Examples
688
+ ========
689
+
690
+ >>> from sympy.combinatorics import free_group
691
+ >>> f, a, b = free_group("a b")
692
+ >>> w = a**5*b*a**2*b**-4*a
693
+ >>> len(w)
694
+ 13
695
+ >>> len(a**17)
696
+ 17
697
+ >>> len(w**0)
698
+ 0
699
+
700
+ """
701
+ return sum(abs(j) for (i, j) in self)
702
+
703
+ def __eq__(self, other):
704
+ """
705
+ Two associative words are equal if they are words over the
706
+ same alphabet and if they are sequences of the same letters.
707
+ This is equivalent to saying that the external representations
708
+ of the words are equal.
709
+ There is no "universal" empty word, every alphabet has its own
710
+ empty word.
711
+
712
+ Examples
713
+ ========
714
+
715
+ >>> from sympy.combinatorics import free_group
716
+ >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1")
717
+ >>> f
718
+ <free group on the generators (swapnil0, swapnil1)>
719
+ >>> g, swap0, swap1 = free_group("swap0 swap1")
720
+ >>> g
721
+ <free group on the generators (swap0, swap1)>
722
+
723
+ >>> swapnil0 == swapnil1
724
+ False
725
+ >>> swapnil0*swapnil1 == swapnil1/swapnil1*swapnil0*swapnil1
726
+ True
727
+ >>> swapnil0*swapnil1 == swapnil1*swapnil0
728
+ False
729
+ >>> swapnil1**0 == swap0**0
730
+ False
731
+
732
+ """
733
+ group = self.group
734
+ if not isinstance(other, group.dtype):
735
+ return False
736
+ return tuple.__eq__(self, other)
737
+
738
+ def __lt__(self, other):
739
+ """
740
+ The ordering of associative words is defined by length and
741
+ lexicography (this ordering is called short-lex ordering), that
742
+ is, shorter words are smaller than longer words, and words of the
743
+ same length are compared w.r.t. the lexicographical ordering induced
744
+ by the ordering of generators. Generators are sorted according
745
+ to the order in which they were created. If the generators are
746
+ invertible then each generator `g` is larger than its inverse `g^{-1}`,
747
+ and `g^{-1}` is larger than every generator that is smaller than `g`.
748
+
749
+ Examples
750
+ ========
751
+
752
+ >>> from sympy.combinatorics import free_group
753
+ >>> f, a, b = free_group("a b")
754
+ >>> b < a
755
+ False
756
+ >>> a < a.inverse()
757
+ False
758
+
759
+ """
760
+ group = self.group
761
+ if not isinstance(other, group.dtype):
762
+ raise TypeError("only FreeGroup elements of same FreeGroup can "
763
+ "be compared")
764
+ l = len(self)
765
+ m = len(other)
766
+ # implement lenlex order
767
+ if l < m:
768
+ return True
769
+ elif l > m:
770
+ return False
771
+ for i in range(l):
772
+ a = self[i].array_form[0]
773
+ b = other[i].array_form[0]
774
+ p = group.symbols.index(a[0])
775
+ q = group.symbols.index(b[0])
776
+ if p < q:
777
+ return True
778
+ elif p > q:
779
+ return False
780
+ elif a[1] < b[1]:
781
+ return True
782
+ elif a[1] > b[1]:
783
+ return False
784
+ return False
785
+
786
+ def __le__(self, other):
787
+ return (self == other or self < other)
788
+
789
+ def __gt__(self, other):
790
+ """
791
+
792
+ Examples
793
+ ========
794
+
795
+ >>> from sympy.combinatorics import free_group
796
+ >>> f, x, y, z = free_group("x y z")
797
+ >>> y**2 > x**2
798
+ True
799
+ >>> y*z > z*y
800
+ False
801
+ >>> x > x.inverse()
802
+ True
803
+
804
+ """
805
+ group = self.group
806
+ if not isinstance(other, group.dtype):
807
+ raise TypeError("only FreeGroup elements of same FreeGroup can "
808
+ "be compared")
809
+ return not self <= other
810
+
811
+ def __ge__(self, other):
812
+ return not self < other
813
+
814
+ def exponent_sum(self, gen):
815
+ """
816
+ For an associative word `self` and a generator or inverse of generator
817
+ `gen`, ``exponent_sum`` returns the number of times `gen` appears in
818
+ `self` minus the number of times its inverse appears in `self`. If
819
+ neither `gen` nor its inverse occur in `self` then 0 is returned.
820
+
821
+ Examples
822
+ ========
823
+
824
+ >>> from sympy.combinatorics import free_group
825
+ >>> F, x, y = free_group("x, y")
826
+ >>> w = x**2*y**3
827
+ >>> w.exponent_sum(x)
828
+ 2
829
+ >>> w.exponent_sum(x**-1)
830
+ -2
831
+ >>> w = x**2*y**4*x**-3
832
+ >>> w.exponent_sum(x)
833
+ -1
834
+
835
+ See Also
836
+ ========
837
+
838
+ generator_count
839
+
840
+ """
841
+ if len(gen) != 1:
842
+ raise ValueError("gen must be a generator or inverse of a generator")
843
+ s = gen.array_form[0]
844
+ return s[1]*sum([i[1] for i in self.array_form if i[0] == s[0]])
845
+
846
+ def generator_count(self, gen):
847
+ """
848
+ For an associative word `self` and a generator `gen`,
849
+ ``generator_count`` returns the multiplicity of generator
850
+ `gen` in `self`.
851
+
852
+ Examples
853
+ ========
854
+
855
+ >>> from sympy.combinatorics import free_group
856
+ >>> F, x, y = free_group("x, y")
857
+ >>> w = x**2*y**3
858
+ >>> w.generator_count(x)
859
+ 2
860
+ >>> w = x**2*y**4*x**-3
861
+ >>> w.generator_count(x)
862
+ 5
863
+
864
+ See Also
865
+ ========
866
+
867
+ exponent_sum
868
+
869
+ """
870
+ if len(gen) != 1 or gen.array_form[0][1] < 0:
871
+ raise ValueError("gen must be a generator")
872
+ s = gen.array_form[0]
873
+ return s[1]*sum([abs(i[1]) for i in self.array_form if i[0] == s[0]])
874
+
875
+ def subword(self, from_i, to_j, strict=True):
876
+ """
877
+ For an associative word `self` and two positive integers `from_i` and
878
+ `to_j`, `subword` returns the subword of `self` that begins at position
879
+ `from_i` and ends at `to_j - 1`, indexing is done with origin 0.
880
+
881
+ Examples
882
+ ========
883
+
884
+ >>> from sympy.combinatorics import free_group
885
+ >>> f, a, b = free_group("a b")
886
+ >>> w = a**5*b*a**2*b**-4*a
887
+ >>> w.subword(2, 6)
888
+ a**3*b
889
+
890
+ """
891
+ group = self.group
892
+ if not strict:
893
+ from_i = max(from_i, 0)
894
+ to_j = min(len(self), to_j)
895
+ if from_i < 0 or to_j > len(self):
896
+ raise ValueError("`from_i`, `to_j` must be positive and no greater than "
897
+ "the length of associative word")
898
+ if to_j <= from_i:
899
+ return group.identity
900
+ else:
901
+ letter_form = self.letter_form[from_i: to_j]
902
+ array_form = letter_form_to_array_form(letter_form, group)
903
+ return group.dtype(array_form)
904
+
905
+ def subword_index(self, word, start = 0):
906
+ '''
907
+ Find the index of `word` in `self`.
908
+
909
+ Examples
910
+ ========
911
+
912
+ >>> from sympy.combinatorics import free_group
913
+ >>> f, a, b = free_group("a b")
914
+ >>> w = a**2*b*a*b**3
915
+ >>> w.subword_index(a*b*a*b)
916
+ 1
917
+
918
+ '''
919
+ l = len(word)
920
+ self_lf = self.letter_form
921
+ word_lf = word.letter_form
922
+ index = None
923
+ for i in range(start,len(self_lf)-l+1):
924
+ if self_lf[i:i+l] == word_lf:
925
+ index = i
926
+ break
927
+ if index is not None:
928
+ return index
929
+ else:
930
+ raise ValueError("The given word is not a subword of self")
931
+
932
+ def is_dependent(self, word):
933
+ """
934
+ Examples
935
+ ========
936
+
937
+ >>> from sympy.combinatorics import free_group
938
+ >>> F, x, y = free_group("x, y")
939
+ >>> (x**4*y**-3).is_dependent(x**4*y**-2)
940
+ True
941
+ >>> (x**2*y**-1).is_dependent(x*y)
942
+ False
943
+ >>> (x*y**2*x*y**2).is_dependent(x*y**2)
944
+ True
945
+ >>> (x**12).is_dependent(x**-4)
946
+ True
947
+
948
+ See Also
949
+ ========
950
+
951
+ is_independent
952
+
953
+ """
954
+ try:
955
+ return self.subword_index(word) is not None
956
+ except ValueError:
957
+ pass
958
+ try:
959
+ return self.subword_index(word**-1) is not None
960
+ except ValueError:
961
+ return False
962
+
963
+ def is_independent(self, word):
964
+ """
965
+
966
+ See Also
967
+ ========
968
+
969
+ is_dependent
970
+
971
+ """
972
+ return not self.is_dependent(word)
973
+
974
+ def contains_generators(self):
975
+ """
976
+ Examples
977
+ ========
978
+
979
+ >>> from sympy.combinatorics import free_group
980
+ >>> F, x, y, z = free_group("x, y, z")
981
+ >>> (x**2*y**-1).contains_generators()
982
+ {x, y}
983
+ >>> (x**3*z).contains_generators()
984
+ {x, z}
985
+
986
+ """
987
+ group = self.group
988
+ gens = set()
989
+ for syllable in self.array_form:
990
+ gens.add(group.dtype(((syllable[0], 1),)))
991
+ return set(gens)
992
+
993
+ def cyclic_subword(self, from_i, to_j):
994
+ group = self.group
995
+ l = len(self)
996
+ letter_form = self.letter_form
997
+ period1 = int(from_i/l)
998
+ if from_i >= l:
999
+ from_i -= l*period1
1000
+ to_j -= l*period1
1001
+ diff = to_j - from_i
1002
+ word = letter_form[from_i: to_j]
1003
+ period2 = int(to_j/l) - 1
1004
+ word += letter_form*period2 + letter_form[:diff-l+from_i-l*period2]
1005
+ word = letter_form_to_array_form(word, group)
1006
+ return group.dtype(word)
1007
+
1008
+ def cyclic_conjugates(self):
1009
+ """Returns a words which are cyclic to the word `self`.
1010
+
1011
+ Examples
1012
+ ========
1013
+
1014
+ >>> from sympy.combinatorics import free_group
1015
+ >>> F, x, y = free_group("x, y")
1016
+ >>> w = x*y*x*y*x
1017
+ >>> w.cyclic_conjugates()
1018
+ {x*y*x**2*y, x**2*y*x*y, y*x*y*x**2, y*x**2*y*x, x*y*x*y*x}
1019
+ >>> s = x*y*x**2*y*x
1020
+ >>> s.cyclic_conjugates()
1021
+ {x**2*y*x**2*y, y*x**2*y*x**2, x*y*x**2*y*x}
1022
+
1023
+ References
1024
+ ==========
1025
+
1026
+ .. [1] https://planetmath.org/cyclicpermutation
1027
+
1028
+ """
1029
+ return {self.cyclic_subword(i, i+len(self)) for i in range(len(self))}
1030
+
1031
+ def is_cyclic_conjugate(self, w):
1032
+ """
1033
+ Checks whether words ``self``, ``w`` are cyclic conjugates.
1034
+
1035
+ Examples
1036
+ ========
1037
+
1038
+ >>> from sympy.combinatorics import free_group
1039
+ >>> F, x, y = free_group("x, y")
1040
+ >>> w1 = x**2*y**5
1041
+ >>> w2 = x*y**5*x
1042
+ >>> w1.is_cyclic_conjugate(w2)
1043
+ True
1044
+ >>> w3 = x**-1*y**5*x**-1
1045
+ >>> w3.is_cyclic_conjugate(w2)
1046
+ False
1047
+
1048
+ """
1049
+ l1 = len(self)
1050
+ l2 = len(w)
1051
+ if l1 != l2:
1052
+ return False
1053
+ w1 = self.identity_cyclic_reduction()
1054
+ w2 = w.identity_cyclic_reduction()
1055
+ letter1 = w1.letter_form
1056
+ letter2 = w2.letter_form
1057
+ str1 = ' '.join(map(str, letter1))
1058
+ str2 = ' '.join(map(str, letter2))
1059
+ if len(str1) != len(str2):
1060
+ return False
1061
+
1062
+ return str1 in str2 + ' ' + str2
1063
+
1064
+ def number_syllables(self):
1065
+ """Returns the number of syllables of the associative word `self`.
1066
+
1067
+ Examples
1068
+ ========
1069
+
1070
+ >>> from sympy.combinatorics import free_group
1071
+ >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1")
1072
+ >>> (swapnil1**3*swapnil0*swapnil1**-1).number_syllables()
1073
+ 3
1074
+
1075
+ """
1076
+ return len(self.array_form)
1077
+
1078
+ def exponent_syllable(self, i):
1079
+ """
1080
+ Returns the exponent of the `i`-th syllable of the associative word
1081
+ `self`.
1082
+
1083
+ Examples
1084
+ ========
1085
+
1086
+ >>> from sympy.combinatorics import free_group
1087
+ >>> f, a, b = free_group("a b")
1088
+ >>> w = a**5*b*a**2*b**-4*a
1089
+ >>> w.exponent_syllable( 2 )
1090
+ 2
1091
+
1092
+ """
1093
+ return self.array_form[i][1]
1094
+
1095
+ def generator_syllable(self, i):
1096
+ """
1097
+ Returns the symbol of the generator that is involved in the
1098
+ i-th syllable of the associative word `self`.
1099
+
1100
+ Examples
1101
+ ========
1102
+
1103
+ >>> from sympy.combinatorics import free_group
1104
+ >>> f, a, b = free_group("a b")
1105
+ >>> w = a**5*b*a**2*b**-4*a
1106
+ >>> w.generator_syllable( 3 )
1107
+ b
1108
+
1109
+ """
1110
+ return self.array_form[i][0]
1111
+
1112
+ def sub_syllables(self, from_i, to_j):
1113
+ """
1114
+ `sub_syllables` returns the subword of the associative word `self` that
1115
+ consists of syllables from positions `from_to` to `to_j`, where
1116
+ `from_to` and `to_j` must be positive integers and indexing is done
1117
+ with origin 0.
1118
+
1119
+ Examples
1120
+ ========
1121
+
1122
+ >>> from sympy.combinatorics import free_group
1123
+ >>> f, a, b = free_group("a, b")
1124
+ >>> w = a**5*b*a**2*b**-4*a
1125
+ >>> w.sub_syllables(1, 2)
1126
+ b
1127
+ >>> w.sub_syllables(3, 3)
1128
+ <identity>
1129
+
1130
+ """
1131
+ if not isinstance(from_i, int) or not isinstance(to_j, int):
1132
+ raise ValueError("both arguments should be integers")
1133
+ group = self.group
1134
+ if to_j <= from_i:
1135
+ return group.identity
1136
+ else:
1137
+ r = tuple(self.array_form[from_i: to_j])
1138
+ return group.dtype(r)
1139
+
1140
+ def substituted_word(self, from_i, to_j, by):
1141
+ """
1142
+ Returns the associative word obtained by replacing the subword of
1143
+ `self` that begins at position `from_i` and ends at position `to_j - 1`
1144
+ by the associative word `by`. `from_i` and `to_j` must be positive
1145
+ integers, indexing is done with origin 0. In other words,
1146
+ `w.substituted_word(w, from_i, to_j, by)` is the product of the three
1147
+ words: `w.subword(0, from_i)`, `by`, and
1148
+ `w.subword(to_j len(w))`.
1149
+
1150
+ See Also
1151
+ ========
1152
+
1153
+ eliminate_word
1154
+
1155
+ """
1156
+ lw = len(self)
1157
+ if from_i >= to_j or from_i > lw or to_j > lw:
1158
+ raise ValueError("values should be within bounds")
1159
+
1160
+ # otherwise there are four possibilities
1161
+
1162
+ # first if from=1 and to=lw then
1163
+ if from_i == 0 and to_j == lw:
1164
+ return by
1165
+ elif from_i == 0: # second if from_i=1 (and to_j < lw) then
1166
+ return by*self.subword(to_j, lw)
1167
+ elif to_j == lw: # third if to_j=1 (and from_i > 1) then
1168
+ return self.subword(0, from_i)*by
1169
+ else: # finally
1170
+ return self.subword(0, from_i)*by*self.subword(to_j, lw)
1171
+
1172
+ def is_cyclically_reduced(self):
1173
+ r"""Returns whether the word is cyclically reduced or not.
1174
+ A word is cyclically reduced if by forming the cycle of the
1175
+ word, the word is not reduced, i.e a word w = `a_1 ... a_n`
1176
+ is called cyclically reduced if `a_1 \ne a_n^{-1}`.
1177
+
1178
+ Examples
1179
+ ========
1180
+
1181
+ >>> from sympy.combinatorics import free_group
1182
+ >>> F, x, y = free_group("x, y")
1183
+ >>> (x**2*y**-1*x**-1).is_cyclically_reduced()
1184
+ False
1185
+ >>> (y*x**2*y**2).is_cyclically_reduced()
1186
+ True
1187
+
1188
+ """
1189
+ if not self:
1190
+ return True
1191
+ return self[0] != self[-1]**-1
1192
+
1193
+ def identity_cyclic_reduction(self):
1194
+ """Return a unique cyclically reduced version of the word.
1195
+
1196
+ Examples
1197
+ ========
1198
+
1199
+ >>> from sympy.combinatorics import free_group
1200
+ >>> F, x, y = free_group("x, y")
1201
+ >>> (x**2*y**2*x**-1).identity_cyclic_reduction()
1202
+ x*y**2
1203
+ >>> (x**-3*y**-1*x**5).identity_cyclic_reduction()
1204
+ x**2*y**-1
1205
+
1206
+ References
1207
+ ==========
1208
+
1209
+ .. [1] https://planetmath.org/cyclicallyreduced
1210
+
1211
+ """
1212
+ word = self.copy()
1213
+ group = self.group
1214
+ while not word.is_cyclically_reduced():
1215
+ exp1 = word.exponent_syllable(0)
1216
+ exp2 = word.exponent_syllable(-1)
1217
+ r = exp1 + exp2
1218
+ if r == 0:
1219
+ rep = word.array_form[1: word.number_syllables() - 1]
1220
+ else:
1221
+ rep = ((word.generator_syllable(0), exp1 + exp2),) + \
1222
+ word.array_form[1: word.number_syllables() - 1]
1223
+ word = group.dtype(rep)
1224
+ return word
1225
+
1226
+ def cyclic_reduction(self, removed=False):
1227
+ """Return a cyclically reduced version of the word. Unlike
1228
+ `identity_cyclic_reduction`, this will not cyclically permute
1229
+ the reduced word - just remove the "unreduced" bits on either
1230
+ side of it. Compare the examples with those of
1231
+ `identity_cyclic_reduction`.
1232
+
1233
+ When `removed` is `True`, return a tuple `(word, r)` where
1234
+ self `r` is such that before the reduction the word was either
1235
+ `r*word*r**-1`.
1236
+
1237
+ Examples
1238
+ ========
1239
+
1240
+ >>> from sympy.combinatorics import free_group
1241
+ >>> F, x, y = free_group("x, y")
1242
+ >>> (x**2*y**2*x**-1).cyclic_reduction()
1243
+ x*y**2
1244
+ >>> (x**-3*y**-1*x**5).cyclic_reduction()
1245
+ y**-1*x**2
1246
+ >>> (x**-3*y**-1*x**5).cyclic_reduction(removed=True)
1247
+ (y**-1*x**2, x**-3)
1248
+
1249
+ """
1250
+ word = self.copy()
1251
+ g = self.group.identity
1252
+ while not word.is_cyclically_reduced():
1253
+ exp1 = abs(word.exponent_syllable(0))
1254
+ exp2 = abs(word.exponent_syllable(-1))
1255
+ exp = min(exp1, exp2)
1256
+ start = word[0]**abs(exp)
1257
+ end = word[-1]**abs(exp)
1258
+ word = start**-1*word*end**-1
1259
+ g = g*start
1260
+ if removed:
1261
+ return word, g
1262
+ return word
1263
+
1264
+ def power_of(self, other):
1265
+ '''
1266
+ Check if `self == other**n` for some integer n.
1267
+
1268
+ Examples
1269
+ ========
1270
+
1271
+ >>> from sympy.combinatorics import free_group
1272
+ >>> F, x, y = free_group("x, y")
1273
+ >>> ((x*y)**2).power_of(x*y)
1274
+ True
1275
+ >>> (x**-3*y**-2*x**3).power_of(x**-3*y*x**3)
1276
+ True
1277
+
1278
+ '''
1279
+ if self.is_identity:
1280
+ return True
1281
+
1282
+ l = len(other)
1283
+ if l == 1:
1284
+ # self has to be a power of one generator
1285
+ gens = self.contains_generators()
1286
+ s = other in gens or other**-1 in gens
1287
+ return len(gens) == 1 and s
1288
+
1289
+ # if self is not cyclically reduced and it is a power of other,
1290
+ # other isn't cyclically reduced and the parts removed during
1291
+ # their reduction must be equal
1292
+ reduced, r1 = self.cyclic_reduction(removed=True)
1293
+ if not r1.is_identity:
1294
+ other, r2 = other.cyclic_reduction(removed=True)
1295
+ if r1 == r2:
1296
+ return reduced.power_of(other)
1297
+ return False
1298
+
1299
+ if len(self) < l or len(self) % l:
1300
+ return False
1301
+
1302
+ prefix = self.subword(0, l)
1303
+ if prefix == other or prefix**-1 == other:
1304
+ rest = self.subword(l, len(self))
1305
+ return rest.power_of(other)
1306
+ return False
1307
+
1308
+
1309
+ def letter_form_to_array_form(array_form, group):
1310
+ """
1311
+ This method converts a list given with possible repetitions of elements in
1312
+ it. It returns a new list such that repetitions of consecutive elements is
1313
+ removed and replace with a tuple element of size two such that the first
1314
+ index contains `value` and the second index contains the number of
1315
+ consecutive repetitions of `value`.
1316
+
1317
+ """
1318
+ a = list(array_form[:])
1319
+ new_array = []
1320
+ n = 1
1321
+ symbols = group.symbols
1322
+ for i in range(len(a)):
1323
+ if i == len(a) - 1:
1324
+ if a[i] == a[i - 1]:
1325
+ if (-a[i]) in symbols:
1326
+ new_array.append((-a[i], -n))
1327
+ else:
1328
+ new_array.append((a[i], n))
1329
+ else:
1330
+ if (-a[i]) in symbols:
1331
+ new_array.append((-a[i], -1))
1332
+ else:
1333
+ new_array.append((a[i], 1))
1334
+ return new_array
1335
+ elif a[i] == a[i + 1]:
1336
+ n += 1
1337
+ else:
1338
+ if (-a[i]) in symbols:
1339
+ new_array.append((-a[i], -n))
1340
+ else:
1341
+ new_array.append((a[i], n))
1342
+ n = 1
1343
+
1344
+
1345
+ def zero_mul_simp(l, index):
1346
+ """Used to combine two reduced words."""
1347
+ while index >=0 and index < len(l) - 1 and l[index][0] == l[index + 1][0]:
1348
+ exp = l[index][1] + l[index + 1][1]
1349
+ base = l[index][0]
1350
+ l[index] = (base, exp)
1351
+ del l[index + 1]
1352
+ if l[index][1] == 0:
1353
+ del l[index]
1354
+ index -= 1
env-llmeval/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
env-llmeval/lib/python3.10/site-packages/sympy/combinatorics/generators.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics.permutations import Permutation
2
+ from sympy.core.symbol import symbols
3
+ from sympy.matrices import Matrix
4
+ from sympy.utilities.iterables import variations, rotate_left
5
+
6
+
7
+ def symmetric(n):
8
+ """
9
+ Generates the symmetric group of order n, Sn.
10
+
11
+ Examples
12
+ ========
13
+
14
+ >>> from sympy.combinatorics.generators import symmetric
15
+ >>> list(symmetric(3))
16
+ [(2), (1 2), (2)(0 1), (0 1 2), (0 2 1), (0 2)]
17
+ """
18
+ for perm in variations(range(n), n):
19
+ yield Permutation(perm)
20
+
21
+
22
+ def cyclic(n):
23
+ """
24
+ Generates the cyclic group of order n, Cn.
25
+
26
+ Examples
27
+ ========
28
+
29
+ >>> from sympy.combinatorics.generators import cyclic
30
+ >>> list(cyclic(5))
31
+ [(4), (0 1 2 3 4), (0 2 4 1 3),
32
+ (0 3 1 4 2), (0 4 3 2 1)]
33
+
34
+ See Also
35
+ ========
36
+
37
+ dihedral
38
+ """
39
+ gen = list(range(n))
40
+ for i in range(n):
41
+ yield Permutation(gen)
42
+ gen = rotate_left(gen, 1)
43
+
44
+
45
+ def alternating(n):
46
+ """
47
+ Generates the alternating group of order n, An.
48
+
49
+ Examples
50
+ ========
51
+
52
+ >>> from sympy.combinatorics.generators import alternating
53
+ >>> list(alternating(3))
54
+ [(2), (0 1 2), (0 2 1)]
55
+ """
56
+ for perm in variations(range(n), n):
57
+ p = Permutation(perm)
58
+ if p.is_even:
59
+ yield p
60
+
61
+
62
+ def dihedral(n):
63
+ """
64
+ Generates the dihedral group of order 2n, Dn.
65
+
66
+ The result is given as a subgroup of Sn, except for the special cases n=1
67
+ (the group S2) and n=2 (the Klein 4-group) where that's not possible
68
+ and embeddings in S2 and S4 respectively are given.
69
+
70
+ Examples
71
+ ========
72
+
73
+ >>> from sympy.combinatorics.generators import dihedral
74
+ >>> list(dihedral(3))
75
+ [(2), (0 2), (0 1 2), (1 2), (0 2 1), (2)(0 1)]
76
+
77
+ See Also
78
+ ========
79
+
80
+ cyclic
81
+ """
82
+ if n == 1:
83
+ yield Permutation([0, 1])
84
+ yield Permutation([1, 0])
85
+ elif n == 2:
86
+ yield Permutation([0, 1, 2, 3])
87
+ yield Permutation([1, 0, 3, 2])
88
+ yield Permutation([2, 3, 0, 1])
89
+ yield Permutation([3, 2, 1, 0])
90
+ else:
91
+ gen = list(range(n))
92
+ for i in range(n):
93
+ yield Permutation(gen)
94
+ yield Permutation(gen[::-1])
95
+ gen = rotate_left(gen, 1)
96
+
97
+
98
+ def rubik_cube_generators():
99
+ """Return the permutations of the 3x3 Rubik's cube, see
100
+ https://www.gap-system.org/Doc/Examples/rubik.html
101
+ """
102
+ a = [
103
+ [(1, 3, 8, 6), (2, 5, 7, 4), (9, 33, 25, 17), (10, 34, 26, 18),
104
+ (11, 35, 27, 19)],
105
+ [(9, 11, 16, 14), (10, 13, 15, 12), (1, 17, 41, 40), (4, 20, 44, 37),
106
+ (6, 22, 46, 35)],
107
+ [(17, 19, 24, 22), (18, 21, 23, 20), (6, 25, 43, 16), (7, 28, 42, 13),
108
+ (8, 30, 41, 11)],
109
+ [(25, 27, 32, 30), (26, 29, 31, 28), (3, 38, 43, 19), (5, 36, 45, 21),
110
+ (8, 33, 48, 24)],
111
+ [(33, 35, 40, 38), (34, 37, 39, 36), (3, 9, 46, 32), (2, 12, 47, 29),
112
+ (1, 14, 48, 27)],
113
+ [(41, 43, 48, 46), (42, 45, 47, 44), (14, 22, 30, 38),
114
+ (15, 23, 31, 39), (16, 24, 32, 40)]
115
+ ]
116
+ return [Permutation([[i - 1 for i in xi] for xi in x], size=48) for x in a]
117
+
118
+
119
+ def rubik(n):
120
+ """Return permutations for an nxn Rubik's cube.
121
+
122
+ Permutations returned are for rotation of each of the slice
123
+ from the face up to the last face for each of the 3 sides (in this order):
124
+ front, right and bottom. Hence, the first n - 1 permutations are for the
125
+ slices from the front.
126
+ """
127
+
128
+ if n < 2:
129
+ raise ValueError('dimension of cube must be > 1')
130
+
131
+ # 1-based reference to rows and columns in Matrix
132
+ def getr(f, i):
133
+ return faces[f].col(n - i)
134
+
135
+ def getl(f, i):
136
+ return faces[f].col(i - 1)
137
+
138
+ def getu(f, i):
139
+ return faces[f].row(i - 1)
140
+
141
+ def getd(f, i):
142
+ return faces[f].row(n - i)
143
+
144
+ def setr(f, i, s):
145
+ faces[f][:, n - i] = Matrix(n, 1, s)
146
+
147
+ def setl(f, i, s):
148
+ faces[f][:, i - 1] = Matrix(n, 1, s)
149
+
150
+ def setu(f, i, s):
151
+ faces[f][i - 1, :] = Matrix(1, n, s)
152
+
153
+ def setd(f, i, s):
154
+ faces[f][n - i, :] = Matrix(1, n, s)
155
+
156
+ # motion of a single face
157
+ def cw(F, r=1):
158
+ for _ in range(r):
159
+ face = faces[F]
160
+ rv = []
161
+ for c in range(n):
162
+ for r in range(n - 1, -1, -1):
163
+ rv.append(face[r, c])
164
+ faces[F] = Matrix(n, n, rv)
165
+
166
+ def ccw(F):
167
+ cw(F, 3)
168
+
169
+ # motion of plane i from the F side;
170
+ # fcw(0) moves the F face, fcw(1) moves the plane
171
+ # just behind the front face, etc...
172
+ def fcw(i, r=1):
173
+ for _ in range(r):
174
+ if i == 0:
175
+ cw(F)
176
+ i += 1
177
+ temp = getr(L, i)
178
+ setr(L, i, list(getu(D, i)))
179
+ setu(D, i, list(reversed(getl(R, i))))
180
+ setl(R, i, list(getd(U, i)))
181
+ setd(U, i, list(reversed(temp)))
182
+ i -= 1
183
+
184
+ def fccw(i):
185
+ fcw(i, 3)
186
+
187
+ # motion of the entire cube from the F side
188
+ def FCW(r=1):
189
+ for _ in range(r):
190
+ cw(F)
191
+ ccw(B)
192
+ cw(U)
193
+ t = faces[U]
194
+ cw(L)
195
+ faces[U] = faces[L]
196
+ cw(D)
197
+ faces[L] = faces[D]
198
+ cw(R)
199
+ faces[D] = faces[R]
200
+ faces[R] = t
201
+
202
+ def FCCW():
203
+ FCW(3)
204
+
205
+ # motion of the entire cube from the U side
206
+ def UCW(r=1):
207
+ for _ in range(r):
208
+ cw(U)
209
+ ccw(D)
210
+ t = faces[F]
211
+ faces[F] = faces[R]
212
+ faces[R] = faces[B]
213
+ faces[B] = faces[L]
214
+ faces[L] = t
215
+
216
+ def UCCW():
217
+ UCW(3)
218
+
219
+ # defining the permutations for the cube
220
+
221
+ U, F, R, B, L, D = names = symbols('U, F, R, B, L, D')
222
+
223
+ # the faces are represented by nxn matrices
224
+ faces = {}
225
+ count = 0
226
+ for fi in range(6):
227
+ f = []
228
+ for a in range(n**2):
229
+ f.append(count)
230
+ count += 1
231
+ faces[names[fi]] = Matrix(n, n, f)
232
+
233
+ # this will either return the value of the current permutation
234
+ # (show != 1) or else append the permutation to the group, g
235
+ def perm(show=0):
236
+ # add perm to the list of perms
237
+ p = []
238
+ for f in names:
239
+ p.extend(faces[f])
240
+ if show:
241
+ return p
242
+ g.append(Permutation(p))
243
+
244
+ g = [] # container for the group's permutations
245
+ I = list(range(6*n**2)) # the identity permutation used for checking
246
+
247
+ # define permutations corresponding to cw rotations of the planes
248
+ # up TO the last plane from that direction; by not including the
249
+ # last plane, the orientation of the cube is maintained.
250
+
251
+ # F slices
252
+ for i in range(n - 1):
253
+ fcw(i)
254
+ perm()
255
+ fccw(i) # restore
256
+ assert perm(1) == I
257
+
258
+ # R slices
259
+ # bring R to front
260
+ UCW()
261
+ for i in range(n - 1):
262
+ fcw(i)
263
+ # put it back in place
264
+ UCCW()
265
+ # record
266
+ perm()
267
+ # restore
268
+ # bring face to front
269
+ UCW()
270
+ fccw(i)
271
+ # restore
272
+ UCCW()
273
+ assert perm(1) == I
274
+
275
+ # D slices
276
+ # bring up bottom
277
+ FCW()
278
+ UCCW()
279
+ FCCW()
280
+ for i in range(n - 1):
281
+ # turn strip
282
+ fcw(i)
283
+ # put bottom back on the bottom
284
+ FCW()
285
+ UCW()
286
+ FCCW()
287
+ # record
288
+ perm()
289
+ # restore
290
+ # bring up bottom
291
+ FCW()
292
+ UCCW()
293
+ FCCW()
294
+ # turn strip
295
+ fccw(i)
296
+ # put bottom back on the bottom
297
+ FCW()
298
+ UCW()
299
+ FCCW()
300
+ assert perm(1) == I
301
+
302
+ return g
env-llmeval/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)
env-llmeval/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