ZTWHHH commited on
Commit
aae0425
·
verified ·
1 Parent(s): 7bb8326

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. .gitattributes +2 -0
  2. mgm/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc +3 -0
  3. mgm/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.py +1354 -0
  4. mgm/lib/python3.10/site-packages/sympy/combinatorics/galois.py +611 -0
  5. mgm/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.py +549 -0
  6. mgm/lib/python3.10/site-packages/sympy/combinatorics/permutations.py +3115 -0
  7. mgm/lib/python3.10/site-packages/sympy/combinatorics/prufer.py +435 -0
  8. mgm/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem.py +453 -0
  9. mgm/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem_fsm.py +60 -0
  10. mgm/lib/python3.10/site-packages/sympy/combinatorics/schur_number.py +160 -0
  11. mgm/lib/python3.10/site-packages/sympy/combinatorics/testutil.py +357 -0
  12. mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/__init__.cpython-310.pyc +0 -0
  13. mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/delta.cpython-310.pyc +0 -0
  14. mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_limits.cpython-310.pyc +0 -0
  15. mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/guess.cpython-310.pyc +0 -0
  16. mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/products.cpython-310.pyc +0 -0
  17. mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/summations.cpython-310.pyc +0 -0
  18. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/__init__.cpython-310.pyc +0 -0
  19. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/appellseqs.cpython-310.pyc +0 -0
  20. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/compatibility.cpython-310.pyc +0 -0
  21. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/constructor.cpython-310.pyc +0 -0
  22. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/densearith.cpython-310.pyc +0 -0
  23. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/densetools.cpython-310.pyc +0 -0
  24. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/distributedmodules.cpython-310.pyc +0 -0
  25. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/domainmatrix.cpython-310.pyc +0 -0
  26. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/factortools.cpython-310.pyc +0 -0
  27. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/fglmtools.cpython-310.pyc +0 -0
  28. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/fields.cpython-310.pyc +0 -0
  29. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/groebnertools.cpython-310.pyc +0 -0
  30. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyconfig.cpython-310.pyc +0 -0
  31. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyerrors.cpython-310.pyc +0 -0
  32. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polymatrix.cpython-310.pyc +0 -0
  33. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyoptions.cpython-310.pyc +0 -0
  34. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyroots.cpython-310.pyc +0 -0
  35. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/rationaltools.cpython-310.pyc +0 -0
  36. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/ring_series.cpython-310.pyc +0 -0
  37. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/rings.cpython-310.pyc +0 -0
  38. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/rootisolation.cpython-310.pyc +0 -0
  39. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/rootoftools.cpython-310.pyc +0 -0
  40. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/solvers.cpython-310.pyc +0 -0
  41. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/sqfreetools.cpython-310.pyc +0 -0
  42. mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/subresultants_qq_zz.cpython-310.pyc +0 -0
  43. mgm/lib/python3.10/site-packages/sympy/polys/dispersion.py +212 -0
  44. mgm/lib/python3.10/site-packages/sympy/polys/domains/__init__.py +57 -0
  45. mgm/lib/python3.10/site-packages/sympy/polys/domains/algebraicfield.py +607 -0
  46. mgm/lib/python3.10/site-packages/sympy/polys/domains/characteristiczero.py +15 -0
  47. mgm/lib/python3.10/site-packages/sympy/polys/domains/compositedomain.py +52 -0
  48. mgm/lib/python3.10/site-packages/sympy/polys/domains/domain.py +1372 -0
  49. mgm/lib/python3.10/site-packages/sympy/polys/domains/domainelement.py +38 -0
  50. mgm/lib/python3.10/site-packages/sympy/polys/domains/expressiondomain.py +278 -0
.gitattributes CHANGED
@@ -1084,3 +1084,5 @@ mantis_evalkit/lib/python3.10/site-packages/pyarrow/libarrow.so.1900 filter=lfs
1084
  wemm/lib/python3.10/site-packages/nvfuser/_C.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1085
  mgm/lib/python3.10/site-packages/torchvision/_C.so filter=lfs diff=lfs merge=lfs -text
1086
  mgm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
1084
  wemm/lib/python3.10/site-packages/nvfuser/_C.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1085
  mgm/lib/python3.10/site-packages/torchvision/_C.so filter=lfs diff=lfs merge=lfs -text
1086
  mgm/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1087
+ vila/lib/python3.10/site-packages/opencv_python.libs/libavcodec-402e4b05.so.59.37.100 filter=lfs diff=lfs merge=lfs -text
1088
+ mgm/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
mgm/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ea26cdb3987cd5d1b38c2a89abdc7f1b723e712780c0ce3cab3df41e3a9be9d
3
+ size 152902
mgm/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.py ADDED
@@ -0,0 +1,1354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
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):
1004
+ """
1005
+ Simplifies a set of relators. All relators are checked to see if they are
1006
+ of the form `gen^n`. If any such relators are found then all other relators
1007
+ are processed for strings in the `gen` known order.
1008
+
1009
+ Examples
1010
+ ========
1011
+
1012
+ >>> from sympy.combinatorics import free_group
1013
+ >>> from sympy.combinatorics.fp_groups import _simplify_relators
1014
+ >>> F, x, y = free_group("x, y")
1015
+ >>> w1 = [x**2*y**4, x**3]
1016
+ >>> _simplify_relators(w1)
1017
+ [x**3, x**-1*y**4]
1018
+
1019
+ >>> w2 = [x**2*y**-4*x**5, x**3, x**2*y**8, y**5]
1020
+ >>> _simplify_relators(w2)
1021
+ [x**-1*y**-2, x**-1*y*x**-1, x**3, y**5]
1022
+
1023
+ >>> w3 = [x**6*y**4, x**4]
1024
+ >>> _simplify_relators(w3)
1025
+ [x**4, x**2*y**4]
1026
+
1027
+ >>> w4 = [x**2, x**5, y**3]
1028
+ >>> _simplify_relators(w4)
1029
+ [x, y**3]
1030
+
1031
+ """
1032
+ rels = rels[:]
1033
+
1034
+ if not rels:
1035
+ return []
1036
+
1037
+ identity = rels[0].group.identity
1038
+
1039
+ # build dictionary with "gen: n" where gen^n is one of the relators
1040
+ exps = {}
1041
+ for i in range(len(rels)):
1042
+ rel = rels[i]
1043
+ if rel.number_syllables() == 1:
1044
+ g = rel[0]
1045
+ exp = abs(rel.array_form[0][1])
1046
+ if rel.array_form[0][1] < 0:
1047
+ rels[i] = rels[i]**-1
1048
+ g = g**-1
1049
+ if g in exps:
1050
+ exp = gcd(exp, exps[g].array_form[0][1])
1051
+ exps[g] = g**exp
1052
+
1053
+ one_syllables_words = list(exps.values())
1054
+ # decrease some of the exponents in relators, making use of the single
1055
+ # syllable relators
1056
+ for i, rel in enumerate(rels):
1057
+ if rel in one_syllables_words:
1058
+ continue
1059
+ rel = rel.eliminate_words(one_syllables_words, _all = True)
1060
+ # if rels[i] contains g**n where abs(n) is greater than half of the power p
1061
+ # of g in exps, g**n can be replaced by g**(n-p) (or g**(p-n) if n<0)
1062
+ for g in rel.contains_generators():
1063
+ if g in exps:
1064
+ exp = exps[g].array_form[0][1]
1065
+ max_exp = (exp + 1)//2
1066
+ rel = rel.eliminate_word(g**(max_exp), g**(max_exp-exp), _all = True)
1067
+ rel = rel.eliminate_word(g**(-max_exp), g**(-(max_exp-exp)), _all = True)
1068
+ rels[i] = rel
1069
+
1070
+ rels = [r.identity_cyclic_reduction() for r in rels]
1071
+
1072
+ rels += one_syllables_words # include one_syllable_words in the list of relators
1073
+ rels = list(set(rels)) # get unique values in rels
1074
+ rels.sort()
1075
+
1076
+ # remove <identity> entries in rels
1077
+ try:
1078
+ rels.remove(identity)
1079
+ except ValueError:
1080
+ pass
1081
+ return rels
1082
+
1083
+ # Pg 350, section 2.5.1 from [2]
1084
+ def elimination_technique_1(gens, rels, identity):
1085
+ rels = rels[:]
1086
+ # the shorter relators are examined first so that generators selected for
1087
+ # elimination will have shorter strings as equivalent
1088
+ rels.sort()
1089
+ gens = gens[:]
1090
+ redundant_gens = {}
1091
+ redundant_rels = []
1092
+ used_gens = set()
1093
+ # examine each relator in relator list for any generator occurring exactly
1094
+ # once
1095
+ for rel in rels:
1096
+ # don't look for a redundant generator in a relator which
1097
+ # depends on previously found ones
1098
+ contained_gens = rel.contains_generators()
1099
+ if any(g in contained_gens for g in redundant_gens):
1100
+ continue
1101
+ contained_gens = list(contained_gens)
1102
+ contained_gens.sort(reverse = True)
1103
+ for gen in contained_gens:
1104
+ if rel.generator_count(gen) == 1 and gen not in used_gens:
1105
+ k = rel.exponent_sum(gen)
1106
+ gen_index = rel.index(gen**k)
1107
+ bk = rel.subword(gen_index + 1, len(rel))
1108
+ fw = rel.subword(0, gen_index)
1109
+ chi = bk*fw
1110
+ redundant_gens[gen] = chi**(-1*k)
1111
+ used_gens.update(chi.contains_generators())
1112
+ redundant_rels.append(rel)
1113
+ break
1114
+ rels = [r for r in rels if r not in redundant_rels]
1115
+ # eliminate the redundant generators from remaining relators
1116
+ rels = [r.eliminate_words(redundant_gens, _all = True).identity_cyclic_reduction() for r in rels]
1117
+ rels = list(set(rels))
1118
+ try:
1119
+ rels.remove(identity)
1120
+ except ValueError:
1121
+ pass
1122
+ gens = [g for g in gens if g not in redundant_gens]
1123
+ return gens, rels
1124
+
1125
+ ###############################################################################
1126
+ # SUBGROUP PRESENTATIONS #
1127
+ ###############################################################################
1128
+
1129
+ # Pg 175 [1]
1130
+ def define_schreier_generators(C, homomorphism=False):
1131
+ '''
1132
+ Parameters
1133
+ ==========
1134
+
1135
+ C -- Coset table.
1136
+ homomorphism -- When set to True, return a dictionary containing the images
1137
+ of the presentation generators in the original group.
1138
+ '''
1139
+ y = []
1140
+ gamma = 1
1141
+ f = C.fp_group
1142
+ X = f.generators
1143
+ if homomorphism:
1144
+ # `_gens` stores the elements of the parent group to
1145
+ # to which the schreier generators correspond to.
1146
+ _gens = {}
1147
+ # compute the schreier Traversal
1148
+ tau = {}
1149
+ tau[0] = f.identity
1150
+ C.P = [[None]*len(C.A) for i in range(C.n)]
1151
+ for alpha, x in product(C.omega, C.A):
1152
+ beta = C.table[alpha][C.A_dict[x]]
1153
+ if beta == gamma:
1154
+ C.P[alpha][C.A_dict[x]] = "<identity>"
1155
+ C.P[beta][C.A_dict_inv[x]] = "<identity>"
1156
+ gamma += 1
1157
+ if homomorphism:
1158
+ tau[beta] = tau[alpha]*x
1159
+ elif x in X and C.P[alpha][C.A_dict[x]] is None:
1160
+ y_alpha_x = '%s_%s' % (x, alpha)
1161
+ y.append(y_alpha_x)
1162
+ C.P[alpha][C.A_dict[x]] = y_alpha_x
1163
+ if homomorphism:
1164
+ _gens[y_alpha_x] = tau[alpha]*x*tau[beta]**-1
1165
+ grp_gens = list(free_group(', '.join(y)))
1166
+ C._schreier_free_group = grp_gens.pop(0)
1167
+ C._schreier_generators = grp_gens
1168
+ if homomorphism:
1169
+ C._schreier_gen_elem = _gens
1170
+ # replace all elements of P by, free group elements
1171
+ for i, j in product(range(len(C.P)), range(len(C.A))):
1172
+ # if equals "<identity>", replace by identity element
1173
+ if C.P[i][j] == "<identity>":
1174
+ C.P[i][j] = C._schreier_free_group.identity
1175
+ elif isinstance(C.P[i][j], str):
1176
+ r = C._schreier_generators[y.index(C.P[i][j])]
1177
+ C.P[i][j] = r
1178
+ beta = C.table[i][j]
1179
+ C.P[beta][j + 1] = r**-1
1180
+
1181
+ def reidemeister_relators(C):
1182
+ R = C.fp_group.relators
1183
+ rels = [rewrite(C, coset, word) for word in R for coset in range(C.n)]
1184
+ order_1_gens = {i for i in rels if len(i) == 1}
1185
+
1186
+ # remove all the order 1 generators from relators
1187
+ rels = list(filter(lambda rel: rel not in order_1_gens, rels))
1188
+
1189
+ # replace order 1 generators by identity element in reidemeister relators
1190
+ for i in range(len(rels)):
1191
+ w = rels[i]
1192
+ w = w.eliminate_words(order_1_gens, _all=True)
1193
+ rels[i] = w
1194
+
1195
+ C._schreier_generators = [i for i in C._schreier_generators
1196
+ if not (i in order_1_gens or i**-1 in order_1_gens)]
1197
+
1198
+ # Tietze transformation 1 i.e TT_1
1199
+ # remove cyclic conjugate elements from relators
1200
+ i = 0
1201
+ while i < len(rels):
1202
+ w = rels[i]
1203
+ j = i + 1
1204
+ while j < len(rels):
1205
+ if w.is_cyclic_conjugate(rels[j]):
1206
+ del rels[j]
1207
+ else:
1208
+ j += 1
1209
+ i += 1
1210
+
1211
+ C._reidemeister_relators = rels
1212
+
1213
+
1214
+ def rewrite(C, alpha, w):
1215
+ """
1216
+ Parameters
1217
+ ==========
1218
+
1219
+ C: CosetTable
1220
+ alpha: A live coset
1221
+ w: A word in `A*`
1222
+
1223
+ Returns
1224
+ =======
1225
+
1226
+ rho(tau(alpha), w)
1227
+
1228
+ Examples
1229
+ ========
1230
+
1231
+ >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, define_schreier_generators, rewrite
1232
+ >>> from sympy.combinatorics import free_group
1233
+ >>> F, x, y = free_group("x, y")
1234
+ >>> f = FpGroup(F, [x**2, y**3, (x*y)**6])
1235
+ >>> C = CosetTable(f, [])
1236
+ >>> 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]]
1237
+ >>> C.p = [0, 1, 2, 3, 4, 5]
1238
+ >>> define_schreier_generators(C)
1239
+ >>> rewrite(C, 0, (x*y)**6)
1240
+ x_4*y_2*x_3*x_1*x_2*y_4*x_5
1241
+
1242
+ """
1243
+ v = C._schreier_free_group.identity
1244
+ for i in range(len(w)):
1245
+ x_i = w[i]
1246
+ v = v*C.P[alpha][C.A_dict[x_i]]
1247
+ alpha = C.table[alpha][C.A_dict[x_i]]
1248
+ return v
1249
+
1250
+ # Pg 350, section 2.5.2 from [2]
1251
+ def elimination_technique_2(C):
1252
+ """
1253
+ This technique eliminates one generator at a time. Heuristically this
1254
+ seems superior in that we may select for elimination the generator with
1255
+ shortest equivalent string at each stage.
1256
+
1257
+ >>> from sympy.combinatorics import free_group
1258
+ >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r, \
1259
+ reidemeister_relators, define_schreier_generators, elimination_technique_2
1260
+ >>> F, x, y = free_group("x, y")
1261
+ >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]); H = [x*y, x**-1*y**-1*x*y*x]
1262
+ >>> C = coset_enumeration_r(f, H)
1263
+ >>> C.compress(); C.standardize()
1264
+ >>> define_schreier_generators(C)
1265
+ >>> reidemeister_relators(C)
1266
+ >>> elimination_technique_2(C)
1267
+ ([y_1, y_2], [y_2**-3, y_2*y_1*y_2*y_1*y_2*y_1, y_1**2])
1268
+
1269
+ """
1270
+ rels = C._reidemeister_relators
1271
+ rels.sort(reverse=True)
1272
+ gens = C._schreier_generators
1273
+ for i in range(len(gens) - 1, -1, -1):
1274
+ rel = rels[i]
1275
+ for j in range(len(gens) - 1, -1, -1):
1276
+ gen = gens[j]
1277
+ if rel.generator_count(gen) == 1:
1278
+ k = rel.exponent_sum(gen)
1279
+ gen_index = rel.index(gen**k)
1280
+ bk = rel.subword(gen_index + 1, len(rel))
1281
+ fw = rel.subword(0, gen_index)
1282
+ rep_by = (bk*fw)**(-1*k)
1283
+ del rels[i]; del gens[j]
1284
+ for l in range(len(rels)):
1285
+ rels[l] = rels[l].eliminate_word(gen, rep_by)
1286
+ break
1287
+ C._reidemeister_relators = rels
1288
+ C._schreier_generators = gens
1289
+ return C._schreier_generators, C._reidemeister_relators
1290
+
1291
+ def reidemeister_presentation(fp_grp, H, C=None, homomorphism=False):
1292
+ """
1293
+ Parameters
1294
+ ==========
1295
+
1296
+ fp_group: A finitely presented group, an instance of FpGroup
1297
+ H: A subgroup whose presentation is to be found, given as a list
1298
+ of words in generators of `fp_grp`
1299
+ homomorphism: When set to True, return a homomorphism from the subgroup
1300
+ to the parent group
1301
+
1302
+ Examples
1303
+ ========
1304
+
1305
+ >>> from sympy.combinatorics import free_group
1306
+ >>> from sympy.combinatorics.fp_groups import FpGroup, reidemeister_presentation
1307
+ >>> F, x, y = free_group("x, y")
1308
+
1309
+ Example 5.6 Pg. 177 from [1]
1310
+ >>> f = FpGroup(F, [x**3, y**5, (x*y)**2])
1311
+ >>> H = [x*y, x**-1*y**-1*x*y*x]
1312
+ >>> reidemeister_presentation(f, H)
1313
+ ((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1))
1314
+
1315
+ Example 5.8 Pg. 183 from [1]
1316
+ >>> f = FpGroup(F, [x**3, y**3, (x*y)**3])
1317
+ >>> H = [x*y, x*y**-1]
1318
+ >>> reidemeister_presentation(f, H)
1319
+ ((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0))
1320
+
1321
+ Exercises Q2. Pg 187 from [1]
1322
+ >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3])
1323
+ >>> H = [x]
1324
+ >>> reidemeister_presentation(f, H)
1325
+ ((x_0,), (x_0**4,))
1326
+
1327
+ Example 5.9 Pg. 183 from [1]
1328
+ >>> f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2])
1329
+ >>> H = [x]
1330
+ >>> reidemeister_presentation(f, H)
1331
+ ((x_0,), (x_0**6,))
1332
+
1333
+ """
1334
+ if not C:
1335
+ C = coset_enumeration_r(fp_grp, H)
1336
+ C.compress(); C.standardize()
1337
+ define_schreier_generators(C, homomorphism=homomorphism)
1338
+ reidemeister_relators(C)
1339
+ gens, rels = C._schreier_generators, C._reidemeister_relators
1340
+ gens, rels = simplify_presentation(gens, rels, change_gens=True)
1341
+
1342
+ C.schreier_generators = tuple(gens)
1343
+ C.reidemeister_relators = tuple(rels)
1344
+
1345
+ if homomorphism:
1346
+ _gens = []
1347
+ for gen in gens:
1348
+ _gens.append(C._schreier_gen_elem[str(gen)])
1349
+ return C.schreier_generators, C.reidemeister_relators, _gens
1350
+
1351
+ return C.schreier_generators, C.reidemeister_relators
1352
+
1353
+
1354
+ FpGroupElement = FreeGroupElement
mgm/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%282,5%29
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
mgm/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from sympy.combinatorics.fp_groups import FpGroup, FpSubgroup, simplify_presentation
3
+ from sympy.combinatorics.free_groups import FreeGroup
4
+ from sympy.combinatorics.perm_groups import PermutationGroup
5
+ from sympy.core.intfunc import igcd
6
+ from sympy.functions.combinatorial.numbers import totient
7
+ from sympy.core.singleton import S
8
+
9
+ class GroupHomomorphism:
10
+ '''
11
+ A class representing group homomorphisms. Instantiate using `homomorphism()`.
12
+
13
+ References
14
+ ==========
15
+
16
+ .. [1] Holt, D., Eick, B. and O'Brien, E. (2005). Handbook of computational group theory.
17
+
18
+ '''
19
+
20
+ def __init__(self, domain, codomain, images):
21
+ self.domain = domain
22
+ self.codomain = codomain
23
+ self.images = images
24
+ self._inverses = None
25
+ self._kernel = None
26
+ self._image = None
27
+
28
+ def _invs(self):
29
+ '''
30
+ Return a dictionary with `{gen: inverse}` where `gen` is a rewriting
31
+ generator of `codomain` (e.g. strong generator for permutation groups)
32
+ and `inverse` is an element of its preimage
33
+
34
+ '''
35
+ image = self.image()
36
+ inverses = {}
37
+ for k in list(self.images.keys()):
38
+ v = self.images[k]
39
+ if not (v in inverses
40
+ or v.is_identity):
41
+ inverses[v] = k
42
+ if isinstance(self.codomain, PermutationGroup):
43
+ gens = image.strong_gens
44
+ else:
45
+ gens = image.generators
46
+ for g in gens:
47
+ if g in inverses or g.is_identity:
48
+ continue
49
+ w = self.domain.identity
50
+ if isinstance(self.codomain, PermutationGroup):
51
+ parts = image._strong_gens_slp[g][::-1]
52
+ else:
53
+ parts = g
54
+ for s in parts:
55
+ if s in inverses:
56
+ w = w*inverses[s]
57
+ else:
58
+ w = w*inverses[s**-1]**-1
59
+ inverses[g] = w
60
+
61
+ return inverses
62
+
63
+ def invert(self, g):
64
+ '''
65
+ Return an element of the preimage of ``g`` or of each element
66
+ of ``g`` if ``g`` is a list.
67
+
68
+ Explanation
69
+ ===========
70
+
71
+ If the codomain is an FpGroup, the inverse for equal
72
+ elements might not always be the same unless the FpGroup's
73
+ rewriting system is confluent. However, making a system
74
+ confluent can be time-consuming. If it's important, try
75
+ `self.codomain.make_confluent()` first.
76
+
77
+ '''
78
+ from sympy.combinatorics import Permutation
79
+ from sympy.combinatorics.free_groups import FreeGroupElement
80
+ if isinstance(g, (Permutation, FreeGroupElement)):
81
+ if isinstance(self.codomain, FpGroup):
82
+ g = self.codomain.reduce(g)
83
+ if self._inverses is None:
84
+ self._inverses = self._invs()
85
+ image = self.image()
86
+ w = self.domain.identity
87
+ if isinstance(self.codomain, PermutationGroup):
88
+ gens = image.generator_product(g)[::-1]
89
+ else:
90
+ gens = g
91
+ # the following can't be "for s in gens:"
92
+ # because that would be equivalent to
93
+ # "for s in gens.array_form:" when g is
94
+ # a FreeGroupElement. On the other hand,
95
+ # when you call gens by index, the generator
96
+ # (or inverse) at position i is returned.
97
+ for i in range(len(gens)):
98
+ s = gens[i]
99
+ if s.is_identity:
100
+ continue
101
+ if s in self._inverses:
102
+ w = w*self._inverses[s]
103
+ else:
104
+ w = w*self._inverses[s**-1]**-1
105
+ return w
106
+ elif isinstance(g, list):
107
+ return [self.invert(e) for e in g]
108
+
109
+ def kernel(self):
110
+ '''
111
+ Compute the kernel of `self`.
112
+
113
+ '''
114
+ if self._kernel is None:
115
+ self._kernel = self._compute_kernel()
116
+ return self._kernel
117
+
118
+ def _compute_kernel(self):
119
+ G = self.domain
120
+ G_order = G.order()
121
+ if G_order is S.Infinity:
122
+ raise NotImplementedError(
123
+ "Kernel computation is not implemented for infinite groups")
124
+ gens = []
125
+ if isinstance(G, PermutationGroup):
126
+ K = PermutationGroup(G.identity)
127
+ else:
128
+ K = FpSubgroup(G, gens, normal=True)
129
+ i = self.image().order()
130
+ while K.order()*i != G_order:
131
+ r = G.random()
132
+ k = r*self.invert(self(r))**-1
133
+ if k not in K:
134
+ gens.append(k)
135
+ if isinstance(G, PermutationGroup):
136
+ K = PermutationGroup(gens)
137
+ else:
138
+ K = FpSubgroup(G, gens, normal=True)
139
+ return K
140
+
141
+ def image(self):
142
+ '''
143
+ Compute the image of `self`.
144
+
145
+ '''
146
+ if self._image is None:
147
+ values = list(set(self.images.values()))
148
+ if isinstance(self.codomain, PermutationGroup):
149
+ self._image = self.codomain.subgroup(values)
150
+ else:
151
+ self._image = FpSubgroup(self.codomain, values)
152
+ return self._image
153
+
154
+ def _apply(self, elem):
155
+ '''
156
+ Apply `self` to `elem`.
157
+
158
+ '''
159
+ if elem not in self.domain:
160
+ if isinstance(elem, (list, tuple)):
161
+ return [self._apply(e) for e in elem]
162
+ raise ValueError("The supplied element does not belong to the domain")
163
+ if elem.is_identity:
164
+ return self.codomain.identity
165
+ else:
166
+ images = self.images
167
+ value = self.codomain.identity
168
+ if isinstance(self.domain, PermutationGroup):
169
+ gens = self.domain.generator_product(elem, original=True)
170
+ for g in gens:
171
+ if g in self.images:
172
+ value = images[g]*value
173
+ else:
174
+ value = images[g**-1]**-1*value
175
+ else:
176
+ i = 0
177
+ for _, p in elem.array_form:
178
+ if p < 0:
179
+ g = elem[i]**-1
180
+ else:
181
+ g = elem[i]
182
+ value = value*images[g]**p
183
+ i += abs(p)
184
+ return value
185
+
186
+ def __call__(self, elem):
187
+ return self._apply(elem)
188
+
189
+ def is_injective(self):
190
+ '''
191
+ Check if the homomorphism is injective
192
+
193
+ '''
194
+ return self.kernel().order() == 1
195
+
196
+ def is_surjective(self):
197
+ '''
198
+ Check if the homomorphism is surjective
199
+
200
+ '''
201
+ im = self.image().order()
202
+ oth = self.codomain.order()
203
+ if im is S.Infinity and oth is S.Infinity:
204
+ return None
205
+ else:
206
+ return im == oth
207
+
208
+ def is_isomorphism(self):
209
+ '''
210
+ Check if `self` is an isomorphism.
211
+
212
+ '''
213
+ return self.is_injective() and self.is_surjective()
214
+
215
+ def is_trivial(self):
216
+ '''
217
+ Check is `self` is a trivial homomorphism, i.e. all elements
218
+ are mapped to the identity.
219
+
220
+ '''
221
+ return self.image().order() == 1
222
+
223
+ def compose(self, other):
224
+ '''
225
+ Return the composition of `self` and `other`, i.e.
226
+ the homomorphism phi such that for all g in the domain
227
+ of `other`, phi(g) = self(other(g))
228
+
229
+ '''
230
+ if not other.image().is_subgroup(self.domain):
231
+ raise ValueError("The image of `other` must be a subgroup of "
232
+ "the domain of `self`")
233
+ images = {g: self(other(g)) for g in other.images}
234
+ return GroupHomomorphism(other.domain, self.codomain, images)
235
+
236
+ def restrict_to(self, H):
237
+ '''
238
+ Return the restriction of the homomorphism to the subgroup `H`
239
+ of the domain.
240
+
241
+ '''
242
+ if not isinstance(H, PermutationGroup) or not H.is_subgroup(self.domain):
243
+ raise ValueError("Given H is not a subgroup of the domain")
244
+ domain = H
245
+ images = {g: self(g) for g in H.generators}
246
+ return GroupHomomorphism(domain, self.codomain, images)
247
+
248
+ def invert_subgroup(self, H):
249
+ '''
250
+ Return the subgroup of the domain that is the inverse image
251
+ of the subgroup ``H`` of the homomorphism image
252
+
253
+ '''
254
+ if not H.is_subgroup(self.image()):
255
+ raise ValueError("Given H is not a subgroup of the image")
256
+ gens = []
257
+ P = PermutationGroup(self.image().identity)
258
+ for h in H.generators:
259
+ h_i = self.invert(h)
260
+ if h_i not in P:
261
+ gens.append(h_i)
262
+ P = PermutationGroup(gens)
263
+ for k in self.kernel().generators:
264
+ if k*h_i not in P:
265
+ gens.append(k*h_i)
266
+ P = PermutationGroup(gens)
267
+ return P
268
+
269
+ def homomorphism(domain, codomain, gens, images=(), check=True):
270
+ '''
271
+ Create (if possible) a group homomorphism from the group ``domain``
272
+ to the group ``codomain`` defined by the images of the domain's
273
+ generators ``gens``. ``gens`` and ``images`` can be either lists or tuples
274
+ of equal sizes. If ``gens`` is a proper subset of the group's generators,
275
+ the unspecified generators will be mapped to the identity. If the
276
+ images are not specified, a trivial homomorphism will be created.
277
+
278
+ If the given images of the generators do not define a homomorphism,
279
+ an exception is raised.
280
+
281
+ If ``check`` is ``False``, do not check whether the given images actually
282
+ define a homomorphism.
283
+
284
+ '''
285
+ if not isinstance(domain, (PermutationGroup, FpGroup, FreeGroup)):
286
+ raise TypeError("The domain must be a group")
287
+ if not isinstance(codomain, (PermutationGroup, FpGroup, FreeGroup)):
288
+ raise TypeError("The codomain must be a group")
289
+
290
+ generators = domain.generators
291
+ if not all(g in generators for g in gens):
292
+ raise ValueError("The supplied generators must be a subset of the domain's generators")
293
+ if not all(g in codomain for g in images):
294
+ raise ValueError("The images must be elements of the codomain")
295
+
296
+ if images and len(images) != len(gens):
297
+ raise ValueError("The number of images must be equal to the number of generators")
298
+
299
+ gens = list(gens)
300
+ images = list(images)
301
+
302
+ images.extend([codomain.identity]*(len(generators)-len(images)))
303
+ gens.extend([g for g in generators if g not in gens])
304
+ images = dict(zip(gens,images))
305
+
306
+ if check and not _check_homomorphism(domain, codomain, images):
307
+ raise ValueError("The given images do not define a homomorphism")
308
+ return GroupHomomorphism(domain, codomain, images)
309
+
310
+ def _check_homomorphism(domain, codomain, images):
311
+ """
312
+ Check that a given mapping of generators to images defines a homomorphism.
313
+
314
+ Parameters
315
+ ==========
316
+ domain : PermutationGroup, FpGroup, FreeGroup
317
+ codomain : PermutationGroup, FpGroup, FreeGroup
318
+ images : dict
319
+ The set of keys must be equal to domain.generators.
320
+ The values must be elements of the codomain.
321
+
322
+ """
323
+ pres = domain if hasattr(domain, 'relators') else domain.presentation()
324
+ rels = pres.relators
325
+ gens = pres.generators
326
+ symbols = [g.ext_rep[0] for g in gens]
327
+ symbols_to_domain_generators = dict(zip(symbols, domain.generators))
328
+ identity = codomain.identity
329
+
330
+ def _image(r):
331
+ w = identity
332
+ for symbol, power in r.array_form:
333
+ g = symbols_to_domain_generators[symbol]
334
+ w *= images[g]**power
335
+ return w
336
+
337
+ for r in rels:
338
+ if isinstance(codomain, FpGroup):
339
+ s = codomain.equals(_image(r), identity)
340
+ if s is None:
341
+ # only try to make the rewriting system
342
+ # confluent when it can't determine the
343
+ # truth of equality otherwise
344
+ success = codomain.make_confluent()
345
+ s = codomain.equals(_image(r), identity)
346
+ if s is None and not success:
347
+ raise RuntimeError("Can't determine if the images "
348
+ "define a homomorphism. Try increasing "
349
+ "the maximum number of rewriting rules "
350
+ "(group._rewriting_system.set_max(new_value); "
351
+ "the current value is stored in group._rewriting"
352
+ "_system.maxeqns)")
353
+ else:
354
+ s = _image(r).is_identity
355
+ if not s:
356
+ return False
357
+ return True
358
+
359
+ def orbit_homomorphism(group, omega):
360
+ '''
361
+ Return the homomorphism induced by the action of the permutation
362
+ group ``group`` on the set ``omega`` that is closed under the action.
363
+
364
+ '''
365
+ from sympy.combinatorics import Permutation
366
+ from sympy.combinatorics.named_groups import SymmetricGroup
367
+ codomain = SymmetricGroup(len(omega))
368
+ identity = codomain.identity
369
+ omega = list(omega)
370
+ images = {g: identity*Permutation([omega.index(o^g) for o in omega]) for g in group.generators}
371
+ group._schreier_sims(base=omega)
372
+ H = GroupHomomorphism(group, codomain, images)
373
+ if len(group.basic_stabilizers) > len(omega):
374
+ H._kernel = group.basic_stabilizers[len(omega)]
375
+ else:
376
+ H._kernel = PermutationGroup([group.identity])
377
+ return H
378
+
379
+ def block_homomorphism(group, blocks):
380
+ '''
381
+ Return the homomorphism induced by the action of the permutation
382
+ group ``group`` on the block system ``blocks``. The latter should be
383
+ of the same form as returned by the ``minimal_block`` method for
384
+ permutation groups, namely a list of length ``group.degree`` where
385
+ the i-th entry is a representative of the block i belongs to.
386
+
387
+ '''
388
+ from sympy.combinatorics import Permutation
389
+ from sympy.combinatorics.named_groups import SymmetricGroup
390
+
391
+ n = len(blocks)
392
+
393
+ # number the blocks; m is the total number,
394
+ # b is such that b[i] is the number of the block i belongs to,
395
+ # p is the list of length m such that p[i] is the representative
396
+ # of the i-th block
397
+ m = 0
398
+ p = []
399
+ b = [None]*n
400
+ for i in range(n):
401
+ if blocks[i] == i:
402
+ p.append(i)
403
+ b[i] = m
404
+ m += 1
405
+ for i in range(n):
406
+ b[i] = b[blocks[i]]
407
+
408
+ codomain = SymmetricGroup(m)
409
+ # the list corresponding to the identity permutation in codomain
410
+ identity = range(m)
411
+ images = {g: Permutation([b[p[i]^g] for i in identity]) for g in group.generators}
412
+ H = GroupHomomorphism(group, codomain, images)
413
+ return H
414
+
415
+ def group_isomorphism(G, H, isomorphism=True):
416
+ '''
417
+ Compute an isomorphism between 2 given groups.
418
+
419
+ Parameters
420
+ ==========
421
+
422
+ G : A finite ``FpGroup`` or a ``PermutationGroup``.
423
+ First group.
424
+
425
+ H : A finite ``FpGroup`` or a ``PermutationGroup``
426
+ Second group.
427
+
428
+ isomorphism : bool
429
+ This is used to avoid the computation of homomorphism
430
+ when the user only wants to check if there exists
431
+ an isomorphism between the groups.
432
+
433
+ Returns
434
+ =======
435
+
436
+ If isomorphism = False -- Returns a boolean.
437
+ If isomorphism = True -- Returns a boolean and an isomorphism between `G` and `H`.
438
+
439
+ Examples
440
+ ========
441
+
442
+ >>> from sympy.combinatorics import free_group, Permutation
443
+ >>> from sympy.combinatorics.perm_groups import PermutationGroup
444
+ >>> from sympy.combinatorics.fp_groups import FpGroup
445
+ >>> from sympy.combinatorics.homomorphisms import group_isomorphism
446
+ >>> from sympy.combinatorics.named_groups import DihedralGroup, AlternatingGroup
447
+
448
+ >>> D = DihedralGroup(8)
449
+ >>> p = Permutation(0, 1, 2, 3, 4, 5, 6, 7)
450
+ >>> P = PermutationGroup(p)
451
+ >>> group_isomorphism(D, P)
452
+ (False, None)
453
+
454
+ >>> F, a, b = free_group("a, b")
455
+ >>> G = FpGroup(F, [a**3, b**3, (a*b)**2])
456
+ >>> H = AlternatingGroup(4)
457
+ >>> (check, T) = group_isomorphism(G, H)
458
+ >>> check
459
+ True
460
+ >>> T(b*a*b**-1*a**-1*b**-1)
461
+ (0 2 3)
462
+
463
+ Notes
464
+ =====
465
+
466
+ Uses the approach suggested by Robert Tarjan to compute the isomorphism between two groups.
467
+ First, the generators of ``G`` are mapped to the elements of ``H`` and
468
+ we check if the mapping induces an isomorphism.
469
+
470
+ '''
471
+ if not isinstance(G, (PermutationGroup, FpGroup)):
472
+ raise TypeError("The group must be a PermutationGroup or an FpGroup")
473
+ if not isinstance(H, (PermutationGroup, FpGroup)):
474
+ raise TypeError("The group must be a PermutationGroup or an FpGroup")
475
+
476
+ if isinstance(G, FpGroup) and isinstance(H, FpGroup):
477
+ G = simplify_presentation(G)
478
+ H = simplify_presentation(H)
479
+ # Two infinite FpGroups with the same generators are isomorphic
480
+ # when the relators are same but are ordered differently.
481
+ if G.generators == H.generators and (G.relators).sort() == (H.relators).sort():
482
+ if not isomorphism:
483
+ return True
484
+ return (True, homomorphism(G, H, G.generators, H.generators))
485
+
486
+ # `_H` is the permutation group isomorphic to `H`.
487
+ _H = H
488
+ g_order = G.order()
489
+ h_order = H.order()
490
+
491
+ if g_order is S.Infinity:
492
+ raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.")
493
+
494
+ if isinstance(H, FpGroup):
495
+ if h_order is S.Infinity:
496
+ raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.")
497
+ _H, h_isomorphism = H._to_perm_group()
498
+
499
+ if (g_order != h_order) or (G.is_abelian != H.is_abelian):
500
+ if not isomorphism:
501
+ return False
502
+ return (False, None)
503
+
504
+ if not isomorphism:
505
+ # Two groups of the same cyclic numbered order
506
+ # are isomorphic to each other.
507
+ n = g_order
508
+ if (igcd(n, totient(n))) == 1:
509
+ return True
510
+
511
+ # Match the generators of `G` with subsets of `_H`
512
+ gens = list(G.generators)
513
+ for subset in itertools.permutations(_H, len(gens)):
514
+ images = list(subset)
515
+ images.extend([_H.identity]*(len(G.generators)-len(images)))
516
+ _images = dict(zip(gens,images))
517
+ if _check_homomorphism(G, _H, _images):
518
+ if isinstance(H, FpGroup):
519
+ images = h_isomorphism.invert(images)
520
+ T = homomorphism(G, H, G.generators, images, check=False)
521
+ if T.is_isomorphism():
522
+ # It is a valid isomorphism
523
+ if not isomorphism:
524
+ return True
525
+ return (True, T)
526
+
527
+ if not isomorphism:
528
+ return False
529
+ return (False, None)
530
+
531
+ def is_isomorphic(G, H):
532
+ '''
533
+ Check if the groups are isomorphic to each other
534
+
535
+ Parameters
536
+ ==========
537
+
538
+ G : A finite ``FpGroup`` or a ``PermutationGroup``
539
+ First group.
540
+
541
+ H : A finite ``FpGroup`` or a ``PermutationGroup``
542
+ Second group.
543
+
544
+ Returns
545
+ =======
546
+
547
+ boolean
548
+ '''
549
+ return group_isomorphism(G, H, isomorphism=False)
mgm/lib/python3.10/site-packages/sympy/combinatorics/permutations.py ADDED
@@ -0,0 +1,3115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ from collections import defaultdict
3
+ from collections.abc import Iterable
4
+ from functools import reduce
5
+
6
+ from sympy.core.parameters import global_parameters
7
+ from sympy.core.basic import Atom
8
+ from sympy.core.expr import Expr
9
+ from sympy.core.numbers import int_valued
10
+ from sympy.core.numbers import Integer
11
+ from sympy.core.sympify import _sympify
12
+ from sympy.matrices import zeros
13
+ from sympy.polys.polytools import lcm
14
+ from sympy.printing.repr import srepr
15
+ from sympy.utilities.iterables import (flatten, has_variety, minlex,
16
+ has_dups, runs, is_sequence)
17
+ from sympy.utilities.misc import as_int
18
+ from mpmath.libmp.libintmath import ifac
19
+ from sympy.multipledispatch import dispatch
20
+
21
+ def _af_rmul(a, b):
22
+ """
23
+ Return the product b*a; input and output are array forms. The ith value
24
+ is a[b[i]].
25
+
26
+ Examples
27
+ ========
28
+
29
+ >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
30
+
31
+ >>> a, b = [1, 0, 2], [0, 2, 1]
32
+ >>> _af_rmul(a, b)
33
+ [1, 2, 0]
34
+ >>> [a[b[i]] for i in range(3)]
35
+ [1, 2, 0]
36
+
37
+ This handles the operands in reverse order compared to the ``*`` operator:
38
+
39
+ >>> a = Permutation(a)
40
+ >>> b = Permutation(b)
41
+ >>> list(a*b)
42
+ [2, 0, 1]
43
+ >>> [b(a(i)) for i in range(3)]
44
+ [2, 0, 1]
45
+
46
+ See Also
47
+ ========
48
+
49
+ rmul, _af_rmuln
50
+ """
51
+ return [a[i] for i in b]
52
+
53
+
54
+ def _af_rmuln(*abc):
55
+ """
56
+ Given [a, b, c, ...] return the product of ...*c*b*a using array forms.
57
+ The ith value is a[b[c[i]]].
58
+
59
+ Examples
60
+ ========
61
+
62
+ >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
63
+
64
+ >>> a, b = [1, 0, 2], [0, 2, 1]
65
+ >>> _af_rmul(a, b)
66
+ [1, 2, 0]
67
+ >>> [a[b[i]] for i in range(3)]
68
+ [1, 2, 0]
69
+
70
+ This handles the operands in reverse order compared to the ``*`` operator:
71
+
72
+ >>> a = Permutation(a); b = Permutation(b)
73
+ >>> list(a*b)
74
+ [2, 0, 1]
75
+ >>> [b(a(i)) for i in range(3)]
76
+ [2, 0, 1]
77
+
78
+ See Also
79
+ ========
80
+
81
+ rmul, _af_rmul
82
+ """
83
+ a = abc
84
+ m = len(a)
85
+ if m == 3:
86
+ p0, p1, p2 = a
87
+ return [p0[p1[i]] for i in p2]
88
+ if m == 4:
89
+ p0, p1, p2, p3 = a
90
+ return [p0[p1[p2[i]]] for i in p3]
91
+ if m == 5:
92
+ p0, p1, p2, p3, p4 = a
93
+ return [p0[p1[p2[p3[i]]]] for i in p4]
94
+ if m == 6:
95
+ p0, p1, p2, p3, p4, p5 = a
96
+ return [p0[p1[p2[p3[p4[i]]]]] for i in p5]
97
+ if m == 7:
98
+ p0, p1, p2, p3, p4, p5, p6 = a
99
+ return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6]
100
+ if m == 8:
101
+ p0, p1, p2, p3, p4, p5, p6, p7 = a
102
+ return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7]
103
+ if m == 1:
104
+ return a[0][:]
105
+ if m == 2:
106
+ a, b = a
107
+ return [a[i] for i in b]
108
+ if m == 0:
109
+ raise ValueError("String must not be empty")
110
+ p0 = _af_rmuln(*a[:m//2])
111
+ p1 = _af_rmuln(*a[m//2:])
112
+ return [p0[i] for i in p1]
113
+
114
+
115
+ def _af_parity(pi):
116
+ """
117
+ Computes the parity of a permutation in array form.
118
+
119
+ Explanation
120
+ ===========
121
+
122
+ The parity of a permutation reflects the parity of the
123
+ number of inversions in the permutation, i.e., the
124
+ number of pairs of x and y such that x > y but p[x] < p[y].
125
+
126
+ Examples
127
+ ========
128
+
129
+ >>> from sympy.combinatorics.permutations import _af_parity
130
+ >>> _af_parity([0, 1, 2, 3])
131
+ 0
132
+ >>> _af_parity([3, 2, 0, 1])
133
+ 1
134
+
135
+ See Also
136
+ ========
137
+
138
+ Permutation
139
+ """
140
+ n = len(pi)
141
+ a = [0] * n
142
+ c = 0
143
+ for j in range(n):
144
+ if a[j] == 0:
145
+ c += 1
146
+ a[j] = 1
147
+ i = j
148
+ while pi[i] != j:
149
+ i = pi[i]
150
+ a[i] = 1
151
+ return (n - c) % 2
152
+
153
+
154
+ def _af_invert(a):
155
+ """
156
+ Finds the inverse, ~A, of a permutation, A, given in array form.
157
+
158
+ Examples
159
+ ========
160
+
161
+ >>> from sympy.combinatorics.permutations import _af_invert, _af_rmul
162
+ >>> A = [1, 2, 0, 3]
163
+ >>> _af_invert(A)
164
+ [2, 0, 1, 3]
165
+ >>> _af_rmul(_, A)
166
+ [0, 1, 2, 3]
167
+
168
+ See Also
169
+ ========
170
+
171
+ Permutation, __invert__
172
+ """
173
+ inv_form = [0] * len(a)
174
+ for i, ai in enumerate(a):
175
+ inv_form[ai] = i
176
+ return inv_form
177
+
178
+
179
+ def _af_pow(a, n):
180
+ """
181
+ Routine for finding powers of a permutation.
182
+
183
+ Examples
184
+ ========
185
+
186
+ >>> from sympy.combinatorics import Permutation
187
+ >>> from sympy.combinatorics.permutations import _af_pow
188
+ >>> p = Permutation([2, 0, 3, 1])
189
+ >>> p.order()
190
+ 4
191
+ >>> _af_pow(p._array_form, 4)
192
+ [0, 1, 2, 3]
193
+ """
194
+ if n == 0:
195
+ return list(range(len(a)))
196
+ if n < 0:
197
+ return _af_pow(_af_invert(a), -n)
198
+ if n == 1:
199
+ return a[:]
200
+ elif n == 2:
201
+ b = [a[i] for i in a]
202
+ elif n == 3:
203
+ b = [a[a[i]] for i in a]
204
+ elif n == 4:
205
+ b = [a[a[a[i]]] for i in a]
206
+ else:
207
+ # use binary multiplication
208
+ b = list(range(len(a)))
209
+ while 1:
210
+ if n & 1:
211
+ b = [b[i] for i in a]
212
+ n -= 1
213
+ if not n:
214
+ break
215
+ if n % 4 == 0:
216
+ a = [a[a[a[i]]] for i in a]
217
+ n = n // 4
218
+ elif n % 2 == 0:
219
+ a = [a[i] for i in a]
220
+ n = n // 2
221
+ return b
222
+
223
+
224
+ def _af_commutes_with(a, b):
225
+ """
226
+ Checks if the two permutations with array forms
227
+ given by ``a`` and ``b`` commute.
228
+
229
+ Examples
230
+ ========
231
+
232
+ >>> from sympy.combinatorics.permutations import _af_commutes_with
233
+ >>> _af_commutes_with([1, 2, 0], [0, 2, 1])
234
+ False
235
+
236
+ See Also
237
+ ========
238
+
239
+ Permutation, commutes_with
240
+ """
241
+ return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
242
+
243
+
244
+ class Cycle(dict):
245
+ """
246
+ Wrapper around dict which provides the functionality of a disjoint cycle.
247
+
248
+ Explanation
249
+ ===========
250
+
251
+ A cycle shows the rule to use to move subsets of elements to obtain
252
+ a permutation. The Cycle class is more flexible than Permutation in
253
+ that 1) all elements need not be present in order to investigate how
254
+ multiple cycles act in sequence and 2) it can contain singletons:
255
+
256
+ >>> from sympy.combinatorics.permutations import Perm, Cycle
257
+
258
+ A Cycle will automatically parse a cycle given as a tuple on the rhs:
259
+
260
+ >>> Cycle(1, 2)(2, 3)
261
+ (1 3 2)
262
+
263
+ The identity cycle, Cycle(), can be used to start a product:
264
+
265
+ >>> Cycle()(1, 2)(2, 3)
266
+ (1 3 2)
267
+
268
+ The array form of a Cycle can be obtained by calling the list
269
+ method (or passing it to the list function) and all elements from
270
+ 0 will be shown:
271
+
272
+ >>> a = Cycle(1, 2)
273
+ >>> a.list()
274
+ [0, 2, 1]
275
+ >>> list(a)
276
+ [0, 2, 1]
277
+
278
+ If a larger (or smaller) range is desired use the list method and
279
+ provide the desired size -- but the Cycle cannot be truncated to
280
+ a size smaller than the largest element that is out of place:
281
+
282
+ >>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3)
283
+ >>> b.list()
284
+ [0, 2, 1, 3, 4]
285
+ >>> b.list(b.size + 1)
286
+ [0, 2, 1, 3, 4, 5]
287
+ >>> b.list(-1)
288
+ [0, 2, 1]
289
+
290
+ Singletons are not shown when printing with one exception: the largest
291
+ element is always shown -- as a singleton if necessary:
292
+
293
+ >>> Cycle(1, 4, 10)(4, 5)
294
+ (1 5 4 10)
295
+ >>> Cycle(1, 2)(4)(5)(10)
296
+ (1 2)(10)
297
+
298
+ The array form can be used to instantiate a Permutation so other
299
+ properties of the permutation can be investigated:
300
+
301
+ >>> Perm(Cycle(1, 2)(3, 4).list()).transpositions()
302
+ [(1, 2), (3, 4)]
303
+
304
+ Notes
305
+ =====
306
+
307
+ The underlying structure of the Cycle is a dictionary and although
308
+ the __iter__ method has been redefined to give the array form of the
309
+ cycle, the underlying dictionary items are still available with the
310
+ such methods as items():
311
+
312
+ >>> list(Cycle(1, 2).items())
313
+ [(1, 2), (2, 1)]
314
+
315
+ See Also
316
+ ========
317
+
318
+ Permutation
319
+ """
320
+ def __missing__(self, arg):
321
+ """Enter arg into dictionary and return arg."""
322
+ return as_int(arg)
323
+
324
+ def __iter__(self):
325
+ yield from self.list()
326
+
327
+ def __call__(self, *other):
328
+ """Return product of cycles processed from R to L.
329
+
330
+ Examples
331
+ ========
332
+
333
+ >>> from sympy.combinatorics import Cycle
334
+ >>> Cycle(1, 2)(2, 3)
335
+ (1 3 2)
336
+
337
+ An instance of a Cycle will automatically parse list-like
338
+ objects and Permutations that are on the right. It is more
339
+ flexible than the Permutation in that all elements need not
340
+ be present:
341
+
342
+ >>> a = Cycle(1, 2)
343
+ >>> a(2, 3)
344
+ (1 3 2)
345
+ >>> a(2, 3)(4, 5)
346
+ (1 3 2)(4 5)
347
+
348
+ """
349
+ rv = Cycle(*other)
350
+ for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]):
351
+ rv[k] = v
352
+ return rv
353
+
354
+ def list(self, size=None):
355
+ """Return the cycles as an explicit list starting from 0 up
356
+ to the greater of the largest value in the cycles and size.
357
+
358
+ Truncation of trailing unmoved items will occur when size
359
+ is less than the maximum element in the cycle; if this is
360
+ desired, setting ``size=-1`` will guarantee such trimming.
361
+
362
+ Examples
363
+ ========
364
+
365
+ >>> from sympy.combinatorics import Cycle
366
+ >>> p = Cycle(2, 3)(4, 5)
367
+ >>> p.list()
368
+ [0, 1, 3, 2, 5, 4]
369
+ >>> p.list(10)
370
+ [0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
371
+
372
+ Passing a length too small will trim trailing, unchanged elements
373
+ in the permutation:
374
+
375
+ >>> Cycle(2, 4)(1, 2, 4).list(-1)
376
+ [0, 2, 1]
377
+ """
378
+ if not self and size is None:
379
+ raise ValueError('must give size for empty Cycle')
380
+ if size is not None:
381
+ big = max([i for i in self.keys() if self[i] != i] + [0])
382
+ size = max(size, big + 1)
383
+ else:
384
+ size = self.size
385
+ return [self[i] for i in range(size)]
386
+
387
+ def __repr__(self):
388
+ """We want it to print as a Cycle, not as a dict.
389
+
390
+ Examples
391
+ ========
392
+
393
+ >>> from sympy.combinatorics import Cycle
394
+ >>> Cycle(1, 2)
395
+ (1 2)
396
+ >>> print(_)
397
+ (1 2)
398
+ >>> list(Cycle(1, 2).items())
399
+ [(1, 2), (2, 1)]
400
+ """
401
+ if not self:
402
+ return 'Cycle()'
403
+ cycles = Permutation(self).cyclic_form
404
+ s = ''.join(str(tuple(c)) for c in cycles)
405
+ big = self.size - 1
406
+ if not any(i == big for c in cycles for i in c):
407
+ s += '(%s)' % big
408
+ return 'Cycle%s' % s
409
+
410
+ def __str__(self):
411
+ """We want it to be printed in a Cycle notation with no
412
+ comma in-between.
413
+
414
+ Examples
415
+ ========
416
+
417
+ >>> from sympy.combinatorics import Cycle
418
+ >>> Cycle(1, 2)
419
+ (1 2)
420
+ >>> Cycle(1, 2, 4)(5, 6)
421
+ (1 2 4)(5 6)
422
+ """
423
+ if not self:
424
+ return '()'
425
+ cycles = Permutation(self).cyclic_form
426
+ s = ''.join(str(tuple(c)) for c in cycles)
427
+ big = self.size - 1
428
+ if not any(i == big for c in cycles for i in c):
429
+ s += '(%s)' % big
430
+ s = s.replace(',', '')
431
+ return s
432
+
433
+ def __init__(self, *args):
434
+ """Load up a Cycle instance with the values for the cycle.
435
+
436
+ Examples
437
+ ========
438
+
439
+ >>> from sympy.combinatorics import Cycle
440
+ >>> Cycle(1, 2, 6)
441
+ (1 2 6)
442
+ """
443
+
444
+ if not args:
445
+ return
446
+ if len(args) == 1:
447
+ if isinstance(args[0], Permutation):
448
+ for c in args[0].cyclic_form:
449
+ self.update(self(*c))
450
+ return
451
+ elif isinstance(args[0], Cycle):
452
+ for k, v in args[0].items():
453
+ self[k] = v
454
+ return
455
+ args = [as_int(a) for a in args]
456
+ if any(i < 0 for i in args):
457
+ raise ValueError('negative integers are not allowed in a cycle.')
458
+ if has_dups(args):
459
+ raise ValueError('All elements must be unique in a cycle.')
460
+ for i in range(-len(args), 0):
461
+ self[args[i]] = args[i + 1]
462
+
463
+ @property
464
+ def size(self):
465
+ if not self:
466
+ return 0
467
+ return max(self.keys()) + 1
468
+
469
+ def copy(self):
470
+ return Cycle(self)
471
+
472
+
473
+ class Permutation(Atom):
474
+ r"""
475
+ A permutation, alternatively known as an 'arrangement number' or 'ordering'
476
+ is an arrangement of the elements of an ordered list into a one-to-one
477
+ mapping with itself. The permutation of a given arrangement is given by
478
+ indicating the positions of the elements after re-arrangement [2]_. For
479
+ example, if one started with elements ``[x, y, a, b]`` (in that order) and
480
+ they were reordered as ``[x, y, b, a]`` then the permutation would be
481
+ ``[0, 1, 3, 2]``. Notice that (in SymPy) the first element is always referred
482
+ to as 0 and the permutation uses the indices of the elements in the
483
+ original ordering, not the elements ``(a, b, ...)`` themselves.
484
+
485
+ >>> from sympy.combinatorics import Permutation
486
+ >>> from sympy import init_printing
487
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
488
+
489
+ Permutations Notation
490
+ =====================
491
+
492
+ Permutations are commonly represented in disjoint cycle or array forms.
493
+
494
+ Array Notation and 2-line Form
495
+ ------------------------------------
496
+
497
+ In the 2-line form, the elements and their final positions are shown
498
+ as a matrix with 2 rows:
499
+
500
+ [0 1 2 ... n-1]
501
+ [p(0) p(1) p(2) ... p(n-1)]
502
+
503
+ Since the first line is always ``range(n)``, where n is the size of p,
504
+ it is sufficient to represent the permutation by the second line,
505
+ referred to as the "array form" of the permutation. This is entered
506
+ in brackets as the argument to the Permutation class:
507
+
508
+ >>> p = Permutation([0, 2, 1]); p
509
+ Permutation([0, 2, 1])
510
+
511
+ Given i in range(p.size), the permutation maps i to i^p
512
+
513
+ >>> [i^p for i in range(p.size)]
514
+ [0, 2, 1]
515
+
516
+ The composite of two permutations p*q means first apply p, then q, so
517
+ i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules:
518
+
519
+ >>> q = Permutation([2, 1, 0])
520
+ >>> [i^p^q for i in range(3)]
521
+ [2, 0, 1]
522
+ >>> [i^(p*q) for i in range(3)]
523
+ [2, 0, 1]
524
+
525
+ One can use also the notation p(i) = i^p, but then the composition
526
+ rule is (p*q)(i) = q(p(i)), not p(q(i)):
527
+
528
+ >>> [(p*q)(i) for i in range(p.size)]
529
+ [2, 0, 1]
530
+ >>> [q(p(i)) for i in range(p.size)]
531
+ [2, 0, 1]
532
+ >>> [p(q(i)) for i in range(p.size)]
533
+ [1, 2, 0]
534
+
535
+ Disjoint Cycle Notation
536
+ -----------------------
537
+
538
+ In disjoint cycle notation, only the elements that have shifted are
539
+ indicated.
540
+
541
+ For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2).
542
+ This can be understood from the 2 line format of the given permutation.
543
+ In the 2-line form,
544
+ [0 1 2 3]
545
+ [1 3 2 0]
546
+
547
+ The element in the 0th position is 1, so 0 -> 1. The element in the 1st
548
+ position is three, so 1 -> 3. And the element in the third position is again
549
+ 0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented
550
+ as 2 cycles: (0, 1, 3)(2).
551
+ In common notation, singular cycles are not explicitly written as they can be
552
+ inferred implicitly.
553
+
554
+ Only the relative ordering of elements in a cycle matter:
555
+
556
+ >>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2)
557
+ True
558
+
559
+ The disjoint cycle notation is convenient when representing
560
+ permutations that have several cycles in them:
561
+
562
+ >>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]])
563
+ True
564
+
565
+ It also provides some economy in entry when computing products of
566
+ permutations that are written in disjoint cycle notation:
567
+
568
+ >>> Permutation(1, 2)(1, 3)(2, 3)
569
+ Permutation([0, 3, 2, 1])
570
+ >>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]])
571
+ True
572
+
573
+ Caution: when the cycles have common elements between them then the order
574
+ in which the permutations are applied matters. This module applies
575
+ the permutations from *left to right*.
576
+
577
+ >>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)])
578
+ True
579
+ >>> Permutation(1, 2)(2, 3).list()
580
+ [0, 3, 1, 2]
581
+
582
+ In the above case, (1,2) is computed before (2,3).
583
+ As 0 -> 0, 0 -> 0, element in position 0 is 0.
584
+ As 1 -> 2, 2 -> 3, element in position 1 is 3.
585
+ As 2 -> 1, 1 -> 1, element in position 2 is 1.
586
+ As 3 -> 3, 3 -> 2, element in position 3 is 2.
587
+
588
+ If the first and second elements had been
589
+ swapped first, followed by the swapping of the second
590
+ and third, the result would have been [0, 2, 3, 1].
591
+ If, you want to apply the cycles in the conventional
592
+ right to left order, call the function with arguments in reverse order
593
+ as demonstrated below:
594
+
595
+ >>> Permutation([(1, 2), (2, 3)][::-1]).list()
596
+ [0, 2, 3, 1]
597
+
598
+ Entering a singleton in a permutation is a way to indicate the size of the
599
+ permutation. The ``size`` keyword can also be used.
600
+
601
+ Array-form entry:
602
+
603
+ >>> Permutation([[1, 2], [9]])
604
+ Permutation([0, 2, 1], size=10)
605
+ >>> Permutation([[1, 2]], size=10)
606
+ Permutation([0, 2, 1], size=10)
607
+
608
+ Cyclic-form entry:
609
+
610
+ >>> Permutation(1, 2, size=10)
611
+ Permutation([0, 2, 1], size=10)
612
+ >>> Permutation(9)(1, 2)
613
+ Permutation([0, 2, 1], size=10)
614
+
615
+ Caution: no singleton containing an element larger than the largest
616
+ in any previous cycle can be entered. This is an important difference
617
+ in how Permutation and Cycle handle the ``__call__`` syntax. A singleton
618
+ argument at the start of a Permutation performs instantiation of the
619
+ Permutation and is permitted:
620
+
621
+ >>> Permutation(5)
622
+ Permutation([], size=6)
623
+
624
+ A singleton entered after instantiation is a call to the permutation
625
+ -- a function call -- and if the argument is out of range it will
626
+ trigger an error. For this reason, it is better to start the cycle
627
+ with the singleton:
628
+
629
+ The following fails because there is no element 3:
630
+
631
+ >>> Permutation(1, 2)(3)
632
+ Traceback (most recent call last):
633
+ ...
634
+ IndexError: list index out of range
635
+
636
+ This is ok: only the call to an out of range singleton is prohibited;
637
+ otherwise the permutation autosizes:
638
+
639
+ >>> Permutation(3)(1, 2)
640
+ Permutation([0, 2, 1, 3])
641
+ >>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2)
642
+ True
643
+
644
+
645
+ Equality testing
646
+ ----------------
647
+
648
+ The array forms must be the same in order for permutations to be equal:
649
+
650
+ >>> Permutation([1, 0, 2, 3]) == Permutation([1, 0])
651
+ False
652
+
653
+
654
+ Identity Permutation
655
+ --------------------
656
+
657
+ The identity permutation is a permutation in which no element is out of
658
+ place. It can be entered in a variety of ways. All the following create
659
+ an identity permutation of size 4:
660
+
661
+ >>> I = Permutation([0, 1, 2, 3])
662
+ >>> all(p == I for p in [
663
+ ... Permutation(3),
664
+ ... Permutation(range(4)),
665
+ ... Permutation([], size=4),
666
+ ... Permutation(size=4)])
667
+ True
668
+
669
+ Watch out for entering the range *inside* a set of brackets (which is
670
+ cycle notation):
671
+
672
+ >>> I == Permutation([range(4)])
673
+ False
674
+
675
+
676
+ Permutation Printing
677
+ ====================
678
+
679
+ There are a few things to note about how Permutations are printed.
680
+
681
+ .. deprecated:: 1.6
682
+
683
+ Configuring Permutation printing by setting
684
+ ``Permutation.print_cyclic`` is deprecated. Users should use the
685
+ ``perm_cyclic`` flag to the printers, as described below.
686
+
687
+ 1) If you prefer one form (array or cycle) over another, you can set
688
+ ``init_printing`` with the ``perm_cyclic`` flag.
689
+
690
+ >>> from sympy import init_printing
691
+ >>> p = Permutation(1, 2)(4, 5)(3, 4)
692
+ >>> p
693
+ Permutation([0, 2, 1, 4, 5, 3])
694
+
695
+ >>> init_printing(perm_cyclic=True, pretty_print=False)
696
+ >>> p
697
+ (1 2)(3 4 5)
698
+
699
+ 2) Regardless of the setting, a list of elements in the array for cyclic
700
+ form can be obtained and either of those can be copied and supplied as
701
+ the argument to Permutation:
702
+
703
+ >>> p.array_form
704
+ [0, 2, 1, 4, 5, 3]
705
+ >>> p.cyclic_form
706
+ [[1, 2], [3, 4, 5]]
707
+ >>> Permutation(_) == p
708
+ True
709
+
710
+ 3) Printing is economical in that as little as possible is printed while
711
+ retaining all information about the size of the permutation:
712
+
713
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
714
+ >>> Permutation([1, 0, 2, 3])
715
+ Permutation([1, 0, 2, 3])
716
+ >>> Permutation([1, 0, 2, 3], size=20)
717
+ Permutation([1, 0], size=20)
718
+ >>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20)
719
+ Permutation([1, 0, 2, 4, 3], size=20)
720
+
721
+ >>> p = Permutation([1, 0, 2, 3])
722
+ >>> init_printing(perm_cyclic=True, pretty_print=False)
723
+ >>> p
724
+ (3)(0 1)
725
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
726
+
727
+ The 2 was not printed but it is still there as can be seen with the
728
+ array_form and size methods:
729
+
730
+ >>> p.array_form
731
+ [1, 0, 2, 3]
732
+ >>> p.size
733
+ 4
734
+
735
+ Short introduction to other methods
736
+ ===================================
737
+
738
+ The permutation can act as a bijective function, telling what element is
739
+ located at a given position
740
+
741
+ >>> q = Permutation([5, 2, 3, 4, 1, 0])
742
+ >>> q.array_form[1] # the hard way
743
+ 2
744
+ >>> q(1) # the easy way
745
+ 2
746
+ >>> {i: q(i) for i in range(q.size)} # showing the bijection
747
+ {0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0}
748
+
749
+ The full cyclic form (including singletons) can be obtained:
750
+
751
+ >>> p.full_cyclic_form
752
+ [[0, 1], [2], [3]]
753
+
754
+ Any permutation can be factored into transpositions of pairs of elements:
755
+
756
+ >>> Permutation([[1, 2], [3, 4, 5]]).transpositions()
757
+ [(1, 2), (3, 5), (3, 4)]
758
+ >>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form
759
+ [[1, 2], [3, 4, 5]]
760
+
761
+ The number of permutations on a set of n elements is given by n! and is
762
+ called the cardinality.
763
+
764
+ >>> p.size
765
+ 4
766
+ >>> p.cardinality
767
+ 24
768
+
769
+ A given permutation has a rank among all the possible permutations of the
770
+ same elements, but what that rank is depends on how the permutations are
771
+ enumerated. (There are a number of different methods of doing so.) The
772
+ lexicographic rank is given by the rank method and this rank is used to
773
+ increment a permutation with addition/subtraction:
774
+
775
+ >>> p.rank()
776
+ 6
777
+ >>> p + 1
778
+ Permutation([1, 0, 3, 2])
779
+ >>> p.next_lex()
780
+ Permutation([1, 0, 3, 2])
781
+ >>> _.rank()
782
+ 7
783
+ >>> p.unrank_lex(p.size, rank=7)
784
+ Permutation([1, 0, 3, 2])
785
+
786
+ The product of two permutations p and q is defined as their composition as
787
+ functions, (p*q)(i) = q(p(i)) [6]_.
788
+
789
+ >>> p = Permutation([1, 0, 2, 3])
790
+ >>> q = Permutation([2, 3, 1, 0])
791
+ >>> list(q*p)
792
+ [2, 3, 0, 1]
793
+ >>> list(p*q)
794
+ [3, 2, 1, 0]
795
+ >>> [q(p(i)) for i in range(p.size)]
796
+ [3, 2, 1, 0]
797
+
798
+ The permutation can be 'applied' to any list-like object, not only
799
+ Permutations:
800
+
801
+ >>> p(['zero', 'one', 'four', 'two'])
802
+ ['one', 'zero', 'four', 'two']
803
+ >>> p('zo42')
804
+ ['o', 'z', '4', '2']
805
+
806
+ If you have a list of arbitrary elements, the corresponding permutation
807
+ can be found with the from_sequence method:
808
+
809
+ >>> Permutation.from_sequence('SymPy')
810
+ Permutation([1, 3, 2, 0, 4])
811
+
812
+ Checking if a Permutation is contained in a Group
813
+ =================================================
814
+
815
+ Generally if you have a group of permutations G on n symbols, and
816
+ you're checking if a permutation on less than n symbols is part
817
+ of that group, the check will fail.
818
+
819
+ Here is an example for n=5 and we check if the cycle
820
+ (1,2,3) is in G:
821
+
822
+ >>> from sympy import init_printing
823
+ >>> init_printing(perm_cyclic=True, pretty_print=False)
824
+ >>> from sympy.combinatorics import Cycle, Permutation
825
+ >>> from sympy.combinatorics.perm_groups import PermutationGroup
826
+ >>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5))
827
+ >>> p1 = Permutation(Cycle(2, 5, 3))
828
+ >>> p2 = Permutation(Cycle(1, 2, 3))
829
+ >>> a1 = Permutation(Cycle(1, 2, 3).list(6))
830
+ >>> a2 = Permutation(Cycle(1, 2, 3)(5))
831
+ >>> a3 = Permutation(Cycle(1, 2, 3),size=6)
832
+ >>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p)
833
+ ((2 5 3), True)
834
+ ((1 2 3), False)
835
+ ((5)(1 2 3), True)
836
+ ((5)(1 2 3), True)
837
+ ((5)(1 2 3), True)
838
+
839
+ The check for p2 above will fail.
840
+
841
+ Checking if p1 is in G works because SymPy knows
842
+ G is a group on 5 symbols, and p1 is also on 5 symbols
843
+ (its largest element is 5).
844
+
845
+ For ``a1``, the ``.list(6)`` call will extend the permutation to 5
846
+ symbols, so the test will work as well. In the case of ``a2`` the
847
+ permutation is being extended to 5 symbols by using a singleton,
848
+ and in the case of ``a3`` it's extended through the constructor
849
+ argument ``size=6``.
850
+
851
+ There is another way to do this, which is to tell the ``contains``
852
+ method that the number of symbols the group is on does not need to
853
+ match perfectly the number of symbols for the permutation:
854
+
855
+ >>> G.contains(p2,strict=False)
856
+ True
857
+
858
+ This can be via the ``strict`` argument to the ``contains`` method,
859
+ and SymPy will try to extend the permutation on its own and then
860
+ perform the containment check.
861
+
862
+ See Also
863
+ ========
864
+
865
+ Cycle
866
+
867
+ References
868
+ ==========
869
+
870
+ .. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics
871
+ Combinatorics and Graph Theory with Mathematica. Reading, MA:
872
+ Addison-Wesley, pp. 3-16, 1990.
873
+
874
+ .. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial
875
+ Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011.
876
+
877
+ .. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking
878
+ permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001),
879
+ 281-284. DOI=10.1016/S0020-0190(01)00141-7
880
+
881
+ .. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms'
882
+ CRC Press, 1999
883
+
884
+ .. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O.
885
+ Concrete Mathematics: A Foundation for Computer Science, 2nd ed.
886
+ Reading, MA: Addison-Wesley, 1994.
887
+
888
+ .. [6] https://en.wikipedia.org/w/index.php?oldid=499948155#Product_and_inverse
889
+
890
+ .. [7] https://en.wikipedia.org/wiki/Lehmer_code
891
+
892
+ """
893
+
894
+ is_Permutation = True
895
+
896
+ _array_form = None
897
+ _cyclic_form = None
898
+ _cycle_structure = None
899
+ _size = None
900
+ _rank = None
901
+
902
+ def __new__(cls, *args, size=None, **kwargs):
903
+ """
904
+ Constructor for the Permutation object from a list or a
905
+ list of lists in which all elements of the permutation may
906
+ appear only once.
907
+
908
+ Examples
909
+ ========
910
+
911
+ >>> from sympy.combinatorics import Permutation
912
+ >>> from sympy import init_printing
913
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
914
+
915
+ Permutations entered in array-form are left unaltered:
916
+
917
+ >>> Permutation([0, 2, 1])
918
+ Permutation([0, 2, 1])
919
+
920
+ Permutations entered in cyclic form are converted to array form;
921
+ singletons need not be entered, but can be entered to indicate the
922
+ largest element:
923
+
924
+ >>> Permutation([[4, 5, 6], [0, 1]])
925
+ Permutation([1, 0, 2, 3, 5, 6, 4])
926
+ >>> Permutation([[4, 5, 6], [0, 1], [19]])
927
+ Permutation([1, 0, 2, 3, 5, 6, 4], size=20)
928
+
929
+ All manipulation of permutations assumes that the smallest element
930
+ is 0 (in keeping with 0-based indexing in Python) so if the 0 is
931
+ missing when entering a permutation in array form, an error will be
932
+ raised:
933
+
934
+ >>> Permutation([2, 1])
935
+ Traceback (most recent call last):
936
+ ...
937
+ ValueError: Integers 0 through 2 must be present.
938
+
939
+ If a permutation is entered in cyclic form, it can be entered without
940
+ singletons and the ``size`` specified so those values can be filled
941
+ in, otherwise the array form will only extend to the maximum value
942
+ in the cycles:
943
+
944
+ >>> Permutation([[1, 4], [3, 5, 2]], size=10)
945
+ Permutation([0, 4, 3, 5, 1, 2], size=10)
946
+ >>> _.array_form
947
+ [0, 4, 3, 5, 1, 2, 6, 7, 8, 9]
948
+ """
949
+ if size is not None:
950
+ size = int(size)
951
+
952
+ #a) ()
953
+ #b) (1) = identity
954
+ #c) (1, 2) = cycle
955
+ #d) ([1, 2, 3]) = array form
956
+ #e) ([[1, 2]]) = cyclic form
957
+ #f) (Cycle) = conversion to permutation
958
+ #g) (Permutation) = adjust size or return copy
959
+ ok = True
960
+ if not args: # a
961
+ return cls._af_new(list(range(size or 0)))
962
+ elif len(args) > 1: # c
963
+ return cls._af_new(Cycle(*args).list(size))
964
+ if len(args) == 1:
965
+ a = args[0]
966
+ if isinstance(a, cls): # g
967
+ if size is None or size == a.size:
968
+ return a
969
+ return cls(a.array_form, size=size)
970
+ if isinstance(a, Cycle): # f
971
+ return cls._af_new(a.list(size))
972
+ if not is_sequence(a): # b
973
+ if size is not None and a + 1 > size:
974
+ raise ValueError('size is too small when max is %s' % a)
975
+ return cls._af_new(list(range(a + 1)))
976
+ if has_variety(is_sequence(ai) for ai in a):
977
+ ok = False
978
+ else:
979
+ ok = False
980
+ if not ok:
981
+ raise ValueError("Permutation argument must be a list of ints, "
982
+ "a list of lists, Permutation or Cycle.")
983
+
984
+ # safe to assume args are valid; this also makes a copy
985
+ # of the args
986
+ args = list(args[0])
987
+
988
+ is_cycle = args and is_sequence(args[0])
989
+ if is_cycle: # e
990
+ args = [[int(i) for i in c] for c in args]
991
+ else: # d
992
+ args = [int(i) for i in args]
993
+
994
+ # if there are n elements present, 0, 1, ..., n-1 should be present
995
+ # unless a cycle notation has been provided. A 0 will be added
996
+ # for convenience in case one wants to enter permutations where
997
+ # counting starts from 1.
998
+
999
+ temp = flatten(args)
1000
+ if has_dups(temp) and not is_cycle:
1001
+ raise ValueError('there were repeated elements.')
1002
+ temp = set(temp)
1003
+
1004
+ if not is_cycle:
1005
+ if temp != set(range(len(temp))):
1006
+ raise ValueError('Integers 0 through %s must be present.' %
1007
+ max(temp))
1008
+ if size is not None and temp and max(temp) + 1 > size:
1009
+ raise ValueError('max element should not exceed %s' % (size - 1))
1010
+
1011
+ if is_cycle:
1012
+ # it's not necessarily canonical so we won't store
1013
+ # it -- use the array form instead
1014
+ c = Cycle()
1015
+ for ci in args:
1016
+ c = c(*ci)
1017
+ aform = c.list()
1018
+ else:
1019
+ aform = list(args)
1020
+ if size and size > len(aform):
1021
+ # don't allow for truncation of permutation which
1022
+ # might split a cycle and lead to an invalid aform
1023
+ # but do allow the permutation size to be increased
1024
+ aform.extend(list(range(len(aform), size)))
1025
+
1026
+ return cls._af_new(aform)
1027
+
1028
+ @classmethod
1029
+ def _af_new(cls, perm):
1030
+ """A method to produce a Permutation object from a list;
1031
+ the list is bound to the _array_form attribute, so it must
1032
+ not be modified; this method is meant for internal use only;
1033
+ the list ``a`` is supposed to be generated as a temporary value
1034
+ in a method, so p = Perm._af_new(a) is the only object
1035
+ to hold a reference to ``a``::
1036
+
1037
+ Examples
1038
+ ========
1039
+
1040
+ >>> from sympy.combinatorics.permutations import Perm
1041
+ >>> from sympy import init_printing
1042
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
1043
+ >>> a = [2, 1, 3, 0]
1044
+ >>> p = Perm._af_new(a)
1045
+ >>> p
1046
+ Permutation([2, 1, 3, 0])
1047
+
1048
+ """
1049
+ p = super().__new__(cls)
1050
+ p._array_form = perm
1051
+ p._size = len(perm)
1052
+ return p
1053
+
1054
+ def copy(self):
1055
+ return self.__class__(self.array_form)
1056
+
1057
+ def __getnewargs__(self):
1058
+ return (self.array_form,)
1059
+
1060
+ def _hashable_content(self):
1061
+ # the array_form (a list) is the Permutation arg, so we need to
1062
+ # return a tuple, instead
1063
+ return tuple(self.array_form)
1064
+
1065
+ @property
1066
+ def array_form(self):
1067
+ """
1068
+ Return a copy of the attribute _array_form
1069
+ Examples
1070
+ ========
1071
+
1072
+ >>> from sympy.combinatorics import Permutation
1073
+ >>> p = Permutation([[2, 0], [3, 1]])
1074
+ >>> p.array_form
1075
+ [2, 3, 0, 1]
1076
+ >>> Permutation([[2, 0, 3, 1]]).array_form
1077
+ [3, 2, 0, 1]
1078
+ >>> Permutation([2, 0, 3, 1]).array_form
1079
+ [2, 0, 3, 1]
1080
+ >>> Permutation([[1, 2], [4, 5]]).array_form
1081
+ [0, 2, 1, 3, 5, 4]
1082
+ """
1083
+ return self._array_form[:]
1084
+
1085
+ def list(self, size=None):
1086
+ """Return the permutation as an explicit list, possibly
1087
+ trimming unmoved elements if size is less than the maximum
1088
+ element in the permutation; if this is desired, setting
1089
+ ``size=-1`` will guarantee such trimming.
1090
+
1091
+ Examples
1092
+ ========
1093
+
1094
+ >>> from sympy.combinatorics import Permutation
1095
+ >>> p = Permutation(2, 3)(4, 5)
1096
+ >>> p.list()
1097
+ [0, 1, 3, 2, 5, 4]
1098
+ >>> p.list(10)
1099
+ [0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
1100
+
1101
+ Passing a length too small will trim trailing, unchanged elements
1102
+ in the permutation:
1103
+
1104
+ >>> Permutation(2, 4)(1, 2, 4).list(-1)
1105
+ [0, 2, 1]
1106
+ >>> Permutation(3).list(-1)
1107
+ []
1108
+ """
1109
+ if not self and size is None:
1110
+ raise ValueError('must give size for empty Cycle')
1111
+ rv = self.array_form
1112
+ if size is not None:
1113
+ if size > self.size:
1114
+ rv.extend(list(range(self.size, size)))
1115
+ else:
1116
+ # find first value from rhs where rv[i] != i
1117
+ i = self.size - 1
1118
+ while rv:
1119
+ if rv[-1] != i:
1120
+ break
1121
+ rv.pop()
1122
+ i -= 1
1123
+ return rv
1124
+
1125
+ @property
1126
+ def cyclic_form(self):
1127
+ """
1128
+ This is used to convert to the cyclic notation
1129
+ from the canonical notation. Singletons are omitted.
1130
+
1131
+ Examples
1132
+ ========
1133
+
1134
+ >>> from sympy.combinatorics import Permutation
1135
+ >>> p = Permutation([0, 3, 1, 2])
1136
+ >>> p.cyclic_form
1137
+ [[1, 3, 2]]
1138
+ >>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form
1139
+ [[0, 1], [3, 4]]
1140
+
1141
+ See Also
1142
+ ========
1143
+
1144
+ array_form, full_cyclic_form
1145
+ """
1146
+ if self._cyclic_form is not None:
1147
+ return list(self._cyclic_form)
1148
+ array_form = self.array_form
1149
+ unchecked = [True] * len(array_form)
1150
+ cyclic_form = []
1151
+ for i in range(len(array_form)):
1152
+ if unchecked[i]:
1153
+ cycle = []
1154
+ cycle.append(i)
1155
+ unchecked[i] = False
1156
+ j = i
1157
+ while unchecked[array_form[j]]:
1158
+ j = array_form[j]
1159
+ cycle.append(j)
1160
+ unchecked[j] = False
1161
+ if len(cycle) > 1:
1162
+ cyclic_form.append(cycle)
1163
+ assert cycle == list(minlex(cycle))
1164
+ cyclic_form.sort()
1165
+ self._cyclic_form = cyclic_form[:]
1166
+ return cyclic_form
1167
+
1168
+ @property
1169
+ def full_cyclic_form(self):
1170
+ """Return permutation in cyclic form including singletons.
1171
+
1172
+ Examples
1173
+ ========
1174
+
1175
+ >>> from sympy.combinatorics import Permutation
1176
+ >>> Permutation([0, 2, 1]).full_cyclic_form
1177
+ [[0], [1, 2]]
1178
+ """
1179
+ need = set(range(self.size)) - set(flatten(self.cyclic_form))
1180
+ rv = self.cyclic_form + [[i] for i in need]
1181
+ rv.sort()
1182
+ return rv
1183
+
1184
+ @property
1185
+ def size(self):
1186
+ """
1187
+ Returns the number of elements in the permutation.
1188
+
1189
+ Examples
1190
+ ========
1191
+
1192
+ >>> from sympy.combinatorics import Permutation
1193
+ >>> Permutation([[3, 2], [0, 1]]).size
1194
+ 4
1195
+
1196
+ See Also
1197
+ ========
1198
+
1199
+ cardinality, length, order, rank
1200
+ """
1201
+ return self._size
1202
+
1203
+ def support(self):
1204
+ """Return the elements in permutation, P, for which P[i] != i.
1205
+
1206
+ Examples
1207
+ ========
1208
+
1209
+ >>> from sympy.combinatorics import Permutation
1210
+ >>> p = Permutation([[3, 2], [0, 1], [4]])
1211
+ >>> p.array_form
1212
+ [1, 0, 3, 2, 4]
1213
+ >>> p.support()
1214
+ [0, 1, 2, 3]
1215
+ """
1216
+ a = self.array_form
1217
+ return [i for i, e in enumerate(a) if a[i] != i]
1218
+
1219
+ def __add__(self, other):
1220
+ """Return permutation that is other higher in rank than self.
1221
+
1222
+ The rank is the lexicographical rank, with the identity permutation
1223
+ having rank of 0.
1224
+
1225
+ Examples
1226
+ ========
1227
+
1228
+ >>> from sympy.combinatorics import Permutation
1229
+ >>> I = Permutation([0, 1, 2, 3])
1230
+ >>> a = Permutation([2, 1, 3, 0])
1231
+ >>> I + a.rank() == a
1232
+ True
1233
+
1234
+ See Also
1235
+ ========
1236
+
1237
+ __sub__, inversion_vector
1238
+
1239
+ """
1240
+ rank = (self.rank() + other) % self.cardinality
1241
+ rv = self.unrank_lex(self.size, rank)
1242
+ rv._rank = rank
1243
+ return rv
1244
+
1245
+ def __sub__(self, other):
1246
+ """Return the permutation that is other lower in rank than self.
1247
+
1248
+ See Also
1249
+ ========
1250
+
1251
+ __add__
1252
+ """
1253
+ return self.__add__(-other)
1254
+
1255
+ @staticmethod
1256
+ def rmul(*args):
1257
+ """
1258
+ Return product of Permutations [a, b, c, ...] as the Permutation whose
1259
+ ith value is a(b(c(i))).
1260
+
1261
+ a, b, c, ... can be Permutation objects or tuples.
1262
+
1263
+ Examples
1264
+ ========
1265
+
1266
+ >>> from sympy.combinatorics import Permutation
1267
+
1268
+ >>> a, b = [1, 0, 2], [0, 2, 1]
1269
+ >>> a = Permutation(a); b = Permutation(b)
1270
+ >>> list(Permutation.rmul(a, b))
1271
+ [1, 2, 0]
1272
+ >>> [a(b(i)) for i in range(3)]
1273
+ [1, 2, 0]
1274
+
1275
+ This handles the operands in reverse order compared to the ``*`` operator:
1276
+
1277
+ >>> a = Permutation(a); b = Permutation(b)
1278
+ >>> list(a*b)
1279
+ [2, 0, 1]
1280
+ >>> [b(a(i)) for i in range(3)]
1281
+ [2, 0, 1]
1282
+
1283
+ Notes
1284
+ =====
1285
+
1286
+ All items in the sequence will be parsed by Permutation as
1287
+ necessary as long as the first item is a Permutation:
1288
+
1289
+ >>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b)
1290
+ True
1291
+
1292
+ The reverse order of arguments will raise a TypeError.
1293
+
1294
+ """
1295
+ rv = args[0]
1296
+ for i in range(1, len(args)):
1297
+ rv = args[i]*rv
1298
+ return rv
1299
+
1300
+ @classmethod
1301
+ def rmul_with_af(cls, *args):
1302
+ """
1303
+ same as rmul, but the elements of args are Permutation objects
1304
+ which have _array_form
1305
+ """
1306
+ a = [x._array_form for x in args]
1307
+ rv = cls._af_new(_af_rmuln(*a))
1308
+ return rv
1309
+
1310
+ def mul_inv(self, other):
1311
+ """
1312
+ other*~self, self and other have _array_form
1313
+ """
1314
+ a = _af_invert(self._array_form)
1315
+ b = other._array_form
1316
+ return self._af_new(_af_rmul(a, b))
1317
+
1318
+ def __rmul__(self, other):
1319
+ """This is needed to coerce other to Permutation in rmul."""
1320
+ cls = type(self)
1321
+ return cls(other)*self
1322
+
1323
+ def __mul__(self, other):
1324
+ """
1325
+ Return the product a*b as a Permutation; the ith value is b(a(i)).
1326
+
1327
+ Examples
1328
+ ========
1329
+
1330
+ >>> from sympy.combinatorics.permutations import _af_rmul, Permutation
1331
+
1332
+ >>> a, b = [1, 0, 2], [0, 2, 1]
1333
+ >>> a = Permutation(a); b = Permutation(b)
1334
+ >>> list(a*b)
1335
+ [2, 0, 1]
1336
+ >>> [b(a(i)) for i in range(3)]
1337
+ [2, 0, 1]
1338
+
1339
+ This handles operands in reverse order compared to _af_rmul and rmul:
1340
+
1341
+ >>> al = list(a); bl = list(b)
1342
+ >>> _af_rmul(al, bl)
1343
+ [1, 2, 0]
1344
+ >>> [al[bl[i]] for i in range(3)]
1345
+ [1, 2, 0]
1346
+
1347
+ It is acceptable for the arrays to have different lengths; the shorter
1348
+ one will be padded to match the longer one:
1349
+
1350
+ >>> from sympy import init_printing
1351
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
1352
+ >>> b*Permutation([1, 0])
1353
+ Permutation([1, 2, 0])
1354
+ >>> Permutation([1, 0])*b
1355
+ Permutation([2, 0, 1])
1356
+
1357
+ It is also acceptable to allow coercion to handle conversion of a
1358
+ single list to the left of a Permutation:
1359
+
1360
+ >>> [0, 1]*a # no change: 2-element identity
1361
+ Permutation([1, 0, 2])
1362
+ >>> [[0, 1]]*a # exchange first two elements
1363
+ Permutation([0, 1, 2])
1364
+
1365
+ You cannot use more than 1 cycle notation in a product of cycles
1366
+ since coercion can only handle one argument to the left. To handle
1367
+ multiple cycles it is convenient to use Cycle instead of Permutation:
1368
+
1369
+ >>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP
1370
+ >>> from sympy.combinatorics.permutations import Cycle
1371
+ >>> Cycle(1, 2)(2, 3)
1372
+ (1 3 2)
1373
+
1374
+ """
1375
+ from sympy.combinatorics.perm_groups import PermutationGroup, Coset
1376
+ if isinstance(other, PermutationGroup):
1377
+ return Coset(self, other, dir='-')
1378
+ a = self.array_form
1379
+ # __rmul__ makes sure the other is a Permutation
1380
+ b = other.array_form
1381
+ if not b:
1382
+ perm = a
1383
+ else:
1384
+ b.extend(list(range(len(b), len(a))))
1385
+ perm = [b[i] for i in a] + b[len(a):]
1386
+ return self._af_new(perm)
1387
+
1388
+ def commutes_with(self, other):
1389
+ """
1390
+ Checks if the elements are commuting.
1391
+
1392
+ Examples
1393
+ ========
1394
+
1395
+ >>> from sympy.combinatorics import Permutation
1396
+ >>> a = Permutation([1, 4, 3, 0, 2, 5])
1397
+ >>> b = Permutation([0, 1, 2, 3, 4, 5])
1398
+ >>> a.commutes_with(b)
1399
+ True
1400
+ >>> b = Permutation([2, 3, 5, 4, 1, 0])
1401
+ >>> a.commutes_with(b)
1402
+ False
1403
+ """
1404
+ a = self.array_form
1405
+ b = other.array_form
1406
+ return _af_commutes_with(a, b)
1407
+
1408
+ def __pow__(self, n):
1409
+ """
1410
+ Routine for finding powers of a permutation.
1411
+
1412
+ Examples
1413
+ ========
1414
+
1415
+ >>> from sympy.combinatorics import Permutation
1416
+ >>> from sympy import init_printing
1417
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
1418
+ >>> p = Permutation([2, 0, 3, 1])
1419
+ >>> p.order()
1420
+ 4
1421
+ >>> p**4
1422
+ Permutation([0, 1, 2, 3])
1423
+ """
1424
+ if isinstance(n, Permutation):
1425
+ raise NotImplementedError(
1426
+ 'p**p is not defined; do you mean p^p (conjugate)?')
1427
+ n = int(n)
1428
+ return self._af_new(_af_pow(self.array_form, n))
1429
+
1430
+ def __rxor__(self, i):
1431
+ """Return self(i) when ``i`` is an int.
1432
+
1433
+ Examples
1434
+ ========
1435
+
1436
+ >>> from sympy.combinatorics import Permutation
1437
+ >>> p = Permutation(1, 2, 9)
1438
+ >>> 2^p == p(2) == 9
1439
+ True
1440
+ """
1441
+ if int_valued(i):
1442
+ return self(i)
1443
+ else:
1444
+ raise NotImplementedError(
1445
+ "i^p = p(i) when i is an integer, not %s." % i)
1446
+
1447
+ def __xor__(self, h):
1448
+ """Return the conjugate permutation ``~h*self*h` `.
1449
+
1450
+ Explanation
1451
+ ===========
1452
+
1453
+ If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and
1454
+ ``b = ~h*a*h`` and both have the same cycle structure.
1455
+
1456
+ Examples
1457
+ ========
1458
+
1459
+ >>> from sympy.combinatorics import Permutation
1460
+ >>> p = Permutation(1, 2, 9)
1461
+ >>> q = Permutation(6, 9, 8)
1462
+ >>> p*q != q*p
1463
+ True
1464
+
1465
+ Calculate and check properties of the conjugate:
1466
+
1467
+ >>> c = p^q
1468
+ >>> c == ~q*p*q and p == q*c*~q
1469
+ True
1470
+
1471
+ The expression q^p^r is equivalent to q^(p*r):
1472
+
1473
+ >>> r = Permutation(9)(4, 6, 8)
1474
+ >>> q^p^r == q^(p*r)
1475
+ True
1476
+
1477
+ If the term to the left of the conjugate operator, i, is an integer
1478
+ then this is interpreted as selecting the ith element from the
1479
+ permutation to the right:
1480
+
1481
+ >>> all(i^p == p(i) for i in range(p.size))
1482
+ True
1483
+
1484
+ Note that the * operator as higher precedence than the ^ operator:
1485
+
1486
+ >>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4)
1487
+ True
1488
+
1489
+ Notes
1490
+ =====
1491
+
1492
+ In Python the precedence rule is p^q^r = (p^q)^r which differs
1493
+ in general from p^(q^r)
1494
+
1495
+ >>> q^p^r
1496
+ (9)(1 4 8)
1497
+ >>> q^(p^r)
1498
+ (9)(1 8 6)
1499
+
1500
+ For a given r and p, both of the following are conjugates of p:
1501
+ ~r*p*r and r*p*~r. But these are not necessarily the same:
1502
+
1503
+ >>> ~r*p*r == r*p*~r
1504
+ True
1505
+
1506
+ >>> p = Permutation(1, 2, 9)(5, 6)
1507
+ >>> ~r*p*r == r*p*~r
1508
+ False
1509
+
1510
+ The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent
1511
+ to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to
1512
+ this method:
1513
+
1514
+ >>> p^~r == r*p*~r
1515
+ True
1516
+ """
1517
+
1518
+ if self.size != h.size:
1519
+ raise ValueError("The permutations must be of equal size.")
1520
+ a = [None]*self.size
1521
+ h = h._array_form
1522
+ p = self._array_form
1523
+ for i in range(self.size):
1524
+ a[h[i]] = h[p[i]]
1525
+ return self._af_new(a)
1526
+
1527
+ def transpositions(self):
1528
+ """
1529
+ Return the permutation decomposed into a list of transpositions.
1530
+
1531
+ Explanation
1532
+ ===========
1533
+
1534
+ It is always possible to express a permutation as the product of
1535
+ transpositions, see [1]
1536
+
1537
+ Examples
1538
+ ========
1539
+
1540
+ >>> from sympy.combinatorics import Permutation
1541
+ >>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]])
1542
+ >>> t = p.transpositions()
1543
+ >>> t
1544
+ [(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)]
1545
+ >>> print(''.join(str(c) for c in t))
1546
+ (0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2)
1547
+ >>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p
1548
+ True
1549
+
1550
+ References
1551
+ ==========
1552
+
1553
+ .. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties
1554
+
1555
+ """
1556
+ a = self.cyclic_form
1557
+ res = []
1558
+ for x in a:
1559
+ nx = len(x)
1560
+ if nx == 2:
1561
+ res.append(tuple(x))
1562
+ elif nx > 2:
1563
+ first = x[0]
1564
+ for y in x[nx - 1:0:-1]:
1565
+ res.append((first, y))
1566
+ return res
1567
+
1568
+ @classmethod
1569
+ def from_sequence(self, i, key=None):
1570
+ """Return the permutation needed to obtain ``i`` from the sorted
1571
+ elements of ``i``. If custom sorting is desired, a key can be given.
1572
+
1573
+ Examples
1574
+ ========
1575
+
1576
+ >>> from sympy.combinatorics import Permutation
1577
+
1578
+ >>> Permutation.from_sequence('SymPy')
1579
+ (4)(0 1 3)
1580
+ >>> _(sorted("SymPy"))
1581
+ ['S', 'y', 'm', 'P', 'y']
1582
+ >>> Permutation.from_sequence('SymPy', key=lambda x: x.lower())
1583
+ (4)(0 2)(1 3)
1584
+ """
1585
+ ic = list(zip(i, list(range(len(i)))))
1586
+ if key:
1587
+ ic.sort(key=lambda x: key(x[0]))
1588
+ else:
1589
+ ic.sort()
1590
+ return ~Permutation([i[1] for i in ic])
1591
+
1592
+ def __invert__(self):
1593
+ """
1594
+ Return the inverse of the permutation.
1595
+
1596
+ A permutation multiplied by its inverse is the identity permutation.
1597
+
1598
+ Examples
1599
+ ========
1600
+
1601
+ >>> from sympy.combinatorics import Permutation
1602
+ >>> from sympy import init_printing
1603
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
1604
+ >>> p = Permutation([[2, 0], [3, 1]])
1605
+ >>> ~p
1606
+ Permutation([2, 3, 0, 1])
1607
+ >>> _ == p**-1
1608
+ True
1609
+ >>> p*~p == ~p*p == Permutation([0, 1, 2, 3])
1610
+ True
1611
+ """
1612
+ return self._af_new(_af_invert(self._array_form))
1613
+
1614
+ def __iter__(self):
1615
+ """Yield elements from array form.
1616
+
1617
+ Examples
1618
+ ========
1619
+
1620
+ >>> from sympy.combinatorics import Permutation
1621
+ >>> list(Permutation(range(3)))
1622
+ [0, 1, 2]
1623
+ """
1624
+ yield from self.array_form
1625
+
1626
+ def __repr__(self):
1627
+ return srepr(self)
1628
+
1629
+ def __call__(self, *i):
1630
+ """
1631
+ Allows applying a permutation instance as a bijective function.
1632
+
1633
+ Examples
1634
+ ========
1635
+
1636
+ >>> from sympy.combinatorics import Permutation
1637
+ >>> p = Permutation([[2, 0], [3, 1]])
1638
+ >>> p.array_form
1639
+ [2, 3, 0, 1]
1640
+ >>> [p(i) for i in range(4)]
1641
+ [2, 3, 0, 1]
1642
+
1643
+ If an array is given then the permutation selects the items
1644
+ from the array (i.e. the permutation is applied to the array):
1645
+
1646
+ >>> from sympy.abc import x
1647
+ >>> p([x, 1, 0, x**2])
1648
+ [0, x**2, x, 1]
1649
+ """
1650
+ # list indices can be Integer or int; leave this
1651
+ # as it is (don't test or convert it) because this
1652
+ # gets called a lot and should be fast
1653
+ if len(i) == 1:
1654
+ i = i[0]
1655
+ if not isinstance(i, Iterable):
1656
+ i = as_int(i)
1657
+ if i < 0 or i > self.size:
1658
+ raise TypeError(
1659
+ "{} should be an integer between 0 and {}"
1660
+ .format(i, self.size-1))
1661
+ return self._array_form[i]
1662
+ # P([a, b, c])
1663
+ if len(i) != self.size:
1664
+ raise TypeError(
1665
+ "{} should have the length {}.".format(i, self.size))
1666
+ return [i[j] for j in self._array_form]
1667
+ # P(1, 2, 3)
1668
+ return self*Permutation(Cycle(*i), size=self.size)
1669
+
1670
+ def atoms(self):
1671
+ """
1672
+ Returns all the elements of a permutation
1673
+
1674
+ Examples
1675
+ ========
1676
+
1677
+ >>> from sympy.combinatorics import Permutation
1678
+ >>> Permutation([0, 1, 2, 3, 4, 5]).atoms()
1679
+ {0, 1, 2, 3, 4, 5}
1680
+ >>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms()
1681
+ {0, 1, 2, 3, 4, 5}
1682
+ """
1683
+ return set(self.array_form)
1684
+
1685
+ def apply(self, i):
1686
+ r"""Apply the permutation to an expression.
1687
+
1688
+ Parameters
1689
+ ==========
1690
+
1691
+ i : Expr
1692
+ It should be an integer between $0$ and $n-1$ where $n$
1693
+ is the size of the permutation.
1694
+
1695
+ If it is a symbol or a symbolic expression that can
1696
+ have integer values, an ``AppliedPermutation`` object
1697
+ will be returned which can represent an unevaluated
1698
+ function.
1699
+
1700
+ Notes
1701
+ =====
1702
+
1703
+ Any permutation can be defined as a bijective function
1704
+ $\sigma : \{ 0, 1, \dots, n-1 \} \rightarrow \{ 0, 1, \dots, n-1 \}$
1705
+ where $n$ denotes the size of the permutation.
1706
+
1707
+ The definition may even be extended for any set with distinctive
1708
+ elements, such that the permutation can even be applied for
1709
+ real numbers or such, however, it is not implemented for now for
1710
+ computational reasons and the integrity with the group theory
1711
+ module.
1712
+
1713
+ This function is similar to the ``__call__`` magic, however,
1714
+ ``__call__`` magic already has some other applications like
1715
+ permuting an array or attaching new cycles, which would
1716
+ not always be mathematically consistent.
1717
+
1718
+ This also guarantees that the return type is a SymPy integer,
1719
+ which guarantees the safety to use assumptions.
1720
+ """
1721
+ i = _sympify(i)
1722
+ if i.is_integer is False:
1723
+ raise NotImplementedError("{} should be an integer.".format(i))
1724
+
1725
+ n = self.size
1726
+ if (i < 0) == True or (i >= n) == True:
1727
+ raise NotImplementedError(
1728
+ "{} should be an integer between 0 and {}".format(i, n-1))
1729
+
1730
+ if i.is_Integer:
1731
+ return Integer(self._array_form[i])
1732
+ return AppliedPermutation(self, i)
1733
+
1734
+ def next_lex(self):
1735
+ """
1736
+ Returns the next permutation in lexicographical order.
1737
+ If self is the last permutation in lexicographical order
1738
+ it returns None.
1739
+ See [4] section 2.4.
1740
+
1741
+
1742
+ Examples
1743
+ ========
1744
+
1745
+ >>> from sympy.combinatorics import Permutation
1746
+ >>> p = Permutation([2, 3, 1, 0])
1747
+ >>> p = Permutation([2, 3, 1, 0]); p.rank()
1748
+ 17
1749
+ >>> p = p.next_lex(); p.rank()
1750
+ 18
1751
+
1752
+ See Also
1753
+ ========
1754
+
1755
+ rank, unrank_lex
1756
+ """
1757
+ perm = self.array_form[:]
1758
+ n = len(perm)
1759
+ i = n - 2
1760
+ while perm[i + 1] < perm[i]:
1761
+ i -= 1
1762
+ if i == -1:
1763
+ return None
1764
+ else:
1765
+ j = n - 1
1766
+ while perm[j] < perm[i]:
1767
+ j -= 1
1768
+ perm[j], perm[i] = perm[i], perm[j]
1769
+ i += 1
1770
+ j = n - 1
1771
+ while i < j:
1772
+ perm[j], perm[i] = perm[i], perm[j]
1773
+ i += 1
1774
+ j -= 1
1775
+ return self._af_new(perm)
1776
+
1777
+ @classmethod
1778
+ def unrank_nonlex(self, n, r):
1779
+ """
1780
+ This is a linear time unranking algorithm that does not
1781
+ respect lexicographic order [3].
1782
+
1783
+ Examples
1784
+ ========
1785
+
1786
+ >>> from sympy.combinatorics import Permutation
1787
+ >>> from sympy import init_printing
1788
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
1789
+ >>> Permutation.unrank_nonlex(4, 5)
1790
+ Permutation([2, 0, 3, 1])
1791
+ >>> Permutation.unrank_nonlex(4, -1)
1792
+ Permutation([0, 1, 2, 3])
1793
+
1794
+ See Also
1795
+ ========
1796
+
1797
+ next_nonlex, rank_nonlex
1798
+ """
1799
+ def _unrank1(n, r, a):
1800
+ if n > 0:
1801
+ a[n - 1], a[r % n] = a[r % n], a[n - 1]
1802
+ _unrank1(n - 1, r//n, a)
1803
+
1804
+ id_perm = list(range(n))
1805
+ n = int(n)
1806
+ r = r % ifac(n)
1807
+ _unrank1(n, r, id_perm)
1808
+ return self._af_new(id_perm)
1809
+
1810
+ def rank_nonlex(self, inv_perm=None):
1811
+ """
1812
+ This is a linear time ranking algorithm that does not
1813
+ enforce lexicographic order [3].
1814
+
1815
+
1816
+ Examples
1817
+ ========
1818
+
1819
+ >>> from sympy.combinatorics import Permutation
1820
+ >>> p = Permutation([0, 1, 2, 3])
1821
+ >>> p.rank_nonlex()
1822
+ 23
1823
+
1824
+ See Also
1825
+ ========
1826
+
1827
+ next_nonlex, unrank_nonlex
1828
+ """
1829
+ def _rank1(n, perm, inv_perm):
1830
+ if n == 1:
1831
+ return 0
1832
+ s = perm[n - 1]
1833
+ t = inv_perm[n - 1]
1834
+ perm[n - 1], perm[t] = perm[t], s
1835
+ inv_perm[n - 1], inv_perm[s] = inv_perm[s], t
1836
+ return s + n*_rank1(n - 1, perm, inv_perm)
1837
+
1838
+ if inv_perm is None:
1839
+ inv_perm = (~self).array_form
1840
+ if not inv_perm:
1841
+ return 0
1842
+ perm = self.array_form[:]
1843
+ r = _rank1(len(perm), perm, inv_perm)
1844
+ return r
1845
+
1846
+ def next_nonlex(self):
1847
+ """
1848
+ Returns the next permutation in nonlex order [3].
1849
+ If self is the last permutation in this order it returns None.
1850
+
1851
+ Examples
1852
+ ========
1853
+
1854
+ >>> from sympy.combinatorics import Permutation
1855
+ >>> from sympy import init_printing
1856
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
1857
+ >>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex()
1858
+ 5
1859
+ >>> p = p.next_nonlex(); p
1860
+ Permutation([3, 0, 1, 2])
1861
+ >>> p.rank_nonlex()
1862
+ 6
1863
+
1864
+ See Also
1865
+ ========
1866
+
1867
+ rank_nonlex, unrank_nonlex
1868
+ """
1869
+ r = self.rank_nonlex()
1870
+ if r == ifac(self.size) - 1:
1871
+ return None
1872
+ return self.unrank_nonlex(self.size, r + 1)
1873
+
1874
+ def rank(self):
1875
+ """
1876
+ Returns the lexicographic rank of the permutation.
1877
+
1878
+ Examples
1879
+ ========
1880
+
1881
+ >>> from sympy.combinatorics import Permutation
1882
+ >>> p = Permutation([0, 1, 2, 3])
1883
+ >>> p.rank()
1884
+ 0
1885
+ >>> p = Permutation([3, 2, 1, 0])
1886
+ >>> p.rank()
1887
+ 23
1888
+
1889
+ See Also
1890
+ ========
1891
+
1892
+ next_lex, unrank_lex, cardinality, length, order, size
1893
+ """
1894
+ if self._rank is not None:
1895
+ return self._rank
1896
+ rank = 0
1897
+ rho = self.array_form[:]
1898
+ n = self.size - 1
1899
+ size = n + 1
1900
+ psize = int(ifac(n))
1901
+ for j in range(size - 1):
1902
+ rank += rho[j]*psize
1903
+ for i in range(j + 1, size):
1904
+ if rho[i] > rho[j]:
1905
+ rho[i] -= 1
1906
+ psize //= n
1907
+ n -= 1
1908
+ self._rank = rank
1909
+ return rank
1910
+
1911
+ @property
1912
+ def cardinality(self):
1913
+ """
1914
+ Returns the number of all possible permutations.
1915
+
1916
+ Examples
1917
+ ========
1918
+
1919
+ >>> from sympy.combinatorics import Permutation
1920
+ >>> p = Permutation([0, 1, 2, 3])
1921
+ >>> p.cardinality
1922
+ 24
1923
+
1924
+ See Also
1925
+ ========
1926
+
1927
+ length, order, rank, size
1928
+ """
1929
+ return int(ifac(self.size))
1930
+
1931
+ def parity(self):
1932
+ """
1933
+ Computes the parity of a permutation.
1934
+
1935
+ Explanation
1936
+ ===========
1937
+
1938
+ The parity of a permutation reflects the parity of the
1939
+ number of inversions in the permutation, i.e., the
1940
+ number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``.
1941
+
1942
+ Examples
1943
+ ========
1944
+
1945
+ >>> from sympy.combinatorics import Permutation
1946
+ >>> p = Permutation([0, 1, 2, 3])
1947
+ >>> p.parity()
1948
+ 0
1949
+ >>> p = Permutation([3, 2, 0, 1])
1950
+ >>> p.parity()
1951
+ 1
1952
+
1953
+ See Also
1954
+ ========
1955
+
1956
+ _af_parity
1957
+ """
1958
+ if self._cyclic_form is not None:
1959
+ return (self.size - self.cycles) % 2
1960
+
1961
+ return _af_parity(self.array_form)
1962
+
1963
+ @property
1964
+ def is_even(self):
1965
+ """
1966
+ Checks if a permutation is even.
1967
+
1968
+ Examples
1969
+ ========
1970
+
1971
+ >>> from sympy.combinatorics import Permutation
1972
+ >>> p = Permutation([0, 1, 2, 3])
1973
+ >>> p.is_even
1974
+ True
1975
+ >>> p = Permutation([3, 2, 1, 0])
1976
+ >>> p.is_even
1977
+ True
1978
+
1979
+ See Also
1980
+ ========
1981
+
1982
+ is_odd
1983
+ """
1984
+ return not self.is_odd
1985
+
1986
+ @property
1987
+ def is_odd(self):
1988
+ """
1989
+ Checks if a permutation is odd.
1990
+
1991
+ Examples
1992
+ ========
1993
+
1994
+ >>> from sympy.combinatorics import Permutation
1995
+ >>> p = Permutation([0, 1, 2, 3])
1996
+ >>> p.is_odd
1997
+ False
1998
+ >>> p = Permutation([3, 2, 0, 1])
1999
+ >>> p.is_odd
2000
+ True
2001
+
2002
+ See Also
2003
+ ========
2004
+
2005
+ is_even
2006
+ """
2007
+ return bool(self.parity() % 2)
2008
+
2009
+ @property
2010
+ def is_Singleton(self):
2011
+ """
2012
+ Checks to see if the permutation contains only one number and is
2013
+ thus the only possible permutation of this set of numbers
2014
+
2015
+ Examples
2016
+ ========
2017
+
2018
+ >>> from sympy.combinatorics import Permutation
2019
+ >>> Permutation([0]).is_Singleton
2020
+ True
2021
+ >>> Permutation([0, 1]).is_Singleton
2022
+ False
2023
+
2024
+ See Also
2025
+ ========
2026
+
2027
+ is_Empty
2028
+ """
2029
+ return self.size == 1
2030
+
2031
+ @property
2032
+ def is_Empty(self):
2033
+ """
2034
+ Checks to see if the permutation is a set with zero elements
2035
+
2036
+ Examples
2037
+ ========
2038
+
2039
+ >>> from sympy.combinatorics import Permutation
2040
+ >>> Permutation([]).is_Empty
2041
+ True
2042
+ >>> Permutation([0]).is_Empty
2043
+ False
2044
+
2045
+ See Also
2046
+ ========
2047
+
2048
+ is_Singleton
2049
+ """
2050
+ return self.size == 0
2051
+
2052
+ @property
2053
+ def is_identity(self):
2054
+ return self.is_Identity
2055
+
2056
+ @property
2057
+ def is_Identity(self):
2058
+ """
2059
+ Returns True if the Permutation is an identity permutation.
2060
+
2061
+ Examples
2062
+ ========
2063
+
2064
+ >>> from sympy.combinatorics import Permutation
2065
+ >>> p = Permutation([])
2066
+ >>> p.is_Identity
2067
+ True
2068
+ >>> p = Permutation([[0], [1], [2]])
2069
+ >>> p.is_Identity
2070
+ True
2071
+ >>> p = Permutation([0, 1, 2])
2072
+ >>> p.is_Identity
2073
+ True
2074
+ >>> p = Permutation([0, 2, 1])
2075
+ >>> p.is_Identity
2076
+ False
2077
+
2078
+ See Also
2079
+ ========
2080
+
2081
+ order
2082
+ """
2083
+ af = self.array_form
2084
+ return not af or all(i == af[i] for i in range(self.size))
2085
+
2086
+ def ascents(self):
2087
+ """
2088
+ Returns the positions of ascents in a permutation, ie, the location
2089
+ where p[i] < p[i+1]
2090
+
2091
+ Examples
2092
+ ========
2093
+
2094
+ >>> from sympy.combinatorics import Permutation
2095
+ >>> p = Permutation([4, 0, 1, 3, 2])
2096
+ >>> p.ascents()
2097
+ [1, 2]
2098
+
2099
+ See Also
2100
+ ========
2101
+
2102
+ descents, inversions, min, max
2103
+ """
2104
+ a = self.array_form
2105
+ pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]]
2106
+ return pos
2107
+
2108
+ def descents(self):
2109
+ """
2110
+ Returns the positions of descents in a permutation, ie, the location
2111
+ where p[i] > p[i+1]
2112
+
2113
+ Examples
2114
+ ========
2115
+
2116
+ >>> from sympy.combinatorics import Permutation
2117
+ >>> p = Permutation([4, 0, 1, 3, 2])
2118
+ >>> p.descents()
2119
+ [0, 3]
2120
+
2121
+ See Also
2122
+ ========
2123
+
2124
+ ascents, inversions, min, max
2125
+ """
2126
+ a = self.array_form
2127
+ pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]]
2128
+ return pos
2129
+
2130
+ def max(self) -> int:
2131
+ """
2132
+ The maximum element moved by the permutation.
2133
+
2134
+ Examples
2135
+ ========
2136
+
2137
+ >>> from sympy.combinatorics import Permutation
2138
+ >>> p = Permutation([1, 0, 2, 3, 4])
2139
+ >>> p.max()
2140
+ 1
2141
+
2142
+ See Also
2143
+ ========
2144
+
2145
+ min, descents, ascents, inversions
2146
+ """
2147
+ a = self.array_form
2148
+ if not a:
2149
+ return 0
2150
+ return max(_a for i, _a in enumerate(a) if _a != i)
2151
+
2152
+ def min(self) -> int:
2153
+ """
2154
+ The minimum element moved by the permutation.
2155
+
2156
+ Examples
2157
+ ========
2158
+
2159
+ >>> from sympy.combinatorics import Permutation
2160
+ >>> p = Permutation([0, 1, 4, 3, 2])
2161
+ >>> p.min()
2162
+ 2
2163
+
2164
+ See Also
2165
+ ========
2166
+
2167
+ max, descents, ascents, inversions
2168
+ """
2169
+ a = self.array_form
2170
+ if not a:
2171
+ return 0
2172
+ return min(_a for i, _a in enumerate(a) if _a != i)
2173
+
2174
+ def inversions(self):
2175
+ """
2176
+ Computes the number of inversions of a permutation.
2177
+
2178
+ Explanation
2179
+ ===========
2180
+
2181
+ An inversion is where i > j but p[i] < p[j].
2182
+
2183
+ For small length of p, it iterates over all i and j
2184
+ values and calculates the number of inversions.
2185
+ For large length of p, it uses a variation of merge
2186
+ sort to calculate the number of inversions.
2187
+
2188
+ Examples
2189
+ ========
2190
+
2191
+ >>> from sympy.combinatorics import Permutation
2192
+ >>> p = Permutation([0, 1, 2, 3, 4, 5])
2193
+ >>> p.inversions()
2194
+ 0
2195
+ >>> Permutation([3, 2, 1, 0]).inversions()
2196
+ 6
2197
+
2198
+ See Also
2199
+ ========
2200
+
2201
+ descents, ascents, min, max
2202
+
2203
+ References
2204
+ ==========
2205
+
2206
+ .. [1] https://www.cp.eng.chula.ac.th/~prabhas//teaching/algo/algo2008/count-inv.htm
2207
+
2208
+ """
2209
+ inversions = 0
2210
+ a = self.array_form
2211
+ n = len(a)
2212
+ if n < 130:
2213
+ for i in range(n - 1):
2214
+ b = a[i]
2215
+ for c in a[i + 1:]:
2216
+ if b > c:
2217
+ inversions += 1
2218
+ else:
2219
+ k = 1
2220
+ right = 0
2221
+ arr = a[:]
2222
+ temp = a[:]
2223
+ while k < n:
2224
+ i = 0
2225
+ while i + k < n:
2226
+ right = i + k * 2 - 1
2227
+ if right >= n:
2228
+ right = n - 1
2229
+ inversions += _merge(arr, temp, i, i + k, right)
2230
+ i = i + k * 2
2231
+ k = k * 2
2232
+ return inversions
2233
+
2234
+ def commutator(self, x):
2235
+ """Return the commutator of ``self`` and ``x``: ``~x*~self*x*self``
2236
+
2237
+ If f and g are part of a group, G, then the commutator of f and g
2238
+ is the group identity iff f and g commute, i.e. fg == gf.
2239
+
2240
+ Examples
2241
+ ========
2242
+
2243
+ >>> from sympy.combinatorics import Permutation
2244
+ >>> from sympy import init_printing
2245
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
2246
+ >>> p = Permutation([0, 2, 3, 1])
2247
+ >>> x = Permutation([2, 0, 3, 1])
2248
+ >>> c = p.commutator(x); c
2249
+ Permutation([2, 1, 3, 0])
2250
+ >>> c == ~x*~p*x*p
2251
+ True
2252
+
2253
+ >>> I = Permutation(3)
2254
+ >>> p = [I + i for i in range(6)]
2255
+ >>> for i in range(len(p)):
2256
+ ... for j in range(len(p)):
2257
+ ... c = p[i].commutator(p[j])
2258
+ ... if p[i]*p[j] == p[j]*p[i]:
2259
+ ... assert c == I
2260
+ ... else:
2261
+ ... assert c != I
2262
+ ...
2263
+
2264
+ References
2265
+ ==========
2266
+
2267
+ .. [1] https://en.wikipedia.org/wiki/Commutator
2268
+ """
2269
+
2270
+ a = self.array_form
2271
+ b = x.array_form
2272
+ n = len(a)
2273
+ if len(b) != n:
2274
+ raise ValueError("The permutations must be of equal size.")
2275
+ inva = [None]*n
2276
+ for i in range(n):
2277
+ inva[a[i]] = i
2278
+ invb = [None]*n
2279
+ for i in range(n):
2280
+ invb[b[i]] = i
2281
+ return self._af_new([a[b[inva[i]]] for i in invb])
2282
+
2283
+ def signature(self):
2284
+ """
2285
+ Gives the signature of the permutation needed to place the
2286
+ elements of the permutation in canonical order.
2287
+
2288
+ The signature is calculated as (-1)^<number of inversions>
2289
+
2290
+ Examples
2291
+ ========
2292
+
2293
+ >>> from sympy.combinatorics import Permutation
2294
+ >>> p = Permutation([0, 1, 2])
2295
+ >>> p.inversions()
2296
+ 0
2297
+ >>> p.signature()
2298
+ 1
2299
+ >>> q = Permutation([0,2,1])
2300
+ >>> q.inversions()
2301
+ 1
2302
+ >>> q.signature()
2303
+ -1
2304
+
2305
+ See Also
2306
+ ========
2307
+
2308
+ inversions
2309
+ """
2310
+ if self.is_even:
2311
+ return 1
2312
+ return -1
2313
+
2314
+ def order(self):
2315
+ """
2316
+ Computes the order of a permutation.
2317
+
2318
+ When the permutation is raised to the power of its
2319
+ order it equals the identity permutation.
2320
+
2321
+ Examples
2322
+ ========
2323
+
2324
+ >>> from sympy.combinatorics import Permutation
2325
+ >>> from sympy import init_printing
2326
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
2327
+ >>> p = Permutation([3, 1, 5, 2, 4, 0])
2328
+ >>> p.order()
2329
+ 4
2330
+ >>> (p**(p.order()))
2331
+ Permutation([], size=6)
2332
+
2333
+ See Also
2334
+ ========
2335
+
2336
+ identity, cardinality, length, rank, size
2337
+ """
2338
+
2339
+ return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1)
2340
+
2341
+ def length(self):
2342
+ """
2343
+ Returns the number of integers moved by a permutation.
2344
+
2345
+ Examples
2346
+ ========
2347
+
2348
+ >>> from sympy.combinatorics import Permutation
2349
+ >>> Permutation([0, 3, 2, 1]).length()
2350
+ 2
2351
+ >>> Permutation([[0, 1], [2, 3]]).length()
2352
+ 4
2353
+
2354
+ See Also
2355
+ ========
2356
+
2357
+ min, max, support, cardinality, order, rank, size
2358
+ """
2359
+
2360
+ return len(self.support())
2361
+
2362
+ @property
2363
+ def cycle_structure(self):
2364
+ """Return the cycle structure of the permutation as a dictionary
2365
+ indicating the multiplicity of each cycle length.
2366
+
2367
+ Examples
2368
+ ========
2369
+
2370
+ >>> from sympy.combinatorics import Permutation
2371
+ >>> Permutation(3).cycle_structure
2372
+ {1: 4}
2373
+ >>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure
2374
+ {2: 2, 3: 1}
2375
+ """
2376
+ if self._cycle_structure:
2377
+ rv = self._cycle_structure
2378
+ else:
2379
+ rv = defaultdict(int)
2380
+ singletons = self.size
2381
+ for c in self.cyclic_form:
2382
+ rv[len(c)] += 1
2383
+ singletons -= len(c)
2384
+ if singletons:
2385
+ rv[1] = singletons
2386
+ self._cycle_structure = rv
2387
+ return dict(rv) # make a copy
2388
+
2389
+ @property
2390
+ def cycles(self):
2391
+ """
2392
+ Returns the number of cycles contained in the permutation
2393
+ (including singletons).
2394
+
2395
+ Examples
2396
+ ========
2397
+
2398
+ >>> from sympy.combinatorics import Permutation
2399
+ >>> Permutation([0, 1, 2]).cycles
2400
+ 3
2401
+ >>> Permutation([0, 1, 2]).full_cyclic_form
2402
+ [[0], [1], [2]]
2403
+ >>> Permutation(0, 1)(2, 3).cycles
2404
+ 2
2405
+
2406
+ See Also
2407
+ ========
2408
+ sympy.functions.combinatorial.numbers.stirling
2409
+ """
2410
+ return len(self.full_cyclic_form)
2411
+
2412
+ def index(self):
2413
+ """
2414
+ Returns the index of a permutation.
2415
+
2416
+ The index of a permutation is the sum of all subscripts j such
2417
+ that p[j] is greater than p[j+1].
2418
+
2419
+ Examples
2420
+ ========
2421
+
2422
+ >>> from sympy.combinatorics import Permutation
2423
+ >>> p = Permutation([3, 0, 2, 1, 4])
2424
+ >>> p.index()
2425
+ 2
2426
+ """
2427
+ a = self.array_form
2428
+
2429
+ return sum(j for j in range(len(a) - 1) if a[j] > a[j + 1])
2430
+
2431
+ def runs(self):
2432
+ """
2433
+ Returns the runs of a permutation.
2434
+
2435
+ An ascending sequence in a permutation is called a run [5].
2436
+
2437
+
2438
+ Examples
2439
+ ========
2440
+
2441
+ >>> from sympy.combinatorics import Permutation
2442
+ >>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8])
2443
+ >>> p.runs()
2444
+ [[2, 5, 7], [3, 6], [0, 1, 4, 8]]
2445
+ >>> q = Permutation([1,3,2,0])
2446
+ >>> q.runs()
2447
+ [[1, 3], [2], [0]]
2448
+ """
2449
+ return runs(self.array_form)
2450
+
2451
+ def inversion_vector(self):
2452
+ """Return the inversion vector of the permutation.
2453
+
2454
+ The inversion vector consists of elements whose value
2455
+ indicates the number of elements in the permutation
2456
+ that are lesser than it and lie on its right hand side.
2457
+
2458
+ The inversion vector is the same as the Lehmer encoding of a
2459
+ permutation.
2460
+
2461
+ Examples
2462
+ ========
2463
+
2464
+ >>> from sympy.combinatorics import Permutation
2465
+ >>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2])
2466
+ >>> p.inversion_vector()
2467
+ [4, 7, 0, 5, 0, 2, 1, 1]
2468
+ >>> p = Permutation([3, 2, 1, 0])
2469
+ >>> p.inversion_vector()
2470
+ [3, 2, 1]
2471
+
2472
+ The inversion vector increases lexicographically with the rank
2473
+ of the permutation, the -ith element cycling through 0..i.
2474
+
2475
+ >>> p = Permutation(2)
2476
+ >>> while p:
2477
+ ... print('%s %s %s' % (p, p.inversion_vector(), p.rank()))
2478
+ ... p = p.next_lex()
2479
+ (2) [0, 0] 0
2480
+ (1 2) [0, 1] 1
2481
+ (2)(0 1) [1, 0] 2
2482
+ (0 1 2) [1, 1] 3
2483
+ (0 2 1) [2, 0] 4
2484
+ (0 2) [2, 1] 5
2485
+
2486
+ See Also
2487
+ ========
2488
+
2489
+ from_inversion_vector
2490
+ """
2491
+ self_array_form = self.array_form
2492
+ n = len(self_array_form)
2493
+ inversion_vector = [0] * (n - 1)
2494
+
2495
+ for i in range(n - 1):
2496
+ val = 0
2497
+ for j in range(i + 1, n):
2498
+ if self_array_form[j] < self_array_form[i]:
2499
+ val += 1
2500
+ inversion_vector[i] = val
2501
+ return inversion_vector
2502
+
2503
+ def rank_trotterjohnson(self):
2504
+ """
2505
+ Returns the Trotter Johnson rank, which we get from the minimal
2506
+ change algorithm. See [4] section 2.4.
2507
+
2508
+ Examples
2509
+ ========
2510
+
2511
+ >>> from sympy.combinatorics import Permutation
2512
+ >>> p = Permutation([0, 1, 2, 3])
2513
+ >>> p.rank_trotterjohnson()
2514
+ 0
2515
+ >>> p = Permutation([0, 2, 1, 3])
2516
+ >>> p.rank_trotterjohnson()
2517
+ 7
2518
+
2519
+ See Also
2520
+ ========
2521
+
2522
+ unrank_trotterjohnson, next_trotterjohnson
2523
+ """
2524
+ if self.array_form == [] or self.is_Identity:
2525
+ return 0
2526
+ if self.array_form == [1, 0]:
2527
+ return 1
2528
+ perm = self.array_form
2529
+ n = self.size
2530
+ rank = 0
2531
+ for j in range(1, n):
2532
+ k = 1
2533
+ i = 0
2534
+ while perm[i] != j:
2535
+ if perm[i] < j:
2536
+ k += 1
2537
+ i += 1
2538
+ j1 = j + 1
2539
+ if rank % 2 == 0:
2540
+ rank = j1*rank + j1 - k
2541
+ else:
2542
+ rank = j1*rank + k - 1
2543
+ return rank
2544
+
2545
+ @classmethod
2546
+ def unrank_trotterjohnson(cls, size, rank):
2547
+ """
2548
+ Trotter Johnson permutation unranking. See [4] section 2.4.
2549
+
2550
+ Examples
2551
+ ========
2552
+
2553
+ >>> from sympy.combinatorics import Permutation
2554
+ >>> from sympy import init_printing
2555
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
2556
+ >>> Permutation.unrank_trotterjohnson(5, 10)
2557
+ Permutation([0, 3, 1, 2, 4])
2558
+
2559
+ See Also
2560
+ ========
2561
+
2562
+ rank_trotterjohnson, next_trotterjohnson
2563
+ """
2564
+ perm = [0]*size
2565
+ r2 = 0
2566
+ n = ifac(size)
2567
+ pj = 1
2568
+ for j in range(2, size + 1):
2569
+ pj *= j
2570
+ r1 = (rank * pj) // n
2571
+ k = r1 - j*r2
2572
+ if r2 % 2 == 0:
2573
+ for i in range(j - 1, j - k - 1, -1):
2574
+ perm[i] = perm[i - 1]
2575
+ perm[j - k - 1] = j - 1
2576
+ else:
2577
+ for i in range(j - 1, k, -1):
2578
+ perm[i] = perm[i - 1]
2579
+ perm[k] = j - 1
2580
+ r2 = r1
2581
+ return cls._af_new(perm)
2582
+
2583
+ def next_trotterjohnson(self):
2584
+ """
2585
+ Returns the next permutation in Trotter-Johnson order.
2586
+ If self is the last permutation it returns None.
2587
+ See [4] section 2.4. If it is desired to generate all such
2588
+ permutations, they can be generated in order more quickly
2589
+ with the ``generate_bell`` function.
2590
+
2591
+ Examples
2592
+ ========
2593
+
2594
+ >>> from sympy.combinatorics import Permutation
2595
+ >>> from sympy import init_printing
2596
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
2597
+ >>> p = Permutation([3, 0, 2, 1])
2598
+ >>> p.rank_trotterjohnson()
2599
+ 4
2600
+ >>> p = p.next_trotterjohnson(); p
2601
+ Permutation([0, 3, 2, 1])
2602
+ >>> p.rank_trotterjohnson()
2603
+ 5
2604
+
2605
+ See Also
2606
+ ========
2607
+
2608
+ rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell
2609
+ """
2610
+ pi = self.array_form[:]
2611
+ n = len(pi)
2612
+ st = 0
2613
+ rho = pi[:]
2614
+ done = False
2615
+ m = n-1
2616
+ while m > 0 and not done:
2617
+ d = rho.index(m)
2618
+ for i in range(d, m):
2619
+ rho[i] = rho[i + 1]
2620
+ par = _af_parity(rho[:m])
2621
+ if par == 1:
2622
+ if d == m:
2623
+ m -= 1
2624
+ else:
2625
+ pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d]
2626
+ done = True
2627
+ else:
2628
+ if d == 0:
2629
+ m -= 1
2630
+ st += 1
2631
+ else:
2632
+ pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d]
2633
+ done = True
2634
+ if m == 0:
2635
+ return None
2636
+ return self._af_new(pi)
2637
+
2638
+ def get_precedence_matrix(self):
2639
+ """
2640
+ Gets the precedence matrix. This is used for computing the
2641
+ distance between two permutations.
2642
+
2643
+ Examples
2644
+ ========
2645
+
2646
+ >>> from sympy.combinatorics import Permutation
2647
+ >>> from sympy import init_printing
2648
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
2649
+ >>> p = Permutation.josephus(3, 6, 1)
2650
+ >>> p
2651
+ Permutation([2, 5, 3, 1, 4, 0])
2652
+ >>> p.get_precedence_matrix()
2653
+ Matrix([
2654
+ [0, 0, 0, 0, 0, 0],
2655
+ [1, 0, 0, 0, 1, 0],
2656
+ [1, 1, 0, 1, 1, 1],
2657
+ [1, 1, 0, 0, 1, 0],
2658
+ [1, 0, 0, 0, 0, 0],
2659
+ [1, 1, 0, 1, 1, 0]])
2660
+
2661
+ See Also
2662
+ ========
2663
+
2664
+ get_precedence_distance, get_adjacency_matrix, get_adjacency_distance
2665
+ """
2666
+ m = zeros(self.size)
2667
+ perm = self.array_form
2668
+ for i in range(m.rows):
2669
+ for j in range(i + 1, m.cols):
2670
+ m[perm[i], perm[j]] = 1
2671
+ return m
2672
+
2673
+ def get_precedence_distance(self, other):
2674
+ """
2675
+ Computes the precedence distance between two permutations.
2676
+
2677
+ Explanation
2678
+ ===========
2679
+
2680
+ Suppose p and p' represent n jobs. The precedence metric
2681
+ counts the number of times a job j is preceded by job i
2682
+ in both p and p'. This metric is commutative.
2683
+
2684
+ Examples
2685
+ ========
2686
+
2687
+ >>> from sympy.combinatorics import Permutation
2688
+ >>> p = Permutation([2, 0, 4, 3, 1])
2689
+ >>> q = Permutation([3, 1, 2, 4, 0])
2690
+ >>> p.get_precedence_distance(q)
2691
+ 7
2692
+ >>> q.get_precedence_distance(p)
2693
+ 7
2694
+
2695
+ See Also
2696
+ ========
2697
+
2698
+ get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance
2699
+ """
2700
+ if self.size != other.size:
2701
+ raise ValueError("The permutations must be of equal size.")
2702
+ self_prec_mat = self.get_precedence_matrix()
2703
+ other_prec_mat = other.get_precedence_matrix()
2704
+ n_prec = 0
2705
+ for i in range(self.size):
2706
+ for j in range(self.size):
2707
+ if i == j:
2708
+ continue
2709
+ if self_prec_mat[i, j] * other_prec_mat[i, j] == 1:
2710
+ n_prec += 1
2711
+ d = self.size * (self.size - 1)//2 - n_prec
2712
+ return d
2713
+
2714
+ def get_adjacency_matrix(self):
2715
+ """
2716
+ Computes the adjacency matrix of a permutation.
2717
+
2718
+ Explanation
2719
+ ===========
2720
+
2721
+ If job i is adjacent to job j in a permutation p
2722
+ then we set m[i, j] = 1 where m is the adjacency
2723
+ matrix of p.
2724
+
2725
+ Examples
2726
+ ========
2727
+
2728
+ >>> from sympy.combinatorics import Permutation
2729
+ >>> p = Permutation.josephus(3, 6, 1)
2730
+ >>> p.get_adjacency_matrix()
2731
+ Matrix([
2732
+ [0, 0, 0, 0, 0, 0],
2733
+ [0, 0, 0, 0, 1, 0],
2734
+ [0, 0, 0, 0, 0, 1],
2735
+ [0, 1, 0, 0, 0, 0],
2736
+ [1, 0, 0, 0, 0, 0],
2737
+ [0, 0, 0, 1, 0, 0]])
2738
+ >>> q = Permutation([0, 1, 2, 3])
2739
+ >>> q.get_adjacency_matrix()
2740
+ Matrix([
2741
+ [0, 1, 0, 0],
2742
+ [0, 0, 1, 0],
2743
+ [0, 0, 0, 1],
2744
+ [0, 0, 0, 0]])
2745
+
2746
+ See Also
2747
+ ========
2748
+
2749
+ get_precedence_matrix, get_precedence_distance, get_adjacency_distance
2750
+ """
2751
+ m = zeros(self.size)
2752
+ perm = self.array_form
2753
+ for i in range(self.size - 1):
2754
+ m[perm[i], perm[i + 1]] = 1
2755
+ return m
2756
+
2757
+ def get_adjacency_distance(self, other):
2758
+ """
2759
+ Computes the adjacency distance between two permutations.
2760
+
2761
+ Explanation
2762
+ ===========
2763
+
2764
+ This metric counts the number of times a pair i,j of jobs is
2765
+ adjacent in both p and p'. If n_adj is this quantity then
2766
+ the adjacency distance is n - n_adj - 1 [1]
2767
+
2768
+ [1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals
2769
+ of Operational Research, 86, pp 473-490. (1999)
2770
+
2771
+
2772
+ Examples
2773
+ ========
2774
+
2775
+ >>> from sympy.combinatorics import Permutation
2776
+ >>> p = Permutation([0, 3, 1, 2, 4])
2777
+ >>> q = Permutation.josephus(4, 5, 2)
2778
+ >>> p.get_adjacency_distance(q)
2779
+ 3
2780
+ >>> r = Permutation([0, 2, 1, 4, 3])
2781
+ >>> p.get_adjacency_distance(r)
2782
+ 4
2783
+
2784
+ See Also
2785
+ ========
2786
+
2787
+ get_precedence_matrix, get_precedence_distance, get_adjacency_matrix
2788
+ """
2789
+ if self.size != other.size:
2790
+ raise ValueError("The permutations must be of the same size.")
2791
+ self_adj_mat = self.get_adjacency_matrix()
2792
+ other_adj_mat = other.get_adjacency_matrix()
2793
+ n_adj = 0
2794
+ for i in range(self.size):
2795
+ for j in range(self.size):
2796
+ if i == j:
2797
+ continue
2798
+ if self_adj_mat[i, j] * other_adj_mat[i, j] == 1:
2799
+ n_adj += 1
2800
+ d = self.size - n_adj - 1
2801
+ return d
2802
+
2803
+ def get_positional_distance(self, other):
2804
+ """
2805
+ Computes the positional distance between two permutations.
2806
+
2807
+ Examples
2808
+ ========
2809
+
2810
+ >>> from sympy.combinatorics import Permutation
2811
+ >>> p = Permutation([0, 3, 1, 2, 4])
2812
+ >>> q = Permutation.josephus(4, 5, 2)
2813
+ >>> r = Permutation([3, 1, 4, 0, 2])
2814
+ >>> p.get_positional_distance(q)
2815
+ 12
2816
+ >>> p.get_positional_distance(r)
2817
+ 12
2818
+
2819
+ See Also
2820
+ ========
2821
+
2822
+ get_precedence_distance, get_adjacency_distance
2823
+ """
2824
+ a = self.array_form
2825
+ b = other.array_form
2826
+ if len(a) != len(b):
2827
+ raise ValueError("The permutations must be of the same size.")
2828
+ return sum(abs(a[i] - b[i]) for i in range(len(a)))
2829
+
2830
+ @classmethod
2831
+ def josephus(cls, m, n, s=1):
2832
+ """Return as a permutation the shuffling of range(n) using the Josephus
2833
+ scheme in which every m-th item is selected until all have been chosen.
2834
+ The returned permutation has elements listed by the order in which they
2835
+ were selected.
2836
+
2837
+ The parameter ``s`` stops the selection process when there are ``s``
2838
+ items remaining and these are selected by continuing the selection,
2839
+ counting by 1 rather than by ``m``.
2840
+
2841
+ Consider selecting every 3rd item from 6 until only 2 remain::
2842
+
2843
+ choices chosen
2844
+ ======== ======
2845
+ 012345
2846
+ 01 345 2
2847
+ 01 34 25
2848
+ 01 4 253
2849
+ 0 4 2531
2850
+ 0 25314
2851
+ 253140
2852
+
2853
+ Examples
2854
+ ========
2855
+
2856
+ >>> from sympy.combinatorics import Permutation
2857
+ >>> Permutation.josephus(3, 6, 2).array_form
2858
+ [2, 5, 3, 1, 4, 0]
2859
+
2860
+ References
2861
+ ==========
2862
+
2863
+ .. [1] https://en.wikipedia.org/wiki/Flavius_Josephus
2864
+ .. [2] https://en.wikipedia.org/wiki/Josephus_problem
2865
+ .. [3] https://web.archive.org/web/20171008094331/http://www.wou.edu/~burtonl/josephus.html
2866
+
2867
+ """
2868
+ from collections import deque
2869
+ m -= 1
2870
+ Q = deque(list(range(n)))
2871
+ perm = []
2872
+ while len(Q) > max(s, 1):
2873
+ for dp in range(m):
2874
+ Q.append(Q.popleft())
2875
+ perm.append(Q.popleft())
2876
+ perm.extend(list(Q))
2877
+ return cls(perm)
2878
+
2879
+ @classmethod
2880
+ def from_inversion_vector(cls, inversion):
2881
+ """
2882
+ Calculates the permutation from the inversion vector.
2883
+
2884
+ Examples
2885
+ ========
2886
+
2887
+ >>> from sympy.combinatorics import Permutation
2888
+ >>> from sympy import init_printing
2889
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
2890
+ >>> Permutation.from_inversion_vector([3, 2, 1, 0, 0])
2891
+ Permutation([3, 2, 1, 0, 4, 5])
2892
+
2893
+ """
2894
+ size = len(inversion)
2895
+ N = list(range(size + 1))
2896
+ perm = []
2897
+ try:
2898
+ for k in range(size):
2899
+ val = N[inversion[k]]
2900
+ perm.append(val)
2901
+ N.remove(val)
2902
+ except IndexError:
2903
+ raise ValueError("The inversion vector is not valid.")
2904
+ perm.extend(N)
2905
+ return cls._af_new(perm)
2906
+
2907
+ @classmethod
2908
+ def random(cls, n):
2909
+ """
2910
+ Generates a random permutation of length ``n``.
2911
+
2912
+ Uses the underlying Python pseudo-random number generator.
2913
+
2914
+ Examples
2915
+ ========
2916
+
2917
+ >>> from sympy.combinatorics import Permutation
2918
+ >>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1]))
2919
+ True
2920
+
2921
+ """
2922
+ perm_array = list(range(n))
2923
+ random.shuffle(perm_array)
2924
+ return cls._af_new(perm_array)
2925
+
2926
+ @classmethod
2927
+ def unrank_lex(cls, size, rank):
2928
+ """
2929
+ Lexicographic permutation unranking.
2930
+
2931
+ Examples
2932
+ ========
2933
+
2934
+ >>> from sympy.combinatorics import Permutation
2935
+ >>> from sympy import init_printing
2936
+ >>> init_printing(perm_cyclic=False, pretty_print=False)
2937
+ >>> a = Permutation.unrank_lex(5, 10)
2938
+ >>> a.rank()
2939
+ 10
2940
+ >>> a
2941
+ Permutation([0, 2, 4, 1, 3])
2942
+
2943
+ See Also
2944
+ ========
2945
+
2946
+ rank, next_lex
2947
+ """
2948
+ perm_array = [0] * size
2949
+ psize = 1
2950
+ for i in range(size):
2951
+ new_psize = psize*(i + 1)
2952
+ d = (rank % new_psize) // psize
2953
+ rank -= d*psize
2954
+ perm_array[size - i - 1] = d
2955
+ for j in range(size - i, size):
2956
+ if perm_array[j] > d - 1:
2957
+ perm_array[j] += 1
2958
+ psize = new_psize
2959
+ return cls._af_new(perm_array)
2960
+
2961
+ def resize(self, n):
2962
+ """Resize the permutation to the new size ``n``.
2963
+
2964
+ Parameters
2965
+ ==========
2966
+
2967
+ n : int
2968
+ The new size of the permutation.
2969
+
2970
+ Raises
2971
+ ======
2972
+
2973
+ ValueError
2974
+ If the permutation cannot be resized to the given size.
2975
+ This may only happen when resized to a smaller size than
2976
+ the original.
2977
+
2978
+ Examples
2979
+ ========
2980
+
2981
+ >>> from sympy.combinatorics import Permutation
2982
+
2983
+ Increasing the size of a permutation:
2984
+
2985
+ >>> p = Permutation(0, 1, 2)
2986
+ >>> p = p.resize(5)
2987
+ >>> p
2988
+ (4)(0 1 2)
2989
+
2990
+ Decreasing the size of the permutation:
2991
+
2992
+ >>> p = p.resize(4)
2993
+ >>> p
2994
+ (3)(0 1 2)
2995
+
2996
+ If resizing to the specific size breaks the cycles:
2997
+
2998
+ >>> p.resize(2)
2999
+ Traceback (most recent call last):
3000
+ ...
3001
+ ValueError: The permutation cannot be resized to 2 because the
3002
+ cycle (0, 1, 2) may break.
3003
+ """
3004
+ aform = self.array_form
3005
+ l = len(aform)
3006
+ if n > l:
3007
+ aform += list(range(l, n))
3008
+ return Permutation._af_new(aform)
3009
+
3010
+ elif n < l:
3011
+ cyclic_form = self.full_cyclic_form
3012
+ new_cyclic_form = []
3013
+ for cycle in cyclic_form:
3014
+ cycle_min = min(cycle)
3015
+ cycle_max = max(cycle)
3016
+ if cycle_min <= n-1:
3017
+ if cycle_max > n-1:
3018
+ raise ValueError(
3019
+ "The permutation cannot be resized to {} "
3020
+ "because the cycle {} may break."
3021
+ .format(n, tuple(cycle)))
3022
+
3023
+ new_cyclic_form.append(cycle)
3024
+ return Permutation(new_cyclic_form)
3025
+
3026
+ return self
3027
+
3028
+ # XXX Deprecated flag
3029
+ print_cyclic = None
3030
+
3031
+
3032
+ def _merge(arr, temp, left, mid, right):
3033
+ """
3034
+ Merges two sorted arrays and calculates the inversion count.
3035
+
3036
+ Helper function for calculating inversions. This method is
3037
+ for internal use only.
3038
+ """
3039
+ i = k = left
3040
+ j = mid
3041
+ inv_count = 0
3042
+ while i < mid and j <= right:
3043
+ if arr[i] < arr[j]:
3044
+ temp[k] = arr[i]
3045
+ k += 1
3046
+ i += 1
3047
+ else:
3048
+ temp[k] = arr[j]
3049
+ k += 1
3050
+ j += 1
3051
+ inv_count += (mid -i)
3052
+ while i < mid:
3053
+ temp[k] = arr[i]
3054
+ k += 1
3055
+ i += 1
3056
+ if j <= right:
3057
+ k += right - j + 1
3058
+ j += right - j + 1
3059
+ arr[left:k + 1] = temp[left:k + 1]
3060
+ else:
3061
+ arr[left:right + 1] = temp[left:right + 1]
3062
+ return inv_count
3063
+
3064
+ Perm = Permutation
3065
+ _af_new = Perm._af_new
3066
+
3067
+
3068
+ class AppliedPermutation(Expr):
3069
+ """A permutation applied to a symbolic variable.
3070
+
3071
+ Parameters
3072
+ ==========
3073
+
3074
+ perm : Permutation
3075
+ x : Expr
3076
+
3077
+ Examples
3078
+ ========
3079
+
3080
+ >>> from sympy import Symbol
3081
+ >>> from sympy.combinatorics import Permutation
3082
+
3083
+ Creating a symbolic permutation function application:
3084
+
3085
+ >>> x = Symbol('x')
3086
+ >>> p = Permutation(0, 1, 2)
3087
+ >>> p.apply(x)
3088
+ AppliedPermutation((0 1 2), x)
3089
+ >>> _.subs(x, 1)
3090
+ 2
3091
+ """
3092
+ def __new__(cls, perm, x, evaluate=None):
3093
+ if evaluate is None:
3094
+ evaluate = global_parameters.evaluate
3095
+
3096
+ perm = _sympify(perm)
3097
+ x = _sympify(x)
3098
+
3099
+ if not isinstance(perm, Permutation):
3100
+ raise ValueError("{} must be a Permutation instance."
3101
+ .format(perm))
3102
+
3103
+ if evaluate:
3104
+ if x.is_Integer:
3105
+ return perm.apply(x)
3106
+
3107
+ obj = super().__new__(cls, perm, x)
3108
+ return obj
3109
+
3110
+
3111
+ @dispatch(Permutation, Permutation)
3112
+ def _eval_is_eq(lhs, rhs):
3113
+ if lhs._size != rhs._size:
3114
+ return None
3115
+ return lhs._array_form == rhs._array_form
mgm/lib/python3.10/site-packages/sympy/combinatorics/prufer.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import Basic
2
+ from sympy.core.containers import Tuple
3
+ from sympy.tensor.array import Array
4
+ from sympy.core.sympify import _sympify
5
+ from sympy.utilities.iterables import flatten, iterable
6
+ from sympy.utilities.misc import as_int
7
+
8
+ from collections import defaultdict
9
+
10
+
11
+ class Prufer(Basic):
12
+ """
13
+ The Prufer correspondence is an algorithm that describes the
14
+ bijection between labeled trees and the Prufer code. A Prufer
15
+ code of a labeled tree is unique up to isomorphism and has
16
+ a length of n - 2.
17
+
18
+ Prufer sequences were first used by Heinz Prufer to give a
19
+ proof of Cayley's formula.
20
+
21
+ References
22
+ ==========
23
+
24
+ .. [1] https://mathworld.wolfram.com/LabeledTree.html
25
+
26
+ """
27
+ _prufer_repr = None
28
+ _tree_repr = None
29
+ _nodes = None
30
+ _rank = None
31
+
32
+ @property
33
+ def prufer_repr(self):
34
+ """Returns Prufer sequence for the Prufer object.
35
+
36
+ This sequence is found by removing the highest numbered vertex,
37
+ recording the node it was attached to, and continuing until only
38
+ two vertices remain. The Prufer sequence is the list of recorded nodes.
39
+
40
+ Examples
41
+ ========
42
+
43
+ >>> from sympy.combinatorics.prufer import Prufer
44
+ >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).prufer_repr
45
+ [3, 3, 3, 4]
46
+ >>> Prufer([1, 0, 0]).prufer_repr
47
+ [1, 0, 0]
48
+
49
+ See Also
50
+ ========
51
+
52
+ to_prufer
53
+
54
+ """
55
+ if self._prufer_repr is None:
56
+ self._prufer_repr = self.to_prufer(self._tree_repr[:], self.nodes)
57
+ return self._prufer_repr
58
+
59
+ @property
60
+ def tree_repr(self):
61
+ """Returns the tree representation of the Prufer object.
62
+
63
+ Examples
64
+ ========
65
+
66
+ >>> from sympy.combinatorics.prufer import Prufer
67
+ >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).tree_repr
68
+ [[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]
69
+ >>> Prufer([1, 0, 0]).tree_repr
70
+ [[1, 2], [0, 1], [0, 3], [0, 4]]
71
+
72
+ See Also
73
+ ========
74
+
75
+ to_tree
76
+
77
+ """
78
+ if self._tree_repr is None:
79
+ self._tree_repr = self.to_tree(self._prufer_repr[:])
80
+ return self._tree_repr
81
+
82
+ @property
83
+ def nodes(self):
84
+ """Returns the number of nodes in the tree.
85
+
86
+ Examples
87
+ ========
88
+
89
+ >>> from sympy.combinatorics.prufer import Prufer
90
+ >>> Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]]).nodes
91
+ 6
92
+ >>> Prufer([1, 0, 0]).nodes
93
+ 5
94
+
95
+ """
96
+ return self._nodes
97
+
98
+ @property
99
+ def rank(self):
100
+ """Returns the rank of the Prufer sequence.
101
+
102
+ Examples
103
+ ========
104
+
105
+ >>> from sympy.combinatorics.prufer import Prufer
106
+ >>> p = Prufer([[0, 3], [1, 3], [2, 3], [3, 4], [4, 5]])
107
+ >>> p.rank
108
+ 778
109
+ >>> p.next(1).rank
110
+ 779
111
+ >>> p.prev().rank
112
+ 777
113
+
114
+ See Also
115
+ ========
116
+
117
+ prufer_rank, next, prev, size
118
+
119
+ """
120
+ if self._rank is None:
121
+ self._rank = self.prufer_rank()
122
+ return self._rank
123
+
124
+ @property
125
+ def size(self):
126
+ """Return the number of possible trees of this Prufer object.
127
+
128
+ Examples
129
+ ========
130
+
131
+ >>> from sympy.combinatorics.prufer import Prufer
132
+ >>> Prufer([0]*4).size == Prufer([6]*4).size == 1296
133
+ True
134
+
135
+ See Also
136
+ ========
137
+
138
+ prufer_rank, rank, next, prev
139
+
140
+ """
141
+ return self.prev(self.rank).prev().rank + 1
142
+
143
+ @staticmethod
144
+ def to_prufer(tree, n):
145
+ """Return the Prufer sequence for a tree given as a list of edges where
146
+ ``n`` is the number of nodes in the tree.
147
+
148
+ Examples
149
+ ========
150
+
151
+ >>> from sympy.combinatorics.prufer import Prufer
152
+ >>> a = Prufer([[0, 1], [0, 2], [0, 3]])
153
+ >>> a.prufer_repr
154
+ [0, 0]
155
+ >>> Prufer.to_prufer([[0, 1], [0, 2], [0, 3]], 4)
156
+ [0, 0]
157
+
158
+ See Also
159
+ ========
160
+ prufer_repr: returns Prufer sequence of a Prufer object.
161
+
162
+ """
163
+ d = defaultdict(int)
164
+ L = []
165
+ for edge in tree:
166
+ # Increment the value of the corresponding
167
+ # node in the degree list as we encounter an
168
+ # edge involving it.
169
+ d[edge[0]] += 1
170
+ d[edge[1]] += 1
171
+ for i in range(n - 2):
172
+ # find the smallest leaf
173
+ for x in range(n):
174
+ if d[x] == 1:
175
+ break
176
+ # find the node it was connected to
177
+ y = None
178
+ for edge in tree:
179
+ if x == edge[0]:
180
+ y = edge[1]
181
+ elif x == edge[1]:
182
+ y = edge[0]
183
+ if y is not None:
184
+ break
185
+ # record and update
186
+ L.append(y)
187
+ for j in (x, y):
188
+ d[j] -= 1
189
+ if not d[j]:
190
+ d.pop(j)
191
+ tree.remove(edge)
192
+ return L
193
+
194
+ @staticmethod
195
+ def to_tree(prufer):
196
+ """Return the tree (as a list of edges) of the given Prufer sequence.
197
+
198
+ Examples
199
+ ========
200
+
201
+ >>> from sympy.combinatorics.prufer import Prufer
202
+ >>> a = Prufer([0, 2], 4)
203
+ >>> a.tree_repr
204
+ [[0, 1], [0, 2], [2, 3]]
205
+ >>> Prufer.to_tree([0, 2])
206
+ [[0, 1], [0, 2], [2, 3]]
207
+
208
+ References
209
+ ==========
210
+
211
+ .. [1] https://hamberg.no/erlend/posts/2010-11-06-prufer-sequence-compact-tree-representation.html
212
+
213
+ See Also
214
+ ========
215
+ tree_repr: returns tree representation of a Prufer object.
216
+
217
+ """
218
+ tree = []
219
+ last = []
220
+ n = len(prufer) + 2
221
+ d = defaultdict(lambda: 1)
222
+ for p in prufer:
223
+ d[p] += 1
224
+ for i in prufer:
225
+ for j in range(n):
226
+ # find the smallest leaf (degree = 1)
227
+ if d[j] == 1:
228
+ break
229
+ # (i, j) is the new edge that we append to the tree
230
+ # and remove from the degree dictionary
231
+ d[i] -= 1
232
+ d[j] -= 1
233
+ tree.append(sorted([i, j]))
234
+ last = [i for i in range(n) if d[i] == 1] or [0, 1]
235
+ tree.append(last)
236
+
237
+ return tree
238
+
239
+ @staticmethod
240
+ def edges(*runs):
241
+ """Return a list of edges and the number of nodes from the given runs
242
+ that connect nodes in an integer-labelled tree.
243
+
244
+ All node numbers will be shifted so that the minimum node is 0. It is
245
+ not a problem if edges are repeated in the runs; only unique edges are
246
+ returned. There is no assumption made about what the range of the node
247
+ labels should be, but all nodes from the smallest through the largest
248
+ must be present.
249
+
250
+ Examples
251
+ ========
252
+
253
+ >>> from sympy.combinatorics.prufer import Prufer
254
+ >>> Prufer.edges([1, 2, 3], [2, 4, 5]) # a T
255
+ ([[0, 1], [1, 2], [1, 3], [3, 4]], 5)
256
+
257
+ Duplicate edges are removed:
258
+
259
+ >>> Prufer.edges([0, 1, 2, 3], [1, 4, 5], [1, 4, 6]) # a K
260
+ ([[0, 1], [1, 2], [1, 4], [2, 3], [4, 5], [4, 6]], 7)
261
+
262
+ """
263
+ e = set()
264
+ nmin = runs[0][0]
265
+ for r in runs:
266
+ for i in range(len(r) - 1):
267
+ a, b = r[i: i + 2]
268
+ if b < a:
269
+ a, b = b, a
270
+ e.add((a, b))
271
+ rv = []
272
+ got = set()
273
+ nmin = nmax = None
274
+ for ei in e:
275
+ got.update(ei)
276
+ nmin = min(ei[0], nmin) if nmin is not None else ei[0]
277
+ nmax = max(ei[1], nmax) if nmax is not None else ei[1]
278
+ rv.append(list(ei))
279
+ missing = set(range(nmin, nmax + 1)) - got
280
+ if missing:
281
+ missing = [i + nmin for i in missing]
282
+ if len(missing) == 1:
283
+ msg = 'Node %s is missing.' % missing.pop()
284
+ else:
285
+ msg = 'Nodes %s are missing.' % sorted(missing)
286
+ raise ValueError(msg)
287
+ if nmin != 0:
288
+ for i, ei in enumerate(rv):
289
+ rv[i] = [n - nmin for n in ei]
290
+ nmax -= nmin
291
+ return sorted(rv), nmax + 1
292
+
293
+ def prufer_rank(self):
294
+ """Computes the rank of a Prufer sequence.
295
+
296
+ Examples
297
+ ========
298
+
299
+ >>> from sympy.combinatorics.prufer import Prufer
300
+ >>> a = Prufer([[0, 1], [0, 2], [0, 3]])
301
+ >>> a.prufer_rank()
302
+ 0
303
+
304
+ See Also
305
+ ========
306
+
307
+ rank, next, prev, size
308
+
309
+ """
310
+ r = 0
311
+ p = 1
312
+ for i in range(self.nodes - 3, -1, -1):
313
+ r += p*self.prufer_repr[i]
314
+ p *= self.nodes
315
+ return r
316
+
317
+ @classmethod
318
+ def unrank(self, rank, n):
319
+ """Finds the unranked Prufer sequence.
320
+
321
+ Examples
322
+ ========
323
+
324
+ >>> from sympy.combinatorics.prufer import Prufer
325
+ >>> Prufer.unrank(0, 4)
326
+ Prufer([0, 0])
327
+
328
+ """
329
+ n, rank = as_int(n), as_int(rank)
330
+ L = defaultdict(int)
331
+ for i in range(n - 3, -1, -1):
332
+ L[i] = rank % n
333
+ rank = (rank - L[i])//n
334
+ return Prufer([L[i] for i in range(len(L))])
335
+
336
+ def __new__(cls, *args, **kw_args):
337
+ """The constructor for the Prufer object.
338
+
339
+ Examples
340
+ ========
341
+
342
+ >>> from sympy.combinatorics.prufer import Prufer
343
+
344
+ A Prufer object can be constructed from a list of edges:
345
+
346
+ >>> a = Prufer([[0, 1], [0, 2], [0, 3]])
347
+ >>> a.prufer_repr
348
+ [0, 0]
349
+
350
+ If the number of nodes is given, no checking of the nodes will
351
+ be performed; it will be assumed that nodes 0 through n - 1 are
352
+ present:
353
+
354
+ >>> Prufer([[0, 1], [0, 2], [0, 3]], 4)
355
+ Prufer([[0, 1], [0, 2], [0, 3]], 4)
356
+
357
+ A Prufer object can be constructed from a Prufer sequence:
358
+
359
+ >>> b = Prufer([1, 3])
360
+ >>> b.tree_repr
361
+ [[0, 1], [1, 3], [2, 3]]
362
+
363
+ """
364
+ arg0 = Array(args[0]) if args[0] else Tuple()
365
+ args = (arg0,) + tuple(_sympify(arg) for arg in args[1:])
366
+ ret_obj = Basic.__new__(cls, *args, **kw_args)
367
+ args = [list(args[0])]
368
+ if args[0] and iterable(args[0][0]):
369
+ if not args[0][0]:
370
+ raise ValueError(
371
+ 'Prufer expects at least one edge in the tree.')
372
+ if len(args) > 1:
373
+ nnodes = args[1]
374
+ else:
375
+ nodes = set(flatten(args[0]))
376
+ nnodes = max(nodes) + 1
377
+ if nnodes != len(nodes):
378
+ missing = set(range(nnodes)) - nodes
379
+ if len(missing) == 1:
380
+ msg = 'Node %s is missing.' % missing.pop()
381
+ else:
382
+ msg = 'Nodes %s are missing.' % sorted(missing)
383
+ raise ValueError(msg)
384
+ ret_obj._tree_repr = [list(i) for i in args[0]]
385
+ ret_obj._nodes = nnodes
386
+ else:
387
+ ret_obj._prufer_repr = args[0]
388
+ ret_obj._nodes = len(ret_obj._prufer_repr) + 2
389
+ return ret_obj
390
+
391
+ def next(self, delta=1):
392
+ """Generates the Prufer sequence that is delta beyond the current one.
393
+
394
+ Examples
395
+ ========
396
+
397
+ >>> from sympy.combinatorics.prufer import Prufer
398
+ >>> a = Prufer([[0, 1], [0, 2], [0, 3]])
399
+ >>> b = a.next(1) # == a.next()
400
+ >>> b.tree_repr
401
+ [[0, 2], [0, 1], [1, 3]]
402
+ >>> b.rank
403
+ 1
404
+
405
+ See Also
406
+ ========
407
+
408
+ prufer_rank, rank, prev, size
409
+
410
+ """
411
+ return Prufer.unrank(self.rank + delta, self.nodes)
412
+
413
+ def prev(self, delta=1):
414
+ """Generates the Prufer sequence that is -delta before the current one.
415
+
416
+ Examples
417
+ ========
418
+
419
+ >>> from sympy.combinatorics.prufer import Prufer
420
+ >>> a = Prufer([[0, 1], [1, 2], [2, 3], [1, 4]])
421
+ >>> a.rank
422
+ 36
423
+ >>> b = a.prev()
424
+ >>> b
425
+ Prufer([1, 2, 0])
426
+ >>> b.rank
427
+ 35
428
+
429
+ See Also
430
+ ========
431
+
432
+ prufer_rank, rank, next, size
433
+
434
+ """
435
+ return Prufer.unrank(self.rank -delta, self.nodes)
mgm/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import deque
2
+ from sympy.combinatorics.rewritingsystem_fsm import StateMachine
3
+
4
+ class RewritingSystem:
5
+ '''
6
+ A class implementing rewriting systems for `FpGroup`s.
7
+
8
+ References
9
+ ==========
10
+ .. [1] Epstein, D., Holt, D. and Rees, S. (1991).
11
+ The use of Knuth-Bendix methods to solve the word problem in automatic groups.
12
+ Journal of Symbolic Computation, 12(4-5), pp.397-414.
13
+
14
+ .. [2] GAP's Manual on its KBMAG package
15
+ https://www.gap-system.org/Manuals/pkg/kbmag-1.5.3/doc/manual.pdf
16
+
17
+ '''
18
+ def __init__(self, group):
19
+ self.group = group
20
+ self.alphabet = group.generators
21
+ self._is_confluent = None
22
+
23
+ # these values are taken from [2]
24
+ self.maxeqns = 32767 # max rules
25
+ self.tidyint = 100 # rules before tidying
26
+
27
+ # _max_exceeded is True if maxeqns is exceeded
28
+ # at any point
29
+ self._max_exceeded = False
30
+
31
+ # Reduction automaton
32
+ self.reduction_automaton = None
33
+ self._new_rules = {}
34
+
35
+ # dictionary of reductions
36
+ self.rules = {}
37
+ self.rules_cache = deque([], 50)
38
+ self._init_rules()
39
+
40
+
41
+ # All the transition symbols in the automaton
42
+ generators = list(self.alphabet)
43
+ generators += [gen**-1 for gen in generators]
44
+ # Create a finite state machine as an instance of the StateMachine object
45
+ self.reduction_automaton = StateMachine('Reduction automaton for '+ repr(self.group), generators)
46
+ self.construct_automaton()
47
+
48
+ def set_max(self, n):
49
+ '''
50
+ Set the maximum number of rules that can be defined
51
+
52
+ '''
53
+ if n > self.maxeqns:
54
+ self._max_exceeded = False
55
+ self.maxeqns = n
56
+ return
57
+
58
+ @property
59
+ def is_confluent(self):
60
+ '''
61
+ Return `True` if the system is confluent
62
+
63
+ '''
64
+ if self._is_confluent is None:
65
+ self._is_confluent = self._check_confluence()
66
+ return self._is_confluent
67
+
68
+ def _init_rules(self):
69
+ identity = self.group.free_group.identity
70
+ for r in self.group.relators:
71
+ self.add_rule(r, identity)
72
+ self._remove_redundancies()
73
+ return
74
+
75
+ def _add_rule(self, r1, r2):
76
+ '''
77
+ Add the rule r1 -> r2 with no checking or further
78
+ deductions
79
+
80
+ '''
81
+ if len(self.rules) + 1 > self.maxeqns:
82
+ self._is_confluent = self._check_confluence()
83
+ self._max_exceeded = True
84
+ raise RuntimeError("Too many rules were defined.")
85
+ self.rules[r1] = r2
86
+ # Add the newly added rule to the `new_rules` dictionary.
87
+ if self.reduction_automaton:
88
+ self._new_rules[r1] = r2
89
+
90
+ def add_rule(self, w1, w2, check=False):
91
+ new_keys = set()
92
+
93
+ if w1 == w2:
94
+ return new_keys
95
+
96
+ if w1 < w2:
97
+ w1, w2 = w2, w1
98
+
99
+ if (w1, w2) in self.rules_cache:
100
+ return new_keys
101
+ self.rules_cache.append((w1, w2))
102
+
103
+ s1, s2 = w1, w2
104
+
105
+ # The following is the equivalent of checking
106
+ # s1 for overlaps with the implicit reductions
107
+ # {g*g**-1 -> <identity>} and {g**-1*g -> <identity>}
108
+ # for any generator g without installing the
109
+ # redundant rules that would result from processing
110
+ # the overlaps. See [1], Section 3 for details.
111
+
112
+ if len(s1) - len(s2) < 3:
113
+ if s1 not in self.rules:
114
+ new_keys.add(s1)
115
+ if not check:
116
+ self._add_rule(s1, s2)
117
+ if s2**-1 > s1**-1 and s2**-1 not in self.rules:
118
+ new_keys.add(s2**-1)
119
+ if not check:
120
+ self._add_rule(s2**-1, s1**-1)
121
+
122
+ # overlaps on the right
123
+ while len(s1) - len(s2) > -1:
124
+ g = s1[len(s1)-1]
125
+ s1 = s1.subword(0, len(s1)-1)
126
+ s2 = s2*g**-1
127
+ if len(s1) - len(s2) < 0:
128
+ if s2 not in self.rules:
129
+ if not check:
130
+ self._add_rule(s2, s1)
131
+ new_keys.add(s2)
132
+ elif len(s1) - len(s2) < 3:
133
+ new = self.add_rule(s1, s2, check)
134
+ new_keys.update(new)
135
+
136
+ # overlaps on the left
137
+ while len(w1) - len(w2) > -1:
138
+ g = w1[0]
139
+ w1 = w1.subword(1, len(w1))
140
+ w2 = g**-1*w2
141
+ if len(w1) - len(w2) < 0:
142
+ if w2 not in self.rules:
143
+ if not check:
144
+ self._add_rule(w2, w1)
145
+ new_keys.add(w2)
146
+ elif len(w1) - len(w2) < 3:
147
+ new = self.add_rule(w1, w2, check)
148
+ new_keys.update(new)
149
+
150
+ return new_keys
151
+
152
+ def _remove_redundancies(self, changes=False):
153
+ '''
154
+ Reduce left- and right-hand sides of reduction rules
155
+ and remove redundant equations (i.e. those for which
156
+ lhs == rhs). If `changes` is `True`, return a set
157
+ containing the removed keys and a set containing the
158
+ added keys
159
+
160
+ '''
161
+ removed = set()
162
+ added = set()
163
+ rules = self.rules.copy()
164
+ for r in rules:
165
+ v = self.reduce(r, exclude=r)
166
+ w = self.reduce(rules[r])
167
+ if v != r:
168
+ del self.rules[r]
169
+ removed.add(r)
170
+ if v > w:
171
+ added.add(v)
172
+ self.rules[v] = w
173
+ elif v < w:
174
+ added.add(w)
175
+ self.rules[w] = v
176
+ else:
177
+ self.rules[v] = w
178
+ if changes:
179
+ return removed, added
180
+ return
181
+
182
+ def make_confluent(self, check=False):
183
+ '''
184
+ Try to make the system confluent using the Knuth-Bendix
185
+ completion algorithm
186
+
187
+ '''
188
+ if self._max_exceeded:
189
+ return self._is_confluent
190
+ lhs = list(self.rules.keys())
191
+
192
+ def _overlaps(r1, r2):
193
+ len1 = len(r1)
194
+ len2 = len(r2)
195
+ result = []
196
+ for j in range(1, len1 + len2):
197
+ if (r1.subword(len1 - j, len1 + len2 - j, strict=False)
198
+ == r2.subword(j - len1, j, strict=False)):
199
+ a = r1.subword(0, len1-j, strict=False)
200
+ a = a*r2.subword(0, j-len1, strict=False)
201
+ b = r2.subword(j-len1, j, strict=False)
202
+ c = r2.subword(j, len2, strict=False)
203
+ c = c*r1.subword(len1 + len2 - j, len1, strict=False)
204
+ result.append(a*b*c)
205
+ return result
206
+
207
+ def _process_overlap(w, r1, r2, check):
208
+ s = w.eliminate_word(r1, self.rules[r1])
209
+ s = self.reduce(s)
210
+ t = w.eliminate_word(r2, self.rules[r2])
211
+ t = self.reduce(t)
212
+ if s != t:
213
+ if check:
214
+ # system not confluent
215
+ return [0]
216
+ try:
217
+ new_keys = self.add_rule(t, s, check)
218
+ return new_keys
219
+ except RuntimeError:
220
+ return False
221
+ return
222
+
223
+ added = 0
224
+ i = 0
225
+ while i < len(lhs):
226
+ r1 = lhs[i]
227
+ i += 1
228
+ # j could be i+1 to not
229
+ # check each pair twice but lhs
230
+ # is extended in the loop and the new
231
+ # elements have to be checked with the
232
+ # preceding ones. there is probably a better way
233
+ # to handle this
234
+ j = 0
235
+ while j < len(lhs):
236
+ r2 = lhs[j]
237
+ j += 1
238
+ if r1 == r2:
239
+ continue
240
+ overlaps = _overlaps(r1, r2)
241
+ overlaps.extend(_overlaps(r1**-1, r2))
242
+ if not overlaps:
243
+ continue
244
+ for w in overlaps:
245
+ new_keys = _process_overlap(w, r1, r2, check)
246
+ if new_keys:
247
+ if check:
248
+ return False
249
+ lhs.extend(new_keys)
250
+ added += len(new_keys)
251
+ elif new_keys == False:
252
+ # too many rules were added so the process
253
+ # couldn't complete
254
+ return self._is_confluent
255
+
256
+ if added > self.tidyint and not check:
257
+ # tidy up
258
+ r, a = self._remove_redundancies(changes=True)
259
+ added = 0
260
+ if r:
261
+ # reset i since some elements were removed
262
+ i = min(lhs.index(s) for s in r)
263
+ lhs = [l for l in lhs if l not in r]
264
+ lhs.extend(a)
265
+ if r1 in r:
266
+ # r1 was removed as redundant
267
+ break
268
+
269
+ self._is_confluent = True
270
+ if not check:
271
+ self._remove_redundancies()
272
+ return True
273
+
274
+ def _check_confluence(self):
275
+ return self.make_confluent(check=True)
276
+
277
+ def reduce(self, word, exclude=None):
278
+ '''
279
+ Apply reduction rules to `word` excluding the reduction rule
280
+ for the lhs equal to `exclude`
281
+
282
+ '''
283
+ rules = {r: self.rules[r] for r in self.rules if r != exclude}
284
+ # the following is essentially `eliminate_words()` code from the
285
+ # `FreeGroupElement` class, the only difference being the first
286
+ # "if" statement
287
+ again = True
288
+ new = word
289
+ while again:
290
+ again = False
291
+ for r in rules:
292
+ prev = new
293
+ if rules[r]**-1 > r**-1:
294
+ new = new.eliminate_word(r, rules[r], _all=True, inverse=False)
295
+ else:
296
+ new = new.eliminate_word(r, rules[r], _all=True)
297
+ if new != prev:
298
+ again = True
299
+ return new
300
+
301
+ def _compute_inverse_rules(self, rules):
302
+ '''
303
+ Compute the inverse rules for a given set of rules.
304
+ The inverse rules are used in the automaton for word reduction.
305
+
306
+ Arguments:
307
+ rules (dictionary): Rules for which the inverse rules are to computed.
308
+
309
+ Returns:
310
+ Dictionary of inverse_rules.
311
+
312
+ '''
313
+ inverse_rules = {}
314
+ for r in rules:
315
+ rule_key_inverse = r**-1
316
+ rule_value_inverse = (rules[r])**-1
317
+ if (rule_value_inverse < rule_key_inverse):
318
+ inverse_rules[rule_key_inverse] = rule_value_inverse
319
+ else:
320
+ inverse_rules[rule_value_inverse] = rule_key_inverse
321
+ return inverse_rules
322
+
323
+ def construct_automaton(self):
324
+ '''
325
+ Construct the automaton based on the set of reduction rules of the system.
326
+
327
+ Automata Design:
328
+ The accept states of the automaton are the proper prefixes of the left hand side of the rules.
329
+ The complete left hand side of the rules are the dead states of the automaton.
330
+
331
+ '''
332
+ self._add_to_automaton(self.rules)
333
+
334
+ def _add_to_automaton(self, rules):
335
+ '''
336
+ Add new states and transitions to the automaton.
337
+
338
+ Summary:
339
+ States corresponding to the new rules added to the system are computed and added to the automaton.
340
+ Transitions in the previously added states are also modified if necessary.
341
+
342
+ Arguments:
343
+ rules (dictionary) -- Dictionary of the newly added rules.
344
+
345
+ '''
346
+ # Automaton variables
347
+ automaton_alphabet = []
348
+ proper_prefixes = {}
349
+
350
+ # compute the inverses of all the new rules added
351
+ all_rules = rules
352
+ inverse_rules = self._compute_inverse_rules(all_rules)
353
+ all_rules.update(inverse_rules)
354
+
355
+ # Keep track of the accept_states.
356
+ accept_states = []
357
+
358
+ for rule in all_rules:
359
+ # The symbols present in the new rules are the symbols to be verified at each state.
360
+ # computes the automaton_alphabet, as the transitions solely depend upon the new states.
361
+ automaton_alphabet += rule.letter_form_elm
362
+ # Compute the proper prefixes for every rule.
363
+ proper_prefixes[rule] = []
364
+ letter_word_array = list(rule.letter_form_elm)
365
+ len_letter_word_array = len(letter_word_array)
366
+ for i in range (1, len_letter_word_array):
367
+ letter_word_array[i] = letter_word_array[i-1]*letter_word_array[i]
368
+ # Add accept states.
369
+ elem = letter_word_array[i-1]
370
+ if elem not in self.reduction_automaton.states:
371
+ self.reduction_automaton.add_state(elem, state_type='a')
372
+ accept_states.append(elem)
373
+ proper_prefixes[rule] = letter_word_array
374
+ # Check for overlaps between dead and accept states.
375
+ if rule in accept_states:
376
+ self.reduction_automaton.states[rule].state_type = 'd'
377
+ self.reduction_automaton.states[rule].rh_rule = all_rules[rule]
378
+ accept_states.remove(rule)
379
+ # Add dead states
380
+ if rule not in self.reduction_automaton.states:
381
+ self.reduction_automaton.add_state(rule, state_type='d', rh_rule=all_rules[rule])
382
+
383
+ automaton_alphabet = set(automaton_alphabet)
384
+
385
+ # Add new transitions for every state.
386
+ for state in self.reduction_automaton.states:
387
+ current_state_name = state
388
+ current_state_type = self.reduction_automaton.states[state].state_type
389
+ # Transitions will be modified only when suffixes of the current_state
390
+ # belongs to the proper_prefixes of the new rules.
391
+ # The rest are ignored if they cannot lead to a dead state after a finite number of transisitons.
392
+ if current_state_type == 's':
393
+ for letter in automaton_alphabet:
394
+ if letter in self.reduction_automaton.states:
395
+ self.reduction_automaton.states[state].add_transition(letter, letter)
396
+ else:
397
+ self.reduction_automaton.states[state].add_transition(letter, current_state_name)
398
+ elif current_state_type == 'a':
399
+ # Check if the transition to any new state in possible.
400
+ for letter in automaton_alphabet:
401
+ _next = current_state_name*letter
402
+ while len(_next) and _next not in self.reduction_automaton.states:
403
+ _next = _next.subword(1, len(_next))
404
+ if not len(_next):
405
+ _next = 'start'
406
+ self.reduction_automaton.states[state].add_transition(letter, _next)
407
+
408
+ # Add transitions for new states. All symbols used in the automaton are considered here.
409
+ # Ignore this if `reduction_automaton.automaton_alphabet` = `automaton_alphabet`.
410
+ if len(self.reduction_automaton.automaton_alphabet) != len(automaton_alphabet):
411
+ for state in accept_states:
412
+ current_state_name = state
413
+ for letter in self.reduction_automaton.automaton_alphabet:
414
+ _next = current_state_name*letter
415
+ while len(_next) and _next not in self.reduction_automaton.states:
416
+ _next = _next.subword(1, len(_next))
417
+ if not len(_next):
418
+ _next = 'start'
419
+ self.reduction_automaton.states[state].add_transition(letter, _next)
420
+
421
+ def reduce_using_automaton(self, word):
422
+ '''
423
+ Reduce a word using an automaton.
424
+
425
+ Summary:
426
+ All the symbols of the word are stored in an array and are given as the input to the automaton.
427
+ If the automaton reaches a dead state that subword is replaced and the automaton is run from the beginning.
428
+ The complete word has to be replaced when the word is read and the automaton reaches a dead state.
429
+ So, this process is repeated until the word is read completely and the automaton reaches the accept state.
430
+
431
+ Arguments:
432
+ word (instance of FreeGroupElement) -- Word that needs to be reduced.
433
+
434
+ '''
435
+ # Modify the automaton if new rules are found.
436
+ if self._new_rules:
437
+ self._add_to_automaton(self._new_rules)
438
+ self._new_rules = {}
439
+
440
+ flag = 1
441
+ while flag:
442
+ flag = 0
443
+ current_state = self.reduction_automaton.states['start']
444
+ for i, s in enumerate(word.letter_form_elm):
445
+ next_state_name = current_state.transitions[s]
446
+ next_state = self.reduction_automaton.states[next_state_name]
447
+ if next_state.state_type == 'd':
448
+ subst = next_state.rh_rule
449
+ word = word.substituted_word(i - len(next_state_name) + 1, i+1, subst)
450
+ flag = 1
451
+ break
452
+ current_state = next_state
453
+ return word
mgm/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem_fsm.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class State:
2
+ '''
3
+ A representation of a state managed by a ``StateMachine``.
4
+
5
+ Attributes:
6
+ name (instance of FreeGroupElement or string) -- State name which is also assigned to the Machine.
7
+ transisitons (OrderedDict) -- Represents all the transitions of the state object.
8
+ state_type (string) -- Denotes the type (accept/start/dead) of the state.
9
+ rh_rule (instance of FreeGroupElement) -- right hand rule for dead state.
10
+ state_machine (instance of StateMachine object) -- The finite state machine that the state belongs to.
11
+ '''
12
+
13
+ def __init__(self, name, state_machine, state_type=None, rh_rule=None):
14
+ self.name = name
15
+ self.transitions = {}
16
+ self.state_machine = state_machine
17
+ self.state_type = state_type[0]
18
+ self.rh_rule = rh_rule
19
+
20
+ def add_transition(self, letter, state):
21
+ '''
22
+ Add a transition from the current state to a new state.
23
+
24
+ Keyword Arguments:
25
+ letter -- The alphabet element the current state reads to make the state transition.
26
+ state -- This will be an instance of the State object which represents a new state after in the transition after the alphabet is read.
27
+
28
+ '''
29
+ self.transitions[letter] = state
30
+
31
+ class StateMachine:
32
+ '''
33
+ Representation of a finite state machine the manages the states and the transitions of the automaton.
34
+
35
+ Attributes:
36
+ states (dictionary) -- Collection of all registered `State` objects.
37
+ name (str) -- Name of the state machine.
38
+ '''
39
+
40
+ def __init__(self, name, automaton_alphabet):
41
+ self.name = name
42
+ self.automaton_alphabet = automaton_alphabet
43
+ self.states = {} # Contains all the states in the machine.
44
+ self.add_state('start', state_type='s')
45
+
46
+ def add_state(self, state_name, state_type=None, rh_rule=None):
47
+ '''
48
+ Instantiate a state object and stores it in the 'states' dictionary.
49
+
50
+ Arguments:
51
+ state_name (instance of FreeGroupElement or string) -- name of the new states.
52
+ state_type (string) -- Denotes the type (accept/start/dead) of the state added.
53
+ rh_rule (instance of FreeGroupElement) -- right hand rule for dead state.
54
+
55
+ '''
56
+ new_state = State(state_name, self, state_type, rh_rule)
57
+ self.states[state_name] = new_state
58
+
59
+ def __repr__(self):
60
+ return "%s" % (self.name)
mgm/lib/python3.10/site-packages/sympy/combinatorics/schur_number.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The Schur number S(k) is the largest integer n for which the interval [1,n]
3
+ can be partitioned into k sum-free sets.(https://mathworld.wolfram.com/SchurNumber.html)
4
+ """
5
+ import math
6
+ from sympy.core import S
7
+ from sympy.core.basic import Basic
8
+ from sympy.core.function import Function
9
+ from sympy.core.numbers import Integer
10
+
11
+
12
+ class SchurNumber(Function):
13
+ r"""
14
+ This function creates a SchurNumber object
15
+ which is evaluated for `k \le 5` otherwise only
16
+ the lower bound information can be retrieved.
17
+
18
+ Examples
19
+ ========
20
+
21
+ >>> from sympy.combinatorics.schur_number import SchurNumber
22
+
23
+ Since S(3) = 13, hence the output is a number
24
+ >>> SchurNumber(3)
25
+ 13
26
+
27
+ We do not know the Schur number for values greater than 5, hence
28
+ only the object is returned
29
+ >>> SchurNumber(6)
30
+ SchurNumber(6)
31
+
32
+ Now, the lower bound information can be retrieved using lower_bound()
33
+ method
34
+ >>> SchurNumber(6).lower_bound()
35
+ 536
36
+
37
+ """
38
+
39
+ @classmethod
40
+ def eval(cls, k):
41
+ if k.is_Number:
42
+ if k is S.Infinity:
43
+ return S.Infinity
44
+ if k.is_zero:
45
+ return S.Zero
46
+ if not k.is_integer or k.is_negative:
47
+ raise ValueError("k should be a positive integer")
48
+ first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44, 5: 160}
49
+ if k <= 5:
50
+ return Integer(first_known_schur_numbers[k])
51
+
52
+ def lower_bound(self):
53
+ f_ = self.args[0]
54
+ # Improved lower bounds known for S(6) and S(7)
55
+ if f_ == 6:
56
+ return Integer(536)
57
+ if f_ == 7:
58
+ return Integer(1680)
59
+ # For other cases, use general expression
60
+ if f_.is_Integer:
61
+ return 3*self.func(f_ - 1).lower_bound() - 1
62
+ return (3**f_ - 1)/2
63
+
64
+
65
+ def _schur_subsets_number(n):
66
+
67
+ if n is S.Infinity:
68
+ raise ValueError("Input must be finite")
69
+ if n <= 0:
70
+ raise ValueError("n must be a non-zero positive integer.")
71
+ elif n <= 3:
72
+ min_k = 1
73
+ else:
74
+ min_k = math.ceil(math.log(2*n + 1, 3))
75
+
76
+ return Integer(min_k)
77
+
78
+
79
+ def schur_partition(n):
80
+ """
81
+
82
+ This function returns the partition in the minimum number of sum-free subsets
83
+ according to the lower bound given by the Schur Number.
84
+
85
+ Parameters
86
+ ==========
87
+
88
+ n: a number
89
+ n is the upper limit of the range [1, n] for which we need to find and
90
+ return the minimum number of free subsets according to the lower bound
91
+ of schur number
92
+
93
+ Returns
94
+ =======
95
+
96
+ List of lists
97
+ List of the minimum number of sum-free subsets
98
+
99
+ Notes
100
+ =====
101
+
102
+ It is possible for some n to make the partition into less
103
+ subsets since the only known Schur numbers are:
104
+ S(1) = 1, S(2) = 4, S(3) = 13, S(4) = 44.
105
+ e.g for n = 44 the lower bound from the function above is 5 subsets but it has been proven
106
+ that can be done with 4 subsets.
107
+
108
+ Examples
109
+ ========
110
+
111
+ For n = 1, 2, 3 the answer is the set itself
112
+
113
+ >>> from sympy.combinatorics.schur_number import schur_partition
114
+ >>> schur_partition(2)
115
+ [[1, 2]]
116
+
117
+ For n > 3, the answer is the minimum number of sum-free subsets:
118
+
119
+ >>> schur_partition(5)
120
+ [[3, 2], [5], [1, 4]]
121
+
122
+ >>> schur_partition(8)
123
+ [[3, 2], [6, 5, 8], [1, 4, 7]]
124
+ """
125
+
126
+ if isinstance(n, Basic) and not n.is_Number:
127
+ raise ValueError("Input value must be a number")
128
+
129
+ number_of_subsets = _schur_subsets_number(n)
130
+ if n == 1:
131
+ sum_free_subsets = [[1]]
132
+ elif n == 2:
133
+ sum_free_subsets = [[1, 2]]
134
+ elif n == 3:
135
+ sum_free_subsets = [[1, 2, 3]]
136
+ else:
137
+ sum_free_subsets = [[1, 4], [2, 3]]
138
+
139
+ while len(sum_free_subsets) < number_of_subsets:
140
+ sum_free_subsets = _generate_next_list(sum_free_subsets, n)
141
+ missed_elements = [3*k + 1 for k in range(len(sum_free_subsets), (n-1)//3 + 1)]
142
+ sum_free_subsets[-1] += missed_elements
143
+
144
+ return sum_free_subsets
145
+
146
+
147
+ def _generate_next_list(current_list, n):
148
+ new_list = []
149
+
150
+ for item in current_list:
151
+ temp_1 = [number*3 for number in item if number*3 <= n]
152
+ temp_2 = [number*3 - 1 for number in item if number*3 - 1 <= n]
153
+ new_item = temp_1 + temp_2
154
+ new_list.append(new_item)
155
+
156
+ last_list = [3*k + 1 for k in range(len(current_list)+1) if 3*k + 1 <= n]
157
+ new_list.append(last_list)
158
+ current_list = new_list
159
+
160
+ return current_list
mgm/lib/python3.10/site-packages/sympy/combinatorics/testutil.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.combinatorics import Permutation
2
+ from sympy.combinatorics.util import _distribute_gens_by_base
3
+
4
+ rmul = Permutation.rmul
5
+
6
+
7
+ def _cmp_perm_lists(first, second):
8
+ """
9
+ Compare two lists of permutations as sets.
10
+
11
+ Explanation
12
+ ===========
13
+
14
+ This is used for testing purposes. Since the array form of a
15
+ permutation is currently a list, Permutation is not hashable
16
+ and cannot be put into a set.
17
+
18
+ Examples
19
+ ========
20
+
21
+ >>> from sympy.combinatorics.permutations import Permutation
22
+ >>> from sympy.combinatorics.testutil import _cmp_perm_lists
23
+ >>> a = Permutation([0, 2, 3, 4, 1])
24
+ >>> b = Permutation([1, 2, 0, 4, 3])
25
+ >>> c = Permutation([3, 4, 0, 1, 2])
26
+ >>> ls1 = [a, b, c]
27
+ >>> ls2 = [b, c, a]
28
+ >>> _cmp_perm_lists(ls1, ls2)
29
+ True
30
+
31
+ """
32
+ return {tuple(a) for a in first} == \
33
+ {tuple(a) for a in second}
34
+
35
+
36
+ def _naive_list_centralizer(self, other, af=False):
37
+ from sympy.combinatorics.perm_groups import PermutationGroup
38
+ """
39
+ Return a list of elements for the centralizer of a subgroup/set/element.
40
+
41
+ Explanation
42
+ ===========
43
+
44
+ This is a brute force implementation that goes over all elements of the
45
+ group and checks for membership in the centralizer. It is used to
46
+ test ``.centralizer()`` from ``sympy.combinatorics.perm_groups``.
47
+
48
+ Examples
49
+ ========
50
+
51
+ >>> from sympy.combinatorics.testutil import _naive_list_centralizer
52
+ >>> from sympy.combinatorics.named_groups import DihedralGroup
53
+ >>> D = DihedralGroup(4)
54
+ >>> _naive_list_centralizer(D, D)
55
+ [Permutation([0, 1, 2, 3]), Permutation([2, 3, 0, 1])]
56
+
57
+ See Also
58
+ ========
59
+
60
+ sympy.combinatorics.perm_groups.centralizer
61
+
62
+ """
63
+ from sympy.combinatorics.permutations import _af_commutes_with
64
+ if hasattr(other, 'generators'):
65
+ elements = list(self.generate_dimino(af=True))
66
+ gens = [x._array_form for x in other.generators]
67
+ commutes_with_gens = lambda x: all(_af_commutes_with(x, gen) for gen in gens)
68
+ centralizer_list = []
69
+ if not af:
70
+ for element in elements:
71
+ if commutes_with_gens(element):
72
+ centralizer_list.append(Permutation._af_new(element))
73
+ else:
74
+ for element in elements:
75
+ if commutes_with_gens(element):
76
+ centralizer_list.append(element)
77
+ return centralizer_list
78
+ elif hasattr(other, 'getitem'):
79
+ return _naive_list_centralizer(self, PermutationGroup(other), af)
80
+ elif hasattr(other, 'array_form'):
81
+ return _naive_list_centralizer(self, PermutationGroup([other]), af)
82
+
83
+
84
+ def _verify_bsgs(group, base, gens):
85
+ """
86
+ Verify the correctness of a base and strong generating set.
87
+
88
+ Explanation
89
+ ===========
90
+
91
+ This is a naive implementation using the definition of a base and a strong
92
+ generating set relative to it. There are other procedures for
93
+ verifying a base and strong generating set, but this one will
94
+ serve for more robust testing.
95
+
96
+ Examples
97
+ ========
98
+
99
+ >>> from sympy.combinatorics.named_groups import AlternatingGroup
100
+ >>> from sympy.combinatorics.testutil import _verify_bsgs
101
+ >>> A = AlternatingGroup(4)
102
+ >>> A.schreier_sims()
103
+ >>> _verify_bsgs(A, A.base, A.strong_gens)
104
+ True
105
+
106
+ See Also
107
+ ========
108
+
109
+ sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims
110
+
111
+ """
112
+ from sympy.combinatorics.perm_groups import PermutationGroup
113
+ strong_gens_distr = _distribute_gens_by_base(base, gens)
114
+ current_stabilizer = group
115
+ for i in range(len(base)):
116
+ candidate = PermutationGroup(strong_gens_distr[i])
117
+ if current_stabilizer.order() != candidate.order():
118
+ return False
119
+ current_stabilizer = current_stabilizer.stabilizer(base[i])
120
+ if current_stabilizer.order() != 1:
121
+ return False
122
+ return True
123
+
124
+
125
+ def _verify_centralizer(group, arg, centr=None):
126
+ """
127
+ Verify the centralizer of a group/set/element inside another group.
128
+
129
+ This is used for testing ``.centralizer()`` from
130
+ ``sympy.combinatorics.perm_groups``
131
+
132
+ Examples
133
+ ========
134
+
135
+ >>> from sympy.combinatorics.named_groups import (SymmetricGroup,
136
+ ... AlternatingGroup)
137
+ >>> from sympy.combinatorics.perm_groups import PermutationGroup
138
+ >>> from sympy.combinatorics.permutations import Permutation
139
+ >>> from sympy.combinatorics.testutil import _verify_centralizer
140
+ >>> S = SymmetricGroup(5)
141
+ >>> A = AlternatingGroup(5)
142
+ >>> centr = PermutationGroup([Permutation([0, 1, 2, 3, 4])])
143
+ >>> _verify_centralizer(S, A, centr)
144
+ True
145
+
146
+ See Also
147
+ ========
148
+
149
+ _naive_list_centralizer,
150
+ sympy.combinatorics.perm_groups.PermutationGroup.centralizer,
151
+ _cmp_perm_lists
152
+
153
+ """
154
+ if centr is None:
155
+ centr = group.centralizer(arg)
156
+ centr_list = list(centr.generate_dimino(af=True))
157
+ centr_list_naive = _naive_list_centralizer(group, arg, af=True)
158
+ return _cmp_perm_lists(centr_list, centr_list_naive)
159
+
160
+
161
+ def _verify_normal_closure(group, arg, closure=None):
162
+ from sympy.combinatorics.perm_groups import PermutationGroup
163
+ """
164
+ Verify the normal closure of a subgroup/subset/element in a group.
165
+
166
+ This is used to test
167
+ sympy.combinatorics.perm_groups.PermutationGroup.normal_closure
168
+
169
+ Examples
170
+ ========
171
+
172
+ >>> from sympy.combinatorics.named_groups import (SymmetricGroup,
173
+ ... AlternatingGroup)
174
+ >>> from sympy.combinatorics.testutil import _verify_normal_closure
175
+ >>> S = SymmetricGroup(3)
176
+ >>> A = AlternatingGroup(3)
177
+ >>> _verify_normal_closure(S, A, closure=A)
178
+ True
179
+
180
+ See Also
181
+ ========
182
+
183
+ sympy.combinatorics.perm_groups.PermutationGroup.normal_closure
184
+
185
+ """
186
+ if closure is None:
187
+ closure = group.normal_closure(arg)
188
+ conjugates = set()
189
+ if hasattr(arg, 'generators'):
190
+ subgr_gens = arg.generators
191
+ elif hasattr(arg, '__getitem__'):
192
+ subgr_gens = arg
193
+ elif hasattr(arg, 'array_form'):
194
+ subgr_gens = [arg]
195
+ for el in group.generate_dimino():
196
+ conjugates.update(gen ^ el for gen in subgr_gens)
197
+ naive_closure = PermutationGroup(list(conjugates))
198
+ return closure.is_subgroup(naive_closure)
199
+
200
+
201
+ def canonicalize_naive(g, dummies, sym, *v):
202
+ """
203
+ Canonicalize tensor formed by tensors of the different types.
204
+
205
+ Explanation
206
+ ===========
207
+
208
+ sym_i symmetry under exchange of two component tensors of type `i`
209
+ None no symmetry
210
+ 0 commuting
211
+ 1 anticommuting
212
+
213
+ Parameters
214
+ ==========
215
+
216
+ g : Permutation representing the tensor.
217
+ dummies : List of dummy indices.
218
+ msym : Symmetry of the metric.
219
+ v : A list of (base_i, gens_i, n_i, sym_i) for tensors of type `i`.
220
+ base_i, gens_i BSGS for tensors of this type
221
+ n_i number of tensors of type `i`
222
+
223
+ Returns
224
+ =======
225
+
226
+ Returns 0 if the tensor is zero, else returns the array form of
227
+ the permutation representing the canonical form of the tensor.
228
+
229
+ Examples
230
+ ========
231
+
232
+ >>> from sympy.combinatorics.testutil import canonicalize_naive
233
+ >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs
234
+ >>> from sympy.combinatorics import Permutation
235
+ >>> g = Permutation([1, 3, 2, 0, 4, 5])
236
+ >>> base2, gens2 = get_symmetric_group_sgs(2)
237
+ >>> canonicalize_naive(g, [2, 3], 0, (base2, gens2, 2, 0))
238
+ [0, 2, 1, 3, 4, 5]
239
+ """
240
+ from sympy.combinatorics.perm_groups import PermutationGroup
241
+ from sympy.combinatorics.tensor_can import gens_products, dummy_sgs
242
+ from sympy.combinatorics.permutations import _af_rmul
243
+ v1 = []
244
+ for i in range(len(v)):
245
+ base_i, gens_i, n_i, sym_i = v[i]
246
+ v1.append((base_i, gens_i, [[]]*n_i, sym_i))
247
+ size, sbase, sgens = gens_products(*v1)
248
+ dgens = dummy_sgs(dummies, sym, size-2)
249
+ if isinstance(sym, int):
250
+ num_types = 1
251
+ dummies = [dummies]
252
+ sym = [sym]
253
+ else:
254
+ num_types = len(sym)
255
+ dgens = []
256
+ for i in range(num_types):
257
+ dgens.extend(dummy_sgs(dummies[i], sym[i], size - 2))
258
+ S = PermutationGroup(sgens)
259
+ D = PermutationGroup([Permutation(x) for x in dgens])
260
+ dlist = list(D.generate(af=True))
261
+ g = g.array_form
262
+ st = set()
263
+ for s in S.generate(af=True):
264
+ h = _af_rmul(g, s)
265
+ for d in dlist:
266
+ q = tuple(_af_rmul(d, h))
267
+ st.add(q)
268
+ a = list(st)
269
+ a.sort()
270
+ prev = (0,)*size
271
+ for h in a:
272
+ if h[:-2] == prev[:-2]:
273
+ if h[-1] != prev[-1]:
274
+ return 0
275
+ prev = h
276
+ return list(a[0])
277
+
278
+
279
+ def graph_certificate(gr):
280
+ """
281
+ Return a certificate for the graph
282
+
283
+ Parameters
284
+ ==========
285
+
286
+ gr : adjacency list
287
+
288
+ Explanation
289
+ ===========
290
+
291
+ The graph is assumed to be unoriented and without
292
+ external lines.
293
+
294
+ Associate to each vertex of the graph a symmetric tensor with
295
+ number of indices equal to the degree of the vertex; indices
296
+ are contracted when they correspond to the same line of the graph.
297
+ The canonical form of the tensor gives a certificate for the graph.
298
+
299
+ This is not an efficient algorithm to get the certificate of a graph.
300
+
301
+ Examples
302
+ ========
303
+
304
+ >>> from sympy.combinatorics.testutil import graph_certificate
305
+ >>> gr1 = {0:[1, 2, 3, 5], 1:[0, 2, 4], 2:[0, 1, 3, 4], 3:[0, 2, 4], 4:[1, 2, 3, 5], 5:[0, 4]}
306
+ >>> gr2 = {0:[1, 5], 1:[0, 2, 3, 4], 2:[1, 3, 5], 3:[1, 2, 4, 5], 4:[1, 3, 5], 5:[0, 2, 3, 4]}
307
+ >>> c1 = graph_certificate(gr1)
308
+ >>> c2 = graph_certificate(gr2)
309
+ >>> c1
310
+ [0, 2, 4, 6, 1, 8, 10, 12, 3, 14, 16, 18, 5, 9, 15, 7, 11, 17, 13, 19, 20, 21]
311
+ >>> c1 == c2
312
+ True
313
+ """
314
+ from sympy.combinatorics.permutations import _af_invert
315
+ from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize
316
+ items = list(gr.items())
317
+ items.sort(key=lambda x: len(x[1]), reverse=True)
318
+ pvert = [x[0] for x in items]
319
+ pvert = _af_invert(pvert)
320
+
321
+ # the indices of the tensor are twice the number of lines of the graph
322
+ num_indices = 0
323
+ for v, neigh in items:
324
+ num_indices += len(neigh)
325
+ # associate to each vertex its indices; for each line
326
+ # between two vertices assign the
327
+ # even index to the vertex which comes first in items,
328
+ # the odd index to the other vertex
329
+ vertices = [[] for i in items]
330
+ i = 0
331
+ for v, neigh in items:
332
+ for v2 in neigh:
333
+ if pvert[v] < pvert[v2]:
334
+ vertices[pvert[v]].append(i)
335
+ vertices[pvert[v2]].append(i+1)
336
+ i += 2
337
+ g = []
338
+ for v in vertices:
339
+ g.extend(v)
340
+ assert len(g) == num_indices
341
+ g += [num_indices, num_indices + 1]
342
+ size = num_indices + 2
343
+ assert sorted(g) == list(range(size))
344
+ g = Permutation(g)
345
+ vlen = [0]*(len(vertices[0])+1)
346
+ for neigh in vertices:
347
+ vlen[len(neigh)] += 1
348
+ v = []
349
+ for i in range(len(vlen)):
350
+ n = vlen[i]
351
+ if n:
352
+ base, gens = get_symmetric_group_sgs(i)
353
+ v.append((base, gens, n, 0))
354
+ v.reverse()
355
+ dummies = list(range(num_indices))
356
+ can = canonicalize(g, dummies, 0, *v)
357
+ return can
mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (320 Bytes). View file
 
mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/delta.cpython-310.pyc ADDED
Binary file (9.21 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/expr_with_limits.cpython-310.pyc ADDED
Binary file (18.8 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/guess.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/products.cpython-310.pyc ADDED
Binary file (18 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/concrete/__pycache__/summations.cpython-310.pyc ADDED
Binary file (42 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (5.29 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/appellseqs.cpython-310.pyc ADDED
Binary file (8.69 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/compatibility.cpython-310.pyc ADDED
Binary file (62.3 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/constructor.cpython-310.pyc ADDED
Binary file (9.3 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/densearith.cpython-310.pyc ADDED
Binary file (34.3 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/densetools.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/distributedmodules.cpython-310.pyc ADDED
Binary file (23 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/domainmatrix.cpython-310.pyc ADDED
Binary file (488 Bytes). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/factortools.cpython-310.pyc ADDED
Binary file (37.9 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/fglmtools.cpython-310.pyc ADDED
Binary file (6.96 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/fields.cpython-310.pyc ADDED
Binary file (18.8 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/groebnertools.cpython-310.pyc ADDED
Binary file (22.7 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyconfig.cpython-310.pyc ADDED
Binary file (1.64 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyerrors.cpython-310.pyc ADDED
Binary file (7.16 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polymatrix.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyoptions.cpython-310.pyc ADDED
Binary file (21.6 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/polyroots.cpython-310.pyc ADDED
Binary file (31 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/rationaltools.cpython-310.pyc ADDED
Binary file (3.11 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/ring_series.cpython-310.pyc ADDED
Binary file (47.9 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/rings.cpython-310.pyc ADDED
Binary file (79.6 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/rootisolation.cpython-310.pyc ADDED
Binary file (51.1 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/rootoftools.cpython-310.pyc ADDED
Binary file (34.3 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/solvers.cpython-310.pyc ADDED
Binary file (13.9 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/sqfreetools.cpython-310.pyc ADDED
Binary file (19 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/__pycache__/subresultants_qq_zz.cpython-310.pyc ADDED
Binary file (68.2 kB). View file
 
mgm/lib/python3.10/site-packages/sympy/polys/dispersion.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core import S
2
+ from sympy.polys import Poly
3
+
4
+
5
+ def dispersionset(p, q=None, *gens, **args):
6
+ r"""Compute the *dispersion set* of two polynomials.
7
+
8
+ For two polynomials `f(x)` and `g(x)` with `\deg f > 0`
9
+ and `\deg g > 0` the dispersion set `\operatorname{J}(f, g)` is defined as:
10
+
11
+ .. math::
12
+ \operatorname{J}(f, g)
13
+ & := \{a \in \mathbb{N}_0 | \gcd(f(x), g(x+a)) \neq 1\} \\
14
+ & = \{a \in \mathbb{N}_0 | \deg \gcd(f(x), g(x+a)) \geq 1\}
15
+
16
+ For a single polynomial one defines `\operatorname{J}(f) := \operatorname{J}(f, f)`.
17
+
18
+ Examples
19
+ ========
20
+
21
+ >>> from sympy import poly
22
+ >>> from sympy.polys.dispersion import dispersion, dispersionset
23
+ >>> from sympy.abc import x
24
+
25
+ Dispersion set and dispersion of a simple polynomial:
26
+
27
+ >>> fp = poly((x - 3)*(x + 3), x)
28
+ >>> sorted(dispersionset(fp))
29
+ [0, 6]
30
+ >>> dispersion(fp)
31
+ 6
32
+
33
+ Note that the definition of the dispersion is not symmetric:
34
+
35
+ >>> fp = poly(x**4 - 3*x**2 + 1, x)
36
+ >>> gp = fp.shift(-3)
37
+ >>> sorted(dispersionset(fp, gp))
38
+ [2, 3, 4]
39
+ >>> dispersion(fp, gp)
40
+ 4
41
+ >>> sorted(dispersionset(gp, fp))
42
+ []
43
+ >>> dispersion(gp, fp)
44
+ -oo
45
+
46
+ Computing the dispersion also works over field extensions:
47
+
48
+ >>> from sympy import sqrt
49
+ >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
50
+ >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
51
+ >>> sorted(dispersionset(fp, gp))
52
+ [2]
53
+ >>> sorted(dispersionset(gp, fp))
54
+ [1, 4]
55
+
56
+ We can even perform the computations for polynomials
57
+ having symbolic coefficients:
58
+
59
+ >>> from sympy.abc import a
60
+ >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
61
+ >>> sorted(dispersionset(fp))
62
+ [0, 1]
63
+
64
+ See Also
65
+ ========
66
+
67
+ dispersion
68
+
69
+ References
70
+ ==========
71
+
72
+ .. [1] [ManWright94]_
73
+ .. [2] [Koepf98]_
74
+ .. [3] [Abramov71]_
75
+ .. [4] [Man93]_
76
+ """
77
+ # Check for valid input
78
+ same = False if q is not None else True
79
+ if same:
80
+ q = p
81
+
82
+ p = Poly(p, *gens, **args)
83
+ q = Poly(q, *gens, **args)
84
+
85
+ if not p.is_univariate or not q.is_univariate:
86
+ raise ValueError("Polynomials need to be univariate")
87
+
88
+ # The generator
89
+ if not p.gen == q.gen:
90
+ raise ValueError("Polynomials must have the same generator")
91
+ gen = p.gen
92
+
93
+ # We define the dispersion of constant polynomials to be zero
94
+ if p.degree() < 1 or q.degree() < 1:
95
+ return {0}
96
+
97
+ # Factor p and q over the rationals
98
+ fp = p.factor_list()
99
+ fq = q.factor_list() if not same else fp
100
+
101
+ # Iterate over all pairs of factors
102
+ J = set()
103
+ for s, unused in fp[1]:
104
+ for t, unused in fq[1]:
105
+ m = s.degree()
106
+ n = t.degree()
107
+ if n != m:
108
+ continue
109
+ an = s.LC()
110
+ bn = t.LC()
111
+ if not (an - bn).is_zero:
112
+ continue
113
+ # Note that the roles of `s` and `t` below are switched
114
+ # w.r.t. the original paper. This is for consistency
115
+ # with the description in the book of W. Koepf.
116
+ anm1 = s.coeff_monomial(gen**(m-1))
117
+ bnm1 = t.coeff_monomial(gen**(n-1))
118
+ alpha = (anm1 - bnm1) / S(n*bn)
119
+ if not alpha.is_integer:
120
+ continue
121
+ if alpha < 0 or alpha in J:
122
+ continue
123
+ if n > 1 and not (s - t.shift(alpha)).is_zero:
124
+ continue
125
+ J.add(alpha)
126
+
127
+ return J
128
+
129
+
130
+ def dispersion(p, q=None, *gens, **args):
131
+ r"""Compute the *dispersion* of polynomials.
132
+
133
+ For two polynomials `f(x)` and `g(x)` with `\deg f > 0`
134
+ and `\deg g > 0` the dispersion `\operatorname{dis}(f, g)` is defined as:
135
+
136
+ .. math::
137
+ \operatorname{dis}(f, g)
138
+ & := \max\{ J(f,g) \cup \{0\} \} \\
139
+ & = \max\{ \{a \in \mathbb{N} | \gcd(f(x), g(x+a)) \neq 1\} \cup \{0\} \}
140
+
141
+ and for a single polynomial `\operatorname{dis}(f) := \operatorname{dis}(f, f)`.
142
+ Note that we make the definition `\max\{\} := -\infty`.
143
+
144
+ Examples
145
+ ========
146
+
147
+ >>> from sympy import poly
148
+ >>> from sympy.polys.dispersion import dispersion, dispersionset
149
+ >>> from sympy.abc import x
150
+
151
+ Dispersion set and dispersion of a simple polynomial:
152
+
153
+ >>> fp = poly((x - 3)*(x + 3), x)
154
+ >>> sorted(dispersionset(fp))
155
+ [0, 6]
156
+ >>> dispersion(fp)
157
+ 6
158
+
159
+ Note that the definition of the dispersion is not symmetric:
160
+
161
+ >>> fp = poly(x**4 - 3*x**2 + 1, x)
162
+ >>> gp = fp.shift(-3)
163
+ >>> sorted(dispersionset(fp, gp))
164
+ [2, 3, 4]
165
+ >>> dispersion(fp, gp)
166
+ 4
167
+ >>> sorted(dispersionset(gp, fp))
168
+ []
169
+ >>> dispersion(gp, fp)
170
+ -oo
171
+
172
+ The maximum of an empty set is defined to be `-\infty`
173
+ as seen in this example.
174
+
175
+ Computing the dispersion also works over field extensions:
176
+
177
+ >>> from sympy import sqrt
178
+ >>> fp = poly(x**2 + sqrt(5)*x - 1, x, domain='QQ<sqrt(5)>')
179
+ >>> gp = poly(x**2 + (2 + sqrt(5))*x + sqrt(5), x, domain='QQ<sqrt(5)>')
180
+ >>> sorted(dispersionset(fp, gp))
181
+ [2]
182
+ >>> sorted(dispersionset(gp, fp))
183
+ [1, 4]
184
+
185
+ We can even perform the computations for polynomials
186
+ having symbolic coefficients:
187
+
188
+ >>> from sympy.abc import a
189
+ >>> fp = poly(4*x**4 + (4*a + 8)*x**3 + (a**2 + 6*a + 4)*x**2 + (a**2 + 2*a)*x, x)
190
+ >>> sorted(dispersionset(fp))
191
+ [0, 1]
192
+
193
+ See Also
194
+ ========
195
+
196
+ dispersionset
197
+
198
+ References
199
+ ==========
200
+
201
+ .. [1] [ManWright94]_
202
+ .. [2] [Koepf98]_
203
+ .. [3] [Abramov71]_
204
+ .. [4] [Man93]_
205
+ """
206
+ J = dispersionset(p, q, *gens, **args)
207
+ if not J:
208
+ # Definition for maximum of empty set
209
+ j = S.NegativeInfinity
210
+ else:
211
+ j = max(J)
212
+ return j
mgm/lib/python3.10/site-packages/sympy/polys/domains/__init__.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of mathematical domains. """
2
+
3
+ __all__ = [
4
+ 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField',
5
+ 'ComplexField', 'AlgebraicField', 'PolynomialRing', 'FractionField',
6
+ 'ExpressionDomain', 'PythonRational',
7
+
8
+ 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW',
9
+ ]
10
+
11
+ from .domain import Domain
12
+ from .finitefield import FiniteField, FF, GF
13
+ from .integerring import IntegerRing, ZZ
14
+ from .rationalfield import RationalField, QQ
15
+ from .algebraicfield import AlgebraicField
16
+ from .gaussiandomains import ZZ_I, QQ_I
17
+ from .realfield import RealField, RR
18
+ from .complexfield import ComplexField, CC
19
+ from .polynomialring import PolynomialRing
20
+ from .fractionfield import FractionField
21
+ from .expressiondomain import ExpressionDomain, EX
22
+ from .expressionrawdomain import EXRAW
23
+ from .pythonrational import PythonRational
24
+
25
+
26
+ # This is imported purely for backwards compatibility because some parts of
27
+ # the codebase used to import this from here and it's possible that downstream
28
+ # does as well:
29
+ from sympy.external.gmpy import GROUND_TYPES # noqa: F401
30
+
31
+ #
32
+ # The rest of these are obsolete and provided only for backwards
33
+ # compatibility:
34
+ #
35
+
36
+ from .pythonfinitefield import PythonFiniteField
37
+ from .gmpyfinitefield import GMPYFiniteField
38
+ from .pythonintegerring import PythonIntegerRing
39
+ from .gmpyintegerring import GMPYIntegerRing
40
+ from .pythonrationalfield import PythonRationalField
41
+ from .gmpyrationalfield import GMPYRationalField
42
+
43
+ FF_python = PythonFiniteField
44
+ FF_gmpy = GMPYFiniteField
45
+
46
+ ZZ_python = PythonIntegerRing
47
+ ZZ_gmpy = GMPYIntegerRing
48
+
49
+ QQ_python = PythonRationalField
50
+ QQ_gmpy = GMPYRationalField
51
+
52
+ __all__.extend((
53
+ 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing',
54
+ 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField',
55
+
56
+ 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy',
57
+ ))
mgm/lib/python3.10/site-packages/sympy/polys/domains/algebraicfield.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`AlgebraicField` class. """
2
+
3
+
4
+ from sympy.core.add import Add
5
+ from sympy.core.mul import Mul
6
+ from sympy.core.singleton import S
7
+ from sympy.polys.domains.characteristiczero import CharacteristicZero
8
+ from sympy.polys.domains.field import Field
9
+ from sympy.polys.domains.simpledomain import SimpleDomain
10
+ from sympy.polys.polyclasses import ANP
11
+ from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed
12
+ from sympy.utilities import public
13
+
14
+ @public
15
+ class AlgebraicField(Field, CharacteristicZero, SimpleDomain):
16
+ r"""Algebraic number field :ref:`QQ(a)`
17
+
18
+ A :ref:`QQ(a)` domain represents an `algebraic number field`_
19
+ `\mathbb{Q}(a)` as a :py:class:`~.Domain` in the domain system (see
20
+ :ref:`polys-domainsintro`).
21
+
22
+ A :py:class:`~.Poly` created from an expression involving `algebraic
23
+ numbers`_ will treat the algebraic numbers as generators if the generators
24
+ argument is not specified.
25
+
26
+ >>> from sympy import Poly, Symbol, sqrt
27
+ >>> x = Symbol('x')
28
+ >>> Poly(x**2 + sqrt(2))
29
+ Poly(x**2 + (sqrt(2)), x, sqrt(2), domain='ZZ')
30
+
31
+ That is a multivariate polynomial with ``sqrt(2)`` treated as one of the
32
+ generators (variables). If the generators are explicitly specified then
33
+ ``sqrt(2)`` will be considered to be a coefficient but by default the
34
+ :ref:`EX` domain is used. To make a :py:class:`~.Poly` with a :ref:`QQ(a)`
35
+ domain the argument ``extension=True`` can be given.
36
+
37
+ >>> Poly(x**2 + sqrt(2), x)
38
+ Poly(x**2 + sqrt(2), x, domain='EX')
39
+ >>> Poly(x**2 + sqrt(2), x, extension=True)
40
+ Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2)>')
41
+
42
+ A generator of the algebraic field extension can also be specified
43
+ explicitly which is particularly useful if the coefficients are all
44
+ rational but an extension field is needed (e.g. to factor the
45
+ polynomial).
46
+
47
+ >>> Poly(x**2 + 1)
48
+ Poly(x**2 + 1, x, domain='ZZ')
49
+ >>> Poly(x**2 + 1, extension=sqrt(2))
50
+ Poly(x**2 + 1, x, domain='QQ<sqrt(2)>')
51
+
52
+ It is possible to factorise a polynomial over a :ref:`QQ(a)` domain using
53
+ the ``extension`` argument to :py:func:`~.factor` or by specifying the domain
54
+ explicitly.
55
+
56
+ >>> from sympy import factor, QQ
57
+ >>> factor(x**2 - 2)
58
+ x**2 - 2
59
+ >>> factor(x**2 - 2, extension=sqrt(2))
60
+ (x - sqrt(2))*(x + sqrt(2))
61
+ >>> factor(x**2 - 2, domain='QQ<sqrt(2)>')
62
+ (x - sqrt(2))*(x + sqrt(2))
63
+ >>> factor(x**2 - 2, domain=QQ.algebraic_field(sqrt(2)))
64
+ (x - sqrt(2))*(x + sqrt(2))
65
+
66
+ The ``extension=True`` argument can be used but will only create an
67
+ extension that contains the coefficients which is usually not enough to
68
+ factorise the polynomial.
69
+
70
+ >>> p = x**3 + sqrt(2)*x**2 - 2*x - 2*sqrt(2)
71
+ >>> factor(p) # treats sqrt(2) as a symbol
72
+ (x + sqrt(2))*(x**2 - 2)
73
+ >>> factor(p, extension=True)
74
+ (x - sqrt(2))*(x + sqrt(2))**2
75
+ >>> factor(x**2 - 2, extension=True) # all rational coefficients
76
+ x**2 - 2
77
+
78
+ It is also possible to use :ref:`QQ(a)` with the :py:func:`~.cancel`
79
+ and :py:func:`~.gcd` functions.
80
+
81
+ >>> from sympy import cancel, gcd
82
+ >>> cancel((x**2 - 2)/(x - sqrt(2)))
83
+ (x**2 - 2)/(x - sqrt(2))
84
+ >>> cancel((x**2 - 2)/(x - sqrt(2)), extension=sqrt(2))
85
+ x + sqrt(2)
86
+ >>> gcd(x**2 - 2, x - sqrt(2))
87
+ 1
88
+ >>> gcd(x**2 - 2, x - sqrt(2), extension=sqrt(2))
89
+ x - sqrt(2)
90
+
91
+ When using the domain directly :ref:`QQ(a)` can be used as a constructor
92
+ to create instances which then support the operations ``+,-,*,**,/``. The
93
+ :py:meth:`~.Domain.algebraic_field` method is used to construct a
94
+ particular :ref:`QQ(a)` domain. The :py:meth:`~.Domain.from_sympy` method
95
+ can be used to create domain elements from normal SymPy expressions.
96
+
97
+ >>> K = QQ.algebraic_field(sqrt(2))
98
+ >>> K
99
+ QQ<sqrt(2)>
100
+ >>> xk = K.from_sympy(3 + 4*sqrt(2))
101
+ >>> xk # doctest: +SKIP
102
+ ANP([4, 3], [1, 0, -2], QQ)
103
+
104
+ Elements of :ref:`QQ(a)` are instances of :py:class:`~.ANP` which have
105
+ limited printing support. The raw display shows the internal
106
+ representation of the element as the list ``[4, 3]`` representing the
107
+ coefficients of ``1`` and ``sqrt(2)`` for this element in the form
108
+ ``a * sqrt(2) + b * 1`` where ``a`` and ``b`` are elements of :ref:`QQ`.
109
+ The minimal polynomial for the generator ``(x**2 - 2)`` is also shown in
110
+ the :ref:`dup-representation` as the list ``[1, 0, -2]``. We can use
111
+ :py:meth:`~.Domain.to_sympy` to get a better printed form for the
112
+ elements and to see the results of operations.
113
+
114
+ >>> xk = K.from_sympy(3 + 4*sqrt(2))
115
+ >>> yk = K.from_sympy(2 + 3*sqrt(2))
116
+ >>> xk * yk # doctest: +SKIP
117
+ ANP([17, 30], [1, 0, -2], QQ)
118
+ >>> K.to_sympy(xk * yk)
119
+ 17*sqrt(2) + 30
120
+ >>> K.to_sympy(xk + yk)
121
+ 5 + 7*sqrt(2)
122
+ >>> K.to_sympy(xk ** 2)
123
+ 24*sqrt(2) + 41
124
+ >>> K.to_sympy(xk / yk)
125
+ sqrt(2)/14 + 9/7
126
+
127
+ Any expression representing an algebraic number can be used to generate
128
+ a :ref:`QQ(a)` domain provided its `minimal polynomial`_ can be computed.
129
+ The function :py:func:`~.minpoly` function is used for this.
130
+
131
+ >>> from sympy import exp, I, pi, minpoly
132
+ >>> g = exp(2*I*pi/3)
133
+ >>> g
134
+ exp(2*I*pi/3)
135
+ >>> g.is_algebraic
136
+ True
137
+ >>> minpoly(g, x)
138
+ x**2 + x + 1
139
+ >>> factor(x**3 - 1, extension=g)
140
+ (x - 1)*(x - exp(2*I*pi/3))*(x + 1 + exp(2*I*pi/3))
141
+
142
+ It is also possible to make an algebraic field from multiple extension
143
+ elements.
144
+
145
+ >>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
146
+ >>> K
147
+ QQ<sqrt(2) + sqrt(3)>
148
+ >>> p = x**4 - 5*x**2 + 6
149
+ >>> factor(p)
150
+ (x**2 - 3)*(x**2 - 2)
151
+ >>> factor(p, domain=K)
152
+ (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3))
153
+ >>> factor(p, extension=[sqrt(2), sqrt(3)])
154
+ (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3))
155
+
156
+ Multiple extension elements are always combined together to make a single
157
+ `primitive element`_. In the case of ``[sqrt(2), sqrt(3)]`` the primitive
158
+ element chosen is ``sqrt(2) + sqrt(3)`` which is why the domain displays
159
+ as ``QQ<sqrt(2) + sqrt(3)>``. The minimal polynomial for the primitive
160
+ element is computed using the :py:func:`~.primitive_element` function.
161
+
162
+ >>> from sympy import primitive_element
163
+ >>> primitive_element([sqrt(2), sqrt(3)], x)
164
+ (x**4 - 10*x**2 + 1, [1, 1])
165
+ >>> minpoly(sqrt(2) + sqrt(3), x)
166
+ x**4 - 10*x**2 + 1
167
+
168
+ The extension elements that generate the domain can be accessed from the
169
+ domain using the :py:attr:`~.ext` and :py:attr:`~.orig_ext` attributes as
170
+ instances of :py:class:`~.AlgebraicNumber`. The minimal polynomial for
171
+ the primitive element as a :py:class:`~.DMP` instance is available as
172
+ :py:attr:`~.mod`.
173
+
174
+ >>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
175
+ >>> K
176
+ QQ<sqrt(2) + sqrt(3)>
177
+ >>> K.ext
178
+ sqrt(2) + sqrt(3)
179
+ >>> K.orig_ext
180
+ (sqrt(2), sqrt(3))
181
+ >>> K.mod # doctest: +SKIP
182
+ DMP_Python([1, 0, -10, 0, 1], QQ)
183
+
184
+ The `discriminant`_ of the field can be obtained from the
185
+ :py:meth:`~.discriminant` method, and an `integral basis`_ from the
186
+ :py:meth:`~.integral_basis` method. The latter returns a list of
187
+ :py:class:`~.ANP` instances by default, but can be made to return instances
188
+ of :py:class:`~.Expr` or :py:class:`~.AlgebraicNumber` by passing a ``fmt``
189
+ argument. The maximal order, or ring of integers, of the field can also be
190
+ obtained from the :py:meth:`~.maximal_order` method, as a
191
+ :py:class:`~sympy.polys.numberfields.modules.Submodule`.
192
+
193
+ >>> zeta5 = exp(2*I*pi/5)
194
+ >>> K = QQ.algebraic_field(zeta5)
195
+ >>> K
196
+ QQ<exp(2*I*pi/5)>
197
+ >>> K.discriminant()
198
+ 125
199
+ >>> K = QQ.algebraic_field(sqrt(5))
200
+ >>> K
201
+ QQ<sqrt(5)>
202
+ >>> K.integral_basis(fmt='sympy')
203
+ [1, 1/2 + sqrt(5)/2]
204
+ >>> K.maximal_order()
205
+ Submodule[[2, 0], [1, 1]]/2
206
+
207
+ The factorization of a rational prime into prime ideals of the field is
208
+ computed by the :py:meth:`~.primes_above` method, which returns a list
209
+ of :py:class:`~sympy.polys.numberfields.primes.PrimeIdeal` instances.
210
+
211
+ >>> zeta7 = exp(2*I*pi/7)
212
+ >>> K = QQ.algebraic_field(zeta7)
213
+ >>> K
214
+ QQ<exp(2*I*pi/7)>
215
+ >>> K.primes_above(11)
216
+ [(11, _x**3 + 5*_x**2 + 4*_x - 1), (11, _x**3 - 4*_x**2 - 5*_x - 1)]
217
+
218
+ The Galois group of the Galois closure of the field can be computed (when
219
+ the minimal polynomial of the field is of sufficiently small degree).
220
+
221
+ >>> K.galois_group(by_name=True)[0]
222
+ S6TransitiveSubgroups.C6
223
+
224
+ Notes
225
+ =====
226
+
227
+ It is not currently possible to generate an algebraic extension over any
228
+ domain other than :ref:`QQ`. Ideally it would be possible to generate
229
+ extensions like ``QQ(x)(sqrt(x**2 - 2))``. This is equivalent to the
230
+ quotient ring ``QQ(x)[y]/(y**2 - x**2 + 2)`` and there are two
231
+ implementations of this kind of quotient ring/extension in the
232
+ :py:class:`~.QuotientRing` and :py:class:`~.MonogenicFiniteExtension`
233
+ classes. Each of those implementations needs some work to make them fully
234
+ usable though.
235
+
236
+ .. _algebraic number field: https://en.wikipedia.org/wiki/Algebraic_number_field
237
+ .. _algebraic numbers: https://en.wikipedia.org/wiki/Algebraic_number
238
+ .. _discriminant: https://en.wikipedia.org/wiki/Discriminant_of_an_algebraic_number_field
239
+ .. _integral basis: https://en.wikipedia.org/wiki/Algebraic_number_field#Integral_basis
240
+ .. _minimal polynomial: https://en.wikipedia.org/wiki/Minimal_polynomial_(field_theory)
241
+ .. _primitive element: https://en.wikipedia.org/wiki/Primitive_element_theorem
242
+ """
243
+
244
+ dtype = ANP
245
+
246
+ is_AlgebraicField = is_Algebraic = True
247
+ is_Numerical = True
248
+
249
+ has_assoc_Ring = False
250
+ has_assoc_Field = True
251
+
252
+ def __init__(self, dom, *ext, alias=None):
253
+ r"""
254
+ Parameters
255
+ ==========
256
+
257
+ dom : :py:class:`~.Domain`
258
+ The base field over which this is an extension field.
259
+ Currently only :ref:`QQ` is accepted.
260
+
261
+ *ext : One or more :py:class:`~.Expr`
262
+ Generators of the extension. These should be expressions that are
263
+ algebraic over `\mathbb{Q}`.
264
+
265
+ alias : str, :py:class:`~.Symbol`, None, optional (default=None)
266
+ If provided, this will be used as the alias symbol for the
267
+ primitive element of the :py:class:`~.AlgebraicField`.
268
+ If ``None``, while ``ext`` consists of exactly one
269
+ :py:class:`~.AlgebraicNumber`, its alias (if any) will be used.
270
+ """
271
+ if not dom.is_QQ:
272
+ raise DomainError("ground domain must be a rational field")
273
+
274
+ from sympy.polys.numberfields import to_number_field
275
+ if len(ext) == 1 and isinstance(ext[0], tuple):
276
+ orig_ext = ext[0][1:]
277
+ else:
278
+ orig_ext = ext
279
+
280
+ if alias is None and len(ext) == 1:
281
+ alias = getattr(ext[0], 'alias', None)
282
+
283
+ self.orig_ext = orig_ext
284
+ """
285
+ Original elements given to generate the extension.
286
+
287
+ >>> from sympy import QQ, sqrt
288
+ >>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
289
+ >>> K.orig_ext
290
+ (sqrt(2), sqrt(3))
291
+ """
292
+
293
+ self.ext = to_number_field(ext, alias=alias)
294
+ """
295
+ Primitive element used for the extension.
296
+
297
+ >>> from sympy import QQ, sqrt
298
+ >>> K = QQ.algebraic_field(sqrt(2), sqrt(3))
299
+ >>> K.ext
300
+ sqrt(2) + sqrt(3)
301
+ """
302
+
303
+ self.mod = self.ext.minpoly.rep
304
+ """
305
+ Minimal polynomial for the primitive element of the extension.
306
+
307
+ >>> from sympy import QQ, sqrt
308
+ >>> K = QQ.algebraic_field(sqrt(2))
309
+ >>> K.mod
310
+ DMP([1, 0, -2], QQ)
311
+ """
312
+
313
+ self.domain = self.dom = dom
314
+
315
+ self.ngens = 1
316
+ self.symbols = self.gens = (self.ext,)
317
+ self.unit = self([dom(1), dom(0)])
318
+
319
+ self.zero = self.dtype.zero(self.mod.to_list(), dom)
320
+ self.one = self.dtype.one(self.mod.to_list(), dom)
321
+
322
+ self._maximal_order = None
323
+ self._discriminant = None
324
+ self._nilradicals_mod_p = {}
325
+
326
+ def new(self, element):
327
+ return self.dtype(element, self.mod.to_list(), self.dom)
328
+
329
+ def __str__(self):
330
+ return str(self.dom) + '<' + str(self.ext) + '>'
331
+
332
+ def __hash__(self):
333
+ return hash((self.__class__.__name__, self.dtype, self.dom, self.ext))
334
+
335
+ def __eq__(self, other):
336
+ """Returns ``True`` if two domains are equivalent. """
337
+ if isinstance(other, AlgebraicField):
338
+ return self.dtype == other.dtype and self.ext == other.ext
339
+ else:
340
+ return NotImplemented
341
+
342
+ def algebraic_field(self, *extension, alias=None):
343
+ r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """
344
+ return AlgebraicField(self.dom, *((self.ext,) + extension), alias=alias)
345
+
346
+ def to_alg_num(self, a):
347
+ """Convert ``a`` of ``dtype`` to an :py:class:`~.AlgebraicNumber`. """
348
+ return self.ext.field_element(a)
349
+
350
+ def to_sympy(self, a):
351
+ """Convert ``a`` of ``dtype`` to a SymPy object. """
352
+ # Precompute a converter to be reused:
353
+ if not hasattr(self, '_converter'):
354
+ self._converter = _make_converter(self)
355
+
356
+ return self._converter(a)
357
+
358
+ def from_sympy(self, a):
359
+ """Convert SymPy's expression to ``dtype``. """
360
+ try:
361
+ return self([self.dom.from_sympy(a)])
362
+ except CoercionFailed:
363
+ pass
364
+
365
+ from sympy.polys.numberfields import to_number_field
366
+
367
+ try:
368
+ return self(to_number_field(a, self.ext).native_coeffs())
369
+ except (NotAlgebraic, IsomorphismFailed):
370
+ raise CoercionFailed(
371
+ "%s is not a valid algebraic number in %s" % (a, self))
372
+
373
+ def from_ZZ(K1, a, K0):
374
+ """Convert a Python ``int`` object to ``dtype``. """
375
+ return K1(K1.dom.convert(a, K0))
376
+
377
+ def from_ZZ_python(K1, a, K0):
378
+ """Convert a Python ``int`` object to ``dtype``. """
379
+ return K1(K1.dom.convert(a, K0))
380
+
381
+ def from_QQ(K1, a, K0):
382
+ """Convert a Python ``Fraction`` object to ``dtype``. """
383
+ return K1(K1.dom.convert(a, K0))
384
+
385
+ def from_QQ_python(K1, a, K0):
386
+ """Convert a Python ``Fraction`` object to ``dtype``. """
387
+ return K1(K1.dom.convert(a, K0))
388
+
389
+ def from_ZZ_gmpy(K1, a, K0):
390
+ """Convert a GMPY ``mpz`` object to ``dtype``. """
391
+ return K1(K1.dom.convert(a, K0))
392
+
393
+ def from_QQ_gmpy(K1, a, K0):
394
+ """Convert a GMPY ``mpq`` object to ``dtype``. """
395
+ return K1(K1.dom.convert(a, K0))
396
+
397
+ def from_RealField(K1, a, K0):
398
+ """Convert a mpmath ``mpf`` object to ``dtype``. """
399
+ return K1(K1.dom.convert(a, K0))
400
+
401
+ def get_ring(self):
402
+ """Returns a ring associated with ``self``. """
403
+ raise DomainError('there is no ring associated with %s' % self)
404
+
405
+ def is_positive(self, a):
406
+ """Returns True if ``a`` is positive. """
407
+ return self.dom.is_positive(a.LC())
408
+
409
+ def is_negative(self, a):
410
+ """Returns True if ``a`` is negative. """
411
+ return self.dom.is_negative(a.LC())
412
+
413
+ def is_nonpositive(self, a):
414
+ """Returns True if ``a`` is non-positive. """
415
+ return self.dom.is_nonpositive(a.LC())
416
+
417
+ def is_nonnegative(self, a):
418
+ """Returns True if ``a`` is non-negative. """
419
+ return self.dom.is_nonnegative(a.LC())
420
+
421
+ def numer(self, a):
422
+ """Returns numerator of ``a``. """
423
+ return a
424
+
425
+ def denom(self, a):
426
+ """Returns denominator of ``a``. """
427
+ return self.one
428
+
429
+ def from_AlgebraicField(K1, a, K0):
430
+ """Convert AlgebraicField element 'a' to another AlgebraicField """
431
+ return K1.from_sympy(K0.to_sympy(a))
432
+
433
+ def from_GaussianIntegerRing(K1, a, K0):
434
+ """Convert a GaussianInteger element 'a' to ``dtype``. """
435
+ return K1.from_sympy(K0.to_sympy(a))
436
+
437
+ def from_GaussianRationalField(K1, a, K0):
438
+ """Convert a GaussianRational element 'a' to ``dtype``. """
439
+ return K1.from_sympy(K0.to_sympy(a))
440
+
441
+ def _do_round_two(self):
442
+ from sympy.polys.numberfields.basis import round_two
443
+ ZK, dK = round_two(self, radicals=self._nilradicals_mod_p)
444
+ self._maximal_order = ZK
445
+ self._discriminant = dK
446
+
447
+ def maximal_order(self):
448
+ """
449
+ Compute the maximal order, or ring of integers, of the field.
450
+
451
+ Returns
452
+ =======
453
+
454
+ :py:class:`~sympy.polys.numberfields.modules.Submodule`.
455
+
456
+ See Also
457
+ ========
458
+
459
+ integral_basis
460
+
461
+ """
462
+ if self._maximal_order is None:
463
+ self._do_round_two()
464
+ return self._maximal_order
465
+
466
+ def integral_basis(self, fmt=None):
467
+ r"""
468
+ Get an integral basis for the field.
469
+
470
+ Parameters
471
+ ==========
472
+
473
+ fmt : str, None, optional (default=None)
474
+ If ``None``, return a list of :py:class:`~.ANP` instances.
475
+ If ``"sympy"``, convert each element of the list to an
476
+ :py:class:`~.Expr`, using ``self.to_sympy()``.
477
+ If ``"alg"``, convert each element of the list to an
478
+ :py:class:`~.AlgebraicNumber`, using ``self.to_alg_num()``.
479
+
480
+ Examples
481
+ ========
482
+
483
+ >>> from sympy import QQ, AlgebraicNumber, sqrt
484
+ >>> alpha = AlgebraicNumber(sqrt(5), alias='alpha')
485
+ >>> k = QQ.algebraic_field(alpha)
486
+ >>> B0 = k.integral_basis()
487
+ >>> B1 = k.integral_basis(fmt='sympy')
488
+ >>> B2 = k.integral_basis(fmt='alg')
489
+ >>> print(B0[1]) # doctest: +SKIP
490
+ ANP([mpq(1,2), mpq(1,2)], [mpq(1,1), mpq(0,1), mpq(-5,1)], QQ)
491
+ >>> print(B1[1])
492
+ 1/2 + alpha/2
493
+ >>> print(B2[1])
494
+ alpha/2 + 1/2
495
+
496
+ In the last two cases we get legible expressions, which print somewhat
497
+ differently because of the different types involved:
498
+
499
+ >>> print(type(B1[1]))
500
+ <class 'sympy.core.add.Add'>
501
+ >>> print(type(B2[1]))
502
+ <class 'sympy.core.numbers.AlgebraicNumber'>
503
+
504
+ See Also
505
+ ========
506
+
507
+ to_sympy
508
+ to_alg_num
509
+ maximal_order
510
+ """
511
+ ZK = self.maximal_order()
512
+ M = ZK.QQ_matrix
513
+ n = M.shape[1]
514
+ B = [self.new(list(reversed(M[:, j].flat()))) for j in range(n)]
515
+ if fmt == 'sympy':
516
+ return [self.to_sympy(b) for b in B]
517
+ elif fmt == 'alg':
518
+ return [self.to_alg_num(b) for b in B]
519
+ return B
520
+
521
+ def discriminant(self):
522
+ """Get the discriminant of the field."""
523
+ if self._discriminant is None:
524
+ self._do_round_two()
525
+ return self._discriminant
526
+
527
+ def primes_above(self, p):
528
+ """Compute the prime ideals lying above a given rational prime *p*."""
529
+ from sympy.polys.numberfields.primes import prime_decomp
530
+ ZK = self.maximal_order()
531
+ dK = self.discriminant()
532
+ rad = self._nilradicals_mod_p.get(p)
533
+ return prime_decomp(p, ZK=ZK, dK=dK, radical=rad)
534
+
535
+ def galois_group(self, by_name=False, max_tries=30, randomize=False):
536
+ """
537
+ Compute the Galois group of the Galois closure of this field.
538
+
539
+ Examples
540
+ ========
541
+
542
+ If the field is Galois, the order of the group will equal the degree
543
+ of the field:
544
+
545
+ >>> from sympy import QQ
546
+ >>> from sympy.abc import x
547
+ >>> k = QQ.alg_field_from_poly(x**4 + 1)
548
+ >>> G, _ = k.galois_group()
549
+ >>> G.order()
550
+ 4
551
+
552
+ If the field is not Galois, then its Galois closure is a proper
553
+ extension, and the order of the Galois group will be greater than the
554
+ degree of the field:
555
+
556
+ >>> k = QQ.alg_field_from_poly(x**4 - 2)
557
+ >>> G, _ = k.galois_group()
558
+ >>> G.order()
559
+ 8
560
+
561
+ See Also
562
+ ========
563
+
564
+ sympy.polys.numberfields.galoisgroups.galois_group
565
+
566
+ """
567
+ return self.ext.minpoly_of_element().galois_group(
568
+ by_name=by_name, max_tries=max_tries, randomize=randomize)
569
+
570
+
571
+ def _make_converter(K):
572
+ """Construct the converter to convert back to Expr"""
573
+ # Precompute the effect of converting to SymPy and expanding expressions
574
+ # like (sqrt(2) + sqrt(3))**2. Asking Expr to do the expansion on every
575
+ # conversion from K to Expr is slow. Here we compute the expansions for
576
+ # each power of the generator and collect together the resulting algebraic
577
+ # terms and the rational coefficients into a matrix.
578
+
579
+ gen = K.ext.as_expr()
580
+ todom = K.dom.from_sympy
581
+
582
+ # We'll let Expr compute the expansions. We won't make any presumptions
583
+ # about what this results in except that it is QQ-linear in some terms
584
+ # that we will call algebraics. The final result will be expressed in
585
+ # terms of those.
586
+ powers = [S.One, gen]
587
+ for n in range(2, K.mod.degree()):
588
+ powers.append((gen * powers[-1]).expand())
589
+
590
+ # Collect the rational coefficients and algebraic Expr that can
591
+ # map the ANP coefficients into an expanded SymPy expression
592
+ terms = [dict(t.as_coeff_Mul()[::-1] for t in Add.make_args(p)) for p in powers]
593
+ algebraics = set().union(*terms)
594
+ matrix = [[todom(t.get(a, S.Zero)) for t in terms] for a in algebraics]
595
+
596
+ # Create a function to do the conversion efficiently:
597
+
598
+ def converter(a):
599
+ """Convert a to Expr using converter"""
600
+ ai = a.to_list()[::-1]
601
+ tosympy = K.dom.to_sympy
602
+ coeffs_dom = [sum(mij*aj for mij, aj in zip(mi, ai)) for mi in matrix]
603
+ coeffs_sympy = [tosympy(c) for c in coeffs_dom]
604
+ res = Add(*(Mul(c, a) for c, a in zip(coeffs_sympy, algebraics)))
605
+ return res
606
+
607
+ return converter
mgm/lib/python3.10/site-packages/sympy/polys/domains/characteristiczero.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`CharacteristicZero` class. """
2
+
3
+
4
+ from sympy.polys.domains.domain import Domain
5
+ from sympy.utilities import public
6
+
7
+ @public
8
+ class CharacteristicZero(Domain):
9
+ """Domain that has infinite number of elements. """
10
+
11
+ has_CharacteristicZero = True
12
+
13
+ def characteristic(self):
14
+ """Return the characteristic of this domain. """
15
+ return 0
mgm/lib/python3.10/site-packages/sympy/polys/domains/compositedomain.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`CompositeDomain` class. """
2
+
3
+
4
+ from sympy.polys.domains.domain import Domain
5
+ from sympy.polys.polyerrors import GeneratorsError
6
+
7
+ from sympy.utilities import public
8
+
9
+ @public
10
+ class CompositeDomain(Domain):
11
+ """Base class for composite domains, e.g. ZZ[x], ZZ(X). """
12
+
13
+ is_Composite = True
14
+
15
+ gens, ngens, symbols, domain = [None]*4
16
+
17
+ def inject(self, *symbols):
18
+ """Inject generators into this domain. """
19
+ if not (set(self.symbols) & set(symbols)):
20
+ return self.__class__(self.domain, self.symbols + symbols, self.order)
21
+ else:
22
+ raise GeneratorsError("common generators in %s and %s" % (self.symbols, symbols))
23
+
24
+ def drop(self, *symbols):
25
+ """Drop generators from this domain. """
26
+ symset = set(symbols)
27
+ newsyms = tuple(s for s in self.symbols if s not in symset)
28
+ domain = self.domain.drop(*symbols)
29
+ if not newsyms:
30
+ return domain
31
+ else:
32
+ return self.__class__(domain, newsyms, self.order)
33
+
34
+ def set_domain(self, domain):
35
+ """Set the ground domain of this domain. """
36
+ return self.__class__(domain, self.symbols, self.order)
37
+
38
+ @property
39
+ def is_Exact(self):
40
+ """Returns ``True`` if this domain is exact. """
41
+ return self.domain.is_Exact
42
+
43
+ def get_exact(self):
44
+ """Returns an exact version of this domain. """
45
+ return self.set_domain(self.domain.get_exact())
46
+
47
+ @property
48
+ def has_CharacteristicZero(self):
49
+ return self.domain.has_CharacteristicZero
50
+
51
+ def characteristic(self):
52
+ return self.domain.characteristic()
mgm/lib/python3.10/site-packages/sympy/polys/domains/domain.py ADDED
@@ -0,0 +1,1372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`Domain` class. """
2
+
3
+ from __future__ import annotations
4
+ from typing import Any
5
+
6
+ from sympy.core.numbers import AlgebraicNumber
7
+ from sympy.core import Basic, sympify
8
+ from sympy.core.sorting import ordered
9
+ from sympy.external.gmpy import GROUND_TYPES
10
+ from sympy.polys.domains.domainelement import DomainElement
11
+ from sympy.polys.orderings import lex
12
+ from sympy.polys.polyerrors import UnificationFailed, CoercionFailed, DomainError
13
+ from sympy.polys.polyutils import _unify_gens, _not_a_coeff
14
+ from sympy.utilities import public
15
+ from sympy.utilities.iterables import is_sequence
16
+
17
+
18
+ @public
19
+ class Domain:
20
+ """Superclass for all domains in the polys domains system.
21
+
22
+ See :ref:`polys-domainsintro` for an introductory explanation of the
23
+ domains system.
24
+
25
+ The :py:class:`~.Domain` class is an abstract base class for all of the
26
+ concrete domain types. There are many different :py:class:`~.Domain`
27
+ subclasses each of which has an associated ``dtype`` which is a class
28
+ representing the elements of the domain. The coefficients of a
29
+ :py:class:`~.Poly` are elements of a domain which must be a subclass of
30
+ :py:class:`~.Domain`.
31
+
32
+ Examples
33
+ ========
34
+
35
+ The most common example domains are the integers :ref:`ZZ` and the
36
+ rationals :ref:`QQ`.
37
+
38
+ >>> from sympy import Poly, symbols, Domain
39
+ >>> x, y = symbols('x, y')
40
+ >>> p = Poly(x**2 + y)
41
+ >>> p
42
+ Poly(x**2 + y, x, y, domain='ZZ')
43
+ >>> p.domain
44
+ ZZ
45
+ >>> isinstance(p.domain, Domain)
46
+ True
47
+ >>> Poly(x**2 + y/2)
48
+ Poly(x**2 + 1/2*y, x, y, domain='QQ')
49
+
50
+ The domains can be used directly in which case the domain object e.g.
51
+ (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of
52
+ ``dtype``.
53
+
54
+ >>> from sympy import ZZ, QQ
55
+ >>> ZZ(2)
56
+ 2
57
+ >>> ZZ.dtype # doctest: +SKIP
58
+ <class 'int'>
59
+ >>> type(ZZ(2)) # doctest: +SKIP
60
+ <class 'int'>
61
+ >>> QQ(1, 2)
62
+ 1/2
63
+ >>> type(QQ(1, 2)) # doctest: +SKIP
64
+ <class 'sympy.polys.domains.pythonrational.PythonRational'>
65
+
66
+ The corresponding domain elements can be used with the arithmetic
67
+ operations ``+,-,*,**`` and depending on the domain some combination of
68
+ ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor
69
+ division) and ``%`` (modulo division) can be used but ``/`` (true
70
+ division) cannot. Since :ref:`QQ` is a :py:class:`~.Field` its elements
71
+ can be used with ``/`` but ``//`` and ``%`` should not be used. Some
72
+ domains have a :py:meth:`~.Domain.gcd` method.
73
+
74
+ >>> ZZ(2) + ZZ(3)
75
+ 5
76
+ >>> ZZ(5) // ZZ(2)
77
+ 2
78
+ >>> ZZ(5) % ZZ(2)
79
+ 1
80
+ >>> QQ(1, 2) / QQ(2, 3)
81
+ 3/4
82
+ >>> ZZ.gcd(ZZ(4), ZZ(2))
83
+ 2
84
+ >>> QQ.gcd(QQ(2,7), QQ(5,3))
85
+ 1/21
86
+ >>> ZZ.is_Field
87
+ False
88
+ >>> QQ.is_Field
89
+ True
90
+
91
+ There are also many other domains including:
92
+
93
+ 1. :ref:`GF(p)` for finite fields of prime order.
94
+ 2. :ref:`RR` for real (floating point) numbers.
95
+ 3. :ref:`CC` for complex (floating point) numbers.
96
+ 4. :ref:`QQ(a)` for algebraic number fields.
97
+ 5. :ref:`K[x]` for polynomial rings.
98
+ 6. :ref:`K(x)` for rational function fields.
99
+ 7. :ref:`EX` for arbitrary expressions.
100
+
101
+ Each domain is represented by a domain object and also an implementation
102
+ class (``dtype``) for the elements of the domain. For example the
103
+ :ref:`K[x]` domains are represented by a domain object which is an
104
+ instance of :py:class:`~.PolynomialRing` and the elements are always
105
+ instances of :py:class:`~.PolyElement`. The implementation class
106
+ represents particular types of mathematical expressions in a way that is
107
+ more efficient than a normal SymPy expression which is of type
108
+ :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and
109
+ :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr`
110
+ to a domain element and vice versa.
111
+
112
+ >>> from sympy import Symbol, ZZ, Expr
113
+ >>> x = Symbol('x')
114
+ >>> K = ZZ[x] # polynomial ring domain
115
+ >>> K
116
+ ZZ[x]
117
+ >>> type(K) # class of the domain
118
+ <class 'sympy.polys.domains.polynomialring.PolynomialRing'>
119
+ >>> K.dtype # class of the elements
120
+ <class 'sympy.polys.rings.PolyElement'>
121
+ >>> p_expr = x**2 + 1 # Expr
122
+ >>> p_expr
123
+ x**2 + 1
124
+ >>> type(p_expr)
125
+ <class 'sympy.core.add.Add'>
126
+ >>> isinstance(p_expr, Expr)
127
+ True
128
+ >>> p_domain = K.from_sympy(p_expr)
129
+ >>> p_domain # domain element
130
+ x**2 + 1
131
+ >>> type(p_domain)
132
+ <class 'sympy.polys.rings.PolyElement'>
133
+ >>> K.to_sympy(p_domain) == p_expr
134
+ True
135
+
136
+ The :py:meth:`~.Domain.convert_from` method is used to convert domain
137
+ elements from one domain to another.
138
+
139
+ >>> from sympy import ZZ, QQ
140
+ >>> ez = ZZ(2)
141
+ >>> eq = QQ.convert_from(ez, ZZ)
142
+ >>> type(ez) # doctest: +SKIP
143
+ <class 'int'>
144
+ >>> type(eq) # doctest: +SKIP
145
+ <class 'sympy.polys.domains.pythonrational.PythonRational'>
146
+
147
+ Elements from different domains should not be mixed in arithmetic or other
148
+ operations: they should be converted to a common domain first. The domain
149
+ method :py:meth:`~.Domain.unify` is used to find a domain that can
150
+ represent all the elements of two given domains.
151
+
152
+ >>> from sympy import ZZ, QQ, symbols
153
+ >>> x, y = symbols('x, y')
154
+ >>> ZZ.unify(QQ)
155
+ QQ
156
+ >>> ZZ[x].unify(QQ)
157
+ QQ[x]
158
+ >>> ZZ[x].unify(QQ[y])
159
+ QQ[x,y]
160
+
161
+ If a domain is a :py:class:`~.Ring` then is might have an associated
162
+ :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and
163
+ :py:meth:`~.Domain.get_ring` methods will find or create the associated
164
+ domain.
165
+
166
+ >>> from sympy import ZZ, QQ, Symbol
167
+ >>> x = Symbol('x')
168
+ >>> ZZ.has_assoc_Field
169
+ True
170
+ >>> ZZ.get_field()
171
+ QQ
172
+ >>> QQ.has_assoc_Ring
173
+ True
174
+ >>> QQ.get_ring()
175
+ ZZ
176
+ >>> K = QQ[x]
177
+ >>> K
178
+ QQ[x]
179
+ >>> K.get_field()
180
+ QQ(x)
181
+
182
+ See also
183
+ ========
184
+
185
+ DomainElement: abstract base class for domain elements
186
+ construct_domain: construct a minimal domain for some expressions
187
+
188
+ """
189
+
190
+ dtype: type | None = None
191
+ """The type (class) of the elements of this :py:class:`~.Domain`:
192
+
193
+ >>> from sympy import ZZ, QQ, Symbol
194
+ >>> ZZ.dtype
195
+ <class 'int'>
196
+ >>> z = ZZ(2)
197
+ >>> z
198
+ 2
199
+ >>> type(z)
200
+ <class 'int'>
201
+ >>> type(z) == ZZ.dtype
202
+ True
203
+
204
+ Every domain has an associated **dtype** ("datatype") which is the
205
+ class of the associated domain elements.
206
+
207
+ See also
208
+ ========
209
+
210
+ of_type
211
+ """
212
+
213
+ zero: Any = None
214
+ """The zero element of the :py:class:`~.Domain`:
215
+
216
+ >>> from sympy import QQ
217
+ >>> QQ.zero
218
+ 0
219
+ >>> QQ.of_type(QQ.zero)
220
+ True
221
+
222
+ See also
223
+ ========
224
+
225
+ of_type
226
+ one
227
+ """
228
+
229
+ one: Any = None
230
+ """The one element of the :py:class:`~.Domain`:
231
+
232
+ >>> from sympy import QQ
233
+ >>> QQ.one
234
+ 1
235
+ >>> QQ.of_type(QQ.one)
236
+ True
237
+
238
+ See also
239
+ ========
240
+
241
+ of_type
242
+ zero
243
+ """
244
+
245
+ is_Ring = False
246
+ """Boolean flag indicating if the domain is a :py:class:`~.Ring`.
247
+
248
+ >>> from sympy import ZZ
249
+ >>> ZZ.is_Ring
250
+ True
251
+
252
+ Basically every :py:class:`~.Domain` represents a ring so this flag is
253
+ not that useful.
254
+
255
+ See also
256
+ ========
257
+
258
+ is_PID
259
+ is_Field
260
+ get_ring
261
+ has_assoc_Ring
262
+ """
263
+
264
+ is_Field = False
265
+ """Boolean flag indicating if the domain is a :py:class:`~.Field`.
266
+
267
+ >>> from sympy import ZZ, QQ
268
+ >>> ZZ.is_Field
269
+ False
270
+ >>> QQ.is_Field
271
+ True
272
+
273
+ See also
274
+ ========
275
+
276
+ is_PID
277
+ is_Ring
278
+ get_field
279
+ has_assoc_Field
280
+ """
281
+
282
+ has_assoc_Ring = False
283
+ """Boolean flag indicating if the domain has an associated
284
+ :py:class:`~.Ring`.
285
+
286
+ >>> from sympy import QQ
287
+ >>> QQ.has_assoc_Ring
288
+ True
289
+ >>> QQ.get_ring()
290
+ ZZ
291
+
292
+ See also
293
+ ========
294
+
295
+ is_Field
296
+ get_ring
297
+ """
298
+
299
+ has_assoc_Field = False
300
+ """Boolean flag indicating if the domain has an associated
301
+ :py:class:`~.Field`.
302
+
303
+ >>> from sympy import ZZ
304
+ >>> ZZ.has_assoc_Field
305
+ True
306
+ >>> ZZ.get_field()
307
+ QQ
308
+
309
+ See also
310
+ ========
311
+
312
+ is_Field
313
+ get_field
314
+ """
315
+
316
+ is_FiniteField = is_FF = False
317
+ is_IntegerRing = is_ZZ = False
318
+ is_RationalField = is_QQ = False
319
+ is_GaussianRing = is_ZZ_I = False
320
+ is_GaussianField = is_QQ_I = False
321
+ is_RealField = is_RR = False
322
+ is_ComplexField = is_CC = False
323
+ is_AlgebraicField = is_Algebraic = False
324
+ is_PolynomialRing = is_Poly = False
325
+ is_FractionField = is_Frac = False
326
+ is_SymbolicDomain = is_EX = False
327
+ is_SymbolicRawDomain = is_EXRAW = False
328
+ is_FiniteExtension = False
329
+
330
+ is_Exact = True
331
+ is_Numerical = False
332
+
333
+ is_Simple = False
334
+ is_Composite = False
335
+
336
+ is_PID = False
337
+ """Boolean flag indicating if the domain is a `principal ideal domain`_.
338
+
339
+ >>> from sympy import ZZ
340
+ >>> ZZ.has_assoc_Field
341
+ True
342
+ >>> ZZ.get_field()
343
+ QQ
344
+
345
+ .. _principal ideal domain: https://en.wikipedia.org/wiki/Principal_ideal_domain
346
+
347
+ See also
348
+ ========
349
+
350
+ is_Field
351
+ get_field
352
+ """
353
+
354
+ has_CharacteristicZero = False
355
+
356
+ rep: str | None = None
357
+ alias: str | None = None
358
+
359
+ def __init__(self):
360
+ raise NotImplementedError
361
+
362
+ def __str__(self):
363
+ return self.rep
364
+
365
+ def __repr__(self):
366
+ return str(self)
367
+
368
+ def __hash__(self):
369
+ return hash((self.__class__.__name__, self.dtype))
370
+
371
+ def new(self, *args):
372
+ return self.dtype(*args)
373
+
374
+ @property
375
+ def tp(self):
376
+ """Alias for :py:attr:`~.Domain.dtype`"""
377
+ return self.dtype
378
+
379
+ def __call__(self, *args):
380
+ """Construct an element of ``self`` domain from ``args``. """
381
+ return self.new(*args)
382
+
383
+ def normal(self, *args):
384
+ return self.dtype(*args)
385
+
386
+ def convert_from(self, element, base):
387
+ """Convert ``element`` to ``self.dtype`` given the base domain. """
388
+ if base.alias is not None:
389
+ method = "from_" + base.alias
390
+ else:
391
+ method = "from_" + base.__class__.__name__
392
+
393
+ _convert = getattr(self, method)
394
+
395
+ if _convert is not None:
396
+ result = _convert(element, base)
397
+
398
+ if result is not None:
399
+ return result
400
+
401
+ raise CoercionFailed("Cannot convert %s of type %s from %s to %s" % (element, type(element), base, self))
402
+
403
+ def convert(self, element, base=None):
404
+ """Convert ``element`` to ``self.dtype``. """
405
+
406
+ if base is not None:
407
+ if _not_a_coeff(element):
408
+ raise CoercionFailed('%s is not in any domain' % element)
409
+ return self.convert_from(element, base)
410
+
411
+ if self.of_type(element):
412
+ return element
413
+
414
+ if _not_a_coeff(element):
415
+ raise CoercionFailed('%s is not in any domain' % element)
416
+
417
+ from sympy.polys.domains import ZZ, QQ, RealField, ComplexField
418
+
419
+ if ZZ.of_type(element):
420
+ return self.convert_from(element, ZZ)
421
+
422
+ if isinstance(element, int):
423
+ return self.convert_from(ZZ(element), ZZ)
424
+
425
+ if GROUND_TYPES != 'python':
426
+ if isinstance(element, ZZ.tp):
427
+ return self.convert_from(element, ZZ)
428
+ if isinstance(element, QQ.tp):
429
+ return self.convert_from(element, QQ)
430
+
431
+ if isinstance(element, float):
432
+ parent = RealField(tol=False)
433
+ return self.convert_from(parent(element), parent)
434
+
435
+ if isinstance(element, complex):
436
+ parent = ComplexField(tol=False)
437
+ return self.convert_from(parent(element), parent)
438
+
439
+ if isinstance(element, DomainElement):
440
+ return self.convert_from(element, element.parent())
441
+
442
+ # TODO: implement this in from_ methods
443
+ if self.is_Numerical and getattr(element, 'is_ground', False):
444
+ return self.convert(element.LC())
445
+
446
+ if isinstance(element, Basic):
447
+ try:
448
+ return self.from_sympy(element)
449
+ except (TypeError, ValueError):
450
+ pass
451
+ else: # TODO: remove this branch
452
+ if not is_sequence(element):
453
+ try:
454
+ element = sympify(element, strict=True)
455
+ if isinstance(element, Basic):
456
+ return self.from_sympy(element)
457
+ except (TypeError, ValueError):
458
+ pass
459
+
460
+ raise CoercionFailed("Cannot convert %s of type %s to %s" % (element, type(element), self))
461
+
462
+ def of_type(self, element):
463
+ """Check if ``a`` is of type ``dtype``. """
464
+ return isinstance(element, self.tp) # XXX: this isn't correct, e.g. PolyElement
465
+
466
+ def __contains__(self, a):
467
+ """Check if ``a`` belongs to this domain. """
468
+ try:
469
+ if _not_a_coeff(a):
470
+ raise CoercionFailed
471
+ self.convert(a) # this might raise, too
472
+ except CoercionFailed:
473
+ return False
474
+
475
+ return True
476
+
477
+ def to_sympy(self, a):
478
+ """Convert domain element *a* to a SymPy expression (Expr).
479
+
480
+ Explanation
481
+ ===========
482
+
483
+ Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most
484
+ public SymPy functions work with objects of type :py:class:`~.Expr`.
485
+ The elements of a :py:class:`~.Domain` have a different internal
486
+ representation. It is not possible to mix domain elements with
487
+ :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and
488
+ :py:meth:`~.Domain.from_sympy` methods to convert its domain elements
489
+ to and from :py:class:`~.Expr`.
490
+
491
+ Parameters
492
+ ==========
493
+
494
+ a: domain element
495
+ An element of this :py:class:`~.Domain`.
496
+
497
+ Returns
498
+ =======
499
+
500
+ expr: Expr
501
+ A normal SymPy expression of type :py:class:`~.Expr`.
502
+
503
+ Examples
504
+ ========
505
+
506
+ Construct an element of the :ref:`QQ` domain and then convert it to
507
+ :py:class:`~.Expr`.
508
+
509
+ >>> from sympy import QQ, Expr
510
+ >>> q_domain = QQ(2)
511
+ >>> q_domain
512
+ 2
513
+ >>> q_expr = QQ.to_sympy(q_domain)
514
+ >>> q_expr
515
+ 2
516
+
517
+ Although the printed forms look similar these objects are not of the
518
+ same type.
519
+
520
+ >>> isinstance(q_domain, Expr)
521
+ False
522
+ >>> isinstance(q_expr, Expr)
523
+ True
524
+
525
+ Construct an element of :ref:`K[x]` and convert to
526
+ :py:class:`~.Expr`.
527
+
528
+ >>> from sympy import Symbol
529
+ >>> x = Symbol('x')
530
+ >>> K = QQ[x]
531
+ >>> x_domain = K.gens[0] # generator x as a domain element
532
+ >>> p_domain = x_domain**2/3 + 1
533
+ >>> p_domain
534
+ 1/3*x**2 + 1
535
+ >>> p_expr = K.to_sympy(p_domain)
536
+ >>> p_expr
537
+ x**2/3 + 1
538
+
539
+ The :py:meth:`~.Domain.from_sympy` method is used for the opposite
540
+ conversion from a normal SymPy expression to a domain element.
541
+
542
+ >>> p_domain == p_expr
543
+ False
544
+ >>> K.from_sympy(p_expr) == p_domain
545
+ True
546
+ >>> K.to_sympy(p_domain) == p_expr
547
+ True
548
+ >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain
549
+ True
550
+ >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr
551
+ True
552
+
553
+ The :py:meth:`~.Domain.from_sympy` method makes it easier to construct
554
+ domain elements interactively.
555
+
556
+ >>> from sympy import Symbol
557
+ >>> x = Symbol('x')
558
+ >>> K = QQ[x]
559
+ >>> K.from_sympy(x**2/3 + 1)
560
+ 1/3*x**2 + 1
561
+
562
+ See also
563
+ ========
564
+
565
+ from_sympy
566
+ convert_from
567
+ """
568
+ raise NotImplementedError
569
+
570
+ def from_sympy(self, a):
571
+ """Convert a SymPy expression to an element of this domain.
572
+
573
+ Explanation
574
+ ===========
575
+
576
+ See :py:meth:`~.Domain.to_sympy` for explanation and examples.
577
+
578
+ Parameters
579
+ ==========
580
+
581
+ expr: Expr
582
+ A normal SymPy expression of type :py:class:`~.Expr`.
583
+
584
+ Returns
585
+ =======
586
+
587
+ a: domain element
588
+ An element of this :py:class:`~.Domain`.
589
+
590
+ See also
591
+ ========
592
+
593
+ to_sympy
594
+ convert_from
595
+ """
596
+ raise NotImplementedError
597
+
598
+ def sum(self, args):
599
+ return sum(args, start=self.zero)
600
+
601
+ def from_FF(K1, a, K0):
602
+ """Convert ``ModularInteger(int)`` to ``dtype``. """
603
+ return None
604
+
605
+ def from_FF_python(K1, a, K0):
606
+ """Convert ``ModularInteger(int)`` to ``dtype``. """
607
+ return None
608
+
609
+ def from_ZZ_python(K1, a, K0):
610
+ """Convert a Python ``int`` object to ``dtype``. """
611
+ return None
612
+
613
+ def from_QQ_python(K1, a, K0):
614
+ """Convert a Python ``Fraction`` object to ``dtype``. """
615
+ return None
616
+
617
+ def from_FF_gmpy(K1, a, K0):
618
+ """Convert ``ModularInteger(mpz)`` to ``dtype``. """
619
+ return None
620
+
621
+ def from_ZZ_gmpy(K1, a, K0):
622
+ """Convert a GMPY ``mpz`` object to ``dtype``. """
623
+ return None
624
+
625
+ def from_QQ_gmpy(K1, a, K0):
626
+ """Convert a GMPY ``mpq`` object to ``dtype``. """
627
+ return None
628
+
629
+ def from_RealField(K1, a, K0):
630
+ """Convert a real element object to ``dtype``. """
631
+ return None
632
+
633
+ def from_ComplexField(K1, a, K0):
634
+ """Convert a complex element to ``dtype``. """
635
+ return None
636
+
637
+ def from_AlgebraicField(K1, a, K0):
638
+ """Convert an algebraic number to ``dtype``. """
639
+ return None
640
+
641
+ def from_PolynomialRing(K1, a, K0):
642
+ """Convert a polynomial to ``dtype``. """
643
+ if a.is_ground:
644
+ return K1.convert(a.LC, K0.dom)
645
+
646
+ def from_FractionField(K1, a, K0):
647
+ """Convert a rational function to ``dtype``. """
648
+ return None
649
+
650
+ def from_MonogenicFiniteExtension(K1, a, K0):
651
+ """Convert an ``ExtensionElement`` to ``dtype``. """
652
+ return K1.convert_from(a.rep, K0.ring)
653
+
654
+ def from_ExpressionDomain(K1, a, K0):
655
+ """Convert a ``EX`` object to ``dtype``. """
656
+ return K1.from_sympy(a.ex)
657
+
658
+ def from_ExpressionRawDomain(K1, a, K0):
659
+ """Convert a ``EX`` object to ``dtype``. """
660
+ return K1.from_sympy(a)
661
+
662
+ def from_GlobalPolynomialRing(K1, a, K0):
663
+ """Convert a polynomial to ``dtype``. """
664
+ if a.degree() <= 0:
665
+ return K1.convert(a.LC(), K0.dom)
666
+
667
+ def from_GeneralizedPolynomialRing(K1, a, K0):
668
+ return K1.from_FractionField(a, K0)
669
+
670
+ def unify_with_symbols(K0, K1, symbols):
671
+ if (K0.is_Composite and (set(K0.symbols) & set(symbols))) or (K1.is_Composite and (set(K1.symbols) & set(symbols))):
672
+ raise UnificationFailed("Cannot unify %s with %s, given %s generators" % (K0, K1, tuple(symbols)))
673
+
674
+ return K0.unify(K1)
675
+
676
+ def unify_composite(K0, K1):
677
+ """Unify two domains where at least one is composite."""
678
+ K0_ground = K0.dom if K0.is_Composite else K0
679
+ K1_ground = K1.dom if K1.is_Composite else K1
680
+
681
+ K0_symbols = K0.symbols if K0.is_Composite else ()
682
+ K1_symbols = K1.symbols if K1.is_Composite else ()
683
+
684
+ domain = K0_ground.unify(K1_ground)
685
+ symbols = _unify_gens(K0_symbols, K1_symbols)
686
+ order = K0.order if K0.is_Composite else K1.order
687
+
688
+ # E.g. ZZ[x].unify(QQ.frac_field(x)) -> ZZ.frac_field(x)
689
+ if ((K0.is_FractionField and K1.is_PolynomialRing or
690
+ K1.is_FractionField and K0.is_PolynomialRing) and
691
+ (not K0_ground.is_Field or not K1_ground.is_Field) and domain.is_Field
692
+ and domain.has_assoc_Ring):
693
+ domain = domain.get_ring()
694
+
695
+ if K0.is_Composite and (not K1.is_Composite or K0.is_FractionField or K1.is_PolynomialRing):
696
+ cls = K0.__class__
697
+ else:
698
+ cls = K1.__class__
699
+
700
+ # Here cls might be PolynomialRing, FractionField, GlobalPolynomialRing
701
+ # (dense/old Polynomialring) or dense/old FractionField.
702
+
703
+ from sympy.polys.domains.old_polynomialring import GlobalPolynomialRing
704
+ if cls == GlobalPolynomialRing:
705
+ return cls(domain, symbols)
706
+
707
+ return cls(domain, symbols, order)
708
+
709
+ def unify(K0, K1, symbols=None):
710
+ """
711
+ Construct a minimal domain that contains elements of ``K0`` and ``K1``.
712
+
713
+ Known domains (from smallest to largest):
714
+
715
+ - ``GF(p)``
716
+ - ``ZZ``
717
+ - ``QQ``
718
+ - ``RR(prec, tol)``
719
+ - ``CC(prec, tol)``
720
+ - ``ALG(a, b, c)``
721
+ - ``K[x, y, z]``
722
+ - ``K(x, y, z)``
723
+ - ``EX``
724
+
725
+ """
726
+ if symbols is not None:
727
+ return K0.unify_with_symbols(K1, symbols)
728
+
729
+ if K0 == K1:
730
+ return K0
731
+
732
+ if not (K0.has_CharacteristicZero and K1.has_CharacteristicZero):
733
+ # Reject unification of domains with different characteristics.
734
+ if K0.characteristic() != K1.characteristic():
735
+ raise UnificationFailed("Cannot unify %s with %s" % (K0, K1))
736
+
737
+ # We do not get here if K0 == K1. The two domains have the same
738
+ # characteristic but are unequal so at least one is composite and
739
+ # we are unifying something like GF(3).unify(GF(3)[x]).
740
+ return K0.unify_composite(K1)
741
+
742
+ # From here we know both domains have characteristic zero and it can be
743
+ # acceptable to fall back on EX.
744
+
745
+ if K0.is_EXRAW:
746
+ return K0
747
+ if K1.is_EXRAW:
748
+ return K1
749
+
750
+ if K0.is_EX:
751
+ return K0
752
+ if K1.is_EX:
753
+ return K1
754
+
755
+ if K0.is_FiniteExtension or K1.is_FiniteExtension:
756
+ if K1.is_FiniteExtension:
757
+ K0, K1 = K1, K0
758
+ if K1.is_FiniteExtension:
759
+ # Unifying two extensions.
760
+ # Try to ensure that K0.unify(K1) == K1.unify(K0)
761
+ if list(ordered([K0.modulus, K1.modulus]))[1] == K0.modulus:
762
+ K0, K1 = K1, K0
763
+ return K1.set_domain(K0)
764
+ else:
765
+ # Drop the generator from other and unify with the base domain
766
+ K1 = K1.drop(K0.symbol)
767
+ K1 = K0.domain.unify(K1)
768
+ return K0.set_domain(K1)
769
+
770
+ if K0.is_Composite or K1.is_Composite:
771
+ return K0.unify_composite(K1)
772
+
773
+ def mkinexact(cls, K0, K1):
774
+ prec = max(K0.precision, K1.precision)
775
+ tol = max(K0.tolerance, K1.tolerance)
776
+ return cls(prec=prec, tol=tol)
777
+
778
+ if K1.is_ComplexField:
779
+ K0, K1 = K1, K0
780
+ if K0.is_ComplexField:
781
+ if K1.is_ComplexField or K1.is_RealField:
782
+ return mkinexact(K0.__class__, K0, K1)
783
+ else:
784
+ return K0
785
+
786
+ if K1.is_RealField:
787
+ K0, K1 = K1, K0
788
+ if K0.is_RealField:
789
+ if K1.is_RealField:
790
+ return mkinexact(K0.__class__, K0, K1)
791
+ elif K1.is_GaussianRing or K1.is_GaussianField:
792
+ from sympy.polys.domains.complexfield import ComplexField
793
+ return ComplexField(prec=K0.precision, tol=K0.tolerance)
794
+ else:
795
+ return K0
796
+
797
+ if K1.is_AlgebraicField:
798
+ K0, K1 = K1, K0
799
+ if K0.is_AlgebraicField:
800
+ if K1.is_GaussianRing:
801
+ K1 = K1.get_field()
802
+ if K1.is_GaussianField:
803
+ K1 = K1.as_AlgebraicField()
804
+ if K1.is_AlgebraicField:
805
+ return K0.__class__(K0.dom.unify(K1.dom), *_unify_gens(K0.orig_ext, K1.orig_ext))
806
+ else:
807
+ return K0
808
+
809
+ if K0.is_GaussianField:
810
+ return K0
811
+ if K1.is_GaussianField:
812
+ return K1
813
+
814
+ if K0.is_GaussianRing:
815
+ if K1.is_RationalField:
816
+ K0 = K0.get_field()
817
+ return K0
818
+ if K1.is_GaussianRing:
819
+ if K0.is_RationalField:
820
+ K1 = K1.get_field()
821
+ return K1
822
+
823
+ if K0.is_RationalField:
824
+ return K0
825
+ if K1.is_RationalField:
826
+ return K1
827
+
828
+ if K0.is_IntegerRing:
829
+ return K0
830
+ if K1.is_IntegerRing:
831
+ return K1
832
+
833
+ from sympy.polys.domains import EX
834
+ return EX
835
+
836
+ def __eq__(self, other):
837
+ """Returns ``True`` if two domains are equivalent. """
838
+ # XXX: Remove this.
839
+ return isinstance(other, Domain) and self.dtype == other.dtype
840
+
841
+ def __ne__(self, other):
842
+ """Returns ``False`` if two domains are equivalent. """
843
+ return not self == other
844
+
845
+ def map(self, seq):
846
+ """Rersively apply ``self`` to all elements of ``seq``. """
847
+ result = []
848
+
849
+ for elt in seq:
850
+ if isinstance(elt, list):
851
+ result.append(self.map(elt))
852
+ else:
853
+ result.append(self(elt))
854
+
855
+ return result
856
+
857
+ def get_ring(self):
858
+ """Returns a ring associated with ``self``. """
859
+ raise DomainError('there is no ring associated with %s' % self)
860
+
861
+ def get_field(self):
862
+ """Returns a field associated with ``self``. """
863
+ raise DomainError('there is no field associated with %s' % self)
864
+
865
+ def get_exact(self):
866
+ """Returns an exact domain associated with ``self``. """
867
+ return self
868
+
869
+ def __getitem__(self, symbols):
870
+ """The mathematical way to make a polynomial ring. """
871
+ if hasattr(symbols, '__iter__'):
872
+ return self.poly_ring(*symbols)
873
+ else:
874
+ return self.poly_ring(symbols)
875
+
876
+ def poly_ring(self, *symbols, order=lex):
877
+ """Returns a polynomial ring, i.e. `K[X]`. """
878
+ from sympy.polys.domains.polynomialring import PolynomialRing
879
+ return PolynomialRing(self, symbols, order)
880
+
881
+ def frac_field(self, *symbols, order=lex):
882
+ """Returns a fraction field, i.e. `K(X)`. """
883
+ from sympy.polys.domains.fractionfield import FractionField
884
+ return FractionField(self, symbols, order)
885
+
886
+ def old_poly_ring(self, *symbols, **kwargs):
887
+ """Returns a polynomial ring, i.e. `K[X]`. """
888
+ from sympy.polys.domains.old_polynomialring import PolynomialRing
889
+ return PolynomialRing(self, *symbols, **kwargs)
890
+
891
+ def old_frac_field(self, *symbols, **kwargs):
892
+ """Returns a fraction field, i.e. `K(X)`. """
893
+ from sympy.polys.domains.old_fractionfield import FractionField
894
+ return FractionField(self, *symbols, **kwargs)
895
+
896
+ def algebraic_field(self, *extension, alias=None):
897
+ r"""Returns an algebraic field, i.e. `K(\alpha, \ldots)`. """
898
+ raise DomainError("Cannot create algebraic field over %s" % self)
899
+
900
+ def alg_field_from_poly(self, poly, alias=None, root_index=-1):
901
+ r"""
902
+ Convenience method to construct an algebraic extension on a root of a
903
+ polynomial, chosen by root index.
904
+
905
+ Parameters
906
+ ==========
907
+
908
+ poly : :py:class:`~.Poly`
909
+ The polynomial whose root generates the extension.
910
+ alias : str, optional (default=None)
911
+ Symbol name for the generator of the extension.
912
+ E.g. "alpha" or "theta".
913
+ root_index : int, optional (default=-1)
914
+ Specifies which root of the polynomial is desired. The ordering is
915
+ as defined by the :py:class:`~.ComplexRootOf` class. The default of
916
+ ``-1`` selects the most natural choice in the common cases of
917
+ quadratic and cyclotomic fields (the square root on the positive
918
+ real or imaginary axis, resp. $\mathrm{e}^{2\pi i/n}$).
919
+
920
+ Examples
921
+ ========
922
+
923
+ >>> from sympy import QQ, Poly
924
+ >>> from sympy.abc import x
925
+ >>> f = Poly(x**2 - 2)
926
+ >>> K = QQ.alg_field_from_poly(f)
927
+ >>> K.ext.minpoly == f
928
+ True
929
+ >>> g = Poly(8*x**3 - 6*x - 1)
930
+ >>> L = QQ.alg_field_from_poly(g, "alpha")
931
+ >>> L.ext.minpoly == g
932
+ True
933
+ >>> L.to_sympy(L([1, 1, 1]))
934
+ alpha**2 + alpha + 1
935
+
936
+ """
937
+ from sympy.polys.rootoftools import CRootOf
938
+ root = CRootOf(poly, root_index)
939
+ alpha = AlgebraicNumber(root, alias=alias)
940
+ return self.algebraic_field(alpha, alias=alias)
941
+
942
+ def cyclotomic_field(self, n, ss=False, alias="zeta", gen=None, root_index=-1):
943
+ r"""
944
+ Convenience method to construct a cyclotomic field.
945
+
946
+ Parameters
947
+ ==========
948
+
949
+ n : int
950
+ Construct the nth cyclotomic field.
951
+ ss : boolean, optional (default=False)
952
+ If True, append *n* as a subscript on the alias string.
953
+ alias : str, optional (default="zeta")
954
+ Symbol name for the generator.
955
+ gen : :py:class:`~.Symbol`, optional (default=None)
956
+ Desired variable for the cyclotomic polynomial that defines the
957
+ field. If ``None``, a dummy variable will be used.
958
+ root_index : int, optional (default=-1)
959
+ Specifies which root of the polynomial is desired. The ordering is
960
+ as defined by the :py:class:`~.ComplexRootOf` class. The default of
961
+ ``-1`` selects the root $\mathrm{e}^{2\pi i/n}$.
962
+
963
+ Examples
964
+ ========
965
+
966
+ >>> from sympy import QQ, latex
967
+ >>> K = QQ.cyclotomic_field(5)
968
+ >>> K.to_sympy(K([-1, 1]))
969
+ 1 - zeta
970
+ >>> L = QQ.cyclotomic_field(7, True)
971
+ >>> a = L.to_sympy(L([-1, 1]))
972
+ >>> print(a)
973
+ 1 - zeta7
974
+ >>> print(latex(a))
975
+ 1 - \zeta_{7}
976
+
977
+ """
978
+ from sympy.polys.specialpolys import cyclotomic_poly
979
+ if ss:
980
+ alias += str(n)
981
+ return self.alg_field_from_poly(cyclotomic_poly(n, gen), alias=alias,
982
+ root_index=root_index)
983
+
984
+ def inject(self, *symbols):
985
+ """Inject generators into this domain. """
986
+ raise NotImplementedError
987
+
988
+ def drop(self, *symbols):
989
+ """Drop generators from this domain. """
990
+ if self.is_Simple:
991
+ return self
992
+ raise NotImplementedError # pragma: no cover
993
+
994
+ def is_zero(self, a):
995
+ """Returns True if ``a`` is zero. """
996
+ return not a
997
+
998
+ def is_one(self, a):
999
+ """Returns True if ``a`` is one. """
1000
+ return a == self.one
1001
+
1002
+ def is_positive(self, a):
1003
+ """Returns True if ``a`` is positive. """
1004
+ return a > 0
1005
+
1006
+ def is_negative(self, a):
1007
+ """Returns True if ``a`` is negative. """
1008
+ return a < 0
1009
+
1010
+ def is_nonpositive(self, a):
1011
+ """Returns True if ``a`` is non-positive. """
1012
+ return a <= 0
1013
+
1014
+ def is_nonnegative(self, a):
1015
+ """Returns True if ``a`` is non-negative. """
1016
+ return a >= 0
1017
+
1018
+ def canonical_unit(self, a):
1019
+ if self.is_negative(a):
1020
+ return -self.one
1021
+ else:
1022
+ return self.one
1023
+
1024
+ def abs(self, a):
1025
+ """Absolute value of ``a``, implies ``__abs__``. """
1026
+ return abs(a)
1027
+
1028
+ def neg(self, a):
1029
+ """Returns ``a`` negated, implies ``__neg__``. """
1030
+ return -a
1031
+
1032
+ def pos(self, a):
1033
+ """Returns ``a`` positive, implies ``__pos__``. """
1034
+ return +a
1035
+
1036
+ def add(self, a, b):
1037
+ """Sum of ``a`` and ``b``, implies ``__add__``. """
1038
+ return a + b
1039
+
1040
+ def sub(self, a, b):
1041
+ """Difference of ``a`` and ``b``, implies ``__sub__``. """
1042
+ return a - b
1043
+
1044
+ def mul(self, a, b):
1045
+ """Product of ``a`` and ``b``, implies ``__mul__``. """
1046
+ return a * b
1047
+
1048
+ def pow(self, a, b):
1049
+ """Raise ``a`` to power ``b``, implies ``__pow__``. """
1050
+ return a ** b
1051
+
1052
+ def exquo(self, a, b):
1053
+ """Exact quotient of *a* and *b*. Analogue of ``a / b``.
1054
+
1055
+ Explanation
1056
+ ===========
1057
+
1058
+ This is essentially the same as ``a / b`` except that an error will be
1059
+ raised if the division is inexact (if there is any remainder) and the
1060
+ result will always be a domain element. When working in a
1061
+ :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ`
1062
+ or :ref:`K[x]`) ``exquo`` should be used instead of ``/``.
1063
+
1064
+ The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does
1065
+ not raise an exception) then ``a == b*q``.
1066
+
1067
+ Examples
1068
+ ========
1069
+
1070
+ We can use ``K.exquo`` instead of ``/`` for exact division.
1071
+
1072
+ >>> from sympy import ZZ
1073
+ >>> ZZ.exquo(ZZ(4), ZZ(2))
1074
+ 2
1075
+ >>> ZZ.exquo(ZZ(5), ZZ(2))
1076
+ Traceback (most recent call last):
1077
+ ...
1078
+ ExactQuotientFailed: 2 does not divide 5 in ZZ
1079
+
1080
+ Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero
1081
+ divisor) is always exact so in that case ``/`` can be used instead of
1082
+ :py:meth:`~.Domain.exquo`.
1083
+
1084
+ >>> from sympy import QQ
1085
+ >>> QQ.exquo(QQ(5), QQ(2))
1086
+ 5/2
1087
+ >>> QQ(5) / QQ(2)
1088
+ 5/2
1089
+
1090
+ Parameters
1091
+ ==========
1092
+
1093
+ a: domain element
1094
+ The dividend
1095
+ b: domain element
1096
+ The divisor
1097
+
1098
+ Returns
1099
+ =======
1100
+
1101
+ q: domain element
1102
+ The exact quotient
1103
+
1104
+ Raises
1105
+ ======
1106
+
1107
+ ExactQuotientFailed: if exact division is not possible.
1108
+ ZeroDivisionError: when the divisor is zero.
1109
+
1110
+ See also
1111
+ ========
1112
+
1113
+ quo: Analogue of ``a // b``
1114
+ rem: Analogue of ``a % b``
1115
+ div: Analogue of ``divmod(a, b)``
1116
+
1117
+ Notes
1118
+ =====
1119
+
1120
+ Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int``
1121
+ (or ``mpz``) division as ``a / b`` should not be used as it would give
1122
+ a ``float`` which is not a domain element.
1123
+
1124
+ >>> ZZ(4) / ZZ(2) # doctest: +SKIP
1125
+ 2.0
1126
+ >>> ZZ(5) / ZZ(2) # doctest: +SKIP
1127
+ 2.5
1128
+
1129
+ On the other hand with `SYMPY_GROUND_TYPES=flint` elements of :ref:`ZZ`
1130
+ are ``flint.fmpz`` and division would raise an exception:
1131
+
1132
+ >>> ZZ(4) / ZZ(2) # doctest: +SKIP
1133
+ Traceback (most recent call last):
1134
+ ...
1135
+ TypeError: unsupported operand type(s) for /: 'fmpz' and 'fmpz'
1136
+
1137
+ Using ``/`` with :ref:`ZZ` will lead to incorrect results so
1138
+ :py:meth:`~.Domain.exquo` should be used instead.
1139
+
1140
+ """
1141
+ raise NotImplementedError
1142
+
1143
+ def quo(self, a, b):
1144
+ """Quotient of *a* and *b*. Analogue of ``a // b``.
1145
+
1146
+ ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See
1147
+ :py:meth:`~.Domain.div` for more explanation.
1148
+
1149
+ See also
1150
+ ========
1151
+
1152
+ rem: Analogue of ``a % b``
1153
+ div: Analogue of ``divmod(a, b)``
1154
+ exquo: Analogue of ``a / b``
1155
+ """
1156
+ raise NotImplementedError
1157
+
1158
+ def rem(self, a, b):
1159
+ """Modulo division of *a* and *b*. Analogue of ``a % b``.
1160
+
1161
+ ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See
1162
+ :py:meth:`~.Domain.div` for more explanation.
1163
+
1164
+ See also
1165
+ ========
1166
+
1167
+ quo: Analogue of ``a // b``
1168
+ div: Analogue of ``divmod(a, b)``
1169
+ exquo: Analogue of ``a / b``
1170
+ """
1171
+ raise NotImplementedError
1172
+
1173
+ def div(self, a, b):
1174
+ """Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)``
1175
+
1176
+ Explanation
1177
+ ===========
1178
+
1179
+ This is essentially the same as ``divmod(a, b)`` except that is more
1180
+ consistent when working over some :py:class:`~.Field` domains such as
1181
+ :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the
1182
+ :py:meth:`~.Domain.div` method should be used instead of ``divmod``.
1183
+
1184
+ The key invariant is that if ``q, r = K.div(a, b)`` then
1185
+ ``a == b*q + r``.
1186
+
1187
+ The result of ``K.div(a, b)`` is the same as the tuple
1188
+ ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and
1189
+ remainder are needed then it is more efficient to use
1190
+ :py:meth:`~.Domain.div`.
1191
+
1192
+ Examples
1193
+ ========
1194
+
1195
+ We can use ``K.div`` instead of ``divmod`` for floor division and
1196
+ remainder.
1197
+
1198
+ >>> from sympy import ZZ, QQ
1199
+ >>> ZZ.div(ZZ(5), ZZ(2))
1200
+ (2, 1)
1201
+
1202
+ If ``K`` is a :py:class:`~.Field` then the division is always exact
1203
+ with a remainder of :py:attr:`~.Domain.zero`.
1204
+
1205
+ >>> QQ.div(QQ(5), QQ(2))
1206
+ (5/2, 0)
1207
+
1208
+ Parameters
1209
+ ==========
1210
+
1211
+ a: domain element
1212
+ The dividend
1213
+ b: domain element
1214
+ The divisor
1215
+
1216
+ Returns
1217
+ =======
1218
+
1219
+ (q, r): tuple of domain elements
1220
+ The quotient and remainder
1221
+
1222
+ Raises
1223
+ ======
1224
+
1225
+ ZeroDivisionError: when the divisor is zero.
1226
+
1227
+ See also
1228
+ ========
1229
+
1230
+ quo: Analogue of ``a // b``
1231
+ rem: Analogue of ``a % b``
1232
+ exquo: Analogue of ``a / b``
1233
+
1234
+ Notes
1235
+ =====
1236
+
1237
+ If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as
1238
+ the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type
1239
+ defines ``divmod`` in a way that is undesirable so
1240
+ :py:meth:`~.Domain.div` should be used instead of ``divmod``.
1241
+
1242
+ >>> a = QQ(1)
1243
+ >>> b = QQ(3, 2)
1244
+ >>> a # doctest: +SKIP
1245
+ mpq(1,1)
1246
+ >>> b # doctest: +SKIP
1247
+ mpq(3,2)
1248
+ >>> divmod(a, b) # doctest: +SKIP
1249
+ (mpz(0), mpq(1,1))
1250
+ >>> QQ.div(a, b) # doctest: +SKIP
1251
+ (mpq(2,3), mpq(0,1))
1252
+
1253
+ Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so
1254
+ :py:meth:`~.Domain.div` should be used instead.
1255
+
1256
+ """
1257
+ raise NotImplementedError
1258
+
1259
+ def invert(self, a, b):
1260
+ """Returns inversion of ``a mod b``, implies something. """
1261
+ raise NotImplementedError
1262
+
1263
+ def revert(self, a):
1264
+ """Returns ``a**(-1)`` if possible. """
1265
+ raise NotImplementedError
1266
+
1267
+ def numer(self, a):
1268
+ """Returns numerator of ``a``. """
1269
+ raise NotImplementedError
1270
+
1271
+ def denom(self, a):
1272
+ """Returns denominator of ``a``. """
1273
+ raise NotImplementedError
1274
+
1275
+ def half_gcdex(self, a, b):
1276
+ """Half extended GCD of ``a`` and ``b``. """
1277
+ s, t, h = self.gcdex(a, b)
1278
+ return s, h
1279
+
1280
+ def gcdex(self, a, b):
1281
+ """Extended GCD of ``a`` and ``b``. """
1282
+ raise NotImplementedError
1283
+
1284
+ def cofactors(self, a, b):
1285
+ """Returns GCD and cofactors of ``a`` and ``b``. """
1286
+ gcd = self.gcd(a, b)
1287
+ cfa = self.quo(a, gcd)
1288
+ cfb = self.quo(b, gcd)
1289
+ return gcd, cfa, cfb
1290
+
1291
+ def gcd(self, a, b):
1292
+ """Returns GCD of ``a`` and ``b``. """
1293
+ raise NotImplementedError
1294
+
1295
+ def lcm(self, a, b):
1296
+ """Returns LCM of ``a`` and ``b``. """
1297
+ raise NotImplementedError
1298
+
1299
+ def log(self, a, b):
1300
+ """Returns b-base logarithm of ``a``. """
1301
+ raise NotImplementedError
1302
+
1303
+ def sqrt(self, a):
1304
+ """Returns a (possibly inexact) square root of ``a``.
1305
+
1306
+ Explanation
1307
+ ===========
1308
+ There is no universal definition of "inexact square root" for all
1309
+ domains. It is not recommended to implement this method for domains
1310
+ other then :ref:`ZZ`.
1311
+
1312
+ See also
1313
+ ========
1314
+ exsqrt
1315
+ """
1316
+ raise NotImplementedError
1317
+
1318
+ def is_square(self, a):
1319
+ """Returns whether ``a`` is a square in the domain.
1320
+
1321
+ Explanation
1322
+ ===========
1323
+ Returns ``True`` if there is an element ``b`` in the domain such that
1324
+ ``b * b == a``, otherwise returns ``False``. For inexact domains like
1325
+ :ref:`RR` and :ref:`CC`, a tiny difference in this equality can be
1326
+ tolerated.
1327
+
1328
+ See also
1329
+ ========
1330
+ exsqrt
1331
+ """
1332
+ raise NotImplementedError
1333
+
1334
+ def exsqrt(self, a):
1335
+ """Principal square root of a within the domain if ``a`` is square.
1336
+
1337
+ Explanation
1338
+ ===========
1339
+ The implementation of this method should return an element ``b`` in the
1340
+ domain such that ``b * b == a``, or ``None`` if there is no such ``b``.
1341
+ For inexact domains like :ref:`RR` and :ref:`CC`, a tiny difference in
1342
+ this equality can be tolerated. The choice of a "principal" square root
1343
+ should follow a consistent rule whenever possible.
1344
+
1345
+ See also
1346
+ ========
1347
+ sqrt, is_square
1348
+ """
1349
+ raise NotImplementedError
1350
+
1351
+ def evalf(self, a, prec=None, **options):
1352
+ """Returns numerical approximation of ``a``. """
1353
+ return self.to_sympy(a).evalf(prec, **options)
1354
+
1355
+ n = evalf
1356
+
1357
+ def real(self, a):
1358
+ return a
1359
+
1360
+ def imag(self, a):
1361
+ return self.zero
1362
+
1363
+ def almosteq(self, a, b, tolerance=None):
1364
+ """Check if ``a`` and ``b`` are almost equal. """
1365
+ return a == b
1366
+
1367
+ def characteristic(self):
1368
+ """Return the characteristic of this domain. """
1369
+ raise NotImplementedError('characteristic()')
1370
+
1371
+
1372
+ __all__ = ['Domain']
mgm/lib/python3.10/site-packages/sympy/polys/domains/domainelement.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Trait for implementing domain elements. """
2
+
3
+
4
+ from sympy.utilities import public
5
+
6
+ @public
7
+ class DomainElement:
8
+ """
9
+ Represents an element of a domain.
10
+
11
+ Mix in this trait into a class whose instances should be recognized as
12
+ elements of a domain. Method ``parent()`` gives that domain.
13
+ """
14
+
15
+ __slots__ = ()
16
+
17
+ def parent(self):
18
+ """Get the domain associated with ``self``
19
+
20
+ Examples
21
+ ========
22
+
23
+ >>> from sympy import ZZ, symbols
24
+ >>> x, y = symbols('x, y')
25
+ >>> K = ZZ[x,y]
26
+ >>> p = K(x)**2 + K(y)**2
27
+ >>> p
28
+ x**2 + y**2
29
+ >>> p.parent()
30
+ ZZ[x,y]
31
+
32
+ Notes
33
+ =====
34
+
35
+ This is used by :py:meth:`~.Domain.convert` to identify the domain
36
+ associated with a domain element.
37
+ """
38
+ raise NotImplementedError("abstract method")
mgm/lib/python3.10/site-packages/sympy/polys/domains/expressiondomain.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Implementation of :class:`ExpressionDomain` class. """
2
+
3
+
4
+ from sympy.core import sympify, SympifyError
5
+ from sympy.polys.domains.domainelement import DomainElement
6
+ from sympy.polys.domains.characteristiczero import CharacteristicZero
7
+ from sympy.polys.domains.field import Field
8
+ from sympy.polys.domains.simpledomain import SimpleDomain
9
+ from sympy.polys.polyutils import PicklableWithSlots
10
+ from sympy.utilities import public
11
+
12
+ eflags = {"deep": False, "mul": True, "power_exp": False, "power_base": False,
13
+ "basic": False, "multinomial": False, "log": False}
14
+
15
+ @public
16
+ class ExpressionDomain(Field, CharacteristicZero, SimpleDomain):
17
+ """A class for arbitrary expressions. """
18
+
19
+ is_SymbolicDomain = is_EX = True
20
+
21
+ class Expression(DomainElement, PicklableWithSlots):
22
+ """An arbitrary expression. """
23
+
24
+ __slots__ = ('ex',)
25
+
26
+ def __init__(self, ex):
27
+ if not isinstance(ex, self.__class__):
28
+ self.ex = sympify(ex)
29
+ else:
30
+ self.ex = ex.ex
31
+
32
+ def __repr__(f):
33
+ return 'EX(%s)' % repr(f.ex)
34
+
35
+ def __str__(f):
36
+ return 'EX(%s)' % str(f.ex)
37
+
38
+ def __hash__(self):
39
+ return hash((self.__class__.__name__, self.ex))
40
+
41
+ def parent(self):
42
+ return EX
43
+
44
+ def as_expr(f):
45
+ return f.ex
46
+
47
+ def numer(f):
48
+ return f.__class__(f.ex.as_numer_denom()[0])
49
+
50
+ def denom(f):
51
+ return f.__class__(f.ex.as_numer_denom()[1])
52
+
53
+ def simplify(f, ex):
54
+ return f.__class__(ex.cancel().expand(**eflags))
55
+
56
+ def __abs__(f):
57
+ return f.__class__(abs(f.ex))
58
+
59
+ def __neg__(f):
60
+ return f.__class__(-f.ex)
61
+
62
+ def _to_ex(f, g):
63
+ try:
64
+ return f.__class__(g)
65
+ except SympifyError:
66
+ return None
67
+
68
+ def __lt__(f, g):
69
+ return f.ex.sort_key() < g.ex.sort_key()
70
+
71
+ def __add__(f, g):
72
+ g = f._to_ex(g)
73
+
74
+ if g is None:
75
+ return NotImplemented
76
+ elif g == EX.zero:
77
+ return f
78
+ elif f == EX.zero:
79
+ return g
80
+ else:
81
+ return f.simplify(f.ex + g.ex)
82
+
83
+ def __radd__(f, g):
84
+ return f.simplify(f.__class__(g).ex + f.ex)
85
+
86
+ def __sub__(f, g):
87
+ g = f._to_ex(g)
88
+
89
+ if g is None:
90
+ return NotImplemented
91
+ elif g == EX.zero:
92
+ return f
93
+ elif f == EX.zero:
94
+ return -g
95
+ else:
96
+ return f.simplify(f.ex - g.ex)
97
+
98
+ def __rsub__(f, g):
99
+ return f.simplify(f.__class__(g).ex - f.ex)
100
+
101
+ def __mul__(f, g):
102
+ g = f._to_ex(g)
103
+
104
+ if g is None:
105
+ return NotImplemented
106
+
107
+ if EX.zero in (f, g):
108
+ return EX.zero
109
+ elif f.ex.is_Number and g.ex.is_Number:
110
+ return f.__class__(f.ex*g.ex)
111
+
112
+ return f.simplify(f.ex*g.ex)
113
+
114
+ def __rmul__(f, g):
115
+ return f.simplify(f.__class__(g).ex*f.ex)
116
+
117
+ def __pow__(f, n):
118
+ n = f._to_ex(n)
119
+
120
+ if n is not None:
121
+ return f.simplify(f.ex**n.ex)
122
+ else:
123
+ return NotImplemented
124
+
125
+ def __truediv__(f, g):
126
+ g = f._to_ex(g)
127
+
128
+ if g is not None:
129
+ return f.simplify(f.ex/g.ex)
130
+ else:
131
+ return NotImplemented
132
+
133
+ def __rtruediv__(f, g):
134
+ return f.simplify(f.__class__(g).ex/f.ex)
135
+
136
+ def __eq__(f, g):
137
+ return f.ex == f.__class__(g).ex
138
+
139
+ def __ne__(f, g):
140
+ return not f == g
141
+
142
+ def __bool__(f):
143
+ return not f.ex.is_zero
144
+
145
+ def gcd(f, g):
146
+ from sympy.polys import gcd
147
+ return f.__class__(gcd(f.ex, f.__class__(g).ex))
148
+
149
+ def lcm(f, g):
150
+ from sympy.polys import lcm
151
+ return f.__class__(lcm(f.ex, f.__class__(g).ex))
152
+
153
+ dtype = Expression
154
+
155
+ zero = Expression(0)
156
+ one = Expression(1)
157
+
158
+ rep = 'EX'
159
+
160
+ has_assoc_Ring = False
161
+ has_assoc_Field = True
162
+
163
+ def __init__(self):
164
+ pass
165
+
166
+ def __eq__(self, other):
167
+ if isinstance(other, ExpressionDomain):
168
+ return True
169
+ else:
170
+ return NotImplemented
171
+
172
+ def __hash__(self):
173
+ return hash("EX")
174
+
175
+ def to_sympy(self, a):
176
+ """Convert ``a`` to a SymPy object. """
177
+ return a.as_expr()
178
+
179
+ def from_sympy(self, a):
180
+ """Convert SymPy's expression to ``dtype``. """
181
+ return self.dtype(a)
182
+
183
+ def from_ZZ(K1, a, K0):
184
+ """Convert a Python ``int`` object to ``dtype``. """
185
+ return K1(K0.to_sympy(a))
186
+
187
+ def from_ZZ_python(K1, a, K0):
188
+ """Convert a Python ``int`` object to ``dtype``. """
189
+ return K1(K0.to_sympy(a))
190
+
191
+ def from_QQ(K1, a, K0):
192
+ """Convert a Python ``Fraction`` object to ``dtype``. """
193
+ return K1(K0.to_sympy(a))
194
+
195
+ def from_QQ_python(K1, a, K0):
196
+ """Convert a Python ``Fraction`` object to ``dtype``. """
197
+ return K1(K0.to_sympy(a))
198
+
199
+ def from_ZZ_gmpy(K1, a, K0):
200
+ """Convert a GMPY ``mpz`` object to ``dtype``. """
201
+ return K1(K0.to_sympy(a))
202
+
203
+ def from_QQ_gmpy(K1, a, K0):
204
+ """Convert a GMPY ``mpq`` object to ``dtype``. """
205
+ return K1(K0.to_sympy(a))
206
+
207
+ def from_GaussianIntegerRing(K1, a, K0):
208
+ """Convert a ``GaussianRational`` object to ``dtype``. """
209
+ return K1(K0.to_sympy(a))
210
+
211
+ def from_GaussianRationalField(K1, a, K0):
212
+ """Convert a ``GaussianRational`` object to ``dtype``. """
213
+ return K1(K0.to_sympy(a))
214
+
215
+ def from_AlgebraicField(K1, a, K0):
216
+ """Convert an ``ANP`` object to ``dtype``. """
217
+ return K1(K0.to_sympy(a))
218
+
219
+ def from_RealField(K1, a, K0):
220
+ """Convert a mpmath ``mpf`` object to ``dtype``. """
221
+ return K1(K0.to_sympy(a))
222
+
223
+ def from_ComplexField(K1, a, K0):
224
+ """Convert a mpmath ``mpc`` object to ``dtype``. """
225
+ return K1(K0.to_sympy(a))
226
+
227
+ def from_PolynomialRing(K1, a, K0):
228
+ """Convert a ``DMP`` object to ``dtype``. """
229
+ return K1(K0.to_sympy(a))
230
+
231
+ def from_FractionField(K1, a, K0):
232
+ """Convert a ``DMF`` object to ``dtype``. """
233
+ return K1(K0.to_sympy(a))
234
+
235
+ def from_ExpressionDomain(K1, a, K0):
236
+ """Convert a ``EX`` object to ``dtype``. """
237
+ return a
238
+
239
+ def get_ring(self):
240
+ """Returns a ring associated with ``self``. """
241
+ return self # XXX: EX is not a ring but we don't have much choice here.
242
+
243
+ def get_field(self):
244
+ """Returns a field associated with ``self``. """
245
+ return self
246
+
247
+ def is_positive(self, a):
248
+ """Returns True if ``a`` is positive. """
249
+ return a.ex.as_coeff_mul()[0].is_positive
250
+
251
+ def is_negative(self, a):
252
+ """Returns True if ``a`` is negative. """
253
+ return a.ex.could_extract_minus_sign()
254
+
255
+ def is_nonpositive(self, a):
256
+ """Returns True if ``a`` is non-positive. """
257
+ return a.ex.as_coeff_mul()[0].is_nonpositive
258
+
259
+ def is_nonnegative(self, a):
260
+ """Returns True if ``a`` is non-negative. """
261
+ return a.ex.as_coeff_mul()[0].is_nonnegative
262
+
263
+ def numer(self, a):
264
+ """Returns numerator of ``a``. """
265
+ return a.numer()
266
+
267
+ def denom(self, a):
268
+ """Returns denominator of ``a``. """
269
+ return a.denom()
270
+
271
+ def gcd(self, a, b):
272
+ return self(1)
273
+
274
+ def lcm(self, a, b):
275
+ return a.lcm(b)
276
+
277
+
278
+ EX = ExpressionDomain()