Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+2
- janus/lib/python3.10/site-packages/sympy/combinatorics/__init__.pyAdded+43
- janus/lib/python3.10/site-packages/sympy/combinatorics/coset_table.pyAdded+1255
- janus/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.pyAdded+1354
- janus/lib/python3.10/site-packages/sympy/combinatorics/free_groups.pyAdded+1354
- janus/lib/python3.10/site-packages/sympy/combinatorics/galois.pyAdded+611
- janus/lib/python3.10/site-packages/sympy/combinatorics/generators.pyAdded+302
- janus/lib/python3.10/site-packages/sympy/combinatorics/graycode.pyAdded+430
- janus/lib/python3.10/site-packages/sympy/combinatorics/group_constructs.pyAdded+61
- janus/lib/python3.10/site-packages/sympy/combinatorics/group_numbers.pyAdded+296
- janus/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.pyAdded+549
- janus/lib/python3.10/site-packages/sympy/combinatorics/named_groups.pyAdded+332
- janus/lib/python3.10/site-packages/sympy/combinatorics/partitions.pyAdded+745
- janus/lib/python3.10/site-packages/sympy/combinatorics/pc_groups.pyAdded+709
- janus/lib/python3.10/site-packages/sympy/combinatorics/perm_groups.pyAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/permutations.pyAdded+3115
- janus/lib/python3.10/site-packages/sympy/combinatorics/polyhedron.pyAdded+1019
- janus/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem.pyAdded+453
- janus/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem_fsm.pyAdded+60
- janus/lib/python3.10/site-packages/sympy/combinatorics/schur_number.pyAdded+160
- janus/lib/python3.10/site-packages/sympy/combinatorics/subsets.pyAdded+619
- janus/lib/python3.10/site-packages/sympy/combinatorics/tensor_can.pyAdded+1190
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__init__.pyAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/__init__.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_fp_groups.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_free_groups.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_galois.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_generators.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_group_constructs.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_homomorphisms.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_named_groups.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_partitions.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_pc_groups.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_perm_groups.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_permutations.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_polyhedron.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_prufer.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_rewriting.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_schur_number.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_subsets.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_testutil.cpython-310.pycAdded
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_free_groups.pyAdded+221
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_generators.pyAdded+105
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_graycode.pyAdded+72
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_numbers.pyAdded+110
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_homomorphisms.pyAdded+114
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_perm_groups.pyAdded+1243
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_polyhedron.pyAdded+105
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_rewriting.pyAdded+49
- janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_subsets.pyAdded+63
445 unmodified lines446447448445 unmodified linesjanus/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so filter=lfs diff=lfs merge=lfs -textjanus/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -textjanus/lib/python3.10/site-packages/transformers/__pycache__/modeling_outputs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text445 unmodified lines446447448449450445 unmodified linesjanus/lib/python3.10/site-packages/safetensors/_safetensors_rust.abi3.so filter=lfs diff=lfs merge=lfs -textjanus/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -textjanus/lib/python3.10/site-packages/transformers/__pycache__/modeling_outputs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -textjanus/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -textjanus/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
12345678910111213141516171819202122232425262728293031323334353637383940414243from sympy.combinatorics.permutations import Permutation, Cyclefrom sympy.combinatorics.prufer import Pruferfrom sympy.combinatorics.generators import cyclic, alternating, symmetric, dihedralfrom sympy.combinatorics.subsets import Subsetfrom sympy.combinatorics.partitions import (Partition, IntegerPartition, RGS_rank, RGS_unrank, RGS_enum)from sympy.combinatorics.polyhedron import (Polyhedron, tetrahedron, cube, octahedron, dodecahedron, icosahedron)from sympy.combinatorics.perm_groups import PermutationGroup, Coset, SymmetricPermutationGroupfrom sympy.combinatorics.group_constructs import DirectProductfrom sympy.combinatorics.graycode import GrayCodefrom sympy.combinatorics.named_groups import (SymmetricGroup, DihedralGroup, CyclicGroup, AlternatingGroup, AbelianGroup, RubikGroup)from sympy.combinatorics.pc_groups import PolycyclicGroup, Collectorfrom sympy.combinatorics.free_groups import free_group
__all__ = [ 'Permutation', 'Cycle',
'Prufer',
'cyclic', 'alternating', 'symmetric', 'dihedral',
'Subset',
'Partition', 'IntegerPartition', 'RGS_rank', 'RGS_unrank', 'RGS_enum',
'Polyhedron', 'tetrahedron', 'cube', 'octahedron', 'dodecahedron', 'icosahedron',
'PermutationGroup', 'Coset', 'SymmetricPermutationGroup',
'DirectProduct',
'GrayCode',
'SymmetricGroup', 'DihedralGroup', 'CyclicGroup', 'AlternatingGroup', 'AbelianGroup', 'RubikGroup',
'PolycyclicGroup', 'Collector',
'free_group',]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255from sympy.combinatorics.free_groups import free_groupfrom sympy.printing.defaults import DefaultPrinting
from itertools import chain, productfrom bisect import bisect_left
################################################################################ COSET TABLE ################################################################################
class CosetTable(DefaultPrinting): # coset_table: Mathematically a coset table # represented using a list of lists # alpha: Mathematically a coset (precisely, a live coset) # represented by an integer between i with 1 <= i <= n # alpha in c # x: Mathematically an element of "A" (set of generators and # their inverses), represented using "FpGroupElement" # fp_grp: Finitely Presented Group with < X|R > as presentation. # H: subgroup of fp_grp. # NOTE: We start with H as being only a list of words in generators # of "fp_grp". Since `.subgroup` method has not been implemented.
r"""
Properties ==========
[1] `0 \in \Omega` and `\tau(1) = \epsilon` [2] `\alpha^x = \beta \Leftrightarrow \beta^{x^{-1}} = \alpha` [3] If `\alpha^x = \beta`, then `H \tau(\alpha)x = H \tau(\beta)` [4] `\forall \alpha \in \Omega, 1^{\tau(\alpha)} = \alpha`
References ==========
.. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory"
.. [2] John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490. "Implementation and Analysis of the Todd-Coxeter Algorithm"
""" # default limit for the number of cosets allowed in a # coset enumeration. coset_table_max_limit = 4096000 # limit for the current instance coset_table_limit = None # maximum size of deduction stack above or equal to # which it is emptied max_stack_size = 100
def __init__(self, fp_grp, subgroup, max_cosets=None): if not max_cosets: max_cosets = CosetTable.coset_table_max_limit self.fp_group = fp_grp self.subgroup = subgroup self.coset_table_limit = max_cosets # "p" is setup independent of Omega and n self.p = [0] # a list of the form `[gen_1, gen_1^{-1}, ... , gen_k, gen_k^{-1}]` self.A = list(chain.from_iterable((gen, gen**-1) \ for gen in self.fp_group.generators)) #P[alpha, x] Only defined when alpha^x is defined. self.P = [[None]*len(self.A)] # the mathematical coset table which is a list of lists self.table = [[None]*len(self.A)] self.A_dict = {x: self.A.index(x) for x in self.A} self.A_dict_inv = {} for x, index in self.A_dict.items(): if index % 2 == 0: self.A_dict_inv[x] = self.A_dict[x] + 1 else: self.A_dict_inv[x] = self.A_dict[x] - 1 # used in the coset-table based method of coset enumeration. Each of # the element is called a "deduction" which is the form (alpha, x) whenever # a value is assigned to alpha^x during a definition or "deduction process" self.deduction_stack = [] # Attributes for modified methods. H = self.subgroup self._grp = free_group(', ' .join(["a_%d" % i for i in range(len(H))]))[0] self.P = [[None]*len(self.A)] self.p_p = {}
@property def omega(self): """Set of live cosets. """ return [coset for coset in range(len(self.p)) if self.p[coset] == coset]
def copy(self): """ Return a shallow copy of Coset Table instance ``self``.
""" self_copy = self.__class__(self.fp_group, self.subgroup) self_copy.table = [list(perm_rep) for perm_rep in self.table] self_copy.p = list(self.p) self_copy.deduction_stack = list(self.deduction_stack) return self_copy
def __str__(self): return "Coset Table on %s with %s as subgroup generators" \ % (self.fp_group, self.subgroup)
__repr__ = __str__
@property def n(self): """The number `n` represents the length of the sublist containing the live cosets.
""" if not self.table: return 0 return max(self.omega) + 1
# Pg. 152 [1] def is_complete(self): r""" The coset table is called complete if it has no undefined entries on the live cosets; that is, `\alpha^x` is defined for all `\alpha \in \Omega` and `x \in A`.
""" return not any(None in self.table[coset] for coset in self.omega)
# Pg. 153 [1] def define(self, alpha, x, modified=False): r""" This routine is used in the relator-based strategy of Todd-Coxeter algorithm if some `\alpha^x` is undefined. We check whether there is space available for defining a new coset. If there is enough space then we remedy this by adjoining a new coset `\beta` to `\Omega` (i.e to set of live cosets) and put that equal to `\alpha^x`, then make an assignment satisfying Property[1]. If there is not enough space then we halt the Coset Table creation. The maximum amount of space that can be used by Coset Table can be manipulated using the class variable ``CosetTable.coset_table_max_limit``.
See Also ========
define_c
""" A = self.A table = self.table len_table = len(table) if len_table >= self.coset_table_limit: # abort the further generation of cosets raise ValueError("the coset enumeration has defined more than " "%s cosets. Try with a greater value max number of cosets " % self.coset_table_limit) table.append([None]*len(A)) self.P.append([None]*len(self.A)) # beta is the new coset generated beta = len_table self.p.append(beta) table[alpha][self.A_dict[x]] = beta table[beta][self.A_dict_inv[x]] = alpha # P[alpha][x] = epsilon, P[beta][x**-1] = epsilon if modified: self.P[alpha][self.A_dict[x]] = self._grp.identity self.P[beta][self.A_dict_inv[x]] = self._grp.identity self.p_p[beta] = self._grp.identity
def define_c(self, alpha, x): r""" A variation of ``define`` routine, described on Pg. 165 [1], used in the coset table-based strategy of Todd-Coxeter algorithm. It differs from ``define`` routine in that for each definition it also adds the tuple `(\alpha, x)` to the deduction stack.
See Also ========
define
""" A = self.A table = self.table len_table = len(table) if len_table >= self.coset_table_limit: # abort the further generation of cosets raise ValueError("the coset enumeration has defined more than " "%s cosets. Try with a greater value max number of cosets " % self.coset_table_limit) table.append([None]*len(A)) # beta is the new coset generated beta = len_table self.p.append(beta) table[alpha][self.A_dict[x]] = beta table[beta][self.A_dict_inv[x]] = alpha # append to deduction stack self.deduction_stack.append((alpha, x))
def scan_c(self, alpha, word): """ A variation of ``scan`` routine, described on pg. 165 of [1], which puts at tuple, whenever a deduction occurs, to deduction stack.
See Also ========
scan, scan_check, scan_and_fill, scan_and_fill_c
""" # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 # list of union of generators and their inverses while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: self.coincidence_c(f, b) return while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # run the "coincidence" routine self.coincidence_c(f, b) elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f self.deduction_stack.append((f, word[i])) # otherwise scan is incomplete and yields no information
# alpha, beta coincide, i.e. alpha, beta represent the pair of cosets where # coincidence occurs def coincidence_c(self, alpha, beta): """ A variation of ``coincidence`` routine used in the coset-table based method of coset enumeration. The only difference being on addition of a new coset in coset table(i.e new coset introduction), then it is appended to ``deduction_stack``.
See Also ========
coincidence
""" A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table # behaves as a queue q = [] self.merge(alpha, beta, q) while len(q) > 0: gamma = q.pop(0) for x in A_dict: delta = table[gamma][A_dict[x]] if delta is not None: table[delta][A_dict_inv[x]] = None # only line of difference from ``coincidence`` routine self.deduction_stack.append((delta, x**-1)) mu = self.rep(gamma) nu = self.rep(delta) if table[mu][A_dict[x]] is not None: self.merge(nu, table[mu][A_dict[x]], q) elif table[nu][A_dict_inv[x]] is not None: self.merge(mu, table[nu][A_dict_inv[x]], q) else: table[mu][A_dict[x]] = nu table[nu][A_dict_inv[x]] = mu
def scan(self, alpha, word, y=None, fill=False, modified=False): r""" ``scan`` performs a scanning process on the input ``word``. It first locates the largest prefix ``s`` of ``word`` for which `\alpha^s` is defined (i.e is not ``None``), ``s`` may be empty. Let ``word=sv``, let ``t`` be the longest suffix of ``v`` for which `\alpha^{t^{-1}}` is defined, and let ``v=ut``. Then three possibilities are there:
1. If ``t=v``, then we say that the scan completes, and if, in addition `\alpha^s = \alpha^{t^{-1}}`, then we say that the scan completes correctly.
2. It can also happen that scan does not complete, but `|u|=1`; that is, the word ``u`` consists of a single generator `x \in A`. In that case, if `\alpha^s = \beta` and `\alpha^{t^{-1}} = \gamma`, then we can set `\beta^x = \gamma` and `\gamma^{x^{-1}} = \beta`. These assignments are known as deductions and enable the scan to complete correctly.
3. See ``coicidence`` routine for explanation of third condition.
Notes =====
The code for the procedure of scanning `\alpha \in \Omega` under `w \in A*` is defined on pg. 155 [1]
See Also ========
scan_c, scan_check, scan_and_fill, scan_and_fill_c
Scan and Fill =============
Performed when the default argument fill=True.
Modified Scan =============
Performed when the default argument modified=True
""" # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 b_p = y if modified: f_p = self._grp.identity flag = 0 while fill or flag == 0: flag = 1 while i <= j and table[f][A_dict[word[i]]] is not None: if modified: f_p = f_p*self.P[f][A_dict[word[i]]] f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: if modified: self.modified_coincidence(f, b, f_p**-1*y) else: self.coincidence(f, b) return while j >= i and table[b][A_dict_inv[word[j]]] is not None: if modified: b_p = b_p*self.P[b][self.A_dict_inv[word[j]]] b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # run the "coincidence" routine if modified: self.modified_coincidence(f, b, f_p**-1*b_p) else: self.coincidence(f, b) elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f if modified: self.P[f][self.A_dict[word[i]]] = f_p**-1*b_p self.P[b][self.A_dict_inv[word[i]]] = b_p**-1*f_p return elif fill: self.define(f, word[i], modified=modified) # otherwise scan is incomplete and yields no information
# used in the low-index subgroups algorithm def scan_check(self, alpha, word): r""" Another version of ``scan`` routine, described on, it checks whether `\alpha` scans correctly under `word`, it is a straightforward modification of ``scan``. ``scan_check`` returns ``False`` (rather than calling ``coincidence``) if the scan completes incorrectly; otherwise it returns ``True``.
See Also ========
scan, scan_c, scan_and_fill, scan_and_fill_c
""" # alpha is an integer representing a "coset" # since scanning can be in two cases # 1. for alpha=0 and w in Y (i.e generating set of H) # 2. alpha in Omega (set of live cosets), w in R (relators) A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table f = alpha i = 0 r = len(word) b = alpha j = r - 1 while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: return f == b while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: # we have an incorrect completed scan with coincidence f ~ b # return False, instead of calling coincidence routine return False elif j == i: # deduction process table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f return True
def merge(self, k, lamda, q, w=None, modified=False): """ Merge two classes with representatives ``k`` and ``lamda``, described on Pg. 157 [1] (for pseudocode), start by putting ``p[k] = lamda``. It is more efficient to choose the new representative from the larger of the two classes being merged, i.e larger among ``k`` and ``lamda``. procedure ``merge`` performs the merging operation, adds the deleted class representative to the queue ``q``.
Parameters ==========
'k', 'lamda' being the two class representatives to be merged.
Notes =====
Pg. 86-87 [1] contains a description of this method.
See Also ========
coincidence, rep
""" p = self.p rep = self.rep phi = rep(k, modified=modified) psi = rep(lamda, modified=modified) if phi != psi: mu = min(phi, psi) v = max(phi, psi) p[v] = mu if modified: if v == phi: self.p_p[phi] = self.p_p[k]**-1*w*self.p_p[lamda] else: self.p_p[psi] = self.p_p[lamda]**-1*w**-1*self.p_p[k] q.append(v)
def rep(self, k, modified=False): r""" Parameters ==========
`k \in [0 \ldots n-1]`, as for ``self`` only array ``p`` is used
Returns =======
Representative of the class containing ``k``.
Returns the representative of `\sim` class containing ``k``, it also makes some modification to array ``p`` of ``self`` to ease further computations, described on Pg. 157 [1].
The information on classes under `\sim` is stored in array `p` of ``self`` argument, which will always satisfy the property:
`p[\alpha] \sim \alpha` and `p[\alpha]=\alpha \iff \alpha=rep(\alpha)` `\forall \in [0 \ldots n-1]`.
So, for `\alpha \in [0 \ldots n-1]`, we find `rep(self, \alpha)` by continually replacing `\alpha` by `p[\alpha]` until it becomes constant (i.e satisfies `p[\alpha] = \alpha`):w
To increase the efficiency of later ``rep`` calculations, whenever we find `rep(self, \alpha)=\beta`, we set `p[\gamma] = \beta \forall \gamma \in p-chain` from `\alpha` to `\beta`
Notes =====
``rep`` routine is also described on Pg. 85-87 [1] in Atkinson's algorithm, this results from the fact that ``coincidence`` routine introduces functionality similar to that introduced by the ``minimal_block`` routine on Pg. 85-87 [1].
See Also ========
coincidence, merge
""" p = self.p lamda = k rho = p[lamda] if modified: s = p[:] while rho != lamda: if modified: s[rho] = lamda lamda = rho rho = p[lamda] if modified: rho = s[lamda] while rho != k: mu = rho rho = s[mu] p[rho] = lamda self.p_p[rho] = self.p_p[rho]*self.p_p[mu] else: mu = k rho = p[mu] while rho != lamda: p[mu] = lamda mu = rho rho = p[mu] return lamda
# alpha, beta coincide, i.e. alpha, beta represent the pair of cosets # where coincidence occurs def coincidence(self, alpha, beta, w=None, modified=False): r""" The third situation described in ``scan`` routine is handled by this routine, described on Pg. 156-161 [1].
The unfortunate situation when the scan completes but not correctly, then ``coincidence`` routine is run. i.e when for some `i` with `1 \le i \le r+1`, we have `w=st` with `s = x_1 x_2 \dots x_{i-1}`, `t = x_i x_{i+1} \dots x_r`, and `\beta = \alpha^s` and `\gamma = \alpha^{t-1}` are defined but unequal. This means that `\beta` and `\gamma` represent the same coset of `H` in `G`. Described on Pg. 156 [1]. ``rep``
See Also ========
scan
""" A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table # behaves as a queue q = [] if modified: self.modified_merge(alpha, beta, w, q) else: self.merge(alpha, beta, q) while len(q) > 0: gamma = q.pop(0) for x in A_dict: delta = table[gamma][A_dict[x]] if delta is not None: table[delta][A_dict_inv[x]] = None mu = self.rep(gamma, modified=modified) nu = self.rep(delta, modified=modified) if table[mu][A_dict[x]] is not None: if modified: v = self.p_p[delta]**-1*self.P[gamma][self.A_dict[x]]**-1 v = v*self.p_p[gamma]*self.P[mu][self.A_dict[x]] self.modified_merge(nu, table[mu][self.A_dict[x]], v, q) else: self.merge(nu, table[mu][A_dict[x]], q) elif table[nu][A_dict_inv[x]] is not None: if modified: v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]] v = v*self.p_p[delta]*self.P[mu][self.A_dict_inv[x]] self.modified_merge(mu, table[nu][self.A_dict_inv[x]], v, q) else: self.merge(mu, table[nu][A_dict_inv[x]], q) else: table[mu][A_dict[x]] = nu table[nu][A_dict_inv[x]] = mu if modified: v = self.p_p[gamma]**-1*self.P[gamma][self.A_dict[x]]*self.p_p[delta] self.P[mu][self.A_dict[x]] = v self.P[nu][self.A_dict_inv[x]] = v**-1
# method used in the HLT strategy def scan_and_fill(self, alpha, word): """ A modified version of ``scan`` routine used in the relator-based method of coset enumeration, described on pg. 162-163 [1], which follows the idea that whenever the procedure is called and the scan is incomplete then it makes new definitions to enable the scan to complete; i.e it fills in the gaps in the scan of the relator or subgroup generator.
""" self.scan(alpha, word, fill=True)
def scan_and_fill_c(self, alpha, word): """ A modified version of ``scan`` routine, described on Pg. 165 second para. [1], with modification similar to that of ``scan_anf_fill`` the only difference being it calls the coincidence procedure used in the coset-table based method i.e. the routine ``coincidence_c`` is used.
See Also ========
scan, scan_and_fill
""" A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table r = len(word) f = alpha i = 0 b = alpha j = r - 1 # loop until it has filled the alpha row in the table. while True: # do the forward scanning while i <= j and table[f][A_dict[word[i]]] is not None: f = table[f][A_dict[word[i]]] i += 1 if i > j: if f != b: self.coincidence_c(f, b) return # forward scan was incomplete, scan backwards while j >= i and table[b][A_dict_inv[word[j]]] is not None: b = table[b][A_dict_inv[word[j]]] j -= 1 if j < i: self.coincidence_c(f, b) elif j == i: table[f][A_dict[word[i]]] = b table[b][A_dict_inv[word[i]]] = f self.deduction_stack.append((f, word[i])) else: self.define_c(f, word[i])
# method used in the HLT strategy def look_ahead(self): """ When combined with the HLT method this is known as HLT+Lookahead method of coset enumeration, described on pg. 164 [1]. Whenever ``define`` aborts due to lack of space available this procedure is executed. This routine helps in recovering space resulting from "coincidence" of cosets.
""" R = self.fp_group.relators p = self.p # complete scan all relators under all cosets(obviously live) # without making new definitions for beta in self.omega: for w in R: self.scan(beta, w) if p[beta] < beta: break
# Pg. 166 def process_deductions(self, R_c_x, R_c_x_inv): """ Processes the deductions that have been pushed onto ``deduction_stack``, described on Pg. 166 [1] and is used in coset-table based enumeration.
See Also ========
deduction_stack
""" p = self.p table = self.table while len(self.deduction_stack) > 0: if len(self.deduction_stack) >= CosetTable.max_stack_size: self.look_ahead() del self.deduction_stack[:] continue else: alpha, x = self.deduction_stack.pop() if p[alpha] == alpha: for w in R_c_x: self.scan_c(alpha, w) if p[alpha] < alpha: break beta = table[alpha][self.A_dict[x]] if beta is not None and p[beta] == beta: for w in R_c_x_inv: self.scan_c(beta, w) if p[beta] < beta: break
def process_deductions_check(self, R_c_x, R_c_x_inv): """ A variation of ``process_deductions``, this calls ``scan_check`` wherever ``process_deductions`` calls ``scan``, described on Pg. [1].
See Also ========
process_deductions
""" table = self.table while len(self.deduction_stack) > 0: alpha, x = self.deduction_stack.pop() for w in R_c_x: if not self.scan_check(alpha, w): return False beta = table[alpha][self.A_dict[x]] if beta is not None: for w in R_c_x_inv: if not self.scan_check(beta, w): return False return True
def switch(self, beta, gamma): r"""Switch the elements `\beta, \gamma \in \Omega` of ``self``, used by the ``standardize`` procedure, described on Pg. 167 [1].
See Also ========
standardize
""" A = self.A A_dict = self.A_dict table = self.table for x in A: z = table[gamma][A_dict[x]] table[gamma][A_dict[x]] = table[beta][A_dict[x]] table[beta][A_dict[x]] = z for alpha in range(len(self.p)): if self.p[alpha] == alpha: if table[alpha][A_dict[x]] == beta: table[alpha][A_dict[x]] = gamma elif table[alpha][A_dict[x]] == gamma: table[alpha][A_dict[x]] = beta
def standardize(self): r""" A coset table is standardized if when running through the cosets and within each coset through the generator images (ignoring generator inverses), the cosets appear in order of the integers `0, 1, \dots, n`. "Standardize" reorders the elements of `\Omega` such that, if we scan the coset table first by elements of `\Omega` and then by elements of A, then the cosets occur in ascending order. ``standardize()`` is used at the end of an enumeration to permute the cosets so that they occur in some sort of standard order.
Notes =====
procedure is described on pg. 167-168 [1], it also makes use of the ``switch`` routine to replace by smaller integer value.
Examples ========
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y")
# Example 5.3 from [1] >>> f = FpGroup(F, [x**2*y**2, x**3*y**5]) >>> C = coset_enumeration_r(f, []) >>> C.compress() >>> C.table [[1, 3, 1, 3], [2, 0, 2, 0], [3, 1, 3, 1], [0, 2, 0, 2]] >>> C.standardize() >>> C.table [[1, 2, 1, 2], [3, 0, 3, 0], [0, 3, 0, 3], [2, 1, 2, 1]]
""" A = self.A A_dict = self.A_dict gamma = 1 for alpha, x in product(range(self.n), A): beta = self.table[alpha][A_dict[x]] if beta >= gamma: if beta > gamma: self.switch(gamma, beta) gamma += 1 if gamma == self.n: return
# Compression of a Coset Table def compress(self): """Removes the non-live cosets from the coset table, described on pg. 167 [1].
""" gamma = -1 A = self.A A_dict = self.A_dict A_dict_inv = self.A_dict_inv table = self.table chi = tuple([i for i in range(len(self.p)) if self.p[i] != i]) for alpha in self.omega: gamma += 1 if gamma != alpha: # replace alpha by gamma in coset table for x in A: beta = table[alpha][A_dict[x]] table[gamma][A_dict[x]] = beta table[beta][A_dict_inv[x]] == gamma # all the cosets in the table are live cosets self.p = list(range(gamma + 1)) # delete the useless columns del table[len(self.p):] # re-define values for row in table: for j in range(len(self.A)): row[j] -= bisect_left(chi, row[j])
def conjugates(self, R): R_c = list(chain.from_iterable((rel.cyclic_conjugates(), \ (rel**-1).cyclic_conjugates()) for rel in R)) R_set = set() for conjugate in R_c: R_set = R_set.union(conjugate) R_c_list = [] for x in self.A: r = {word for word in R_set if word[0] == x} R_c_list.append(r) R_set.difference_update(r) return R_c_list
def coset_representative(self, coset): ''' Compute the coset representative of a given coset.
Examples ========
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_r(f, [x]) >>> C.compress() >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]] >>> C.coset_representative(0) <identity> >>> C.coset_representative(1) y >>> C.coset_representative(2) y**-1
''' for x in self.A: gamma = self.table[coset][self.A_dict[x]] if coset == 0: return self.fp_group.identity if gamma < coset: return self.coset_representative(gamma)*x**-1
############################## # Modified Methods # ##############################
def modified_define(self, alpha, x): r""" Define a function p_p from from [1..n] to A* as an additional component of the modified coset table.
Parameters ==========
\alpha \in \Omega x \in A*
See Also ========
define
""" self.define(alpha, x, modified=True)
def modified_scan(self, alpha, w, y, fill=False): r""" Parameters ========== \alpha \in \Omega w \in A* y \in (YUY^-1) fill -- `modified_scan_and_fill` when set to True.
See Also ========
scan """ self.scan(alpha, w, y=y, fill=fill, modified=True)
def modified_scan_and_fill(self, alpha, w, y): self.modified_scan(alpha, w, y, fill=True)
def modified_merge(self, k, lamda, w, q): r""" Parameters ==========
'k', 'lamda' -- the two class representatives to be merged. q -- queue of length l of elements to be deleted from `\Omega` *. w -- Word in (YUY^-1)
See Also ========
merge """ self.merge(k, lamda, q, w=w, modified=True)
def modified_rep(self, k): r""" Parameters ==========
`k \in [0 \ldots n-1]`
See Also ========
rep """ self.rep(k, modified=True)
def modified_coincidence(self, alpha, beta, w): r""" Parameters ==========
A coincident pair `\alpha, \beta \in \Omega, w \in Y \cup Y^{-1}`
See Also ========
coincidence
""" self.coincidence(alpha, beta, w=w, modified=True)
################################################################################ COSET ENUMERATION ################################################################################
# relator-based methoddef coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None, incomplete=False, modified=False): """ This is easier of the two implemented methods of coset enumeration. and is often called the HLT method, after Hazelgrove, Leech, Trotter The idea is that we make use of ``scan_and_fill`` makes new definitions whenever the scan is incomplete to enable the scan to complete; this way we fill in the gaps in the scan of the relator or subgroup generator, that's why the name relator-based method.
An instance of `CosetTable` for `fp_grp` can be passed as the keyword argument `draft` in which case the coset enumeration will start with that instance and attempt to complete it.
When `incomplete` is `True` and the function is unable to complete for some reason, the partially complete table will be returned.
# TODO: complete the docstring
See Also ========
scan_and_fill,
Examples ========
>>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r >>> F, x, y = free_group("x, y")
# Example 5.1 from [1] >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_r(f, [x]) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 1, 2] [1, 1, 2, 0] [2, 2, 0, 1] >>> C.p [0, 1, 2, 1, 1]
# Example from exercises Q2 [1] >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> C = coset_enumeration_r(f, []) >>> C.compress(); C.standardize() >>> C.table [[1, 2, 3, 4], [5, 0, 6, 7], [0, 5, 7, 6], [7, 6, 5, 0], [6, 7, 0, 5], [2, 1, 4, 3], [3, 4, 2, 1], [4, 3, 1, 2]]
# Example 5.2 >>> f = FpGroup(F, [x**2, y**3, (x*y)**3]) >>> Y = [x*y] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [1, 1, 2, 1] [0, 0, 0, 2] [3, 3, 1, 0] [2, 2, 3, 3]
# Example 5.3 >>> f = FpGroup(F, [x**2*y**2, x**3*y**5]) >>> Y = [] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [1, 3, 1, 3] [2, 0, 2, 0] [3, 1, 3, 1] [0, 2, 0, 2]
# Example 5.4 >>> F, a, b, c, d, e = free_group("a, b, c, d, e") >>> f = FpGroup(F, [a*b*c**-1, b*c*d**-1, c*d*e**-1, d*e*a**-1, e*a*b**-1]) >>> Y = [a] >>> C = coset_enumeration_r(f, Y) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# example of "compress" method >>> C.compress() >>> C.table [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
# Exercises Pg. 161, Q2. >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> Y = [] >>> C = coset_enumeration_r(f, Y) >>> C.compress() >>> C.standardize() >>> C.table [[1, 2, 3, 4], [5, 0, 6, 7], [0, 5, 7, 6], [7, 6, 5, 0], [6, 7, 0, 5], [2, 1, 4, 3], [3, 4, 2, 1], [4, 3, 1, 2]]
# John J. Cannon; Lucien A. Dimino; George Havas; Jane M. Watson # Mathematics of Computation, Vol. 27, No. 123. (Jul., 1973), pp. 463-490 # from 1973chwd.pdf # Table 1. Ex. 1 >>> F, r, s, t = free_group("r, s, t") >>> E1 = FpGroup(F, [t**-1*r*t*r**-2, r**-1*s*r*s**-2, s**-1*t*s*t**-2]) >>> C = coset_enumeration_r(E1, [r]) >>> for i in range(len(C.p)): ... if C.p[i] == i: ... print(C.table[i]) [0, 0, 0, 0, 0, 0]
Ex. 2 >>> F, a, b = free_group("a, b") >>> Cox = FpGroup(F, [a**6, b**6, (a*b)**2, (a**2*b**2)**2, (a**3*b**3)**5]) >>> C = coset_enumeration_r(Cox, [a]) >>> index = 0 >>> for i in range(len(C.p)): ... if C.p[i] == i: ... index += 1 >>> index 500
# Ex. 3 >>> F, a, b = free_group("a, b") >>> B_2_4 = FpGroup(F, [a**4, b**4, (a*b)**4, (a**-1*b)**4, (a**2*b)**4, \ (a*b**2)**4, (a**2*b**2)**4, (a**-1*b*a*b)**4, (a*b**-1*a*b)**4]) >>> C = coset_enumeration_r(B_2_4, [a]) >>> index = 0 >>> for i in range(len(C.p)): ... if C.p[i] == i: ... index += 1 >>> index 1024
References ==========
.. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory"
""" # 1. Initialize a coset table C for < X|R > C = CosetTable(fp_grp, Y, max_cosets=max_cosets) # Define coset table methods. if modified: _scan_and_fill = C.modified_scan_and_fill _define = C.modified_define else: _scan_and_fill = C.scan_and_fill _define = C.define if draft: C.table = draft.table[:] C.p = draft.p[:] R = fp_grp.relators A_dict = C.A_dict p = C.p for i in range(len(Y)): if modified: _scan_and_fill(0, Y[i], C._grp.generators[i]) else: _scan_and_fill(0, Y[i]) alpha = 0 while alpha < C.n: if p[alpha] == alpha: try: for w in R: if modified: _scan_and_fill(alpha, w, C._grp.identity) else: _scan_and_fill(alpha, w) # if alpha was eliminated during the scan then break if p[alpha] < alpha: break if p[alpha] == alpha: for x in A_dict: if C.table[alpha][A_dict[x]] is None: _define(alpha, x) except ValueError as e: if incomplete: return C raise e alpha += 1 return C
def modified_coset_enumeration_r(fp_grp, Y, max_cosets=None, draft=None, incomplete=False): r""" Introduce a new set of symbols y \in Y that correspond to the generators of the subgroup. Store the elements of Y as a word P[\alpha, x] and compute the coset table similar to that of the regular coset enumeration methods.
Examples ========
>>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.coset_table import modified_coset_enumeration_r >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = modified_coset_enumeration_r(f, [x]) >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1], [None, 1, None, None], [1, 3, None, None]]
See Also ========
coset_enumertation_r
References ==========
.. [1] Holt, D., Eick, B., O'Brien, E., "Handbook of Computational Group Theory", Section 5.3.2 """ return coset_enumeration_r(fp_grp, Y, max_cosets=max_cosets, draft=draft, incomplete=incomplete, modified=True)
# Pg. 166# coset-table based methoddef coset_enumeration_c(fp_grp, Y, max_cosets=None, draft=None, incomplete=False): """ >>> from sympy.combinatorics.free_groups import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_c >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y]) >>> C = coset_enumeration_c(f, [x]) >>> C.table [[0, 0, 1, 2], [1, 1, 2, 0], [2, 2, 0, 1]]
""" # Initialize a coset table C for < X|R > X = fp_grp.generators R = fp_grp.relators C = CosetTable(fp_grp, Y, max_cosets=max_cosets) if draft: C.table = draft.table[:] C.p = draft.p[:] C.deduction_stack = draft.deduction_stack for alpha, x in product(range(len(C.table)), X): if C.table[alpha][C.A_dict[x]] is not None: C.deduction_stack.append((alpha, x)) A = C.A # replace all the elements by cyclic reductions R_cyc_red = [rel.identity_cyclic_reduction() for rel in R] R_c = list(chain.from_iterable((rel.cyclic_conjugates(), (rel**-1).cyclic_conjugates()) \ for rel in R_cyc_red)) R_set = set() for conjugate in R_c: R_set = R_set.union(conjugate) # a list of subsets of R_c whose words start with "x". R_c_list = [] for x in C.A: r = {word for word in R_set if word[0] == x} R_c_list.append(r) R_set.difference_update(r) for w in Y: C.scan_and_fill_c(0, w) for x in A: C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]]) alpha = 0 while alpha < len(C.table): if C.p[alpha] == alpha: try: for x in C.A: if C.p[alpha] != alpha: break if C.table[alpha][C.A_dict[x]] is None: C.define_c(alpha, x) C.process_deductions(R_c_list[C.A_dict[x]], R_c_list[C.A_dict_inv[x]]) except ValueError as e: if incomplete: return C raise e alpha += 1 return C1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354"""Finitely Presented Groups and its algorithms. """
from sympy.core.singleton import Sfrom sympy.core.symbol import symbolsfrom sympy.combinatorics.free_groups import (FreeGroup, FreeGroupElement, free_group)from sympy.combinatorics.rewritingsystem import RewritingSystemfrom sympy.combinatorics.coset_table import (CosetTable, coset_enumeration_r, coset_enumeration_c)from sympy.combinatorics import PermutationGroupfrom sympy.matrices.normalforms import invariant_factorsfrom sympy.matrices import Matrixfrom sympy.polys.polytools import gcdfrom sympy.printing.defaults import DefaultPrintingfrom sympy.utilities import publicfrom sympy.utilities.magic import pollute
from itertools import product
@publicdef fp_group(fr_grp, relators=()): _fp_group = FpGroup(fr_grp, relators) return (_fp_group,) + tuple(_fp_group._generators)
@publicdef xfp_group(fr_grp, relators=()): _fp_group = FpGroup(fr_grp, relators) return (_fp_group, _fp_group._generators)
# Does not work. Both symbols and pollute are undefined. Never tested.@publicdef vfp_group(fr_grpm, relators): _fp_group = FpGroup(symbols, relators) pollute([sym.name for sym in _fp_group.symbols], _fp_group.generators) return _fp_group
def _parse_relators(rels): """Parse the passed relators.""" return rels
################################################################################ FINITELY PRESENTED GROUPS ################################################################################
class FpGroup(DefaultPrinting): """ The FpGroup would take a FreeGroup and a list/tuple of relators, the relators would be specified in such a way that each of them be equal to the identity of the provided free group.
""" is_group = True is_FpGroup = True is_PermutationGroup = False
def __init__(self, fr_grp, relators): relators = _parse_relators(relators) self.free_group = fr_grp self.relators = relators self.generators = self._generators() self.dtype = type("FpGroupElement", (FpGroupElement,), {"group": self})
# CosetTable instance on identity subgroup self._coset_table = None # returns whether coset table on identity subgroup # has been standardized self._is_standardized = False
self._order = None self._center = None
self._rewriting_system = RewritingSystem(self) self._perm_isomorphism = None return
def _generators(self): return self.free_group.generators
def make_confluent(self): ''' Try to make the group's rewriting system confluent
''' self._rewriting_system.make_confluent() return
def reduce(self, word): ''' Return the reduced form of `word` in `self` according to the group's rewriting system. If it's confluent, the reduced form is the unique normal form of the word in the group.
''' return self._rewriting_system.reduce(word)
def equals(self, word1, word2): ''' Compare `word1` and `word2` for equality in the group using the group's rewriting system. If the system is confluent, the returned answer is necessarily correct. (If it is not, `False` could be returned in some cases where in fact `word1 == word2`)
''' if self.reduce(word1*word2**-1) == self.identity: return True elif self._rewriting_system.is_confluent: return False return None
@property def identity(self): return self.free_group.identity
def __contains__(self, g): return g in self.free_group
def subgroup(self, gens, C=None, homomorphism=False): ''' Return the subgroup generated by `gens` using the Reidemeister-Schreier algorithm homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group.
Examples ========
>>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) >>> H = [x*y, x**-1*y**-1*x*y*x] >>> K, T = f.subgroup(H, homomorphism=True) >>> T(K.generators) [x*y, x**-1*y**2*x**-1]
'''
if not all(isinstance(g, FreeGroupElement) for g in gens): raise ValueError("Generators must be `FreeGroupElement`s") if not all(g.group == self.free_group for g in gens): raise ValueError("Given generators are not members of the group") if homomorphism: g, rels, _gens = reidemeister_presentation(self, gens, C=C, homomorphism=True) else: g, rels = reidemeister_presentation(self, gens, C=C) if g: g = FpGroup(g[0].group, rels) else: g = FpGroup(free_group('')[0], []) if homomorphism: from sympy.combinatorics.homomorphisms import homomorphism return g, homomorphism(g, self, g.generators, _gens, check=False) return g
def coset_enumeration(self, H, strategy="relator_based", max_cosets=None, draft=None, incomplete=False): """ Return an instance of ``coset table``, when Todd-Coxeter algorithm is run over the ``self`` with ``H`` as subgroup, using ``strategy`` argument as strategy. The returned coset table is compressed but not standardized.
An instance of `CosetTable` for `fp_grp` can be passed as the keyword argument `draft` in which case the coset enumeration will start with that instance and attempt to complete it.
When `incomplete` is `True` and the function is unable to complete for some reason, the partially complete table will be returned.
""" if not max_cosets: max_cosets = CosetTable.coset_table_max_limit if strategy == 'relator_based': C = coset_enumeration_r(self, H, max_cosets=max_cosets, draft=draft, incomplete=incomplete) else: C = coset_enumeration_c(self, H, max_cosets=max_cosets, draft=draft, incomplete=incomplete) if C.is_complete(): C.compress() return C
def standardize_coset_table(self): """ Standardized the coset table ``self`` and makes the internal variable ``_is_standardized`` equal to ``True``.
""" self._coset_table.standardize() self._is_standardized = True
def coset_table(self, H, strategy="relator_based", max_cosets=None, draft=None, incomplete=False): """ Return the mathematical coset table of ``self`` in ``H``.
""" if not H: if self._coset_table is not None: if not self._is_standardized: self.standardize_coset_table() else: C = self.coset_enumeration([], strategy, max_cosets=max_cosets, draft=draft, incomplete=incomplete) self._coset_table = C self.standardize_coset_table() return self._coset_table.table else: C = self.coset_enumeration(H, strategy, max_cosets=max_cosets, draft=draft, incomplete=incomplete) C.standardize() return C.table
def order(self, strategy="relator_based"): """ Returns the order of the finitely presented group ``self``. It uses the coset enumeration with identity group as subgroup, i.e ``H=[]``.
Examples ========
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x, y**2]) >>> f.order(strategy="coset_table_based") 2
""" if self._order is not None: return self._order if self._coset_table is not None: self._order = len(self._coset_table.table) elif len(self.relators) == 0: self._order = self.free_group.order() elif len(self.generators) == 1: self._order = abs(gcd([r.array_form[0][1] for r in self.relators])) elif self._is_infinite(): self._order = S.Infinity else: gens, C = self._finite_index_subgroup() if C: ind = len(C.table) self._order = ind*self.subgroup(gens, C=C).order() else: self._order = self.index([]) return self._order
def _is_infinite(self): ''' Test if the group is infinite. Return `True` if the test succeeds and `None` otherwise
''' used_gens = set() for r in self.relators: used_gens.update(r.contains_generators()) if not set(self.generators) <= used_gens: return True # Abelianisation test: check is the abelianisation is infinite abelian_rels = [] for rel in self.relators: abelian_rels.append([rel.exponent_sum(g) for g in self.generators]) m = Matrix(Matrix(abelian_rels)) if 0 in invariant_factors(m): return True else: return None
def _finite_index_subgroup(self, s=None): ''' Find the elements of `self` that generate a finite index subgroup and, if found, return the list of elements and the coset table of `self` by the subgroup, otherwise return `(None, None)`
''' gen = self.most_frequent_generator() rels = list(self.generators) rels.extend(self.relators) if not s: if len(self.generators) == 2: s = [gen] + [g for g in self.generators if g != gen] else: rand = self.free_group.identity i = 0 while ((rand in rels or rand**-1 in rels or rand.is_identity) and i<10): rand = self.random() i += 1 s = [gen, rand] + [g for g in self.generators if g != gen] mid = (len(s)+1)//2 half1 = s[:mid] half2 = s[mid:] draft1 = None draft2 = None m = 200 C = None while not C and (m/2 < CosetTable.coset_table_max_limit): m = min(m, CosetTable.coset_table_max_limit) draft1 = self.coset_enumeration(half1, max_cosets=m, draft=draft1, incomplete=True) if draft1.is_complete(): C = draft1 half = half1 else: draft2 = self.coset_enumeration(half2, max_cosets=m, draft=draft2, incomplete=True) if draft2.is_complete(): C = draft2 half = half2 if not C: m *= 2 if not C: return None, None C.compress() return half, C
def most_frequent_generator(self): gens = self.generators rels = self.relators freqs = [sum(r.generator_count(g) for r in rels) for g in gens] return gens[freqs.index(max(freqs))]
def random(self): import random r = self.free_group.identity for i in range(random.randint(2,3)): r = r*random.choice(self.generators)**random.choice([1,-1]) return r
def index(self, H, strategy="relator_based"): """ Return the index of subgroup ``H`` in group ``self``.
Examples ========
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import FpGroup >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**5, y**4, y*x*y**3*x**3]) >>> f.index([x]) 4
""" # TODO: use |G:H| = |G|/|H| (currently H can't be made into a group) # when we know |G| and |H|
if H == []: return self.order() else: C = self.coset_enumeration(H, strategy) return len(C.table)
def __str__(self): if self.free_group.rank > 30: str_form = "<fp group with %s generators>" % self.free_group.rank else: str_form = "<fp group on the generators %s>" % str(self.generators) return str_form
__repr__ = __str__
#==============================================================================# PERMUTATION GROUP METHODS#==============================================================================
def _to_perm_group(self): ''' Return an isomorphic permutation group and the isomorphism. The implementation is dependent on coset enumeration so will only terminate for finite groups.
''' from sympy.combinatorics import Permutation from sympy.combinatorics.homomorphisms import homomorphism if self.order() is S.Infinity: raise NotImplementedError("Permutation presentation of infinite " "groups is not implemented") if self._perm_isomorphism: T = self._perm_isomorphism P = T.image() else: C = self.coset_table([]) gens = self.generators images = [[C[i][2*gens.index(g)] for i in range(len(C))] for g in gens] images = [Permutation(i) for i in images] P = PermutationGroup(images) T = homomorphism(self, P, gens, images, check=False) self._perm_isomorphism = T return P, T
def _perm_group_list(self, method_name, *args): ''' Given the name of a `PermutationGroup` method (returning a subgroup or a list of subgroups) and (optionally) additional arguments it takes, return a list or a list of lists containing the generators of this (or these) subgroups in terms of the generators of `self`.
''' P, T = self._to_perm_group() perm_result = getattr(P, method_name)(*args) single = False if isinstance(perm_result, PermutationGroup): perm_result, single = [perm_result], True result = [] for group in perm_result: gens = group.generators result.append(T.invert(gens)) return result[0] if single else result
def derived_series(self): ''' Return the list of lists containing the generators of the subgroups in the derived series of `self`.
''' return self._perm_group_list('derived_series')
def lower_central_series(self): ''' Return the list of lists containing the generators of the subgroups in the lower central series of `self`.
''' return self._perm_group_list('lower_central_series')
def center(self): ''' Return the list of generators of the center of `self`.
''' return self._perm_group_list('center')
def derived_subgroup(self): ''' Return the list of generators of the derived subgroup of `self`.
''' return self._perm_group_list('derived_subgroup')
def centralizer(self, other): ''' Return the list of generators of the centralizer of `other` (a list of elements of `self`) in `self`.
''' T = self._to_perm_group()[1] other = T(other) return self._perm_group_list('centralizer', other)
def normal_closure(self, other): ''' Return the list of generators of the normal closure of `other` (a list of elements of `self`) in `self`.
''' T = self._to_perm_group()[1] other = T(other) return self._perm_group_list('normal_closure', other)
def _perm_property(self, attr): ''' Given an attribute of a `PermutationGroup`, return its value for a permutation group isomorphic to `self`.
''' P = self._to_perm_group()[0] return getattr(P, attr)
@property def is_abelian(self): ''' Check if `self` is abelian.
''' return self._perm_property("is_abelian")
@property def is_nilpotent(self): ''' Check if `self` is nilpotent.
''' return self._perm_property("is_nilpotent")
@property def is_solvable(self): ''' Check if `self` is solvable.
''' return self._perm_property("is_solvable")
@property def elements(self): ''' List the elements of `self`.
''' P, T = self._to_perm_group() return T.invert(P.elements)
@property def is_cyclic(self): """ Return ``True`` if group is Cyclic.
""" if len(self.generators) <= 1: return True try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("Check for infinite Cyclic group " "is not implemented") return P.is_cyclic
def abelian_invariants(self): """ Return Abelian Invariants of a group. """ try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("abelian invariants is not implemented" "for infinite group") return P.abelian_invariants()
def composition_series(self): """ Return subnormal series of maximum length for a group. """ try: P, T = self._to_perm_group() except NotImplementedError: raise NotImplementedError("composition series is not implemented" "for infinite group") return P.composition_series()
class FpSubgroup(DefaultPrinting): ''' The class implementing a subgroup of an FpGroup or a FreeGroup (only finite index subgroups are supported at this point). This is to be used if one wishes to check if an element of the original group belongs to the subgroup
''' def __init__(self, G, gens, normal=False): super().__init__() self.parent = G self.generators = list({g for g in gens if g != G.identity}) self._min_words = None #for use in __contains__ self.C = None self.normal = normal
def __contains__(self, g):
if isinstance(self.parent, FreeGroup): if self._min_words is None: # make _min_words - a list of subwords such that # g is in the subgroup if and only if it can be # partitioned into these subwords. Infinite families of # subwords are presented by tuples, e.g. (r, w) # stands for the family of subwords r*w**n*r**-1
def _process(w): # this is to be used before adding new words # into _min_words; if the word w is not cyclically # reduced, it will generate an infinite family of # subwords so should be written as a tuple; # if it is, w**-1 should be added to the list # as well p, r = w.cyclic_reduction(removed=True) if not r.is_identity: return [(r, p)] else: return [w, w**-1]
# make the initial list gens = [] for w in self.generators: if self.normal: w = w.cyclic_reduction() gens.extend(_process(w))
for w1 in gens: for w2 in gens: # if w1 and w2 are equal or are inverses, continue if w1 == w2 or (not isinstance(w1, tuple) and w1**-1 == w2): continue
# if the start of one word is the inverse of the # end of the other, their multiple should be added # to _min_words because of cancellation if isinstance(w1, tuple): # start, end s1, s2 = w1[0][0], w1[0][0]**-1 else: s1, s2 = w1[0], w1[len(w1)-1]
if isinstance(w2, tuple): # start, end r1, r2 = w2[0][0], w2[0][0]**-1 else: r1, r2 = w2[0], w2[len(w1)-1]
# p1 and p2 are w1 and w2 or, in case when # w1 or w2 is an infinite family, a representative p1, p2 = w1, w2 if isinstance(w1, tuple): p1 = w1[0]*w1[1]*w1[0]**-1 if isinstance(w2, tuple): p2 = w2[0]*w2[1]*w2[0]**-1
# add the product of the words to the list is necessary if r1**-1 == s2 and not (p1*p2).is_identity: new = _process(p1*p2) if new not in gens: gens.extend(new)
if r2**-1 == s1 and not (p2*p1).is_identity: new = _process(p2*p1) if new not in gens: gens.extend(new)
self._min_words = gens
min_words = self._min_words
def _is_subword(w): # check if w is a word in _min_words or one of # the infinite families in it w, r = w.cyclic_reduction(removed=True) if r.is_identity or self.normal: return w in min_words else: t = [s[1] for s in min_words if isinstance(s, tuple) and s[0] == r] return [s for s in t if w.power_of(s)] != []
# store the solution of words for which the result of # _word_break (below) is known known = {}
def _word_break(w): # check if w can be written as a product of words # in min_words if len(w) == 0: return True i = 0 while i < len(w): i += 1 prefix = w.subword(0, i) if not _is_subword(prefix): continue rest = w.subword(i, len(w)) if rest not in known: known[rest] = _word_break(rest) if known[rest]: return True return False
if self.normal: g = g.cyclic_reduction() return _word_break(g) else: if self.C is None: C = self.parent.coset_enumeration(self.generators) self.C = C i = 0 C = self.C for j in range(len(g)): i = C.table[i][C.A_dict[g[j]]] return i == 0
def order(self): if not self.generators: return S.One if isinstance(self.parent, FreeGroup): return S.Infinity if self.C is None: C = self.parent.coset_enumeration(self.generators) self.C = C # This is valid because `len(self.C.table)` (the index of the subgroup) # will always be finite - otherwise coset enumeration doesn't terminate return self.parent.order()/len(self.C.table)
def to_FpGroup(self): if isinstance(self.parent, FreeGroup): gen_syms = [('x_%d'%i) for i in range(len(self.generators))] return free_group(', '.join(gen_syms))[0] return self.parent.subgroup(C=self.C)
def __str__(self): if len(self.generators) > 30: str_form = "<fp subgroup with %s generators>" % len(self.generators) else: str_form = "<fp subgroup on the generators %s>" % str(self.generators) return str_form
__repr__ = __str__
################################################################################ LOW INDEX SUBGROUPS ################################################################################
def low_index_subgroups(G, N, Y=()): """ Implements the Low Index Subgroups algorithm, i.e find all subgroups of ``G`` upto a given index ``N``. This implements the method described in [Sim94]. This procedure involves a backtrack search over incomplete Coset Tables, rather than over forced coincidences.
Parameters ==========
G: An FpGroup < X|R > N: positive integer, representing the maximum index value for subgroups Y: (an optional argument) specifying a list of subgroup generators, such that each of the resulting subgroup contains the subgroup generated by Y.
Examples ========
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, low_index_subgroups >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**4]) >>> L = low_index_subgroups(f, 4) >>> for coset_table in L: ... print(coset_table.table) [[0, 0, 0, 0]] [[0, 0, 1, 2], [1, 1, 2, 0], [3, 3, 0, 1], [2, 2, 3, 3]] [[0, 0, 1, 2], [2, 2, 2, 0], [1, 1, 0, 1]] [[1, 1, 0, 0], [0, 0, 1, 1]]
References ==========
.. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 5.4
.. [2] Marston Conder and Peter Dobcsanyi "Applications and Adaptions of the Low Index Subgroups Procedure"
""" C = CosetTable(G, []) R = G.relators # length chosen for the length of the short relators len_short_rel = 5 # elements of R2 only checked at the last step for complete # coset tables R2 = {rel for rel in R if len(rel) > len_short_rel} # elements of R1 are used in inner parts of the process to prune # branches of the search tree, R1 = {rel.identity_cyclic_reduction() for rel in set(R) - R2} R1_c_list = C.conjugates(R1) S = [] descendant_subgroups(S, C, R1_c_list, C.A[0], R2, N, Y) return S
def descendant_subgroups(S, C, R1_c_list, x, R2, N, Y): A_dict = C.A_dict A_dict_inv = C.A_dict_inv if C.is_complete(): # if C is complete then it only needs to test # whether the relators in R2 are satisfied for w, alpha in product(R2, C.omega): if not C.scan_check(alpha, w): return # relators in R2 are satisfied, append the table to list S.append(C) else: # find the first undefined entry in Coset Table for alpha, x in product(range(len(C.table)), C.A): if C.table[alpha][A_dict[x]] is None: # this is "x" in pseudo-code (using "y" makes it clear) undefined_coset, undefined_gen = alpha, x break # for filling up the undefine entry we try all possible values # of beta in Omega or beta = n where beta^(undefined_gen^-1) is undefined reach = C.omega + [C.n] for beta in reach: if beta < N: if beta == C.n or C.table[beta][A_dict_inv[undefined_gen]] is None: try_descendant(S, C, R1_c_list, R2, N, undefined_coset, \ undefined_gen, beta, Y)
def try_descendant(S, C, R1_c_list, R2, N, alpha, x, beta, Y): r""" Solves the problem of trying out each individual possibility for `\alpha^x.
""" D = C.copy() if beta == D.n and beta < N: D.table.append([None]*len(D.A)) D.p.append(beta) D.table[alpha][D.A_dict[x]] = beta D.table[beta][D.A_dict_inv[x]] = alpha D.deduction_stack.append((alpha, x)) if not D.process_deductions_check(R1_c_list[D.A_dict[x]], \ R1_c_list[D.A_dict_inv[x]]): return for w in Y: if not D.scan_check(0, w): return if first_in_class(D, Y): descendant_subgroups(S, D, R1_c_list, x, R2, N, Y)
def first_in_class(C, Y=()): """ Checks whether the subgroup ``H=G1`` corresponding to the Coset Table could possibly be the canonical representative of its conjugacy class.
Parameters ==========
C: CosetTable
Returns =======
bool: True/False
If this returns False, then no descendant of C can have that property, and so we can abandon C. If it returns True, then we need to process further the node of the search tree corresponding to C, and so we call ``descendant_subgroups`` recursively on C.
Examples ========
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, first_in_class >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**4]) >>> C = CosetTable(f, []) >>> C.table = [[0, 0, None, None]] >>> first_in_class(C) True >>> C.table = [[1, 1, 1, None], [0, 0, None, 1]]; C.p = [0, 1] >>> first_in_class(C) True >>> C.table = [[1, 1, 2, 1], [0, 0, 0, None], [None, None, None, 0]] >>> C.p = [0, 1, 2] >>> first_in_class(C) False >>> C.table = [[1, 1, 1, 2], [0, 0, 2, 0], [2, None, 0, 1]] >>> first_in_class(C) False
# TODO:: Sims points out in [Sim94] that performance can be improved by # remembering some of the information computed by ``first_in_class``. If # the ``continue alpha`` statement is executed at line 14, then the same thing # will happen for that value of alpha in any descendant of the table C, and so # the values the values of alpha for which this occurs could profitably be # stored and passed through to the descendants of C. Of course this would # make the code more complicated.
# The code below is taken directly from the function on page 208 of [Sim94] # nu[alpha]
""" n = C.n # lamda is the largest numbered point in Omega_c_alpha which is currently defined lamda = -1 # for alpha in Omega_c, nu[alpha] is the point in Omega_c_alpha corresponding to alpha nu = [None]*n # for alpha in Omega_c_alpha, mu[alpha] is the point in Omega_c corresponding to alpha mu = [None]*n # mutually nu and mu are the mutually-inverse equivalence maps between # Omega_c_alpha and Omega_c next_alpha = False # For each 0!=alpha in [0 .. nc-1], we start by constructing the equivalent # standardized coset table C_alpha corresponding to H_alpha for alpha in range(1, n): # reset nu to "None" after previous value of alpha for beta in range(lamda+1): nu[mu[beta]] = None # we only want to reject our current table in favour of a preceding # table in the ordering in which 1 is replaced by alpha, if the subgroup # G_alpha corresponding to this preceding table definitely contains the # given subgroup for w in Y: # TODO: this should support input of a list of general words # not just the words which are in "A" (i.e gen and gen^-1) if C.table[alpha][C.A_dict[w]] != alpha: # continue with alpha next_alpha = True break if next_alpha: next_alpha = False continue # try alpha as the new point 0 in Omega_C_alpha mu[0] = alpha nu[alpha] = 0 # compare corresponding entries in C and C_alpha lamda = 0 for beta in range(n): for x in C.A: gamma = C.table[beta][C.A_dict[x]] delta = C.table[mu[beta]][C.A_dict[x]] # if either of the entries is undefined, # we move with next alpha if gamma is None or delta is None: # continue with alpha next_alpha = True break if nu[delta] is None: # delta becomes the next point in Omega_C_alpha lamda += 1 nu[delta] = lamda mu[lamda] = delta if nu[delta] < gamma: return False if nu[delta] > gamma: # continue with alpha next_alpha = True break if next_alpha: next_alpha = False break return True
#========================================================================# Simplifying Presentation#========================================================================
def simplify_presentation(*args, change_gens=False): ''' For an instance of `FpGroup`, return a simplified isomorphic copy of the group (e.g. remove redundant generators or relators). Alternatively, a list of generators and relators can be passed in which case the simplified lists will be returned.
By default, the generators of the group are unchanged. If you would like to remove redundant generators, set the keyword argument `change_gens = True`.
''' if len(args) == 1: if not isinstance(args[0], FpGroup): raise TypeError("The argument must be an instance of FpGroup") G = args[0] gens, rels = simplify_presentation(G.generators, G.relators, change_gens=change_gens) if gens: return FpGroup(gens[0].group, rels) return FpGroup(FreeGroup([]), []) elif len(args) == 2: gens, rels = args[0][:], args[1][:] if not gens: return gens, rels identity = gens[0].group.identity else: if len(args) == 0: m = "Not enough arguments" else: m = "Too many arguments" raise RuntimeError(m)
prev_gens = [] prev_rels = [] while not set(prev_rels) == set(rels): prev_rels = rels while change_gens and not set(prev_gens) == set(gens): prev_gens = gens gens, rels = elimination_technique_1(gens, rels, identity) rels = _simplify_relators(rels)
if change_gens: syms = [g.array_form[0][0] for g in gens] F = free_group(syms)[0] identity = F.identity gens = F.generators subs = dict(zip(syms, gens)) for j, r in enumerate(rels): a = r.array_form rel = identity for sym, p in a: rel = rel*subs[sym]**p rels[j] = rel return gens, rels
def _simplify_relators(rels): """ Simplifies a set of relators. All relators are checked to see if they are of the form `gen^n`. If any such relators are found then all other relators are processed for strings in the `gen` known order.
Examples ========
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import _simplify_relators >>> F, x, y = free_group("x, y") >>> w1 = [x**2*y**4, x**3] >>> _simplify_relators(w1) [x**3, x**-1*y**4]
>>> w2 = [x**2*y**-4*x**5, x**3, x**2*y**8, y**5] >>> _simplify_relators(w2) [x**-1*y**-2, x**-1*y*x**-1, x**3, y**5]
>>> w3 = [x**6*y**4, x**4] >>> _simplify_relators(w3) [x**4, x**2*y**4]
>>> w4 = [x**2, x**5, y**3] >>> _simplify_relators(w4) [x, y**3]
""" rels = rels[:]
if not rels: return []
identity = rels[0].group.identity
# build dictionary with "gen: n" where gen^n is one of the relators exps = {} for i in range(len(rels)): rel = rels[i] if rel.number_syllables() == 1: g = rel[0] exp = abs(rel.array_form[0][1]) if rel.array_form[0][1] < 0: rels[i] = rels[i]**-1 g = g**-1 if g in exps: exp = gcd(exp, exps[g].array_form[0][1]) exps[g] = g**exp
one_syllables_words = list(exps.values()) # decrease some of the exponents in relators, making use of the single # syllable relators for i, rel in enumerate(rels): if rel in one_syllables_words: continue rel = rel.eliminate_words(one_syllables_words, _all = True) # if rels[i] contains g**n where abs(n) is greater than half of the power p # of g in exps, g**n can be replaced by g**(n-p) (or g**(p-n) if n<0) for g in rel.contains_generators(): if g in exps: exp = exps[g].array_form[0][1] max_exp = (exp + 1)//2 rel = rel.eliminate_word(g**(max_exp), g**(max_exp-exp), _all = True) rel = rel.eliminate_word(g**(-max_exp), g**(-(max_exp-exp)), _all = True) rels[i] = rel
rels = [r.identity_cyclic_reduction() for r in rels]
rels += one_syllables_words # include one_syllable_words in the list of relators rels = list(set(rels)) # get unique values in rels rels.sort()
# remove <identity> entries in rels try: rels.remove(identity) except ValueError: pass return rels
# Pg 350, section 2.5.1 from [2]def elimination_technique_1(gens, rels, identity): rels = rels[:] # the shorter relators are examined first so that generators selected for # elimination will have shorter strings as equivalent rels.sort() gens = gens[:] redundant_gens = {} redundant_rels = [] used_gens = set() # examine each relator in relator list for any generator occurring exactly # once for rel in rels: # don't look for a redundant generator in a relator which # depends on previously found ones contained_gens = rel.contains_generators() if any(g in contained_gens for g in redundant_gens): continue contained_gens = list(contained_gens) contained_gens.sort(reverse = True) for gen in contained_gens: if rel.generator_count(gen) == 1 and gen not in used_gens: k = rel.exponent_sum(gen) gen_index = rel.index(gen**k) bk = rel.subword(gen_index + 1, len(rel)) fw = rel.subword(0, gen_index) chi = bk*fw redundant_gens[gen] = chi**(-1*k) used_gens.update(chi.contains_generators()) redundant_rels.append(rel) break rels = [r for r in rels if r not in redundant_rels] # eliminate the redundant generators from remaining relators rels = [r.eliminate_words(redundant_gens, _all = True).identity_cyclic_reduction() for r in rels] rels = list(set(rels)) try: rels.remove(identity) except ValueError: pass gens = [g for g in gens if g not in redundant_gens] return gens, rels
################################################################################ SUBGROUP PRESENTATIONS ################################################################################
# Pg 175 [1]def define_schreier_generators(C, homomorphism=False): ''' Parameters ==========
C -- Coset table. homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group. ''' y = [] gamma = 1 f = C.fp_group X = f.generators if homomorphism: # `_gens` stores the elements of the parent group to # to which the schreier generators correspond to. _gens = {} # compute the schreier Traversal tau = {} tau[0] = f.identity C.P = [[None]*len(C.A) for i in range(C.n)] for alpha, x in product(C.omega, C.A): beta = C.table[alpha][C.A_dict[x]] if beta == gamma: C.P[alpha][C.A_dict[x]] = "<identity>" C.P[beta][C.A_dict_inv[x]] = "<identity>" gamma += 1 if homomorphism: tau[beta] = tau[alpha]*x elif x in X and C.P[alpha][C.A_dict[x]] is None: y_alpha_x = '%s_%s' % (x, alpha) y.append(y_alpha_x) C.P[alpha][C.A_dict[x]] = y_alpha_x if homomorphism: _gens[y_alpha_x] = tau[alpha]*x*tau[beta]**-1 grp_gens = list(free_group(', '.join(y))) C._schreier_free_group = grp_gens.pop(0) C._schreier_generators = grp_gens if homomorphism: C._schreier_gen_elem = _gens # replace all elements of P by, free group elements for i, j in product(range(len(C.P)), range(len(C.A))): # if equals "<identity>", replace by identity element if C.P[i][j] == "<identity>": C.P[i][j] = C._schreier_free_group.identity elif isinstance(C.P[i][j], str): r = C._schreier_generators[y.index(C.P[i][j])] C.P[i][j] = r beta = C.table[i][j] C.P[beta][j + 1] = r**-1
def reidemeister_relators(C): R = C.fp_group.relators rels = [rewrite(C, coset, word) for word in R for coset in range(C.n)] order_1_gens = {i for i in rels if len(i) == 1}
# remove all the order 1 generators from relators rels = list(filter(lambda rel: rel not in order_1_gens, rels))
# replace order 1 generators by identity element in reidemeister relators for i in range(len(rels)): w = rels[i] w = w.eliminate_words(order_1_gens, _all=True) rels[i] = w
C._schreier_generators = [i for i in C._schreier_generators if not (i in order_1_gens or i**-1 in order_1_gens)]
# Tietze transformation 1 i.e TT_1 # remove cyclic conjugate elements from relators i = 0 while i < len(rels): w = rels[i] j = i + 1 while j < len(rels): if w.is_cyclic_conjugate(rels[j]): del rels[j] else: j += 1 i += 1
C._reidemeister_relators = rels
def rewrite(C, alpha, w): """ Parameters ==========
C: CosetTable alpha: A live coset w: A word in `A*`
Returns =======
rho(tau(alpha), w)
Examples ========
>>> from sympy.combinatorics.fp_groups import FpGroup, CosetTable, define_schreier_generators, rewrite >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**2, y**3, (x*y)**6]) >>> C = CosetTable(f, []) >>> 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]] >>> C.p = [0, 1, 2, 3, 4, 5] >>> define_schreier_generators(C) >>> rewrite(C, 0, (x*y)**6) x_4*y_2*x_3*x_1*x_2*y_4*x_5
""" v = C._schreier_free_group.identity for i in range(len(w)): x_i = w[i] v = v*C.P[alpha][C.A_dict[x_i]] alpha = C.table[alpha][C.A_dict[x_i]] return v
# Pg 350, section 2.5.2 from [2]def elimination_technique_2(C): """ This technique eliminates one generator at a time. Heuristically this seems superior in that we may select for elimination the generator with shortest equivalent string at each stage.
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_r, \ reidemeister_relators, define_schreier_generators, elimination_technique_2 >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]); H = [x*y, x**-1*y**-1*x*y*x] >>> C = coset_enumeration_r(f, H) >>> C.compress(); C.standardize() >>> define_schreier_generators(C) >>> reidemeister_relators(C) >>> elimination_technique_2(C) ([y_1, y_2], [y_2**-3, y_2*y_1*y_2*y_1*y_2*y_1, y_1**2])
""" rels = C._reidemeister_relators rels.sort(reverse=True) gens = C._schreier_generators for i in range(len(gens) - 1, -1, -1): rel = rels[i] for j in range(len(gens) - 1, -1, -1): gen = gens[j] if rel.generator_count(gen) == 1: k = rel.exponent_sum(gen) gen_index = rel.index(gen**k) bk = rel.subword(gen_index + 1, len(rel)) fw = rel.subword(0, gen_index) rep_by = (bk*fw)**(-1*k) del rels[i]; del gens[j] for l in range(len(rels)): rels[l] = rels[l].eliminate_word(gen, rep_by) break C._reidemeister_relators = rels C._schreier_generators = gens return C._schreier_generators, C._reidemeister_relators
def reidemeister_presentation(fp_grp, H, C=None, homomorphism=False): """ Parameters ==========
fp_group: A finitely presented group, an instance of FpGroup H: A subgroup whose presentation is to be found, given as a list of words in generators of `fp_grp` homomorphism: When set to True, return a homomorphism from the subgroup to the parent group
Examples ========
>>> from sympy.combinatorics import free_group >>> from sympy.combinatorics.fp_groups import FpGroup, reidemeister_presentation >>> F, x, y = free_group("x, y")
Example 5.6 Pg. 177 from [1] >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) >>> H = [x*y, x**-1*y**-1*x*y*x] >>> reidemeister_presentation(f, H) ((y_1, y_2), (y_1**2, y_2**3, y_2*y_1*y_2*y_1*y_2*y_1))
Example 5.8 Pg. 183 from [1] >>> f = FpGroup(F, [x**3, y**3, (x*y)**3]) >>> H = [x*y, x*y**-1] >>> reidemeister_presentation(f, H) ((x_0, y_0), (x_0**3, y_0**3, x_0*y_0*x_0*y_0*x_0*y_0))
Exercises Q2. Pg 187 from [1] >>> f = FpGroup(F, [x**2*y**2, y**-1*x*y*x**-3]) >>> H = [x] >>> reidemeister_presentation(f, H) ((x_0,), (x_0**4,))
Example 5.9 Pg. 183 from [1] >>> f = FpGroup(F, [x**3*y**-3, (x*y)**3, (x*y**-1)**2]) >>> H = [x] >>> reidemeister_presentation(f, H) ((x_0,), (x_0**6,))
""" if not C: C = coset_enumeration_r(fp_grp, H) C.compress(); C.standardize() define_schreier_generators(C, homomorphism=homomorphism) reidemeister_relators(C) gens, rels = C._schreier_generators, C._reidemeister_relators gens, rels = simplify_presentation(gens, rels, change_gens=True)
C.schreier_generators = tuple(gens) C.reidemeister_relators = tuple(rels)
if homomorphism: _gens = [] for gen in gens: _gens.append(C._schreier_gen_elem[str(gen)]) return C.schreier_generators, C.reidemeister_relators, _gens
return C.schreier_generators, C.reidemeister_relators
FpGroupElement = FreeGroupElement1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354from __future__ import annotations
from sympy.core import Sfrom sympy.core.expr import Exprfrom sympy.core.symbol import Symbol, symbols as _symbolsfrom sympy.core.sympify import CantSympifyfrom sympy.printing.defaults import DefaultPrintingfrom sympy.utilities import publicfrom sympy.utilities.iterables import flatten, is_sequencefrom sympy.utilities.magic import pollutefrom sympy.utilities.misc import as_int
@publicdef free_group(symbols): """Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1))``.
Parameters ==========
symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty)
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y, z = free_group("x, y, z") >>> F <free group on the generators (x, y, z)> >>> x**2*y**-1 x**2*y**-1 >>> type(_) <class 'sympy.combinatorics.free_groups.FreeGroupElement'>
""" _free_group = FreeGroup(symbols) return (_free_group,) + tuple(_free_group.generators)
@publicdef xfree_group(symbols): """Construct a free group returning ``(FreeGroup, (f_0, f_1, ..., f_(n-1)))``.
Parameters ==========
symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty)
Examples ========
>>> from sympy.combinatorics.free_groups import xfree_group >>> F, (x, y, z) = xfree_group("x, y, z") >>> F <free group on the generators (x, y, z)> >>> y**2*x**-2*z**-1 y**2*x**-2*z**-1 >>> type(_) <class 'sympy.combinatorics.free_groups.FreeGroupElement'>
""" _free_group = FreeGroup(symbols) return (_free_group, _free_group.generators)
@publicdef vfree_group(symbols): """Construct a free group and inject ``f_0, f_1, ..., f_(n-1)`` as symbols into the global namespace.
Parameters ==========
symbols : str, Symbol/Expr or sequence of str, Symbol/Expr (may be empty)
Examples ========
>>> from sympy.combinatorics.free_groups import vfree_group >>> vfree_group("x, y, z") <free group on the generators (x, y, z)> >>> x**2*y**-2*z # noqa: F821 x**2*y**-2*z >>> type(_) <class 'sympy.combinatorics.free_groups.FreeGroupElement'>
""" _free_group = FreeGroup(symbols) pollute([sym.name for sym in _free_group.symbols], _free_group.generators) return _free_group
def _parse_symbols(symbols): if not symbols: return () if isinstance(symbols, str): return _symbols(symbols, seq=True) elif isinstance(symbols, (Expr, FreeGroupElement)): return (symbols,) elif is_sequence(symbols): if all(isinstance(s, str) for s in symbols): return _symbols(symbols) elif all(isinstance(s, Expr) for s in symbols): return symbols raise ValueError("The type of `symbols` must be one of the following: " "a str, Symbol/Expr or a sequence of " "one of these types")
############################################################################### FREE GROUP ###############################################################################
_free_group_cache: dict[int, FreeGroup] = {}
class FreeGroup(DefaultPrinting): """ Free group with finite or infinite number of generators. Its input API is that of a str, Symbol/Expr or a sequence of one of these types (which may be empty)
See Also ========
sympy.polys.rings.PolyRing
References ==========
.. [1] https://www.gap-system.org/Manuals/doc/ref/chap37.html
.. [2] https://en.wikipedia.org/wiki/Free_group
""" is_associative = True is_group = True is_FreeGroup = True is_PermutationGroup = False relators: list[Expr] = []
def __new__(cls, symbols): symbols = tuple(_parse_symbols(symbols)) rank = len(symbols) _hash = hash((cls.__name__, symbols, rank)) obj = _free_group_cache.get(_hash)
if obj is None: obj = object.__new__(cls) obj._hash = _hash obj._rank = rank # dtype method is used to create new instances of FreeGroupElement obj.dtype = type("FreeGroupElement", (FreeGroupElement,), {"group": obj}) obj.symbols = symbols obj.generators = obj._generators() obj._gens_set = set(obj.generators) for symbol, generator in zip(obj.symbols, obj.generators): if isinstance(symbol, Symbol): name = symbol.name if hasattr(obj, name): setattr(obj, name, generator)
_free_group_cache[_hash] = obj
return obj
def _generators(group): """Returns the generators of the FreeGroup.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y, z = free_group("x, y, z") >>> F.generators (x, y, z)
""" gens = [] for sym in group.symbols: elm = ((sym, 1),) gens.append(group.dtype(elm)) return tuple(gens)
def clone(self, symbols=None): return self.__class__(symbols or self.symbols)
def __contains__(self, i): """Return True if ``i`` is contained in FreeGroup.""" if not isinstance(i, FreeGroupElement): return False group = i.group return self == group
def __hash__(self): return self._hash
def __len__(self): return self.rank
def __str__(self): if self.rank > 30: str_form = "<free group with %s generators>" % self.rank else: str_form = "<free group on the generators " gens = self.generators str_form += str(gens) + ">" return str_form
__repr__ = __str__
def __getitem__(self, index): symbols = self.symbols[index] return self.clone(symbols=symbols)
def __eq__(self, other): """No ``FreeGroup`` is equal to any "other" ``FreeGroup``. """ return self is other
def index(self, gen): """Return the index of the generator `gen` from ``(f_0, ..., f_(n-1))``.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> F.index(y) 1 >>> F.index(x) 0
""" if isinstance(gen, self.dtype): return self.generators.index(gen) else: raise ValueError("expected a generator of Free Group %s, got %s" % (self, gen))
def order(self): """Return the order of the free group.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> F.order() oo
>>> free_group("")[0].order() 1
""" if self.rank == 0: return S.One else: return S.Infinity
@property def elements(self): """ Return the elements of the free group.
Examples ========
>>> from sympy.combinatorics import free_group >>> (z,) = free_group("") >>> z.elements {<identity>}
""" if self.rank == 0: # A set containing Identity element of `FreeGroup` self is returned return {self.identity} else: raise ValueError("Group contains infinitely many elements" ", hence cannot be represented")
@property def rank(self): r""" In group theory, the `rank` of a group `G`, denoted `G.rank`, can refer to the smallest cardinality of a generating set for G, that is
\operatorname{rank}(G)=\min\{ |X|: X\subseteq G, \left\langle X\right\rangle =G\}.
""" return self._rank
@property def is_abelian(self): """Returns if the group is Abelian.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> f.is_abelian False
""" return self.rank in (0, 1)
@property def identity(self): """Returns the identity element of free group.""" return self.dtype()
def contains(self, g): """Tests if Free Group element ``g`` belong to self, ``G``.
In mathematical terms any linear combination of generators of a Free Group is contained in it.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> f.contains(x**3*y**2) True
""" if not isinstance(g, FreeGroupElement): return False elif self != g.group: return False else: return True
def center(self): """Returns the center of the free group `self`.""" return {self.identity}
############################################################################# FreeGroupElement #############################################################################
class FreeGroupElement(CantSympify, DefaultPrinting, tuple): """Used to create elements of FreeGroup. It cannot be used directly to create a free group element. It is called by the `dtype` method of the `FreeGroup` class.
""" is_assoc_word = True
def new(self, init): return self.__class__(init)
_hash = None
def __hash__(self): _hash = self._hash if _hash is None: self._hash = _hash = hash((self.group, frozenset(tuple(self)))) return _hash
def copy(self): return self.new(self)
@property def is_identity(self): if self.array_form == (): return True else: return False
@property def array_form(self): """ SymPy provides two different internal kinds of representation of associative words. The first one is called the `array_form` which is a tuple containing `tuples` as its elements, where the size of each tuple is two. At the first position the tuple contains the `symbol-generator`, while at the second position of tuple contains the exponent of that generator at the position. Since elements (i.e. words) do not commute, the indexing of tuple makes that property to stay.
The structure in ``array_form`` of ``FreeGroupElement`` is of form:
``( ( symbol_of_gen, exponent ), ( , ), ... ( , ) )``
Examples ========
>>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> (x*z).array_form ((x, 1), (z, 1)) >>> (x**2*z*y*x**2).array_form ((x, 2), (z, 1), (y, 1), (x, 2))
See Also ========
letter_repr
""" return tuple(self)
@property def letter_form(self): """ The letter representation of a ``FreeGroupElement`` is a tuple of generator symbols, with each entry corresponding to a group generator. Inverses of the generators are represented by negative generator symbols.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, a, b, c, d = free_group("a b c d") >>> (a**3).letter_form (a, a, a) >>> (a**2*d**-2*a*b**-4).letter_form (a, a, -d, -d, a, -b, -b, -b, -b) >>> (a**-2*b**3*d).letter_form (-a, -a, b, b, b, d)
See Also ========
array_form
""" return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j) for i, j in self.array_form]))
def __getitem__(self, i): group = self.group r = self.letter_form[i] if r.is_Symbol: return group.dtype(((r, 1),)) else: return group.dtype(((-r, -1),))
def index(self, gen): if len(gen) != 1: raise ValueError() return (self.letter_form).index(gen.letter_form[0])
@property def letter_form_elm(self): """ """ group = self.group r = self.letter_form return [group.dtype(((elm,1),)) if elm.is_Symbol \ else group.dtype(((-elm,-1),)) for elm in r]
@property def ext_rep(self): """This is called the External Representation of ``FreeGroupElement`` """ return tuple(flatten(self.array_form))
def __contains__(self, gen): return gen.array_form[0][0] in tuple([r[0] for r in self.array_form])
def __str__(self): if self.is_identity: return "<identity>"
str_form = "" array_form = self.array_form for i in range(len(array_form)): if i == len(array_form) - 1: if array_form[i][1] == 1: str_form += str(array_form[i][0]) else: str_form += str(array_form[i][0]) + \ "**" + str(array_form[i][1]) else: if array_form[i][1] == 1: str_form += str(array_form[i][0]) + "*" else: str_form += str(array_form[i][0]) + \ "**" + str(array_form[i][1]) + "*" return str_form
__repr__ = __str__
def __pow__(self, n): n = as_int(n) result = self.group.identity if n == 0: return result if n < 0: n = -n x = self.inverse() else: x = self while True: if n % 2: result *= x n >>= 1 if not n: break x *= x return result
def __mul__(self, other): """Returns the product of elements belonging to the same ``FreeGroup``.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> x*y**2*y**-4 x*y**-2 >>> z*y**-2 z*y**-2 >>> x**2*y*y**-1*x**-2 <identity>
""" group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be multiplied") if self.is_identity: return other if other.is_identity: return self r = list(self.array_form + other.array_form) zero_mul_simp(r, len(self.array_form) - 1) return group.dtype(tuple(r))
def __truediv__(self, other): group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be multiplied") return self*(other.inverse())
def __rtruediv__(self, other): group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be multiplied") return other*(self.inverse())
def __add__(self, other): return NotImplemented
def inverse(self): """ Returns the inverse of a ``FreeGroupElement`` element
Examples ========
>>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> x.inverse() x**-1 >>> (x*y).inverse() y**-1*x**-1
""" group = self.group r = tuple([(i, -j) for i, j in self.array_form[::-1]]) return group.dtype(r)
def order(self): """Find the order of a ``FreeGroupElement``.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, x, y = free_group("x y") >>> (x**2*y*y**-1*x**-2).order() 1
""" if self.is_identity: return S.One else: return S.Infinity
def commutator(self, other): """ Return the commutator of `self` and `x`: ``~x*~self*x*self``
""" group = self.group if not isinstance(other, group.dtype): raise ValueError("commutator of only FreeGroupElement of the same " "FreeGroup exists") else: return self.inverse()*other.inverse()*self*other
def eliminate_words(self, words, _all=False, inverse=True): ''' Replace each subword from the dictionary `words` by words[subword]. If words is a list, replace the words by the identity.
''' again = True new = self if isinstance(words, dict): while again: again = False for sub in words: prev = new new = new.eliminate_word(sub, words[sub], _all=_all, inverse=inverse) if new != prev: again = True else: while again: again = False for sub in words: prev = new new = new.eliminate_word(sub, _all=_all, inverse=inverse) if new != prev: again = True return new
def eliminate_word(self, gen, by=None, _all=False, inverse=True): """ For an associative word `self`, a subword `gen`, and an associative word `by` (identity by default), return the associative word obtained by replacing each occurrence of `gen` in `self` by `by`. If `_all = True`, the occurrences of `gen` that may appear after the first substitution will also be replaced and so on until no occurrences are found. This might not always terminate (e.g. `(x).eliminate_word(x, x**2, _all=True)`).
Examples ========
>>> from sympy.combinatorics import free_group >>> f, x, y = free_group("x y") >>> w = x**5*y*x**2*y**-4*x >>> w.eliminate_word( x, x**2 ) x**10*y*x**4*y**-4*x**2 >>> w.eliminate_word( x, y**-1 ) y**-11 >>> w.eliminate_word(x**5) y*x**2*y**-4*x >>> w.eliminate_word(x*y, y) x**4*y*x**2*y**-4*x
See Also ======== substituted_word
""" if by is None: by = self.group.identity if self.is_independent(gen) or gen == by: return self if gen == self: return by if gen**-1 == by: _all = False word = self l = len(gen)
try: i = word.subword_index(gen) k = 1 except ValueError: if not inverse: return word try: i = word.subword_index(gen**-1) k = -1 except ValueError: return word
word = word.subword(0, i)*by**k*word.subword(i+l, len(word)).eliminate_word(gen, by)
if _all: return word.eliminate_word(gen, by, _all=True, inverse=inverse) else: return word
def __len__(self): """ For an associative word `self`, returns the number of letters in it.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**5*b*a**2*b**-4*a >>> len(w) 13 >>> len(a**17) 17 >>> len(w**0) 0
""" return sum(abs(j) for (i, j) in self)
def __eq__(self, other): """ Two associative words are equal if they are words over the same alphabet and if they are sequences of the same letters. This is equivalent to saying that the external representations of the words are equal. There is no "universal" empty word, every alphabet has its own empty word.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") >>> f <free group on the generators (swapnil0, swapnil1)> >>> g, swap0, swap1 = free_group("swap0 swap1") >>> g <free group on the generators (swap0, swap1)>
>>> swapnil0 == swapnil1 False >>> swapnil0*swapnil1 == swapnil1/swapnil1*swapnil0*swapnil1 True >>> swapnil0*swapnil1 == swapnil1*swapnil0 False >>> swapnil1**0 == swap0**0 False
""" group = self.group if not isinstance(other, group.dtype): return False return tuple.__eq__(self, other)
def __lt__(self, other): """ The ordering of associative words is defined by length and lexicography (this ordering is called short-lex ordering), that is, shorter words are smaller than longer words, and words of the same length are compared w.r.t. the lexicographical ordering induced by the ordering of generators. Generators are sorted according to the order in which they were created. If the generators are invertible then each generator `g` is larger than its inverse `g^{-1}`, and `g^{-1}` is larger than every generator that is smaller than `g`.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> b < a False >>> a < a.inverse() False
""" group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be compared") l = len(self) m = len(other) # implement lenlex order if l < m: return True elif l > m: return False for i in range(l): a = self[i].array_form[0] b = other[i].array_form[0] p = group.symbols.index(a[0]) q = group.symbols.index(b[0]) if p < q: return True elif p > q: return False elif a[1] < b[1]: return True elif a[1] > b[1]: return False return False
def __le__(self, other): return (self == other or self < other)
def __gt__(self, other): """
Examples ========
>>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> y**2 > x**2 True >>> y*z > z*y False >>> x > x.inverse() True
""" group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be compared") return not self <= other
def __ge__(self, other): return not self < other
def exponent_sum(self, gen): """ For an associative word `self` and a generator or inverse of generator `gen`, ``exponent_sum`` returns the number of times `gen` appears in `self` minus the number of times its inverse appears in `self`. If neither `gen` nor its inverse occur in `self` then 0 is returned.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> w = x**2*y**3 >>> w.exponent_sum(x) 2 >>> w.exponent_sum(x**-1) -2 >>> w = x**2*y**4*x**-3 >>> w.exponent_sum(x) -1
See Also ========
generator_count
""" if len(gen) != 1: raise ValueError("gen must be a generator or inverse of a generator") s = gen.array_form[0] return s[1]*sum(i[1] for i in self.array_form if i[0] == s[0])
def generator_count(self, gen): """ For an associative word `self` and a generator `gen`, ``generator_count`` returns the multiplicity of generator `gen` in `self`.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> w = x**2*y**3 >>> w.generator_count(x) 2 >>> w = x**2*y**4*x**-3 >>> w.generator_count(x) 5
See Also ========
exponent_sum
""" if len(gen) != 1 or gen.array_form[0][1] < 0: raise ValueError("gen must be a generator") s = gen.array_form[0] return s[1]*sum(abs(i[1]) for i in self.array_form if i[0] == s[0])
def subword(self, from_i, to_j, strict=True): """ For an associative word `self` and two positive integers `from_i` and `to_j`, `subword` returns the subword of `self` that begins at position `from_i` and ends at `to_j - 1`, indexing is done with origin 0.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**5*b*a**2*b**-4*a >>> w.subword(2, 6) a**3*b
""" group = self.group if not strict: from_i = max(from_i, 0) to_j = min(len(self), to_j) if from_i < 0 or to_j > len(self): raise ValueError("`from_i`, `to_j` must be positive and no greater than " "the length of associative word") if to_j <= from_i: return group.identity else: letter_form = self.letter_form[from_i: to_j] array_form = letter_form_to_array_form(letter_form, group) return group.dtype(array_form)
def subword_index(self, word, start = 0): ''' Find the index of `word` in `self`.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**2*b*a*b**3 >>> w.subword_index(a*b*a*b) 1
''' l = len(word) self_lf = self.letter_form word_lf = word.letter_form index = None for i in range(start,len(self_lf)-l+1): if self_lf[i:i+l] == word_lf: index = i break if index is not None: return index else: raise ValueError("The given word is not a subword of self")
def is_dependent(self, word): """ Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> (x**4*y**-3).is_dependent(x**4*y**-2) True >>> (x**2*y**-1).is_dependent(x*y) False >>> (x*y**2*x*y**2).is_dependent(x*y**2) True >>> (x**12).is_dependent(x**-4) True
See Also ========
is_independent
""" try: return self.subword_index(word) is not None except ValueError: pass try: return self.subword_index(word**-1) is not None except ValueError: return False
def is_independent(self, word): """
See Also ========
is_dependent
""" return not self.is_dependent(word)
def contains_generators(self): """ Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y, z = free_group("x, y, z") >>> (x**2*y**-1).contains_generators() {x, y} >>> (x**3*z).contains_generators() {x, z}
""" group = self.group gens = {group.dtype(((syllable[0], 1),)) for syllable in self.array_form} return gens
def cyclic_subword(self, from_i, to_j): group = self.group l = len(self) letter_form = self.letter_form period1 = int(from_i/l) if from_i >= l: from_i -= l*period1 to_j -= l*period1 diff = to_j - from_i word = letter_form[from_i: to_j] period2 = int(to_j/l) - 1 word += letter_form*period2 + letter_form[:diff-l+from_i-l*period2] word = letter_form_to_array_form(word, group) return group.dtype(word)
def cyclic_conjugates(self): """Returns a words which are cyclic to the word `self`.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> w = x*y*x*y*x >>> w.cyclic_conjugates() {x*y*x**2*y, x**2*y*x*y, y*x*y*x**2, y*x**2*y*x, x*y*x*y*x} >>> s = x*y*x**2*y*x >>> s.cyclic_conjugates() {x**2*y*x**2*y, y*x**2*y*x**2, x*y*x**2*y*x}
References ==========
.. [1] https://planetmath.org/cyclicpermutation
""" return {self.cyclic_subword(i, i+len(self)) for i in range(len(self))}
def is_cyclic_conjugate(self, w): """ Checks whether words ``self``, ``w`` are cyclic conjugates.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> w1 = x**2*y**5 >>> w2 = x*y**5*x >>> w1.is_cyclic_conjugate(w2) True >>> w3 = x**-1*y**5*x**-1 >>> w3.is_cyclic_conjugate(w2) False
""" l1 = len(self) l2 = len(w) if l1 != l2: return False w1 = self.identity_cyclic_reduction() w2 = w.identity_cyclic_reduction() letter1 = w1.letter_form letter2 = w2.letter_form str1 = ' '.join(map(str, letter1)) str2 = ' '.join(map(str, letter2)) if len(str1) != len(str2): return False
return str1 in str2 + ' ' + str2
def number_syllables(self): """Returns the number of syllables of the associative word `self`.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") >>> (swapnil1**3*swapnil0*swapnil1**-1).number_syllables() 3
""" return len(self.array_form)
def exponent_syllable(self, i): """ Returns the exponent of the `i`-th syllable of the associative word `self`.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**5*b*a**2*b**-4*a >>> w.exponent_syllable( 2 ) 2
""" return self.array_form[i][1]
def generator_syllable(self, i): """ Returns the symbol of the generator that is involved in the i-th syllable of the associative word `self`.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**5*b*a**2*b**-4*a >>> w.generator_syllable( 3 ) b
""" return self.array_form[i][0]
def sub_syllables(self, from_i, to_j): """ `sub_syllables` returns the subword of the associative word `self` that consists of syllables from positions `from_to` to `to_j`, where `from_to` and `to_j` must be positive integers and indexing is done with origin 0.
Examples ========
>>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a, b") >>> w = a**5*b*a**2*b**-4*a >>> w.sub_syllables(1, 2) b >>> w.sub_syllables(3, 3) <identity>
""" if not isinstance(from_i, int) or not isinstance(to_j, int): raise ValueError("both arguments should be integers") group = self.group if to_j <= from_i: return group.identity else: r = tuple(self.array_form[from_i: to_j]) return group.dtype(r)
def substituted_word(self, from_i, to_j, by): """ Returns the associative word obtained by replacing the subword of `self` that begins at position `from_i` and ends at position `to_j - 1` by the associative word `by`. `from_i` and `to_j` must be positive integers, indexing is done with origin 0. In other words, `w.substituted_word(w, from_i, to_j, by)` is the product of the three words: `w.subword(0, from_i)`, `by`, and `w.subword(to_j len(w))`.
See Also ========
eliminate_word
""" lw = len(self) if from_i >= to_j or from_i > lw or to_j > lw: raise ValueError("values should be within bounds")
# otherwise there are four possibilities
# first if from=1 and to=lw then if from_i == 0 and to_j == lw: return by elif from_i == 0: # second if from_i=1 (and to_j < lw) then return by*self.subword(to_j, lw) elif to_j == lw: # third if to_j=1 (and from_i > 1) then return self.subword(0, from_i)*by else: # finally return self.subword(0, from_i)*by*self.subword(to_j, lw)
def is_cyclically_reduced(self): r"""Returns whether the word is cyclically reduced or not. A word is cyclically reduced if by forming the cycle of the word, the word is not reduced, i.e a word w = `a_1 ... a_n` is called cyclically reduced if `a_1 \ne a_n^{-1}`.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> (x**2*y**-1*x**-1).is_cyclically_reduced() False >>> (y*x**2*y**2).is_cyclically_reduced() True
""" if not self: return True return self[0] != self[-1]**-1
def identity_cyclic_reduction(self): """Return a unique cyclically reduced version of the word.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> (x**2*y**2*x**-1).identity_cyclic_reduction() x*y**2 >>> (x**-3*y**-1*x**5).identity_cyclic_reduction() x**2*y**-1
References ==========
.. [1] https://planetmath.org/cyclicallyreduced
""" word = self.copy() group = self.group while not word.is_cyclically_reduced(): exp1 = word.exponent_syllable(0) exp2 = word.exponent_syllable(-1) r = exp1 + exp2 if r == 0: rep = word.array_form[1: word.number_syllables() - 1] else: rep = ((word.generator_syllable(0), exp1 + exp2),) + \ word.array_form[1: word.number_syllables() - 1] word = group.dtype(rep) return word
def cyclic_reduction(self, removed=False): """Return a cyclically reduced version of the word. Unlike `identity_cyclic_reduction`, this will not cyclically permute the reduced word - just remove the "unreduced" bits on either side of it. Compare the examples with those of `identity_cyclic_reduction`.
When `removed` is `True`, return a tuple `(word, r)` where self `r` is such that before the reduction the word was either `r*word*r**-1`.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> (x**2*y**2*x**-1).cyclic_reduction() x*y**2 >>> (x**-3*y**-1*x**5).cyclic_reduction() y**-1*x**2 >>> (x**-3*y**-1*x**5).cyclic_reduction(removed=True) (y**-1*x**2, x**-3)
""" word = self.copy() g = self.group.identity while not word.is_cyclically_reduced(): exp1 = abs(word.exponent_syllable(0)) exp2 = abs(word.exponent_syllable(-1)) exp = min(exp1, exp2) start = word[0]**abs(exp) end = word[-1]**abs(exp) word = start**-1*word*end**-1 g = g*start if removed: return word, g return word
def power_of(self, other): ''' Check if `self == other**n` for some integer n.
Examples ========
>>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> ((x*y)**2).power_of(x*y) True >>> (x**-3*y**-2*x**3).power_of(x**-3*y*x**3) True
''' if self.is_identity: return True
l = len(other) if l == 1: # self has to be a power of one generator gens = self.contains_generators() s = other in gens or other**-1 in gens return len(gens) == 1 and s
# if self is not cyclically reduced and it is a power of other, # other isn't cyclically reduced and the parts removed during # their reduction must be equal reduced, r1 = self.cyclic_reduction(removed=True) if not r1.is_identity: other, r2 = other.cyclic_reduction(removed=True) if r1 == r2: return reduced.power_of(other) return False
if len(self) < l or len(self) % l: return False
prefix = self.subword(0, l) if prefix == other or prefix**-1 == other: rest = self.subword(l, len(self)) return rest.power_of(other) return False
def letter_form_to_array_form(array_form, group): """ This method converts a list given with possible repetitions of elements in it. It returns a new list such that repetitions of consecutive elements is removed and replace with a tuple element of size two such that the first index contains `value` and the second index contains the number of consecutive repetitions of `value`.
""" a = list(array_form[:]) new_array = [] n = 1 symbols = group.symbols for i in range(len(a)): if i == len(a) - 1: if a[i] == a[i - 1]: if (-a[i]) in symbols: new_array.append((-a[i], -n)) else: new_array.append((a[i], n)) else: if (-a[i]) in symbols: new_array.append((-a[i], -1)) else: new_array.append((a[i], 1)) return new_array elif a[i] == a[i + 1]: n += 1 else: if (-a[i]) in symbols: new_array.append((-a[i], -n)) else: new_array.append((a[i], n)) n = 1
def zero_mul_simp(l, index): """Used to combine two reduced words.""" while index >=0 and index < len(l) - 1 and l[index][0] == l[index + 1][0]: exp = l[index][1] + l[index + 1][1] base = l[index][0] l[index] = (base, exp) del l[index + 1] if l[index][1] == 0: del l[index] index -= 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611r"""Construct transitive subgroups of symmetric groups, useful in Galois theory.
Besides constructing instances of the :py:class:`~.PermutationGroup` class torepresent the transitive subgroups of $S_n$ for small $n$, this module provides*names* for these groups.
In some applications, it may be preferable to know the name of a group,rather than receive an instance of the :py:class:`~.PermutationGroup`class, and then have to do extra work to determine which group it is, bychecking various properties.
Names are instances of ``Enum`` classes defined in this module. With a name inhand, the name's ``get_perm_group`` method can then be used to retrieve a:py:class:`~.PermutationGroup`.
The names used for groups in this module are taken from [1].
References==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.
"""
from collections import defaultdictfrom enum import Enumimport itertools
from sympy.combinatorics.named_groups import ( SymmetricGroup, AlternatingGroup, CyclicGroup, DihedralGroup, set_symmetric_group_properties, set_alternating_group_properties,)from sympy.combinatorics.perm_groups import PermutationGroupfrom sympy.combinatorics.permutations import Permutation
class S1TransitiveSubgroups(Enum): """ Names for the transitive subgroups of S1. """ S1 = "S1"
def get_perm_group(self): return SymmetricGroup(1)
class S2TransitiveSubgroups(Enum): """ Names for the transitive subgroups of S2. """ S2 = "S2"
def get_perm_group(self): return SymmetricGroup(2)
class S3TransitiveSubgroups(Enum): """ Names for the transitive subgroups of S3. """ A3 = "A3" S3 = "S3"
def get_perm_group(self): if self == S3TransitiveSubgroups.A3: return AlternatingGroup(3) elif self == S3TransitiveSubgroups.S3: return SymmetricGroup(3)
class S4TransitiveSubgroups(Enum): """ Names for the transitive subgroups of S4. """ C4 = "C4" V = "V" D4 = "D4" A4 = "A4" S4 = "S4"
def get_perm_group(self): if self == S4TransitiveSubgroups.C4: return CyclicGroup(4) elif self == S4TransitiveSubgroups.V: return four_group() elif self == S4TransitiveSubgroups.D4: return DihedralGroup(4) elif self == S4TransitiveSubgroups.A4: return AlternatingGroup(4) elif self == S4TransitiveSubgroups.S4: return SymmetricGroup(4)
class S5TransitiveSubgroups(Enum): """ Names for the transitive subgroups of S5. """ C5 = "C5" D5 = "D5" M20 = "M20" A5 = "A5" S5 = "S5"
def get_perm_group(self): if self == S5TransitiveSubgroups.C5: return CyclicGroup(5) elif self == S5TransitiveSubgroups.D5: return DihedralGroup(5) elif self == S5TransitiveSubgroups.M20: return M20() elif self == S5TransitiveSubgroups.A5: return AlternatingGroup(5) elif self == S5TransitiveSubgroups.S5: return SymmetricGroup(5)
class S6TransitiveSubgroups(Enum): """ Names for the transitive subgroups of S6. """ C6 = "C6" S3 = "S3" D6 = "D6" A4 = "A4" G18 = "G18" A4xC2 = "A4 x C2" S4m = "S4-" S4p = "S4+" G36m = "G36-" G36p = "G36+" S4xC2 = "S4 x C2" PSL2F5 = "PSL2(F5)" G72 = "G72" PGL2F5 = "PGL2(F5)" A6 = "A6" S6 = "S6"
def get_perm_group(self): if self == S6TransitiveSubgroups.C6: return CyclicGroup(6) elif self == S6TransitiveSubgroups.S3: return S3_in_S6() elif self == S6TransitiveSubgroups.D6: return DihedralGroup(6) elif self == S6TransitiveSubgroups.A4: return A4_in_S6() elif self == S6TransitiveSubgroups.G18: return G18() elif self == S6TransitiveSubgroups.A4xC2: return A4xC2() elif self == S6TransitiveSubgroups.S4m: return S4m() elif self == S6TransitiveSubgroups.S4p: return S4p() elif self == S6TransitiveSubgroups.G36m: return G36m() elif self == S6TransitiveSubgroups.G36p: return G36p() elif self == S6TransitiveSubgroups.S4xC2: return S4xC2() elif self == S6TransitiveSubgroups.PSL2F5: return PSL2F5() elif self == S6TransitiveSubgroups.G72: return G72() elif self == S6TransitiveSubgroups.PGL2F5: return PGL2F5() elif self == S6TransitiveSubgroups.A6: return AlternatingGroup(6) elif self == S6TransitiveSubgroups.S6: return SymmetricGroup(6)
def four_group(): """ Return a representation of the Klein four-group as a transitive subgroup of S4. """ return PermutationGroup( Permutation(0, 1)(2, 3), Permutation(0, 2)(1, 3) )
def M20(): """ Return a representation of the metacyclic group M20, a transitive subgroup of S5 that is one of the possible Galois groups for polys of degree 5.
Notes =====
See [1], Page 323.
""" G = PermutationGroup(Permutation(0, 1, 2, 3, 4), Permutation(1, 2, 4, 3)) G._degree = 5 G._order = 20 G._is_transitive = True G._is_sym = False G._is_alt = False G._is_cyclic = False G._is_dihedral = False return G
def S3_in_S6(): """ Return a representation of S3 as a transitive subgroup of S6.
Notes =====
The representation is found by viewing the group as the symmetries of a triangular prism.
""" G = PermutationGroup(Permutation(0, 1, 2)(3, 4, 5), Permutation(0, 3)(2, 4)(1, 5)) set_symmetric_group_properties(G, 3, 6) return G
def A4_in_S6(): """ Return a representation of A4 as a transitive subgroup of S6.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" G = PermutationGroup(Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4)) set_alternating_group_properties(G, 4, 6) return G
def S4m(): """ Return a representation of the S4- transitive subgroup of S6.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" G = PermutationGroup(Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3)) set_symmetric_group_properties(G, 4, 6) return G
def S4p(): """ Return a representation of the S4+ transitive subgroup of S6.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" G = PermutationGroup(Permutation(0, 2, 4, 1)(3, 5), Permutation(0, 3)(4, 5)) set_symmetric_group_properties(G, 4, 6) return G
def A4xC2(): """ Return a representation of the (A4 x C2) transitive subgroup of S6.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" return PermutationGroup( Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 1, 2)(3, 5, 4), Permutation(5)(2, 4))
def S4xC2(): """ Return a representation of the (S4 x C2) transitive subgroup of S6.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" return PermutationGroup( Permutation(1, 4, 5, 3), Permutation(0, 4)(1, 5)(2, 3), Permutation(1, 4)(3, 5))
def G18(): """ Return a representation of the group G18, a transitive subgroup of S6 isomorphic to the semidirect product of C3^2 with C2.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" return PermutationGroup( Permutation(5)(0, 1, 2), Permutation(3, 4, 5), Permutation(0, 4)(1, 5)(2, 3))
def G36m(): """ Return a representation of the group G36-, a transitive subgroup of S6 isomorphic to the semidirect product of C3^2 with C2^2.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" return PermutationGroup( Permutation(5)(0, 1, 2), Permutation(3, 4, 5), Permutation(1, 2)(3, 5), Permutation(0, 4)(1, 5)(2, 3))
def G36p(): """ Return a representation of the group G36+, a transitive subgroup of S6 isomorphic to the semidirect product of C3^2 with C4.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" return PermutationGroup( Permutation(5)(0, 1, 2), Permutation(3, 4, 5), Permutation(0, 5, 2, 3)(1, 4))
def G72(): """ Return a representation of the group G72, a transitive subgroup of S6 isomorphic to the semidirect product of C3^2 with D4.
Notes =====
See [1], Page 325.
""" return PermutationGroup( Permutation(5)(0, 1, 2), Permutation(0, 4, 1, 3)(2, 5), Permutation(0, 3)(1, 4)(2, 5))
def PSL2F5(): r""" Return a representation of the group $PSL_2(\mathbb{F}_5)$, as a transitive subgroup of S6, isomorphic to $A_5$.
Notes =====
This was computed using :py:func:`~.find_transitive_subgroups_of_S6`.
""" G = PermutationGroup( Permutation(0, 4, 5)(1, 3, 2), Permutation(0, 4, 3, 1, 5)) set_alternating_group_properties(G, 5, 6) return G
def PGL2F5(): r""" Return a representation of the group $PGL_2(\mathbb{F}_5)$, as a transitive subgroup of S6, isomorphic to $S_5$.
Notes =====
See [1], Page 325.
""" G = PermutationGroup( Permutation(0, 1, 2, 3, 4), Permutation(0, 5)(1, 2)(3, 4)) set_symmetric_group_properties(G, 5, 6) return G
def find_transitive_subgroups_of_S6(*targets, print_report=False): r""" Search for certain transitive subgroups of $S_6$.
The symmetric group $S_6$ has 16 different transitive subgroups, up to conjugacy. Some are more easily constructed than others. For example, the dihedral group $D_6$ is immediately found, but it is not at all obvious how to realize $S_4$ or $S_5$ *transitively* within $S_6$.
In some cases there are well-known constructions that can be used. For example, $S_5$ is isomorphic to $PGL_2(\mathbb{F}_5)$, which acts in a natural way on the projective line $P^1(\mathbb{F}_5)$, a set of order 6.
In absence of such special constructions however, we can simply search for generators. For example, transitive instances of $A_4$ and $S_4$ can be found within $S_6$ in this way.
Once we are engaged in such searches, it may then be easier (if less elegant) to find even those groups like $S_5$ that do have special constructions, by mere search.
This function locates generators for transitive instances in $S_6$ of the following subgroups:
* $A_4$ * $S_4^-$ ($S_4$ not contained within $A_6$) * $S_4^+$ ($S_4$ contained within $A_6$) * $A_4 \times C_2$ * $S_4 \times C_2$ * $G_{18} = C_3^2 \rtimes C_2$ * $G_{36}^- = C_3^2 \rtimes C_2^2$ * $G_{36}^+ = C_3^2 \rtimes C_4$ * $G_{72} = C_3^2 \rtimes D_4$ * $A_5$ * $S_5$
Note: Each of these groups also has a dedicated function in this module that returns the group immediately, using generators that were found by this search procedure.
The search procedure serves as a record of how these generators were found. Also, due to randomness in the generation of the elements of permutation groups, it can be called again, in order to (probably) get different generators for the same groups.
Parameters ==========
targets : list of :py:class:`~.S6TransitiveSubgroups` values The groups you want to find.
print_report : bool (default False) If True, print to stdout the generators found for each group.
Returns =======
dict mapping each name in *targets* to the :py:class:`~.PermutationGroup` that was found
References ==========
.. [2] https://en.wikipedia.org/wiki/Projective_linear_group#Exceptional_isomorphisms .. [3] https://en.wikipedia.org/wiki/Automorphisms_of_the_symmetric_and_alternating_groups#PGL%282,5%29
""" def elts_by_order(G): """Sort the elements of a group by their order. """ elts = defaultdict(list) for g in G.elements: elts[g.order()].append(g) return elts
def order_profile(G, name=None): """Determine how many elements a group has, of each order. """ elts = elts_by_order(G) profile = {o:len(e) for o, e in elts.items()} if name: print(f'{name}: ' + ' '.join(f'{len(profile[r])}@{r}' for r in sorted(profile.keys()))) return profile
S6 = SymmetricGroup(6) A6 = AlternatingGroup(6) S6_by_order = elts_by_order(S6)
def search(existing_gens, needed_gen_orders, order, alt=None, profile=None, anti_profile=None): """ Find a transitive subgroup of S6.
Parameters ==========
existing_gens : list of Permutation Optionally empty list of generators that must be in the group.
needed_gen_orders : list of positive int Nonempty list of the orders of the additional generators that are to be found.
order: int The order of the group being sought.
alt: bool, None If True, require the group to be contained in A6. If False, require the group not to be contained in A6.
profile : dict If given, the group's order profile must equal this.
anti_profile : dict If given, the group's order profile must *not* equal this.
""" for gens in itertools.product(*[S6_by_order[n] for n in needed_gen_orders]): if len(set(gens)) < len(gens): continue G = PermutationGroup(existing_gens + list(gens)) if G.order() == order and G.is_transitive(): if alt is not None and G.is_subgroup(A6) != alt: continue if profile and order_profile(G) != profile: continue if anti_profile and order_profile(G) == anti_profile: continue return G
def match_known_group(G, alt=None): needed = [g.order() for g in G.generators] return search([], needed, G.order(), alt=alt, profile=order_profile(G))
found = {}
def finish_up(name, G): found[name] = G if print_report: print("=" * 40) print(f"{name}:") print(G.generators)
if S6TransitiveSubgroups.A4 in targets or S6TransitiveSubgroups.A4xC2 in targets: A4_in_S6 = match_known_group(AlternatingGroup(4)) finish_up(S6TransitiveSubgroups.A4, A4_in_S6)
if S6TransitiveSubgroups.S4m in targets or S6TransitiveSubgroups.S4xC2 in targets: S4m_in_S6 = match_known_group(SymmetricGroup(4), alt=False) finish_up(S6TransitiveSubgroups.S4m, S4m_in_S6)
if S6TransitiveSubgroups.S4p in targets: S4p_in_S6 = match_known_group(SymmetricGroup(4), alt=True) finish_up(S6TransitiveSubgroups.S4p, S4p_in_S6)
if S6TransitiveSubgroups.A4xC2 in targets: A4xC2_in_S6 = search(A4_in_S6.generators, [2], 24, anti_profile=order_profile(SymmetricGroup(4))) finish_up(S6TransitiveSubgroups.A4xC2, A4xC2_in_S6)
if S6TransitiveSubgroups.S4xC2 in targets: S4xC2_in_S6 = search(S4m_in_S6.generators, [2], 48) finish_up(S6TransitiveSubgroups.S4xC2, S4xC2_in_S6)
# For the normal factor N = C3^2 in any of the G_n subgroups, we take one # obvious instance of C3^2 in S6: N_gens = [Permutation(5)(0, 1, 2), Permutation(5)(3, 4, 5)]
if S6TransitiveSubgroups.G18 in targets: G18_in_S6 = search(N_gens, [2], 18) finish_up(S6TransitiveSubgroups.G18, G18_in_S6)
if S6TransitiveSubgroups.G36m in targets: G36m_in_S6 = search(N_gens, [2, 2], 36, alt=False) finish_up(S6TransitiveSubgroups.G36m, G36m_in_S6)
if S6TransitiveSubgroups.G36p in targets: G36p_in_S6 = search(N_gens, [4], 36, alt=True) finish_up(S6TransitiveSubgroups.G36p, G36p_in_S6)
if S6TransitiveSubgroups.G72 in targets: G72_in_S6 = search(N_gens, [4, 2], 72) finish_up(S6TransitiveSubgroups.G72, G72_in_S6)
# The PSL2(F5) and PGL2(F5) subgroups are isomorphic to A5 and S5, resp.
if S6TransitiveSubgroups.PSL2F5 in targets: PSL2F5_in_S6 = match_known_group(AlternatingGroup(5)) finish_up(S6TransitiveSubgroups.PSL2F5, PSL2F5_in_S6)
if S6TransitiveSubgroups.PGL2F5 in targets: PGL2F5_in_S6 = match_known_group(SymmetricGroup(5)) finish_up(S6TransitiveSubgroups.PGL2F5, PGL2F5_in_S6)
# There is little need to "search" for any of the groups C6, S3, D6, A6, # or S6, since they all have obvious realizations within S6. However, we # support them here just in case a random representation is desired.
if S6TransitiveSubgroups.C6 in targets: C6 = match_known_group(CyclicGroup(6)) finish_up(S6TransitiveSubgroups.C6, C6)
if S6TransitiveSubgroups.S3 in targets: S3 = match_known_group(SymmetricGroup(3)) finish_up(S6TransitiveSubgroups.S3, S3)
if S6TransitiveSubgroups.D6 in targets: D6 = match_known_group(DihedralGroup(6)) finish_up(S6TransitiveSubgroups.D6, D6)
if S6TransitiveSubgroups.A6 in targets: A6 = match_known_group(A6) finish_up(S6TransitiveSubgroups.A6, A6)
if S6TransitiveSubgroups.S6 in targets: S6 = match_known_group(S6) finish_up(S6TransitiveSubgroups.S6, S6)
return found123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302from sympy.combinatorics.permutations import Permutationfrom sympy.core.symbol import symbolsfrom sympy.matrices import Matrixfrom sympy.utilities.iterables import variations, rotate_left
def symmetric(n): """ Generates the symmetric group of order n, Sn.
Examples ========
>>> from sympy.combinatorics.generators import symmetric >>> list(symmetric(3)) [(2), (1 2), (2)(0 1), (0 1 2), (0 2 1), (0 2)] """ for perm in variations(range(n), n): yield Permutation(perm)
def cyclic(n): """ Generates the cyclic group of order n, Cn.
Examples ========
>>> from sympy.combinatorics.generators import cyclic >>> list(cyclic(5)) [(4), (0 1 2 3 4), (0 2 4 1 3), (0 3 1 4 2), (0 4 3 2 1)]
See Also ========
dihedral """ gen = list(range(n)) for i in range(n): yield Permutation(gen) gen = rotate_left(gen, 1)
def alternating(n): """ Generates the alternating group of order n, An.
Examples ========
>>> from sympy.combinatorics.generators import alternating >>> list(alternating(3)) [(2), (0 1 2), (0 2 1)] """ for perm in variations(range(n), n): p = Permutation(perm) if p.is_even: yield p
def dihedral(n): """ Generates the dihedral group of order 2n, Dn.
The result is given as a subgroup of Sn, except for the special cases n=1 (the group S2) and n=2 (the Klein 4-group) where that's not possible and embeddings in S2 and S4 respectively are given.
Examples ========
>>> from sympy.combinatorics.generators import dihedral >>> list(dihedral(3)) [(2), (0 2), (0 1 2), (1 2), (0 2 1), (2)(0 1)]
See Also ========
cyclic """ if n == 1: yield Permutation([0, 1]) yield Permutation([1, 0]) elif n == 2: yield Permutation([0, 1, 2, 3]) yield Permutation([1, 0, 3, 2]) yield Permutation([2, 3, 0, 1]) yield Permutation([3, 2, 1, 0]) else: gen = list(range(n)) for i in range(n): yield Permutation(gen) yield Permutation(gen[::-1]) gen = rotate_left(gen, 1)
def rubik_cube_generators(): """Return the permutations of the 3x3 Rubik's cube, see https://www.gap-system.org/Doc/Examples/rubik.html """ a = [ [(1, 3, 8, 6), (2, 5, 7, 4), (9, 33, 25, 17), (10, 34, 26, 18), (11, 35, 27, 19)], [(9, 11, 16, 14), (10, 13, 15, 12), (1, 17, 41, 40), (4, 20, 44, 37), (6, 22, 46, 35)], [(17, 19, 24, 22), (18, 21, 23, 20), (6, 25, 43, 16), (7, 28, 42, 13), (8, 30, 41, 11)], [(25, 27, 32, 30), (26, 29, 31, 28), (3, 38, 43, 19), (5, 36, 45, 21), (8, 33, 48, 24)], [(33, 35, 40, 38), (34, 37, 39, 36), (3, 9, 46, 32), (2, 12, 47, 29), (1, 14, 48, 27)], [(41, 43, 48, 46), (42, 45, 47, 44), (14, 22, 30, 38), (15, 23, 31, 39), (16, 24, 32, 40)] ] return [Permutation([[i - 1 for i in xi] for xi in x], size=48) for x in a]
def rubik(n): """Return permutations for an nxn Rubik's cube.
Permutations returned are for rotation of each of the slice from the face up to the last face for each of the 3 sides (in this order): front, right and bottom. Hence, the first n - 1 permutations are for the slices from the front. """
if n < 2: raise ValueError('dimension of cube must be > 1')
# 1-based reference to rows and columns in Matrix def getr(f, i): return faces[f].col(n - i)
def getl(f, i): return faces[f].col(i - 1)
def getu(f, i): return faces[f].row(i - 1)
def getd(f, i): return faces[f].row(n - i)
def setr(f, i, s): faces[f][:, n - i] = Matrix(n, 1, s)
def setl(f, i, s): faces[f][:, i - 1] = Matrix(n, 1, s)
def setu(f, i, s): faces[f][i - 1, :] = Matrix(1, n, s)
def setd(f, i, s): faces[f][n - i, :] = Matrix(1, n, s)
# motion of a single face def cw(F, r=1): for _ in range(r): face = faces[F] rv = [] for c in range(n): for r in range(n - 1, -1, -1): rv.append(face[r, c]) faces[F] = Matrix(n, n, rv)
def ccw(F): cw(F, 3)
# motion of plane i from the F side; # fcw(0) moves the F face, fcw(1) moves the plane # just behind the front face, etc... def fcw(i, r=1): for _ in range(r): if i == 0: cw(F) i += 1 temp = getr(L, i) setr(L, i, list(getu(D, i))) setu(D, i, list(reversed(getl(R, i)))) setl(R, i, list(getd(U, i))) setd(U, i, list(reversed(temp))) i -= 1
def fccw(i): fcw(i, 3)
# motion of the entire cube from the F side def FCW(r=1): for _ in range(r): cw(F) ccw(B) cw(U) t = faces[U] cw(L) faces[U] = faces[L] cw(D) faces[L] = faces[D] cw(R) faces[D] = faces[R] faces[R] = t
def FCCW(): FCW(3)
# motion of the entire cube from the U side def UCW(r=1): for _ in range(r): cw(U) ccw(D) t = faces[F] faces[F] = faces[R] faces[R] = faces[B] faces[B] = faces[L] faces[L] = t
def UCCW(): UCW(3)
# defining the permutations for the cube
U, F, R, B, L, D = names = symbols('U, F, R, B, L, D')
# the faces are represented by nxn matrices faces = {} count = 0 for fi in range(6): f = [] for a in range(n**2): f.append(count) count += 1 faces[names[fi]] = Matrix(n, n, f)
# this will either return the value of the current permutation # (show != 1) or else append the permutation to the group, g def perm(show=0): # add perm to the list of perms p = [] for f in names: p.extend(faces[f]) if show: return p g.append(Permutation(p))
g = [] # container for the group's permutations I = list(range(6*n**2)) # the identity permutation used for checking
# define permutations corresponding to cw rotations of the planes # up TO the last plane from that direction; by not including the # last plane, the orientation of the cube is maintained.
# F slices for i in range(n - 1): fcw(i) perm() fccw(i) # restore assert perm(1) == I
# R slices # bring R to front UCW() for i in range(n - 1): fcw(i) # put it back in place UCCW() # record perm() # restore # bring face to front UCW() fccw(i) # restore UCCW() assert perm(1) == I
# D slices # bring up bottom FCW() UCCW() FCCW() for i in range(n - 1): # turn strip fcw(i) # put bottom back on the bottom FCW() UCW() FCCW() # record perm() # restore # bring up bottom FCW() UCCW() FCCW() # turn strip fccw(i) # put bottom back on the bottom FCW() UCW() FCCW() assert perm(1) == I
return g123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430from sympy.core import Basic, Integer
import random
class GrayCode(Basic): """ A Gray code is essentially a Hamiltonian walk on a n-dimensional cube with edge length of one. The vertices of the cube are represented by vectors whose values are binary. The Hamilton walk visits each vertex exactly once. The Gray code for a 3d cube is ['000','100','110','010','011','111','101', '001'].
A Gray code solves the problem of sequentially generating all possible subsets of n objects in such a way that each subset is obtained from the previous one by either deleting or adding a single object. In the above example, 1 indicates that the object is present, and 0 indicates that its absent.
Gray codes have applications in statistics as well when we want to compute various statistics related to subsets in an efficient manner.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> a = GrayCode(4) >>> list(a.generate_gray()) ['0000', '0001', '0011', '0010', '0110', '0111', '0101', '0100', \ '1100', '1101', '1111', '1110', '1010', '1011', '1001', '1000']
References ==========
.. [1] Nijenhuis,A. and Wilf,H.S.(1978). Combinatorial Algorithms. Academic Press. .. [2] Knuth, D. (2011). The Art of Computer Programming, Vol 4 Addison Wesley
"""
_skip = False _current = 0 _rank = None
def __new__(cls, n, *args, **kw_args): """ Default constructor.
It takes a single argument ``n`` which gives the dimension of the Gray code. The starting Gray code string (``start``) or the starting ``rank`` may also be given; the default is to start at rank = 0 ('0...0').
Examples ========
>>> from sympy.combinatorics import GrayCode >>> a = GrayCode(3) >>> a GrayCode(3) >>> a.n 3
>>> a = GrayCode(3, start='100') >>> a.current '100'
>>> a = GrayCode(4, rank=4) >>> a.current '0110' >>> a.rank 4
""" if n < 1 or int(n) != n: raise ValueError( 'Gray code dimension must be a positive integer, not %i' % n) n = Integer(n) args = (n,) + args obj = Basic.__new__(cls, *args) if 'start' in kw_args: obj._current = kw_args["start"] if len(obj._current) > n: raise ValueError('Gray code start has length %i but ' 'should not be greater than %i' % (len(obj._current), n)) elif 'rank' in kw_args: if int(kw_args["rank"]) != kw_args["rank"]: raise ValueError('Gray code rank must be a positive integer, ' 'not %i' % kw_args["rank"]) obj._rank = int(kw_args["rank"]) % obj.selections obj._current = obj.unrank(n, obj._rank) return obj
def next(self, delta=1): """ Returns the Gray code a distance ``delta`` (default = 1) from the current value in canonical order.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> a = GrayCode(3, start='110') >>> a.next().current '111' >>> a.next(-1).current '010' """ return GrayCode(self.n, rank=(self.rank + delta) % self.selections)
@property def selections(self): """ Returns the number of bit vectors in the Gray code.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> a = GrayCode(3) >>> a.selections 8 """ return 2**self.n
@property def n(self): """ Returns the dimension of the Gray code.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> a = GrayCode(5) >>> a.n 5 """ return self.args[0]
def generate_gray(self, **hints): """ Generates the sequence of bit vectors of a Gray Code.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> list(a.generate_gray(start='011')) ['011', '010', '110', '111', '101', '100'] >>> list(a.generate_gray(rank=4)) ['110', '111', '101', '100']
See Also ========
skip
References ==========
.. [1] Knuth, D. (2011). The Art of Computer Programming, Vol 4, Addison Wesley
""" bits = self.n start = None if "start" in hints: start = hints["start"] elif "rank" in hints: start = GrayCode.unrank(self.n, hints["rank"]) if start is not None: self._current = start current = self.current graycode_bin = gray_to_bin(current) if len(graycode_bin) > self.n: raise ValueError('Gray code start has length %i but should ' 'not be greater than %i' % (len(graycode_bin), bits)) self._current = int(current, 2) graycode_int = int(''.join(graycode_bin), 2) for i in range(graycode_int, 1 << bits): if self._skip: self._skip = False else: yield self.current bbtc = (i ^ (i + 1)) gbtc = (bbtc ^ (bbtc >> 1)) self._current = (self._current ^ gbtc) self._current = 0
def skip(self): """ Skips the bit generation.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> a = GrayCode(3) >>> for i in a.generate_gray(): ... if i == '010': ... a.skip() ... print(i) ... 000 001 011 010 111 101 100
See Also ========
generate_gray """ self._skip = True
@property def rank(self): """ Ranks the Gray code.
A ranking algorithm determines the position (or rank) of a combinatorial object among all the objects w.r.t. a given order. For example, the 4 bit binary reflected Gray code (BRGC) '0101' has a rank of 6 as it appears in the 6th position in the canonical ordering of the family of 4 bit Gray codes.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> a = GrayCode(3) >>> list(a.generate_gray()) ['000', '001', '011', '010', '110', '111', '101', '100'] >>> GrayCode(3, start='100').rank 7 >>> GrayCode(3, rank=7).current '100'
See Also ========
unrank
References ==========
.. [1] https://web.archive.org/web/20200224064753/http://statweb.stanford.edu/~susan/courses/s208/node12.html
""" if self._rank is None: self._rank = int(gray_to_bin(self.current), 2) return self._rank
@property def current(self): """ Returns the currently referenced Gray code as a bit string.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> GrayCode(3, start='100').current '100' """ rv = self._current or '0' if not isinstance(rv, str): rv = bin(rv)[2:] return rv.rjust(self.n, '0')
@classmethod def unrank(self, n, rank): """ Unranks an n-bit sized Gray code of rank k. This method exists so that a derivative GrayCode class can define its own code of a given rank.
The string here is generated in reverse order to allow for tail-call optimization.
Examples ========
>>> from sympy.combinatorics import GrayCode >>> GrayCode(5, rank=3).current '00010' >>> GrayCode.unrank(5, 3) '00010'
See Also ========
rank """ def _unrank(k, n): if n == 1: return str(k % 2) m = 2**(n - 1) if k < m: return '0' + _unrank(k, n - 1) return '1' + _unrank(m - (k % m) - 1, n - 1) return _unrank(rank, n)
def random_bitstring(n): """ Generates a random bitlist of length n.
Examples ========
>>> from sympy.combinatorics.graycode import random_bitstring >>> random_bitstring(3) # doctest: +SKIP 100 """ return ''.join([random.choice('01') for i in range(n)])
def gray_to_bin(bin_list): """ Convert from Gray coding to binary coding.
We assume big endian encoding.
Examples ========
>>> from sympy.combinatorics.graycode import gray_to_bin >>> gray_to_bin('100') '111'
See Also ========
bin_to_gray """ b = [bin_list[0]] for i in range(1, len(bin_list)): b += str(int(b[i - 1] != bin_list[i])) return ''.join(b)
def bin_to_gray(bin_list): """ Convert from binary coding to gray coding.
We assume big endian encoding.
Examples ========
>>> from sympy.combinatorics.graycode import bin_to_gray >>> bin_to_gray('111') '100'
See Also ========
gray_to_bin """ b = [bin_list[0]] for i in range(1, len(bin_list)): b += str(int(bin_list[i]) ^ int(bin_list[i - 1])) return ''.join(b)
def get_subset_from_bitstring(super_set, bitstring): """ Gets the subset defined by the bitstring.
Examples ========
>>> from sympy.combinatorics.graycode import get_subset_from_bitstring >>> get_subset_from_bitstring(['a', 'b', 'c', 'd'], '0011') ['c', 'd'] >>> get_subset_from_bitstring(['c', 'a', 'c', 'c'], '1100') ['c', 'a']
See Also ========
graycode_subsets """ if len(super_set) != len(bitstring): raise ValueError("The sizes of the lists are not equal") return [super_set[i] for i, j in enumerate(bitstring) if bitstring[i] == '1']
def graycode_subsets(gray_code_set): """ Generates the subsets as enumerated by a Gray code.
Examples ========
>>> from sympy.combinatorics.graycode import graycode_subsets >>> list(graycode_subsets(['a', 'b', 'c'])) [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], \ ['a', 'c'], ['a']] >>> list(graycode_subsets(['a', 'b', 'c', 'c'])) [[], ['c'], ['c', 'c'], ['c'], ['b', 'c'], ['b', 'c', 'c'], \ ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'c'], \ ['a', 'b', 'c'], ['a', 'c'], ['a', 'c', 'c'], ['a', 'c'], ['a']]
See Also ========
get_subset_from_bitstring """ for bitstring in list(GrayCode(len(gray_code_set)).generate_gray()): yield get_subset_from_bitstring(gray_code_set, bitstring)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061from sympy.combinatorics.perm_groups import PermutationGroupfrom sympy.combinatorics.permutations import Permutationfrom sympy.utilities.iterables import uniq
_af_new = Permutation._af_new
def DirectProduct(*groups): """ Returns the direct product of several groups as a permutation group.
Explanation ===========
This is implemented much like the __mul__ procedure for taking the direct product of two permutation groups, but the idea of shifting the generators is realized in the case of an arbitrary number of groups. A call to DirectProduct(G1, G2, ..., Gn) is generally expected to be faster than a call to G1*G2*...*Gn (and thus the need for this algorithm).
Examples ========
>>> from sympy.combinatorics.group_constructs import DirectProduct >>> from sympy.combinatorics.named_groups import CyclicGroup >>> C = CyclicGroup(4) >>> G = DirectProduct(C, C, C) >>> G.order() 64
See Also ========
sympy.combinatorics.perm_groups.PermutationGroup.__mul__
""" degrees = [] gens_count = [] total_degree = 0 total_gens = 0 for group in groups: current_deg = group.degree current_num_gens = len(group.generators) degrees.append(current_deg) total_degree += current_deg gens_count.append(current_num_gens) total_gens += current_num_gens array_gens = [] for i in range(total_gens): array_gens.append(list(range(total_degree))) current_gen = 0 current_deg = 0 for i in range(len(gens_count)): for j in range(current_gen, current_gen + gens_count[i]): gen = ((groups[i].generators)[j - current_gen]).array_form array_gens[j][current_deg:current_deg + degrees[i]] = \ [x + current_deg for x in gen] current_gen += gens_count[i] current_deg += degrees[i] perm_gens = list(uniq([_af_new(list(a)) for a in array_gens])) return PermutationGroup(perm_gens, dups=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296from itertools import chain, combinations
from sympy.external.gmpy import gcdfrom sympy.ntheory.factor_ import factorintfrom sympy.utilities.misc import as_int
def _is_nilpotent_number(factors: dict) -> bool: """ Check whether `n` is a nilpotent number. Note that ``factors`` is a prime factorization of `n`.
This is a low-level helper for ``is_nilpotent_number``, for internal use. """ for p in factors.keys(): for q, e in factors.items(): # We want to calculate # any(pow(q, k, p) == 1 for k in range(1, e + 1)) m = 1 for _ in range(e): m = m*q % p if m == 1: return False return True
def is_nilpotent_number(n) -> bool: """ Check whether `n` is a nilpotent number. A number `n` is said to be nilpotent if and only if every finite group of order `n` is nilpotent. For more information see [1]_.
Examples ========
>>> from sympy.combinatorics.group_numbers import is_nilpotent_number >>> from sympy import randprime >>> is_nilpotent_number(21) False >>> is_nilpotent_number(randprime(1, 30)**12) True
References ==========
.. [1] Pakianathan, J., Shankar, K., Nilpotent Numbers, The American Mathematical Monthly, 107(7), 631-634. .. [2] https://oeis.org/A056867
""" n = as_int(n) if n <= 0: raise ValueError("n must be a positive integer, not %i" % n) return _is_nilpotent_number(factorint(n))
def is_abelian_number(n) -> bool: """ Check whether `n` is an abelian number. A number `n` is said to be abelian if and only if every finite group of order `n` is abelian. For more information see [1]_.
Examples ========
>>> from sympy.combinatorics.group_numbers import is_abelian_number >>> from sympy import randprime >>> is_abelian_number(4) True >>> is_abelian_number(randprime(1, 2000)**2) True >>> is_abelian_number(60) False
References ==========
.. [1] Pakianathan, J., Shankar, K., Nilpotent Numbers, The American Mathematical Monthly, 107(7), 631-634. .. [2] https://oeis.org/A051532
""" n = as_int(n) if n <= 0: raise ValueError("n must be a positive integer, not %i" % n) factors = factorint(n) return all(e < 3 for e in factors.values()) and _is_nilpotent_number(factors)
def is_cyclic_number(n) -> bool: """ Check whether `n` is a cyclic number. A number `n` is said to be cyclic if and only if every finite group of order `n` is cyclic. For more information see [1]_.
Examples ========
>>> from sympy.combinatorics.group_numbers import is_cyclic_number >>> from sympy import randprime >>> is_cyclic_number(15) True >>> is_cyclic_number(randprime(1, 2000)**2) False >>> is_cyclic_number(4) False
References ==========
.. [1] Pakianathan, J., Shankar, K., Nilpotent Numbers, The American Mathematical Monthly, 107(7), 631-634. .. [2] https://oeis.org/A003277
""" n = as_int(n) if n <= 0: raise ValueError("n must be a positive integer, not %i" % n) factors = factorint(n) return all(e == 1 for e in factors.values()) and _is_nilpotent_number(factors)
def _holder_formula(prime_factors): r""" Number of groups of order `n`. where `n` is squarefree and its prime factors are ``prime_factors``. i.e., ``n == math.prod(prime_factors)``
Explanation ===========
When `n` is squarefree, the number of groups of order `n` is expressed by
.. math :: \sum_{d \mid n} \prod_p \frac{p^{c(p, d)} - 1}{p - 1}
where `n=de`, `p` is the prime factor of `e`, and `c(p, d)` is the number of prime factors `q` of `d` such that `q \equiv 1 \pmod{p}` [2]_.
The formula is elegant, but can be improved when implemented as an algorithm. Since `n` is assumed to be squarefree, the divisor `d` of `n` can be identified with the power set of prime factors. We let `N` be the set of prime factors of `n`. `F = \{p \in N : \forall q \in N, q \not\equiv 1 \pmod{p} \}, M = N \setminus F`, we have the following.
.. math :: \sum_{d \in 2^{M}} \prod_{p \in M \setminus d} \frac{p^{c(p, F \cup d)} - 1}{p - 1}
Practically, many prime factors are expected to be members of `F`, thus reducing computation time.
Parameters ==========
prime_factors : set The set of prime factors of ``n``. where `n` is squarefree.
Returns =======
int : Number of groups of order ``n``
Examples ========
>>> from sympy.combinatorics.group_numbers import _holder_formula >>> _holder_formula({2}) # n = 2 1 >>> _holder_formula({2, 3}) # n = 2*3 = 6 2
See Also ========
groups_count
References ==========
.. [1] Otto Holder, Die Gruppen der Ordnungen p^3, pq^2, pqr, p^4, Math. Ann. 43 pp. 301-412 (1893). http://dx.doi.org/10.1007/BF01443651 .. [2] John H. Conway, Heiko Dietrich and E.A. O'Brien, Counting groups: gnus, moas and other exotica The Mathematical Intelligencer 30, 6-15 (2008) https://doi.org/10.1007/BF02985731
""" F = {p for p in prime_factors if all(q % p != 1 for q in prime_factors)} M = prime_factors - F
s = 0 powerset = chain.from_iterable(combinations(M, r) for r in range(len(M)+1)) for ps in powerset: ps = set(ps) prod = 1 for p in M - ps: c = len([q for q in F | ps if q % p == 1]) prod *= (p**c - 1) // (p - 1) if not prod: break s += prod return s
def groups_count(n): r""" Number of groups of order `n`. In [1]_, ``gnu(n)`` is given, so we follow this notation here as well.
Parameters ==========
n : Integer ``n`` is a positive integer
Returns =======
int : ``gnu(n)``
Raises ======
ValueError Number of groups of order ``n`` is unknown or not implemented. For example, gnu(`2^{11}`) is not yet known. On the other hand, gnu(12) is known to be 5, but this has not yet been implemented in this function.
Examples ========
>>> from sympy.combinatorics.group_numbers import groups_count >>> groups_count(3) # There is only one cyclic group of order 3 1 >>> # There are two groups of order 10: the cyclic group and the dihedral group >>> groups_count(10) 2
See Also ========
is_cyclic_number `n` is cyclic iff gnu(n) = 1
References ==========
.. [1] John H. Conway, Heiko Dietrich and E.A. O'Brien, Counting groups: gnus, moas and other exotica The Mathematical Intelligencer 30, 6-15 (2008) https://doi.org/10.1007/BF02985731 .. [2] https://oeis.org/A000001
""" n = as_int(n) if n <= 0: raise ValueError("n must be a positive integer, not %i" % n) factors = factorint(n) if len(factors) == 1: (p, e) = list(factors.items())[0] if p == 2: A000679 = [1, 1, 2, 5, 14, 51, 267, 2328, 56092, 10494213, 49487367289] if e < len(A000679): return A000679[e] if p == 3: A090091 = [1, 1, 2, 5, 15, 67, 504, 9310, 1396077, 5937876645] if e < len(A090091): return A090091[e] if e <= 2: # gnu(p) = 1, gnu(p**2) = 2 return e if e == 3: # gnu(p**3) = 5 return 5 if e == 4: # if p is an odd prime, gnu(p**4) = 15 return 15 if e == 5: # if p >= 5, gnu(p**5) is expressed by the following equation return 61 + 2*p + 2*gcd(p-1, 3) + gcd(p-1, 4) if e == 6: # if p >= 6, gnu(p**6) is expressed by the following equation return 3*p**2 + 39*p + 344 +\ 24*gcd(p-1, 3) + 11*gcd(p-1, 4) + 2*gcd(p-1, 5) if e == 7: # if p >= 7, gnu(p**7) is expressed by the following equation if p == 5: return 34297 return 3*p**5 + 12*p**4 + 44*p**3 + 170*p**2 + 707*p + 2455 +\ (4*p**2 + 44*p + 291)*gcd(p-1, 3) + (p**2 + 19*p + 135)*gcd(p-1, 4) + \ (3*p + 31)*gcd(p-1, 5) + 4*gcd(p-1, 7) + 5*gcd(p-1, 8) + gcd(p-1, 9) if any(e > 1 for e in factors.values()): # n is not squarefree # some known values for small n that have more than 1 factor and are not square free (https://oeis.org/A000001) small = {12: 5, 18: 5, 20: 5, 24: 15, 28: 4, 36: 14, 40: 14, 44: 4, 45: 2, 48: 52, 50: 5, 52: 5, 54: 15, 56: 13, 60: 13, 63: 4, 68: 5, 72: 50, 75: 3, 76: 4, 80: 52, 84: 15, 88: 12, 90: 10, 92: 4} if n in small: return small[n] raise ValueError("Number of groups of order n is unknown or not implemented") if len(factors) == 2: # n is squarefree semiprime p, q = list(factors.keys()) if p > q: p, q = q, p return 2 if q % p == 1 else 1 return _holder_formula(set(factors.keys()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549import itertoolsfrom sympy.combinatorics.fp_groups import FpGroup, FpSubgroup, simplify_presentationfrom sympy.combinatorics.free_groups import FreeGroupfrom sympy.combinatorics.perm_groups import PermutationGroupfrom sympy.core.intfunc import igcdfrom sympy.functions.combinatorial.numbers import totientfrom sympy.core.singleton import S
class GroupHomomorphism: ''' A class representing group homomorphisms. Instantiate using `homomorphism()`.
References ==========
.. [1] Holt, D., Eick, B. and O'Brien, E. (2005). Handbook of computational group theory.
'''
def __init__(self, domain, codomain, images): self.domain = domain self.codomain = codomain self.images = images self._inverses = None self._kernel = None self._image = None
def _invs(self): ''' Return a dictionary with `{gen: inverse}` where `gen` is a rewriting generator of `codomain` (e.g. strong generator for permutation groups) and `inverse` is an element of its preimage
''' image = self.image() inverses = {} for k in list(self.images.keys()): v = self.images[k] if not (v in inverses or v.is_identity): inverses[v] = k if isinstance(self.codomain, PermutationGroup): gens = image.strong_gens else: gens = image.generators for g in gens: if g in inverses or g.is_identity: continue w = self.domain.identity if isinstance(self.codomain, PermutationGroup): parts = image._strong_gens_slp[g][::-1] else: parts = g for s in parts: if s in inverses: w = w*inverses[s] else: w = w*inverses[s**-1]**-1 inverses[g] = w
return inverses
def invert(self, g): ''' Return an element of the preimage of ``g`` or of each element of ``g`` if ``g`` is a list.
Explanation ===========
If the codomain is an FpGroup, the inverse for equal elements might not always be the same unless the FpGroup's rewriting system is confluent. However, making a system confluent can be time-consuming. If it's important, try `self.codomain.make_confluent()` first.
''' from sympy.combinatorics import Permutation from sympy.combinatorics.free_groups import FreeGroupElement if isinstance(g, (Permutation, FreeGroupElement)): if isinstance(self.codomain, FpGroup): g = self.codomain.reduce(g) if self._inverses is None: self._inverses = self._invs() image = self.image() w = self.domain.identity if isinstance(self.codomain, PermutationGroup): gens = image.generator_product(g)[::-1] else: gens = g # the following can't be "for s in gens:" # because that would be equivalent to # "for s in gens.array_form:" when g is # a FreeGroupElement. On the other hand, # when you call gens by index, the generator # (or inverse) at position i is returned. for i in range(len(gens)): s = gens[i] if s.is_identity: continue if s in self._inverses: w = w*self._inverses[s] else: w = w*self._inverses[s**-1]**-1 return w elif isinstance(g, list): return [self.invert(e) for e in g]
def kernel(self): ''' Compute the kernel of `self`.
''' if self._kernel is None: self._kernel = self._compute_kernel() return self._kernel
def _compute_kernel(self): G = self.domain G_order = G.order() if G_order is S.Infinity: raise NotImplementedError( "Kernel computation is not implemented for infinite groups") gens = [] if isinstance(G, PermutationGroup): K = PermutationGroup(G.identity) else: K = FpSubgroup(G, gens, normal=True) i = self.image().order() while K.order()*i != G_order: r = G.random() k = r*self.invert(self(r))**-1 if k not in K: gens.append(k) if isinstance(G, PermutationGroup): K = PermutationGroup(gens) else: K = FpSubgroup(G, gens, normal=True) return K
def image(self): ''' Compute the image of `self`.
''' if self._image is None: values = list(set(self.images.values())) if isinstance(self.codomain, PermutationGroup): self._image = self.codomain.subgroup(values) else: self._image = FpSubgroup(self.codomain, values) return self._image
def _apply(self, elem): ''' Apply `self` to `elem`.
''' if elem not in self.domain: if isinstance(elem, (list, tuple)): return [self._apply(e) for e in elem] raise ValueError("The supplied element does not belong to the domain") if elem.is_identity: return self.codomain.identity else: images = self.images value = self.codomain.identity if isinstance(self.domain, PermutationGroup): gens = self.domain.generator_product(elem, original=True) for g in gens: if g in self.images: value = images[g]*value else: value = images[g**-1]**-1*value else: i = 0 for _, p in elem.array_form: if p < 0: g = elem[i]**-1 else: g = elem[i] value = value*images[g]**p i += abs(p) return value
def __call__(self, elem): return self._apply(elem)
def is_injective(self): ''' Check if the homomorphism is injective
''' return self.kernel().order() == 1
def is_surjective(self): ''' Check if the homomorphism is surjective
''' im = self.image().order() oth = self.codomain.order() if im is S.Infinity and oth is S.Infinity: return None else: return im == oth
def is_isomorphism(self): ''' Check if `self` is an isomorphism.
''' return self.is_injective() and self.is_surjective()
def is_trivial(self): ''' Check is `self` is a trivial homomorphism, i.e. all elements are mapped to the identity.
''' return self.image().order() == 1
def compose(self, other): ''' Return the composition of `self` and `other`, i.e. the homomorphism phi such that for all g in the domain of `other`, phi(g) = self(other(g))
''' if not other.image().is_subgroup(self.domain): raise ValueError("The image of `other` must be a subgroup of " "the domain of `self`") images = {g: self(other(g)) for g in other.images} return GroupHomomorphism(other.domain, self.codomain, images)
def restrict_to(self, H): ''' Return the restriction of the homomorphism to the subgroup `H` of the domain.
''' if not isinstance(H, PermutationGroup) or not H.is_subgroup(self.domain): raise ValueError("Given H is not a subgroup of the domain") domain = H images = {g: self(g) for g in H.generators} return GroupHomomorphism(domain, self.codomain, images)
def invert_subgroup(self, H): ''' Return the subgroup of the domain that is the inverse image of the subgroup ``H`` of the homomorphism image
''' if not H.is_subgroup(self.image()): raise ValueError("Given H is not a subgroup of the image") gens = [] P = PermutationGroup(self.image().identity) for h in H.generators: h_i = self.invert(h) if h_i not in P: gens.append(h_i) P = PermutationGroup(gens) for k in self.kernel().generators: if k*h_i not in P: gens.append(k*h_i) P = PermutationGroup(gens) return P
def homomorphism(domain, codomain, gens, images=(), check=True): ''' Create (if possible) a group homomorphism from the group ``domain`` to the group ``codomain`` defined by the images of the domain's generators ``gens``. ``gens`` and ``images`` can be either lists or tuples of equal sizes. If ``gens`` is a proper subset of the group's generators, the unspecified generators will be mapped to the identity. If the images are not specified, a trivial homomorphism will be created.
If the given images of the generators do not define a homomorphism, an exception is raised.
If ``check`` is ``False``, do not check whether the given images actually define a homomorphism.
''' if not isinstance(domain, (PermutationGroup, FpGroup, FreeGroup)): raise TypeError("The domain must be a group") if not isinstance(codomain, (PermutationGroup, FpGroup, FreeGroup)): raise TypeError("The codomain must be a group")
generators = domain.generators if not all(g in generators for g in gens): raise ValueError("The supplied generators must be a subset of the domain's generators") if not all(g in codomain for g in images): raise ValueError("The images must be elements of the codomain")
if images and len(images) != len(gens): raise ValueError("The number of images must be equal to the number of generators")
gens = list(gens) images = list(images)
images.extend([codomain.identity]*(len(generators)-len(images))) gens.extend([g for g in generators if g not in gens]) images = dict(zip(gens,images))
if check and not _check_homomorphism(domain, codomain, images): raise ValueError("The given images do not define a homomorphism") return GroupHomomorphism(domain, codomain, images)
def _check_homomorphism(domain, codomain, images): """ Check that a given mapping of generators to images defines a homomorphism.
Parameters ========== domain : PermutationGroup, FpGroup, FreeGroup codomain : PermutationGroup, FpGroup, FreeGroup images : dict The set of keys must be equal to domain.generators. The values must be elements of the codomain.
""" pres = domain if hasattr(domain, 'relators') else domain.presentation() rels = pres.relators gens = pres.generators symbols = [g.ext_rep[0] for g in gens] symbols_to_domain_generators = dict(zip(symbols, domain.generators)) identity = codomain.identity
def _image(r): w = identity for symbol, power in r.array_form: g = symbols_to_domain_generators[symbol] w *= images[g]**power return w
for r in rels: if isinstance(codomain, FpGroup): s = codomain.equals(_image(r), identity) if s is None: # only try to make the rewriting system # confluent when it can't determine the # truth of equality otherwise success = codomain.make_confluent() s = codomain.equals(_image(r), identity) if s is None and not success: raise RuntimeError("Can't determine if the images " "define a homomorphism. Try increasing " "the maximum number of rewriting rules " "(group._rewriting_system.set_max(new_value); " "the current value is stored in group._rewriting" "_system.maxeqns)") else: s = _image(r).is_identity if not s: return False return True
def orbit_homomorphism(group, omega): ''' Return the homomorphism induced by the action of the permutation group ``group`` on the set ``omega`` that is closed under the action.
''' from sympy.combinatorics import Permutation from sympy.combinatorics.named_groups import SymmetricGroup codomain = SymmetricGroup(len(omega)) identity = codomain.identity omega = list(omega) images = {g: identity*Permutation([omega.index(o^g) for o in omega]) for g in group.generators} group._schreier_sims(base=omega) H = GroupHomomorphism(group, codomain, images) if len(group.basic_stabilizers) > len(omega): H._kernel = group.basic_stabilizers[len(omega)] else: H._kernel = PermutationGroup([group.identity]) return H
def block_homomorphism(group, blocks): ''' Return the homomorphism induced by the action of the permutation group ``group`` on the block system ``blocks``. The latter should be of the same form as returned by the ``minimal_block`` method for permutation groups, namely a list of length ``group.degree`` where the i-th entry is a representative of the block i belongs to.
''' from sympy.combinatorics import Permutation from sympy.combinatorics.named_groups import SymmetricGroup
n = len(blocks)
# number the blocks; m is the total number, # b is such that b[i] is the number of the block i belongs to, # p is the list of length m such that p[i] is the representative # of the i-th block m = 0 p = [] b = [None]*n for i in range(n): if blocks[i] == i: p.append(i) b[i] = m m += 1 for i in range(n): b[i] = b[blocks[i]]
codomain = SymmetricGroup(m) # the list corresponding to the identity permutation in codomain identity = range(m) images = {g: Permutation([b[p[i]^g] for i in identity]) for g in group.generators} H = GroupHomomorphism(group, codomain, images) return H
def group_isomorphism(G, H, isomorphism=True): ''' Compute an isomorphism between 2 given groups.
Parameters ==========
G : A finite ``FpGroup`` or a ``PermutationGroup``. First group.
H : A finite ``FpGroup`` or a ``PermutationGroup`` Second group.
isomorphism : bool This is used to avoid the computation of homomorphism when the user only wants to check if there exists an isomorphism between the groups.
Returns =======
If isomorphism = False -- Returns a boolean. If isomorphism = True -- Returns a boolean and an isomorphism between `G` and `H`.
Examples ========
>>> from sympy.combinatorics import free_group, Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.homomorphisms import group_isomorphism >>> from sympy.combinatorics.named_groups import DihedralGroup, AlternatingGroup
>>> D = DihedralGroup(8) >>> p = Permutation(0, 1, 2, 3, 4, 5, 6, 7) >>> P = PermutationGroup(p) >>> group_isomorphism(D, P) (False, None)
>>> F, a, b = free_group("a, b") >>> G = FpGroup(F, [a**3, b**3, (a*b)**2]) >>> H = AlternatingGroup(4) >>> (check, T) = group_isomorphism(G, H) >>> check True >>> T(b*a*b**-1*a**-1*b**-1) (0 2 3)
Notes =====
Uses the approach suggested by Robert Tarjan to compute the isomorphism between two groups. First, the generators of ``G`` are mapped to the elements of ``H`` and we check if the mapping induces an isomorphism.
''' if not isinstance(G, (PermutationGroup, FpGroup)): raise TypeError("The group must be a PermutationGroup or an FpGroup") if not isinstance(H, (PermutationGroup, FpGroup)): raise TypeError("The group must be a PermutationGroup or an FpGroup")
if isinstance(G, FpGroup) and isinstance(H, FpGroup): G = simplify_presentation(G) H = simplify_presentation(H) # Two infinite FpGroups with the same generators are isomorphic # when the relators are same but are ordered differently. if G.generators == H.generators and (G.relators).sort() == (H.relators).sort(): if not isomorphism: return True return (True, homomorphism(G, H, G.generators, H.generators))
# `_H` is the permutation group isomorphic to `H`. _H = H g_order = G.order() h_order = H.order()
if g_order is S.Infinity: raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.")
if isinstance(H, FpGroup): if h_order is S.Infinity: raise NotImplementedError("Isomorphism methods are not implemented for infinite groups.") _H, h_isomorphism = H._to_perm_group()
if (g_order != h_order) or (G.is_abelian != H.is_abelian): if not isomorphism: return False return (False, None)
if not isomorphism: # Two groups of the same cyclic numbered order # are isomorphic to each other. n = g_order if (igcd(n, totient(n))) == 1: return True
# Match the generators of `G` with subsets of `_H` gens = list(G.generators) for subset in itertools.permutations(_H, len(gens)): images = list(subset) images.extend([_H.identity]*(len(G.generators)-len(images))) _images = dict(zip(gens,images)) if _check_homomorphism(G, _H, _images): if isinstance(H, FpGroup): images = h_isomorphism.invert(images) T = homomorphism(G, H, G.generators, images, check=False) if T.is_isomorphism(): # It is a valid isomorphism if not isomorphism: return True return (True, T)
if not isomorphism: return False return (False, None)
def is_isomorphic(G, H): ''' Check if the groups are isomorphic to each other
Parameters ==========
G : A finite ``FpGroup`` or a ``PermutationGroup`` First group.
H : A finite ``FpGroup`` or a ``PermutationGroup`` Second group.
Returns =======
boolean ''' return group_isomorphism(G, H, isomorphism=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332from sympy.combinatorics.group_constructs import DirectProductfrom sympy.combinatorics.perm_groups import PermutationGroupfrom sympy.combinatorics.permutations import Permutation
_af_new = Permutation._af_new
def AbelianGroup(*cyclic_orders): """ Returns the direct product of cyclic groups with the given orders.
Explanation ===========
According to the structure theorem for finite abelian groups ([1]), every finite abelian group can be written as the direct product of finitely many cyclic groups.
Examples ========
>>> from sympy.combinatorics.named_groups import AbelianGroup >>> AbelianGroup(3, 4) PermutationGroup([ (6)(0 1 2), (3 4 5 6)]) >>> _.is_group True
See Also ========
DirectProduct
References ==========
.. [1] https://groupprops.subwiki.org/wiki/Structure_theorem_for_finitely_generated_abelian_groups
""" groups = [] degree = 0 order = 1 for size in cyclic_orders: degree += size order *= size groups.append(CyclicGroup(size)) G = DirectProduct(*groups) G._is_abelian = True G._degree = degree G._order = order
return G
def AlternatingGroup(n): """ Generates the alternating group on ``n`` elements as a permutation group.
Explanation ===========
For ``n > 2``, the generators taken are ``(0 1 2), (0 1 2 ... n-1)`` for ``n`` odd and ``(0 1 2), (1 2 ... n-1)`` for ``n`` even (See [1], p.31, ex.6.9.). After the group is generated, some of its basic properties are set. The cases ``n = 1, 2`` are handled separately.
Examples ========
>>> from sympy.combinatorics.named_groups import AlternatingGroup >>> G = AlternatingGroup(4) >>> G.is_group True >>> a = list(G.generate_dimino()) >>> len(a) 12 >>> all(perm.is_even for perm in a) True
See Also ========
SymmetricGroup, CyclicGroup, DihedralGroup
References ==========
.. [1] Armstrong, M. "Groups and Symmetry"
""" # small cases are special if n in (1, 2): return PermutationGroup([Permutation([0])])
a = list(range(n)) a[0], a[1], a[2] = a[1], a[2], a[0] gen1 = a if n % 2: a = list(range(1, n)) a.append(0) gen2 = a else: a = list(range(2, n)) a.append(1) a.insert(0, 0) gen2 = a gens = [gen1, gen2] if gen1 == gen2: gens = gens[:1] G = PermutationGroup([_af_new(a) for a in gens], dups=False)
set_alternating_group_properties(G, n, n) G._is_alt = True return G
def set_alternating_group_properties(G, n, degree): """Set known properties of an alternating group. """ if n < 4: G._is_abelian = True G._is_nilpotent = True else: G._is_abelian = False G._is_nilpotent = False if n < 5: G._is_solvable = True else: G._is_solvable = False G._degree = degree G._is_transitive = True G._is_dihedral = False
def CyclicGroup(n): """ Generates the cyclic group of order ``n`` as a permutation group.
Explanation ===========
The generator taken is the ``n``-cycle ``(0 1 2 ... n-1)`` (in cycle notation). After the group is generated, some of its basic properties are set.
Examples ========
>>> from sympy.combinatorics.named_groups import CyclicGroup >>> G = CyclicGroup(6) >>> G.is_group True >>> G.order() 6 >>> list(G.generate_schreier_sims(af=True)) [[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 0], [2, 3, 4, 5, 0, 1], [3, 4, 5, 0, 1, 2], [4, 5, 0, 1, 2, 3], [5, 0, 1, 2, 3, 4]]
See Also ========
SymmetricGroup, DihedralGroup, AlternatingGroup
""" a = list(range(1, n)) a.append(0) gen = _af_new(a) G = PermutationGroup([gen])
G._is_abelian = True G._is_nilpotent = True G._is_solvable = True G._degree = n G._is_transitive = True G._order = n G._is_dihedral = (n == 2) return G
def DihedralGroup(n): r""" Generates the dihedral group `D_n` as a permutation group.
Explanation ===========
The dihedral group `D_n` is the group of symmetries of the regular ``n``-gon. The generators taken are the ``n``-cycle ``a = (0 1 2 ... n-1)`` (a rotation of the ``n``-gon) and ``b = (0 n-1)(1 n-2)...`` (a reflection of the ``n``-gon) in cycle rotation. It is easy to see that these satisfy ``a**n = b**2 = 1`` and ``bab = ~a`` so they indeed generate `D_n` (See [1]). After the group is generated, some of its basic properties are set.
Examples ========
>>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(5) >>> G.is_group True >>> a = list(G.generate_dimino()) >>> [perm.cyclic_form for perm in a] [[], [[0, 1, 2, 3, 4]], [[0, 2, 4, 1, 3]], [[0, 3, 1, 4, 2]], [[0, 4, 3, 2, 1]], [[0, 4], [1, 3]], [[1, 4], [2, 3]], [[0, 1], [2, 4]], [[0, 2], [3, 4]], [[0, 3], [1, 2]]]
See Also ========
SymmetricGroup, CyclicGroup, AlternatingGroup
References ==========
.. [1] https://en.wikipedia.org/wiki/Dihedral_group
""" # small cases are special if n == 1: return PermutationGroup([Permutation([1, 0])]) if n == 2: return PermutationGroup([Permutation([1, 0, 3, 2]), Permutation([2, 3, 0, 1]), Permutation([3, 2, 1, 0])])
a = list(range(1, n)) a.append(0) gen1 = _af_new(a) a = list(range(n)) a.reverse() gen2 = _af_new(a) G = PermutationGroup([gen1, gen2]) # if n is a power of 2, group is nilpotent if n & (n-1) == 0: G._is_nilpotent = True else: G._is_nilpotent = False G._is_dihedral = True G._is_abelian = False G._is_solvable = True G._degree = n G._is_transitive = True G._order = 2*n return G
def SymmetricGroup(n): """ Generates the symmetric group on ``n`` elements as a permutation group.
Explanation ===========
The generators taken are the ``n``-cycle ``(0 1 2 ... n-1)`` and the transposition ``(0 1)`` (in cycle notation). (See [1]). After the group is generated, some of its basic properties are set.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(4) >>> G.is_group True >>> G.order() 24 >>> list(G.generate_schreier_sims(af=True)) [[0, 1, 2, 3], [1, 2, 3, 0], [2, 3, 0, 1], [3, 1, 2, 0], [0, 2, 3, 1], [1, 3, 0, 2], [2, 0, 1, 3], [3, 2, 0, 1], [0, 3, 1, 2], [1, 0, 2, 3], [2, 1, 3, 0], [3, 0, 1, 2], [0, 1, 3, 2], [1, 2, 0, 3], [2, 3, 1, 0], [3, 1, 0, 2], [0, 2, 1, 3], [1, 3, 2, 0], [2, 0, 3, 1], [3, 2, 1, 0], [0, 3, 2, 1], [1, 0, 3, 2], [2, 1, 0, 3], [3, 0, 2, 1]]
See Also ========
CyclicGroup, DihedralGroup, AlternatingGroup
References ==========
.. [1] https://en.wikipedia.org/wiki/Symmetric_group#Generators_and_relations
""" if n == 1: G = PermutationGroup([Permutation([0])]) elif n == 2: G = PermutationGroup([Permutation([1, 0])]) else: a = list(range(1, n)) a.append(0) gen1 = _af_new(a) a = list(range(n)) a[0], a[1] = a[1], a[0] gen2 = _af_new(a) G = PermutationGroup([gen1, gen2]) set_symmetric_group_properties(G, n, n) G._is_sym = True return G
def set_symmetric_group_properties(G, n, degree): """Set known properties of a symmetric group. """ if n < 3: G._is_abelian = True G._is_nilpotent = True else: G._is_abelian = False G._is_nilpotent = False if n < 5: G._is_solvable = True else: G._is_solvable = False G._degree = degree G._is_transitive = True G._is_dihedral = (n in [2, 3]) # cf Landau's func and Stirling's approx
def RubikGroup(n): """Return a group of Rubik's cube generators
>>> from sympy.combinatorics.named_groups import RubikGroup >>> RubikGroup(2).is_group True """ from sympy.combinatorics.generators import rubik if n <= 1: raise ValueError("Invalid cube. n has to be greater than 1") return PermutationGroup(rubik(n))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745from sympy.core import Basic, Dict, sympify, Tuplefrom sympy.core.numbers import Integerfrom sympy.core.sorting import default_sort_keyfrom sympy.core.sympify import _sympifyfrom sympy.functions.combinatorial.numbers import bellfrom sympy.matrices import zerosfrom sympy.sets.sets import FiniteSet, Unionfrom sympy.utilities.iterables import flatten, groupfrom sympy.utilities.misc import as_int
from collections import defaultdict
class Partition(FiniteSet): """ This class represents an abstract partition.
A partition is a set of disjoint sets whose union equals a given set.
See Also ========
sympy.utilities.iterables.partitions, sympy.utilities.iterables.multiset_partitions """
_rank = None _partition = None
def __new__(cls, *partition): """ Generates a new partition object.
This method also verifies if the arguments passed are valid and raises a ValueError if they are not.
Examples ========
Creating Partition from Python lists:
>>> from sympy.combinatorics import Partition >>> a = Partition([1, 2], [3]) >>> a Partition({3}, {1, 2}) >>> a.partition [[1, 2], [3]] >>> len(a) 2 >>> a.members (1, 2, 3)
Creating Partition from Python sets:
>>> Partition({1, 2, 3}, {4, 5}) Partition({4, 5}, {1, 2, 3})
Creating Partition from SymPy finite sets:
>>> from sympy import FiniteSet >>> a = FiniteSet(1, 2, 3) >>> b = FiniteSet(4, 5) >>> Partition(a, b) Partition({4, 5}, {1, 2, 3}) """ args = [] dups = False for arg in partition: if isinstance(arg, list): as_set = set(arg) if len(as_set) < len(arg): dups = True break # error below arg = as_set args.append(_sympify(arg))
if not all(isinstance(part, FiniteSet) for part in args): raise ValueError( "Each argument to Partition should be " \ "a list, set, or a FiniteSet")
# sort so we have a canonical reference for RGS U = Union(*args) if dups or len(U) < sum(len(arg) for arg in args): raise ValueError("Partition contained duplicate elements.")
obj = FiniteSet.__new__(cls, *args) obj.members = tuple(U) obj.size = len(U) return obj
def sort_key(self, order=None): """Return a canonical key that can be used for sorting.
Ordering is based on the size and sorted elements of the partition and ties are broken with the rank.
Examples ========
>>> from sympy import default_sort_key >>> from sympy.combinatorics import Partition >>> from sympy.abc import x >>> a = Partition([1, 2]) >>> b = Partition([3, 4]) >>> c = Partition([1, x]) >>> d = Partition(list(range(4))) >>> l = [d, b, a + 1, a, c] >>> l.sort(key=default_sort_key); l [Partition({1, 2}), Partition({1}, {2}), Partition({1, x}), Partition({3, 4}), Partition({0, 1, 2, 3})] """ if order is None: members = self.members else: members = tuple(sorted(self.members, key=lambda w: default_sort_key(w, order))) return tuple(map(default_sort_key, (self.size, members, self.rank)))
@property def partition(self): """Return partition as a sorted list of lists.
Examples ========
>>> from sympy.combinatorics import Partition >>> Partition([1], [2, 3]).partition [[1], [2, 3]] """ if self._partition is None: self._partition = sorted([sorted(p, key=default_sort_key) for p in self.args]) return self._partition
def __add__(self, other): """ Return permutation whose rank is ``other`` greater than current rank, (mod the maximum rank for the set).
Examples ========
>>> from sympy.combinatorics import Partition >>> a = Partition([1, 2], [3]) >>> a.rank 1 >>> (a + 1).rank 2 >>> (a + 100).rank 1 """ other = as_int(other) offset = self.rank + other result = RGS_unrank((offset) % RGS_enum(self.size), self.size) return Partition.from_rgs(result, self.members)
def __sub__(self, other): """ Return permutation whose rank is ``other`` less than current rank, (mod the maximum rank for the set).
Examples ========
>>> from sympy.combinatorics import Partition >>> a = Partition([1, 2], [3]) >>> a.rank 1 >>> (a - 1).rank 0 >>> (a - 100).rank 1 """ return self.__add__(-other)
def __le__(self, other): """ Checks if a partition is less than or equal to the other based on rank.
Examples ========
>>> from sympy.combinatorics import Partition >>> a = Partition([1, 2], [3, 4, 5]) >>> b = Partition([1], [2, 3], [4], [5]) >>> a.rank, b.rank (9, 34) >>> a <= a True >>> a <= b True """ return self.sort_key() <= sympify(other).sort_key()
def __lt__(self, other): """ Checks if a partition is less than the other.
Examples ========
>>> from sympy.combinatorics import Partition >>> a = Partition([1, 2], [3, 4, 5]) >>> b = Partition([1], [2, 3], [4], [5]) >>> a.rank, b.rank (9, 34) >>> a < b True """ return self.sort_key() < sympify(other).sort_key()
@property def rank(self): """ Gets the rank of a partition.
Examples ========
>>> from sympy.combinatorics import Partition >>> a = Partition([1, 2], [3], [4, 5]) >>> a.rank 13 """ if self._rank is not None: return self._rank self._rank = RGS_rank(self.RGS) return self._rank
@property def RGS(self): """ Returns the "restricted growth string" of the partition.
Explanation ===========
The RGS is returned as a list of indices, L, where L[i] indicates the block in which element i appears. For example, in a partition of 3 elements (a, b, c) into 2 blocks ([c], [a, b]) the RGS is [1, 1, 0]: "a" is in block 1, "b" is in block 1 and "c" is in block 0.
Examples ========
>>> from sympy.combinatorics import Partition >>> a = Partition([1, 2], [3], [4, 5]) >>> a.members (1, 2, 3, 4, 5) >>> a.RGS (0, 0, 1, 2, 2) >>> a + 1 Partition({3}, {4}, {5}, {1, 2}) >>> _.RGS (0, 0, 1, 2, 3) """ rgs = {} partition = self.partition for i, part in enumerate(partition): for j in part: rgs[j] = i return tuple([rgs[i] for i in sorted( [i for p in partition for i in p], key=default_sort_key)])
@classmethod def from_rgs(self, rgs, elements): """ Creates a set partition from a restricted growth string.
Explanation ===========
The indices given in rgs are assumed to be the index of the element as given in elements *as provided* (the elements are not sorted by this routine). Block numbering starts from 0. If any block was not referenced in ``rgs`` an error will be raised.
Examples ========
>>> from sympy.combinatorics import Partition >>> Partition.from_rgs([0, 1, 2, 0, 1], list('abcde')) Partition({c}, {a, d}, {b, e}) >>> Partition.from_rgs([0, 1, 2, 0, 1], list('cbead')) Partition({e}, {a, c}, {b, d}) >>> a = Partition([1, 4], [2], [3, 5]) >>> Partition.from_rgs(a.RGS, a.members) Partition({2}, {1, 4}, {3, 5}) """ if len(rgs) != len(elements): raise ValueError('mismatch in rgs and element lengths') max_elem = max(rgs) + 1 partition = [[] for i in range(max_elem)] j = 0 for i in rgs: partition[i].append(elements[j]) j += 1 if not all(p for p in partition): raise ValueError('some blocks of the partition were empty.') return Partition(*partition)
class IntegerPartition(Basic): """ This class represents an integer partition.
Explanation ===========
In number theory and combinatorics, a partition of a positive integer, ``n``, also called an integer partition, is a way of writing ``n`` as a list of positive integers that sum to n. Two partitions that differ only in the order of summands are considered to be the same partition; if order matters then the partitions are referred to as compositions. For example, 4 has five partitions: [4], [3, 1], [2, 2], [2, 1, 1], and [1, 1, 1, 1]; the compositions [1, 2, 1] and [1, 1, 2] are the same as partition [2, 1, 1].
See Also ========
sympy.utilities.iterables.partitions, sympy.utilities.iterables.multiset_partitions
References ==========
.. [1] https://en.wikipedia.org/wiki/Partition_%28number_theory%29 """
_dict = None _keys = None
def __new__(cls, partition, integer=None): """ Generates a new IntegerPartition object from a list or dictionary.
Explanation ===========
The partition can be given as a list of positive integers or a dictionary of (integer, multiplicity) items. If the partition is preceded by an integer an error will be raised if the partition does not sum to that given integer.
Examples ========
>>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([5, 4, 3, 1, 1]) >>> a IntegerPartition(14, (5, 4, 3, 1, 1)) >>> print(a) [5, 4, 3, 1, 1] >>> IntegerPartition({1:3, 2:1}) IntegerPartition(5, (2, 1, 1, 1))
If the value that the partition should sum to is given first, a check will be made to see n error will be raised if there is a discrepancy:
>>> IntegerPartition(10, [5, 4, 3, 1]) Traceback (most recent call last): ... ValueError: The partition is not valid
""" if integer is not None: integer, partition = partition, integer if isinstance(partition, (dict, Dict)): _ = [] for k, v in sorted(partition.items(), reverse=True): if not v: continue k, v = as_int(k), as_int(v) _.extend([k]*v) partition = tuple(_) else: partition = tuple(sorted(map(as_int, partition), reverse=True)) sum_ok = False if integer is None: integer = sum(partition) sum_ok = True else: integer = as_int(integer)
if not sum_ok and sum(partition) != integer: raise ValueError("Partition did not add to %s" % integer) if any(i < 1 for i in partition): raise ValueError("All integer summands must be greater than one")
obj = Basic.__new__(cls, Integer(integer), Tuple(*partition)) obj.partition = list(partition) obj.integer = integer return obj
def prev_lex(self): """Return the previous partition of the integer, n, in lexical order, wrapping around to [1, ..., 1] if the partition is [n].
Examples ========
>>> from sympy.combinatorics.partitions import IntegerPartition >>> p = IntegerPartition([4]) >>> print(p.prev_lex()) [3, 1] >>> p.partition > p.prev_lex().partition True """ d = defaultdict(int) d.update(self.as_dict()) keys = self._keys if keys == [1]: return IntegerPartition({self.integer: 1}) if keys[-1] != 1: d[keys[-1]] -= 1 if keys[-1] == 2: d[1] = 2 else: d[keys[-1] - 1] = d[1] = 1 else: d[keys[-2]] -= 1 left = d[1] + keys[-2] new = keys[-2] d[1] = 0 while left: new -= 1 if left - new >= 0: d[new] += left//new left -= d[new]*new return IntegerPartition(self.integer, d)
def next_lex(self): """Return the next partition of the integer, n, in lexical order, wrapping around to [n] if the partition is [1, ..., 1].
Examples ========
>>> from sympy.combinatorics.partitions import IntegerPartition >>> p = IntegerPartition([3, 1]) >>> print(p.next_lex()) [4] >>> p.partition < p.next_lex().partition True """ d = defaultdict(int) d.update(self.as_dict()) key = self._keys a = key[-1] if a == self.integer: d.clear() d[1] = self.integer elif a == 1: if d[a] > 1: d[a + 1] += 1 d[a] -= 2 else: b = key[-2] d[b + 1] += 1 d[1] = (d[b] - 1)*b d[b] = 0 else: if d[a] > 1: if len(key) == 1: d.clear() d[a + 1] = 1 d[1] = self.integer - a - 1 else: a1 = a + 1 d[a1] += 1 d[1] = d[a]*a - a1 d[a] = 0 else: b = key[-2] b1 = b + 1 d[b1] += 1 need = d[b]*b + d[a]*a - b1 d[a] = d[b] = 0 d[1] = need return IntegerPartition(self.integer, d)
def as_dict(self): """Return the partition as a dictionary whose keys are the partition integers and the values are the multiplicity of that integer.
Examples ========
>>> from sympy.combinatorics.partitions import IntegerPartition >>> IntegerPartition([1]*3 + [2] + [3]*4).as_dict() {1: 3, 2: 1, 3: 4} """ if self._dict is None: groups = group(self.partition, multiple=False) self._keys = [g[0] for g in groups] self._dict = dict(groups) return self._dict
@property def conjugate(self): """ Computes the conjugate partition of itself.
Examples ========
>>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([6, 3, 3, 2, 1]) >>> a.conjugate [5, 4, 3, 1, 1, 1] """ j = 1 temp_arr = list(self.partition) + [0] k = temp_arr[0] b = [0]*k while k > 0: while k > temp_arr[j]: b[k - 1] = j k -= 1 j += 1 return b
def __lt__(self, other): """Return True if self is less than other when the partition is listed from smallest to biggest.
Examples ========
>>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([3, 1]) >>> a < a False >>> b = a.next_lex() >>> a < b True >>> a == b False """ return list(reversed(self.partition)) < list(reversed(other.partition))
def __le__(self, other): """Return True if self is less than other when the partition is listed from smallest to biggest.
Examples ========
>>> from sympy.combinatorics.partitions import IntegerPartition >>> a = IntegerPartition([4]) >>> a <= a True """ return list(reversed(self.partition)) <= list(reversed(other.partition))
def as_ferrers(self, char='#'): """ Prints the ferrer diagram of a partition.
Examples ========
>>> from sympy.combinatorics.partitions import IntegerPartition >>> print(IntegerPartition([1, 1, 5]).as_ferrers()) ##### # # """ return "\n".join([char*i for i in self.partition])
def __str__(self): return str(list(self.partition))
def random_integer_partition(n, seed=None): """ Generates a random integer partition summing to ``n`` as a list of reverse-sorted integers.
Examples ========
>>> from sympy.combinatorics.partitions import random_integer_partition
For the following, a seed is given so a known value can be shown; in practice, the seed would not be given.
>>> random_integer_partition(100, seed=[1, 1, 12, 1, 2, 1, 85, 1]) [85, 12, 2, 1] >>> random_integer_partition(10, seed=[1, 2, 3, 1, 5, 1]) [5, 3, 1, 1] >>> random_integer_partition(1) [1] """ from sympy.core.random import _randint
n = as_int(n) if n < 1: raise ValueError('n must be a positive integer')
randint = _randint(seed)
partition = [] while (n > 0): k = randint(1, n) mult = randint(1, n//k) partition.append((k, mult)) n -= k*mult partition.sort(reverse=True) partition = flatten([[k]*m for k, m in partition]) return partition
def RGS_generalized(m): """ Computes the m + 1 generalized unrestricted growth strings and returns them as rows in matrix.
Examples ========
>>> from sympy.combinatorics.partitions import RGS_generalized >>> RGS_generalized(6) Matrix([ [ 1, 1, 1, 1, 1, 1, 1], [ 1, 2, 3, 4, 5, 6, 0], [ 2, 5, 10, 17, 26, 0, 0], [ 5, 15, 37, 77, 0, 0, 0], [ 15, 52, 151, 0, 0, 0, 0], [ 52, 203, 0, 0, 0, 0, 0], [203, 0, 0, 0, 0, 0, 0]]) """ d = zeros(m + 1) for i in range(m + 1): d[0, i] = 1
for i in range(1, m + 1): for j in range(m): if j <= m - i: d[i, j] = j * d[i - 1, j] + d[i - 1, j + 1] else: d[i, j] = 0 return d
def RGS_enum(m): """ RGS_enum computes the total number of restricted growth strings possible for a superset of size m.
Examples ========
>>> from sympy.combinatorics.partitions import RGS_enum >>> from sympy.combinatorics import Partition >>> RGS_enum(4) 15 >>> RGS_enum(5) 52 >>> RGS_enum(6) 203
We can check that the enumeration is correct by actually generating the partitions. Here, the 15 partitions of 4 items are generated:
>>> a = Partition(list(range(4))) >>> s = set() >>> for i in range(20): ... s.add(a) ... a += 1 ... >>> assert len(s) == 15
""" if (m < 1): return 0 elif (m == 1): return 1 else: return bell(m)
def RGS_unrank(rank, m): """ Gives the unranked restricted growth string for a given superset size.
Examples ========
>>> from sympy.combinatorics.partitions import RGS_unrank >>> RGS_unrank(14, 4) [0, 1, 2, 3] >>> RGS_unrank(0, 4) [0, 0, 0, 0] """ if m < 1: raise ValueError("The superset size must be >= 1") if rank < 0 or RGS_enum(m) <= rank: raise ValueError("Invalid arguments")
L = [1] * (m + 1) j = 1 D = RGS_generalized(m) for i in range(2, m + 1): v = D[m - i, j] cr = j*v if cr <= rank: L[i] = j + 1 rank -= cr j += 1 else: L[i] = int(rank / v + 1) rank %= v return [x - 1 for x in L[1:]]
def RGS_rank(rgs): """ Computes the rank of a restricted growth string.
Examples ========
>>> from sympy.combinatorics.partitions import RGS_rank, RGS_unrank >>> RGS_rank([0, 1, 2, 1, 3]) 42 >>> RGS_rank(RGS_unrank(4, 7)) 4 """ rgs_size = len(rgs) rank = 0 D = RGS_generalized(rgs_size) for i in range(1, rgs_size): n = len(rgs[(i + 1):]) m = max(rgs[0:i]) rank += D[n, m + 1] * rgs[i] return rank123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709from sympy.ntheory.primetest import isprimefrom sympy.combinatorics.perm_groups import PermutationGroupfrom sympy.printing.defaults import DefaultPrintingfrom sympy.combinatorics.free_groups import free_group
class PolycyclicGroup(DefaultPrinting):
is_group = True is_solvable = True
def __init__(self, pc_sequence, pc_series, relative_order, collector=None): """
Parameters ==========
pc_sequence : list A sequence of elements whose classes generate the cyclic factor groups of pc_series. pc_series : list A subnormal sequence of subgroups where each factor group is cyclic. relative_order : list The orders of factor groups of pc_series. collector : Collector By default, it is None. Collector class provides the polycyclic presentation with various other functionalities.
""" self.pcgs = pc_sequence self.pc_series = pc_series self.relative_order = relative_order self.collector = Collector(self.pcgs, pc_series, relative_order) if not collector else collector
def is_prime_order(self): return all(isprime(order) for order in self.relative_order)
def length(self): return len(self.pcgs)
class Collector(DefaultPrinting):
""" References ==========
.. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.3 """
def __init__(self, pcgs, pc_series, relative_order, free_group_=None, pc_presentation=None): """
Most of the parameters for the Collector class are the same as for PolycyclicGroup. Others are described below.
Parameters ==========
free_group_ : tuple free_group_ provides the mapping of polycyclic generating sequence with the free group elements. pc_presentation : dict Provides the presentation of polycyclic groups with the help of power and conjugate relators.
See Also ========
PolycyclicGroup
""" self.pcgs = pcgs self.pc_series = pc_series self.relative_order = relative_order self.free_group = free_group('x:{}'.format(len(pcgs)))[0] if not free_group_ else free_group_ self.index = {s: i for i, s in enumerate(self.free_group.symbols)} self.pc_presentation = self.pc_relators()
def minimal_uncollected_subword(self, word): r""" Returns the minimal uncollected subwords.
Explanation ===========
A word ``v`` defined on generators in ``X`` is a minimal uncollected subword of the word ``w`` if ``v`` is a subword of ``w`` and it has one of the following form
* `v = {x_{i+1}}^{a_j}x_i`
* `v = {x_{i+1}}^{a_j}{x_i}^{-1}`
* `v = {x_i}^{a_j}`
for `a_j` not in `\{1, \ldots, s-1\}`. Where, ``s`` is the power exponent of the corresponding generator.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x1, x2 = free_group("x1, x2") >>> word = x2**2*x1**7 >>> collector.minimal_uncollected_subword(word) ((x2, 2),)
""" # To handle the case word = <identity> if not word: return None
array = word.array_form re = self.relative_order index = self.index
for i in range(len(array)): s1, e1 = array[i]
if re[index[s1]] and (e1 < 0 or e1 > re[index[s1]]-1): return ((s1, e1), )
for i in range(len(array)-1): s1, e1 = array[i] s2, e2 = array[i+1]
if index[s1] > index[s2]: e = 1 if e2 > 0 else -1 return ((s1, e1), (s2, e))
return None
def relations(self): """ Separates the given relators of pc presentation in power and conjugate relations.
Returns =======
(power_rel, conj_rel) Separates pc presentation into power and conjugate relations.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> power_rel, conj_rel = collector.relations() >>> power_rel {x0**2: (), x1**3: ()} >>> conj_rel {x0**-1*x1*x0: x1**2}
See Also ========
pc_relators
""" power_relators = {} conjugate_relators = {} for key, value in self.pc_presentation.items(): if len(key.array_form) == 1: power_relators[key] = value else: conjugate_relators[key] = value return power_relators, conjugate_relators
def subword_index(self, word, w): """ Returns the start and ending index of a given subword in a word.
Parameters ==========
word : FreeGroupElement word defined on free group elements for a polycyclic group. w : FreeGroupElement subword of a given word, whose starting and ending index to be computed.
Returns =======
(i, j) A tuple containing starting and ending index of ``w`` in the given word.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x1, x2 = free_group("x1, x2") >>> word = x2**2*x1**7 >>> w = x2**2*x1 >>> collector.subword_index(word, w) (0, 3) >>> w = x1**7 >>> collector.subword_index(word, w) (2, 9)
""" low = -1 high = -1 for i in range(len(word)-len(w)+1): if word.subword(i, i+len(w)) == w: low = i high = i+len(w) break if low == high == -1: return -1, -1 return low, high
def map_relation(self, w): """ Return a conjugate relation.
Explanation ===========
Given a word formed by two free group elements, the corresponding conjugate relation with those free group elements is formed and mapped with the collected word in the polycyclic presentation.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics import free_group >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x0, x1 = free_group("x0, x1") >>> w = x1*x0 >>> collector.map_relation(w) x1**2
See Also ========
pc_presentation
""" array = w.array_form s1 = array[0][0] s2 = array[1][0] key = ((s2, -1), (s1, 1), (s2, 1)) key = self.free_group.dtype(key) return self.pc_presentation[key]
def collected_word(self, word): r""" Return the collected form of a word.
Explanation ===========
A word ``w`` is called collected, if `w = {x_{i_1}}^{a_1} * \ldots * {x_{i_r}}^{a_r}` with `i_1 < i_2< \ldots < i_r` and `a_j` is in `\{1, \ldots, {s_j}-1\}`.
Otherwise w is uncollected.
Parameters ==========
word : FreeGroupElement An uncollected word.
Returns =======
word A collected word of form `w = {x_{i_1}}^{a_1}, \ldots, {x_{i_r}}^{a_r}` with `i_1, i_2, \ldots, i_r` and `a_j \in \{1, \ldots, {s_j}-1\}`.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics import free_group >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> F, x0, x1, x2, x3 = free_group("x0, x1, x2, x3") >>> word = x3*x2*x1*x0 >>> collected_word = collector.collected_word(word) >>> free_to_perm = {} >>> free_group = collector.free_group >>> for sym, gen in zip(free_group.symbols, collector.pcgs): ... free_to_perm[sym] = gen >>> G1 = PermutationGroup() >>> for w in word: ... sym = w[0] ... perm = free_to_perm[sym] ... G1 = PermutationGroup([perm] + G1.generators) >>> G2 = PermutationGroup() >>> for w in collected_word: ... sym = w[0] ... perm = free_to_perm[sym] ... G2 = PermutationGroup([perm] + G2.generators)
The two are not identical, but they are equivalent:
>>> G1.equals(G2), G1 == G2 (True, False)
See Also ========
minimal_uncollected_subword
""" free_group = self.free_group while True: w = self.minimal_uncollected_subword(word) if not w: break
low, high = self.subword_index(word, free_group.dtype(w)) if low == -1: continue
s1, e1 = w[0] if len(w) == 1: re = self.relative_order[self.index[s1]] q = e1 // re r = e1-q*re
key = ((w[0][0], re), ) key = free_group.dtype(key) if self.pc_presentation[key]: presentation = self.pc_presentation[key].array_form sym, exp = presentation[0] word_ = ((w[0][0], r), (sym, q*exp)) word_ = free_group.dtype(word_) else: if r != 0: word_ = ((w[0][0], r), ) word_ = free_group.dtype(word_) else: word_ = None word = word.eliminate_word(free_group.dtype(w), word_)
if len(w) == 2 and w[1][1] > 0: s2, e2 = w[1] s2 = ((s2, 1), ) s2 = free_group.dtype(s2) word_ = self.map_relation(free_group.dtype(w)) word_ = s2*word_**e1 word_ = free_group.dtype(word_) word = word.substituted_word(low, high, word_)
elif len(w) == 2 and w[1][1] < 0: s2, e2 = w[1] s2 = ((s2, 1), ) s2 = free_group.dtype(s2) word_ = self.map_relation(free_group.dtype(w)) word_ = s2**-1*word_**e1 word_ = free_group.dtype(word_) word = word.substituted_word(low, high, word_)
return word
def pc_relators(self): r""" Return the polycyclic presentation.
Explanation ===========
There are two types of relations used in polycyclic presentation.
* Power relations : Power relators are of the form `x_i^{re_i}`, where `i \in \{0, \ldots, \mathrm{len(pcgs)}\}`, ``x`` represents polycyclic generator and ``re`` is the corresponding relative order.
* Conjugate relations : Conjugate relators are of the form `x_j^-1x_ix_j`, where `j < i \in \{0, \ldots, \mathrm{len(pcgs)}\}`.
Returns =======
A dictionary with power and conjugate relations as key and their collected form as corresponding values.
Notes =====
Identity Permutation is mapped with empty ``()``.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.permutations import Permutation >>> S = SymmetricGroup(49).sylow_subgroup(7) >>> der = S.derived_series() >>> G = der[len(der)-2] >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> pcgs = PcGroup.pcgs >>> len(pcgs) 6 >>> free_group = collector.free_group >>> pc_resentation = collector.pc_presentation >>> free_to_perm = {} >>> for s, g in zip(free_group.symbols, pcgs): ... free_to_perm[s] = g
>>> for k, v in pc_resentation.items(): ... k_array = k.array_form ... if v != (): ... v_array = v.array_form ... lhs = Permutation() ... for gen in k_array: ... s = gen[0] ... e = gen[1] ... lhs = lhs*free_to_perm[s]**e ... if v == (): ... assert lhs.is_identity ... continue ... rhs = Permutation() ... for gen in v_array: ... s = gen[0] ... e = gen[1] ... rhs = rhs*free_to_perm[s]**e ... assert lhs == rhs
""" free_group = self.free_group rel_order = self.relative_order pc_relators = {} perm_to_free = {} pcgs = self.pcgs
for gen, s in zip(pcgs, free_group.generators): perm_to_free[gen**-1] = s**-1 perm_to_free[gen] = s
pcgs = pcgs[::-1] series = self.pc_series[::-1] rel_order = rel_order[::-1] collected_gens = []
for i, gen in enumerate(pcgs): re = rel_order[i] relation = perm_to_free[gen]**re G = series[i]
l = G.generator_product(gen**re, original = True) l.reverse()
word = free_group.identity for g in l: word = word*perm_to_free[g]
word = self.collected_word(word) pc_relators[relation] = word if word else () self.pc_presentation = pc_relators
collected_gens.append(gen) if len(collected_gens) > 1: conj = collected_gens[len(collected_gens)-1] conjugator = perm_to_free[conj]
for j in range(len(collected_gens)-1): conjugated = perm_to_free[collected_gens[j]]
relation = conjugator**-1*conjugated*conjugator gens = conj**-1*collected_gens[j]*conj
l = G.generator_product(gens, original = True) l.reverse() word = free_group.identity for g in l: word = word*perm_to_free[g]
word = self.collected_word(word) pc_relators[relation] = word if word else () self.pc_presentation = pc_relators
return pc_relators
def exponent_vector(self, element): r""" Return the exponent vector of length equal to the length of polycyclic generating sequence.
Explanation ===========
For a given generator/element ``g`` of the polycyclic group, it can be represented as `g = {x_1}^{e_1}, \ldots, {x_n}^{e_n}`, where `x_i` represents polycyclic generators and ``n`` is the number of generators in the free_group equal to the length of pcgs.
Parameters ==========
element : Permutation Generator of a polycyclic group.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.permutations import Permutation >>> G = SymmetricGroup(4) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> pcgs = PcGroup.pcgs >>> collector.exponent_vector(G[0]) [1, 0, 0, 0] >>> exp = collector.exponent_vector(G[1]) >>> g = Permutation() >>> for i in range(len(exp)): ... g = g*pcgs[i]**exp[i] if exp[i] else g >>> assert g == G[1]
References ==========
.. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.1, Definition 8.4
""" free_group = self.free_group G = PermutationGroup() for g in self.pcgs: G = PermutationGroup([g] + G.generators) gens = G.generator_product(element, original = True) gens.reverse()
perm_to_free = {} for sym, g in zip(free_group.generators, self.pcgs): perm_to_free[g**-1] = sym**-1 perm_to_free[g] = sym w = free_group.identity for g in gens: w = w*perm_to_free[g]
word = self.collected_word(w)
index = self.index exp_vector = [0]*len(free_group) word = word.array_form for t in word: exp_vector[index[t[0]]] = t[1] return exp_vector
def depth(self, element): r""" Return the depth of a given element.
Explanation ===========
The depth of a given element ``g`` is defined by `\mathrm{dep}[g] = i` if `e_1 = e_2 = \ldots = e_{i-1} = 0` and `e_i != 0`, where ``e`` represents the exponent-vector.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> collector.depth(G[0]) 2 >>> collector.depth(G[1]) 1
References ==========
.. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" Section 8.1.1, Definition 8.5
""" exp_vector = self.exponent_vector(element) return next((i+1 for i, x in enumerate(exp_vector) if x), len(self.pcgs)+1)
def leading_exponent(self, element): r""" Return the leading non-zero exponent.
Explanation ===========
The leading exponent for a given element `g` is defined by `\mathrm{leading\_exponent}[g]` `= e_i`, if `\mathrm{depth}[g] = i`.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> G = SymmetricGroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> collector.leading_exponent(G[1]) 1
""" exp_vector = self.exponent_vector(element) depth = self.depth(element) if depth != len(self.pcgs)+1: return exp_vector[depth-1] return None
def _sift(self, z, g): h = g d = self.depth(h) while d < len(self.pcgs) and z[d-1] != 1: k = z[d-1] e = self.leading_exponent(h)*(self.leading_exponent(k))**-1 e = e % self.relative_order[d-1] h = k**-e*h d = self.depth(h) return h
def induced_pcgs(self, gens): """
Parameters ==========
gens : list A list of generators on which polycyclic subgroup is to be defined.
Examples ========
>>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(8) >>> G = S.sylow_subgroup(2) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> gens = [G[0], G[1]] >>> ipcgs = collector.induced_pcgs(gens) >>> [gen.order() for gen in ipcgs] [2, 2, 2] >>> G = S.sylow_subgroup(3) >>> PcGroup = G.polycyclic_group() >>> collector = PcGroup.collector >>> gens = [G[0], G[1]] >>> ipcgs = collector.induced_pcgs(gens) >>> [gen.order() for gen in ipcgs] [3]
""" z = [1]*len(self.pcgs) G = gens while G: g = G.pop(0) h = self._sift(z, g) d = self.depth(h) if d < len(self.pcgs): for gen in z: if gen != 1: G.append(h**-1*gen**-1*h*gen) z[d-1] = h; z = [gen for gen in z if gen != 1] return z
def constructive_membership_test(self, ipcgs, g): """ Return the exponent vector for induced pcgs. """ e = [0]*len(ipcgs) h = g d = self.depth(h) for i, gen in enumerate(ipcgs): while self.depth(gen) == d: f = self.leading_exponent(h)*self.leading_exponent(gen) f = f % self.relative_order[d-1] h = gen**(-f)*h e[i] = f d = self.depth(h) if h == 1: return e return False1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115import randomfrom collections import defaultdictfrom collections.abc import Iterablefrom functools import reduce
from sympy.core.parameters import global_parametersfrom sympy.core.basic import Atomfrom sympy.core.expr import Exprfrom sympy.core.numbers import int_valuedfrom sympy.core.numbers import Integerfrom sympy.core.sympify import _sympifyfrom sympy.matrices import zerosfrom sympy.polys.polytools import lcmfrom sympy.printing.repr import sreprfrom sympy.utilities.iterables import (flatten, has_variety, minlex, has_dups, runs, is_sequence)from sympy.utilities.misc import as_intfrom mpmath.libmp.libintmath import ifacfrom sympy.multipledispatch import dispatch
def _af_rmul(a, b): """ Return the product b*a; input and output are array forms. The ith value is a[b[i]].
Examples ========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> a, b = [1, 0, 2], [0, 2, 1] >>> _af_rmul(a, b) [1, 2, 0] >>> [a[b[i]] for i in range(3)] [1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a) >>> b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1]
See Also ========
rmul, _af_rmuln """ return [a[i] for i in b]
def _af_rmuln(*abc): """ Given [a, b, c, ...] return the product of ...*c*b*a using array forms. The ith value is a[b[c[i]]].
Examples ========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> a, b = [1, 0, 2], [0, 2, 1] >>> _af_rmul(a, b) [1, 2, 0] >>> [a[b[i]] for i in range(3)] [1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1]
See Also ========
rmul, _af_rmul """ a = abc m = len(a) if m == 3: p0, p1, p2 = a return [p0[p1[i]] for i in p2] if m == 4: p0, p1, p2, p3 = a return [p0[p1[p2[i]]] for i in p3] if m == 5: p0, p1, p2, p3, p4 = a return [p0[p1[p2[p3[i]]]] for i in p4] if m == 6: p0, p1, p2, p3, p4, p5 = a return [p0[p1[p2[p3[p4[i]]]]] for i in p5] if m == 7: p0, p1, p2, p3, p4, p5, p6 = a return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6] if m == 8: p0, p1, p2, p3, p4, p5, p6, p7 = a return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7] if m == 1: return a[0][:] if m == 2: a, b = a return [a[i] for i in b] if m == 0: raise ValueError("String must not be empty") p0 = _af_rmuln(*a[:m//2]) p1 = _af_rmuln(*a[m//2:]) return [p0[i] for i in p1]
def _af_parity(pi): """ Computes the parity of a permutation in array form.
Explanation ===========
The parity of a permutation reflects the parity of the number of inversions in the permutation, i.e., the number of pairs of x and y such that x > y but p[x] < p[y].
Examples ========
>>> from sympy.combinatorics.permutations import _af_parity >>> _af_parity([0, 1, 2, 3]) 0 >>> _af_parity([3, 2, 0, 1]) 1
See Also ========
Permutation """ n = len(pi) a = [0] * n c = 0 for j in range(n): if a[j] == 0: c += 1 a[j] = 1 i = j while pi[i] != j: i = pi[i] a[i] = 1 return (n - c) % 2
def _af_invert(a): """ Finds the inverse, ~A, of a permutation, A, given in array form.
Examples ========
>>> from sympy.combinatorics.permutations import _af_invert, _af_rmul >>> A = [1, 2, 0, 3] >>> _af_invert(A) [2, 0, 1, 3] >>> _af_rmul(_, A) [0, 1, 2, 3]
See Also ========
Permutation, __invert__ """ inv_form = [0] * len(a) for i, ai in enumerate(a): inv_form[ai] = i return inv_form
def _af_pow(a, n): """ Routine for finding powers of a permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.permutations import _af_pow >>> p = Permutation([2, 0, 3, 1]) >>> p.order() 4 >>> _af_pow(p._array_form, 4) [0, 1, 2, 3] """ if n == 0: return list(range(len(a))) if n < 0: return _af_pow(_af_invert(a), -n) if n == 1: return a[:] elif n == 2: b = [a[i] for i in a] elif n == 3: b = [a[a[i]] for i in a] elif n == 4: b = [a[a[a[i]]] for i in a] else: # use binary multiplication b = list(range(len(a))) while 1: if n & 1: b = [b[i] for i in a] n -= 1 if not n: break if n % 4 == 0: a = [a[a[a[i]]] for i in a] n = n // 4 elif n % 2 == 0: a = [a[i] for i in a] n = n // 2 return b
def _af_commutes_with(a, b): """ Checks if the two permutations with array forms given by ``a`` and ``b`` commute.
Examples ========
>>> from sympy.combinatorics.permutations import _af_commutes_with >>> _af_commutes_with([1, 2, 0], [0, 2, 1]) False
See Also ========
Permutation, commutes_with """ return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
class Cycle(dict): """ Wrapper around dict which provides the functionality of a disjoint cycle.
Explanation ===========
A cycle shows the rule to use to move subsets of elements to obtain a permutation. The Cycle class is more flexible than Permutation in that 1) all elements need not be present in order to investigate how multiple cycles act in sequence and 2) it can contain singletons:
>>> from sympy.combinatorics.permutations import Perm, Cycle
A Cycle will automatically parse a cycle given as a tuple on the rhs:
>>> Cycle(1, 2)(2, 3) (1 3 2)
The identity cycle, Cycle(), can be used to start a product:
>>> Cycle()(1, 2)(2, 3) (1 3 2)
The array form of a Cycle can be obtained by calling the list method (or passing it to the list function) and all elements from 0 will be shown:
>>> a = Cycle(1, 2) >>> a.list() [0, 2, 1] >>> list(a) [0, 2, 1]
If a larger (or smaller) range is desired use the list method and provide the desired size -- but the Cycle cannot be truncated to a size smaller than the largest element that is out of place:
>>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3) >>> b.list() [0, 2, 1, 3, 4] >>> b.list(b.size + 1) [0, 2, 1, 3, 4, 5] >>> b.list(-1) [0, 2, 1]
Singletons are not shown when printing with one exception: the largest element is always shown -- as a singleton if necessary:
>>> Cycle(1, 4, 10)(4, 5) (1 5 4 10) >>> Cycle(1, 2)(4)(5)(10) (1 2)(10)
The array form can be used to instantiate a Permutation so other properties of the permutation can be investigated:
>>> Perm(Cycle(1, 2)(3, 4).list()).transpositions() [(1, 2), (3, 4)]
Notes =====
The underlying structure of the Cycle is a dictionary and although the __iter__ method has been redefined to give the array form of the cycle, the underlying dictionary items are still available with the such methods as items():
>>> list(Cycle(1, 2).items()) [(1, 2), (2, 1)]
See Also ========
Permutation """ def __missing__(self, arg): """Enter arg into dictionary and return arg.""" return as_int(arg)
def __iter__(self): yield from self.list()
def __call__(self, *other): """Return product of cycles processed from R to L.
Examples ========
>>> from sympy.combinatorics import Cycle >>> Cycle(1, 2)(2, 3) (1 3 2)
An instance of a Cycle will automatically parse list-like objects and Permutations that are on the right. It is more flexible than the Permutation in that all elements need not be present:
>>> a = Cycle(1, 2) >>> a(2, 3) (1 3 2) >>> a(2, 3)(4, 5) (1 3 2)(4 5)
""" rv = Cycle(*other) for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]): rv[k] = v return rv
def list(self, size=None): """Return the cycles as an explicit list starting from 0 up to the greater of the largest value in the cycles and size.
Truncation of trailing unmoved items will occur when size is less than the maximum element in the cycle; if this is desired, setting ``size=-1`` will guarantee such trimming.
Examples ========
>>> from sympy.combinatorics import Cycle >>> p = Cycle(2, 3)(4, 5) >>> p.list() [0, 1, 3, 2, 5, 4] >>> p.list(10) [0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
Passing a length too small will trim trailing, unchanged elements in the permutation:
>>> Cycle(2, 4)(1, 2, 4).list(-1) [0, 2, 1] """ if not self and size is None: raise ValueError('must give size for empty Cycle') if size is not None: big = max([i for i in self.keys() if self[i] != i] + [0]) size = max(size, big + 1) else: size = self.size return [self[i] for i in range(size)]
def __repr__(self): """We want it to print as a Cycle, not as a dict.
Examples ========
>>> from sympy.combinatorics import Cycle >>> Cycle(1, 2) (1 2) >>> print(_) (1 2) >>> list(Cycle(1, 2).items()) [(1, 2), (2, 1)] """ if not self: return 'Cycle()' cycles = Permutation(self).cyclic_form s = ''.join(str(tuple(c)) for c in cycles) big = self.size - 1 if not any(i == big for c in cycles for i in c): s += '(%s)' % big return 'Cycle%s' % s
def __str__(self): """We want it to be printed in a Cycle notation with no comma in-between.
Examples ========
>>> from sympy.combinatorics import Cycle >>> Cycle(1, 2) (1 2) >>> Cycle(1, 2, 4)(5, 6) (1 2 4)(5 6) """ if not self: return '()' cycles = Permutation(self).cyclic_form s = ''.join(str(tuple(c)) for c in cycles) big = self.size - 1 if not any(i == big for c in cycles for i in c): s += '(%s)' % big s = s.replace(',', '') return s
def __init__(self, *args): """Load up a Cycle instance with the values for the cycle.
Examples ========
>>> from sympy.combinatorics import Cycle >>> Cycle(1, 2, 6) (1 2 6) """
if not args: return if len(args) == 1: if isinstance(args[0], Permutation): for c in args[0].cyclic_form: self.update(self(*c)) return elif isinstance(args[0], Cycle): for k, v in args[0].items(): self[k] = v return args = [as_int(a) for a in args] if any(i < 0 for i in args): raise ValueError('negative integers are not allowed in a cycle.') if has_dups(args): raise ValueError('All elements must be unique in a cycle.') for i in range(-len(args), 0): self[args[i]] = args[i + 1]
@property def size(self): if not self: return 0 return max(self.keys()) + 1
def copy(self): return Cycle(self)
class Permutation(Atom): r""" A permutation, alternatively known as an 'arrangement number' or 'ordering' is an arrangement of the elements of an ordered list into a one-to-one mapping with itself. The permutation of a given arrangement is given by indicating the positions of the elements after re-arrangement [2]_. For example, if one started with elements ``[x, y, a, b]`` (in that order) and they were reordered as ``[x, y, b, a]`` then the permutation would be ``[0, 1, 3, 2]``. Notice that (in SymPy) the first element is always referred to as 0 and the permutation uses the indices of the elements in the original ordering, not the elements ``(a, b, ...)`` themselves.
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False)
Permutations Notation =====================
Permutations are commonly represented in disjoint cycle or array forms.
Array Notation and 2-line Form ------------------------------------
In the 2-line form, the elements and their final positions are shown as a matrix with 2 rows:
[0 1 2 ... n-1] [p(0) p(1) p(2) ... p(n-1)]
Since the first line is always ``range(n)``, where n is the size of p, it is sufficient to represent the permutation by the second line, referred to as the "array form" of the permutation. This is entered in brackets as the argument to the Permutation class:
>>> p = Permutation([0, 2, 1]); p Permutation([0, 2, 1])
Given i in range(p.size), the permutation maps i to i^p
>>> [i^p for i in range(p.size)] [0, 2, 1]
The composite of two permutations p*q means first apply p, then q, so i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules:
>>> q = Permutation([2, 1, 0]) >>> [i^p^q for i in range(3)] [2, 0, 1] >>> [i^(p*q) for i in range(3)] [2, 0, 1]
One can use also the notation p(i) = i^p, but then the composition rule is (p*q)(i) = q(p(i)), not p(q(i)):
>>> [(p*q)(i) for i in range(p.size)] [2, 0, 1] >>> [q(p(i)) for i in range(p.size)] [2, 0, 1] >>> [p(q(i)) for i in range(p.size)] [1, 2, 0]
Disjoint Cycle Notation -----------------------
In disjoint cycle notation, only the elements that have shifted are indicated.
For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2). This can be understood from the 2 line format of the given permutation. In the 2-line form, [0 1 2 3] [1 3 2 0]
The element in the 0th position is 1, so 0 -> 1. The element in the 1st position is three, so 1 -> 3. And the element in the third position is again 0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented as 2 cycles: (0, 1, 3)(2). In common notation, singular cycles are not explicitly written as they can be inferred implicitly.
Only the relative ordering of elements in a cycle matter:
>>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2) True
The disjoint cycle notation is convenient when representing permutations that have several cycles in them:
>>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]]) True
It also provides some economy in entry when computing products of permutations that are written in disjoint cycle notation:
>>> Permutation(1, 2)(1, 3)(2, 3) Permutation([0, 3, 2, 1]) >>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]]) True
Caution: when the cycles have common elements between them then the order in which the permutations are applied matters. This module applies the permutations from *left to right*.
>>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)]) True >>> Permutation(1, 2)(2, 3).list() [0, 3, 1, 2]
In the above case, (1,2) is computed before (2,3). As 0 -> 0, 0 -> 0, element in position 0 is 0. As 1 -> 2, 2 -> 3, element in position 1 is 3. As 2 -> 1, 1 -> 1, element in position 2 is 1. As 3 -> 3, 3 -> 2, element in position 3 is 2.
If the first and second elements had been swapped first, followed by the swapping of the second and third, the result would have been [0, 2, 3, 1]. If, you want to apply the cycles in the conventional right to left order, call the function with arguments in reverse order as demonstrated below:
>>> Permutation([(1, 2), (2, 3)][::-1]).list() [0, 2, 3, 1]
Entering a singleton in a permutation is a way to indicate the size of the permutation. The ``size`` keyword can also be used.
Array-form entry:
>>> Permutation([[1, 2], [9]]) Permutation([0, 2, 1], size=10) >>> Permutation([[1, 2]], size=10) Permutation([0, 2, 1], size=10)
Cyclic-form entry:
>>> Permutation(1, 2, size=10) Permutation([0, 2, 1], size=10) >>> Permutation(9)(1, 2) Permutation([0, 2, 1], size=10)
Caution: no singleton containing an element larger than the largest in any previous cycle can be entered. This is an important difference in how Permutation and Cycle handle the ``__call__`` syntax. A singleton argument at the start of a Permutation performs instantiation of the Permutation and is permitted:
>>> Permutation(5) Permutation([], size=6)
A singleton entered after instantiation is a call to the permutation -- a function call -- and if the argument is out of range it will trigger an error. For this reason, it is better to start the cycle with the singleton:
The following fails because there is no element 3:
>>> Permutation(1, 2)(3) Traceback (most recent call last): ... IndexError: list index out of range
This is ok: only the call to an out of range singleton is prohibited; otherwise the permutation autosizes:
>>> Permutation(3)(1, 2) Permutation([0, 2, 1, 3]) >>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2) True
Equality testing ----------------
The array forms must be the same in order for permutations to be equal:
>>> Permutation([1, 0, 2, 3]) == Permutation([1, 0]) False
Identity Permutation --------------------
The identity permutation is a permutation in which no element is out of place. It can be entered in a variety of ways. All the following create an identity permutation of size 4:
>>> I = Permutation([0, 1, 2, 3]) >>> all(p == I for p in [ ... Permutation(3), ... Permutation(range(4)), ... Permutation([], size=4), ... Permutation(size=4)]) True
Watch out for entering the range *inside* a set of brackets (which is cycle notation):
>>> I == Permutation([range(4)]) False
Permutation Printing ====================
There are a few things to note about how Permutations are printed.
.. deprecated:: 1.6
Configuring Permutation printing by setting ``Permutation.print_cyclic`` is deprecated. Users should use the ``perm_cyclic`` flag to the printers, as described below.
1) If you prefer one form (array or cycle) over another, you can set ``init_printing`` with the ``perm_cyclic`` flag.
>>> from sympy import init_printing >>> p = Permutation(1, 2)(4, 5)(3, 4) >>> p Permutation([0, 2, 1, 4, 5, 3])
>>> init_printing(perm_cyclic=True, pretty_print=False) >>> p (1 2)(3 4 5)
2) Regardless of the setting, a list of elements in the array for cyclic form can be obtained and either of those can be copied and supplied as the argument to Permutation:
>>> p.array_form [0, 2, 1, 4, 5, 3] >>> p.cyclic_form [[1, 2], [3, 4, 5]] >>> Permutation(_) == p True
3) Printing is economical in that as little as possible is printed while retaining all information about the size of the permutation:
>>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation([1, 0, 2, 3]) Permutation([1, 0, 2, 3]) >>> Permutation([1, 0, 2, 3], size=20) Permutation([1, 0], size=20) >>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20) Permutation([1, 0, 2, 4, 3], size=20)
>>> p = Permutation([1, 0, 2, 3]) >>> init_printing(perm_cyclic=True, pretty_print=False) >>> p (3)(0 1) >>> init_printing(perm_cyclic=False, pretty_print=False)
The 2 was not printed but it is still there as can be seen with the array_form and size methods:
>>> p.array_form [1, 0, 2, 3] >>> p.size 4
Short introduction to other methods ===================================
The permutation can act as a bijective function, telling what element is located at a given position
>>> q = Permutation([5, 2, 3, 4, 1, 0]) >>> q.array_form[1] # the hard way 2 >>> q(1) # the easy way 2 >>> {i: q(i) for i in range(q.size)} # showing the bijection {0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0}
The full cyclic form (including singletons) can be obtained:
>>> p.full_cyclic_form [[0, 1], [2], [3]]
Any permutation can be factored into transpositions of pairs of elements:
>>> Permutation([[1, 2], [3, 4, 5]]).transpositions() [(1, 2), (3, 5), (3, 4)] >>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form [[1, 2], [3, 4, 5]]
The number of permutations on a set of n elements is given by n! and is called the cardinality.
>>> p.size 4 >>> p.cardinality 24
A given permutation has a rank among all the possible permutations of the same elements, but what that rank is depends on how the permutations are enumerated. (There are a number of different methods of doing so.) The lexicographic rank is given by the rank method and this rank is used to increment a permutation with addition/subtraction:
>>> p.rank() 6 >>> p + 1 Permutation([1, 0, 3, 2]) >>> p.next_lex() Permutation([1, 0, 3, 2]) >>> _.rank() 7 >>> p.unrank_lex(p.size, rank=7) Permutation([1, 0, 3, 2])
The product of two permutations p and q is defined as their composition as functions, (p*q)(i) = q(p(i)) [6]_.
>>> p = Permutation([1, 0, 2, 3]) >>> q = Permutation([2, 3, 1, 0]) >>> list(q*p) [2, 3, 0, 1] >>> list(p*q) [3, 2, 1, 0] >>> [q(p(i)) for i in range(p.size)] [3, 2, 1, 0]
The permutation can be 'applied' to any list-like object, not only Permutations:
>>> p(['zero', 'one', 'four', 'two']) ['one', 'zero', 'four', 'two'] >>> p('zo42') ['o', 'z', '4', '2']
If you have a list of arbitrary elements, the corresponding permutation can be found with the from_sequence method:
>>> Permutation.from_sequence('SymPy') Permutation([1, 3, 2, 0, 4])
Checking if a Permutation is contained in a Group =================================================
Generally if you have a group of permutations G on n symbols, and you're checking if a permutation on less than n symbols is part of that group, the check will fail.
Here is an example for n=5 and we check if the cycle (1,2,3) is in G:
>>> from sympy import init_printing >>> init_printing(perm_cyclic=True, pretty_print=False) >>> from sympy.combinatorics import Cycle, Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5)) >>> p1 = Permutation(Cycle(2, 5, 3)) >>> p2 = Permutation(Cycle(1, 2, 3)) >>> a1 = Permutation(Cycle(1, 2, 3).list(6)) >>> a2 = Permutation(Cycle(1, 2, 3)(5)) >>> a3 = Permutation(Cycle(1, 2, 3),size=6) >>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p) ((2 5 3), True) ((1 2 3), False) ((5)(1 2 3), True) ((5)(1 2 3), True) ((5)(1 2 3), True)
The check for p2 above will fail.
Checking if p1 is in G works because SymPy knows G is a group on 5 symbols, and p1 is also on 5 symbols (its largest element is 5).
For ``a1``, the ``.list(6)`` call will extend the permutation to 5 symbols, so the test will work as well. In the case of ``a2`` the permutation is being extended to 5 symbols by using a singleton, and in the case of ``a3`` it's extended through the constructor argument ``size=6``.
There is another way to do this, which is to tell the ``contains`` method that the number of symbols the group is on does not need to match perfectly the number of symbols for the permutation:
>>> G.contains(p2,strict=False) True
This can be via the ``strict`` argument to the ``contains`` method, and SymPy will try to extend the permutation on its own and then perform the containment check.
See Also ========
Cycle
References ==========
.. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics Combinatorics and Graph Theory with Mathematica. Reading, MA: Addison-Wesley, pp. 3-16, 1990.
.. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011.
.. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001), 281-284. DOI=10.1016/S0020-0190(01)00141-7
.. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms' CRC Press, 1999
.. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O. Concrete Mathematics: A Foundation for Computer Science, 2nd ed. Reading, MA: Addison-Wesley, 1994.
.. [6] https://en.wikipedia.org/w/index.php?oldid=499948155#Product_and_inverse
.. [7] https://en.wikipedia.org/wiki/Lehmer_code
"""
is_Permutation = True
_array_form = None _cyclic_form = None _cycle_structure = None _size = None _rank = None
def __new__(cls, *args, size=None, **kwargs): """ Constructor for the Permutation object from a list or a list of lists in which all elements of the permutation may appear only once.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False)
Permutations entered in array-form are left unaltered:
>>> Permutation([0, 2, 1]) Permutation([0, 2, 1])
Permutations entered in cyclic form are converted to array form; singletons need not be entered, but can be entered to indicate the largest element:
>>> Permutation([[4, 5, 6], [0, 1]]) Permutation([1, 0, 2, 3, 5, 6, 4]) >>> Permutation([[4, 5, 6], [0, 1], [19]]) Permutation([1, 0, 2, 3, 5, 6, 4], size=20)
All manipulation of permutations assumes that the smallest element is 0 (in keeping with 0-based indexing in Python) so if the 0 is missing when entering a permutation in array form, an error will be raised:
>>> Permutation([2, 1]) Traceback (most recent call last): ... ValueError: Integers 0 through 2 must be present.
If a permutation is entered in cyclic form, it can be entered without singletons and the ``size`` specified so those values can be filled in, otherwise the array form will only extend to the maximum value in the cycles:
>>> Permutation([[1, 4], [3, 5, 2]], size=10) Permutation([0, 4, 3, 5, 1, 2], size=10) >>> _.array_form [0, 4, 3, 5, 1, 2, 6, 7, 8, 9] """ if size is not None: size = int(size)
#a) () #b) (1) = identity #c) (1, 2) = cycle #d) ([1, 2, 3]) = array form #e) ([[1, 2]]) = cyclic form #f) (Cycle) = conversion to permutation #g) (Permutation) = adjust size or return copy ok = True if not args: # a return cls._af_new(list(range(size or 0))) elif len(args) > 1: # c return cls._af_new(Cycle(*args).list(size)) if len(args) == 1: a = args[0] if isinstance(a, cls): # g if size is None or size == a.size: return a return cls(a.array_form, size=size) if isinstance(a, Cycle): # f return cls._af_new(a.list(size)) if not is_sequence(a): # b if size is not None and a + 1 > size: raise ValueError('size is too small when max is %s' % a) return cls._af_new(list(range(a + 1))) if has_variety(is_sequence(ai) for ai in a): ok = False else: ok = False if not ok: raise ValueError("Permutation argument must be a list of ints, " "a list of lists, Permutation or Cycle.")
# safe to assume args are valid; this also makes a copy # of the args args = list(args[0])
is_cycle = args and is_sequence(args[0]) if is_cycle: # e args = [[int(i) for i in c] for c in args] else: # d args = [int(i) for i in args]
# if there are n elements present, 0, 1, ..., n-1 should be present # unless a cycle notation has been provided. A 0 will be added # for convenience in case one wants to enter permutations where # counting starts from 1.
temp = flatten(args) if has_dups(temp) and not is_cycle: raise ValueError('there were repeated elements.') temp = set(temp)
if not is_cycle: if temp != set(range(len(temp))): raise ValueError('Integers 0 through %s must be present.' % max(temp)) if size is not None and temp and max(temp) + 1 > size: raise ValueError('max element should not exceed %s' % (size - 1))
if is_cycle: # it's not necessarily canonical so we won't store # it -- use the array form instead c = Cycle() for ci in args: c = c(*ci) aform = c.list() else: aform = list(args) if size and size > len(aform): # don't allow for truncation of permutation which # might split a cycle and lead to an invalid aform # but do allow the permutation size to be increased aform.extend(list(range(len(aform), size)))
return cls._af_new(aform)
@classmethod def _af_new(cls, perm): """A method to produce a Permutation object from a list; the list is bound to the _array_form attribute, so it must not be modified; this method is meant for internal use only; the list ``a`` is supposed to be generated as a temporary value in a method, so p = Perm._af_new(a) is the only object to hold a reference to ``a``::
Examples ========
>>> from sympy.combinatorics.permutations import Perm >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> a = [2, 1, 3, 0] >>> p = Perm._af_new(a) >>> p Permutation([2, 1, 3, 0])
""" p = super().__new__(cls) p._array_form = perm p._size = len(perm) return p
def copy(self): return self.__class__(self.array_form)
def __getnewargs__(self): return (self.array_form,)
def _hashable_content(self): # the array_form (a list) is the Permutation arg, so we need to # return a tuple, instead return tuple(self.array_form)
@property def array_form(self): """ Return a copy of the attribute _array_form Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([[2, 0], [3, 1]]) >>> p.array_form [2, 3, 0, 1] >>> Permutation([[2, 0, 3, 1]]).array_form [3, 2, 0, 1] >>> Permutation([2, 0, 3, 1]).array_form [2, 0, 3, 1] >>> Permutation([[1, 2], [4, 5]]).array_form [0, 2, 1, 3, 5, 4] """ return self._array_form[:]
def list(self, size=None): """Return the permutation as an explicit list, possibly trimming unmoved elements if size is less than the maximum element in the permutation; if this is desired, setting ``size=-1`` will guarantee such trimming.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation(2, 3)(4, 5) >>> p.list() [0, 1, 3, 2, 5, 4] >>> p.list(10) [0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
Passing a length too small will trim trailing, unchanged elements in the permutation:
>>> Permutation(2, 4)(1, 2, 4).list(-1) [0, 2, 1] >>> Permutation(3).list(-1) [] """ if not self and size is None: raise ValueError('must give size for empty Cycle') rv = self.array_form if size is not None: if size > self.size: rv.extend(list(range(self.size, size))) else: # find first value from rhs where rv[i] != i i = self.size - 1 while rv: if rv[-1] != i: break rv.pop() i -= 1 return rv
@property def cyclic_form(self): """ This is used to convert to the cyclic notation from the canonical notation. Singletons are omitted.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 3, 1, 2]) >>> p.cyclic_form [[1, 3, 2]] >>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form [[0, 1], [3, 4]]
See Also ========
array_form, full_cyclic_form """ if self._cyclic_form is not None: return list(self._cyclic_form) array_form = self.array_form unchecked = [True] * len(array_form) cyclic_form = [] for i in range(len(array_form)): if unchecked[i]: cycle = [] cycle.append(i) unchecked[i] = False j = i while unchecked[array_form[j]]: j = array_form[j] cycle.append(j) unchecked[j] = False if len(cycle) > 1: cyclic_form.append(cycle) assert cycle == list(minlex(cycle)) cyclic_form.sort() self._cyclic_form = cyclic_form[:] return cyclic_form
@property def full_cyclic_form(self): """Return permutation in cyclic form including singletons.
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation([0, 2, 1]).full_cyclic_form [[0], [1, 2]] """ need = set(range(self.size)) - set(flatten(self.cyclic_form)) rv = self.cyclic_form + [[i] for i in need] rv.sort() return rv
@property def size(self): """ Returns the number of elements in the permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation([[3, 2], [0, 1]]).size 4
See Also ========
cardinality, length, order, rank """ return self._size
def support(self): """Return the elements in permutation, P, for which P[i] != i.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([[3, 2], [0, 1], [4]]) >>> p.array_form [1, 0, 3, 2, 4] >>> p.support() [0, 1, 2, 3] """ a = self.array_form return [i for i, e in enumerate(a) if a[i] != i]
def __add__(self, other): """Return permutation that is other higher in rank than self.
The rank is the lexicographical rank, with the identity permutation having rank of 0.
Examples ========
>>> from sympy.combinatorics import Permutation >>> I = Permutation([0, 1, 2, 3]) >>> a = Permutation([2, 1, 3, 0]) >>> I + a.rank() == a True
See Also ========
__sub__, inversion_vector
""" rank = (self.rank() + other) % self.cardinality rv = self.unrank_lex(self.size, rank) rv._rank = rank return rv
def __sub__(self, other): """Return the permutation that is other lower in rank than self.
See Also ========
__add__ """ return self.__add__(-other)
@staticmethod def rmul(*args): """ Return product of Permutations [a, b, c, ...] as the Permutation whose ith value is a(b(c(i))).
a, b, c, ... can be Permutation objects or tuples.
Examples ========
>>> from sympy.combinatorics import Permutation
>>> a, b = [1, 0, 2], [0, 2, 1] >>> a = Permutation(a); b = Permutation(b) >>> list(Permutation.rmul(a, b)) [1, 2, 0] >>> [a(b(i)) for i in range(3)] [1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1]
Notes =====
All items in the sequence will be parsed by Permutation as necessary as long as the first item is a Permutation:
>>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b) True
The reverse order of arguments will raise a TypeError.
""" rv = args[0] for i in range(1, len(args)): rv = args[i]*rv return rv
@classmethod def rmul_with_af(cls, *args): """ same as rmul, but the elements of args are Permutation objects which have _array_form """ a = [x._array_form for x in args] rv = cls._af_new(_af_rmuln(*a)) return rv
def mul_inv(self, other): """ other*~self, self and other have _array_form """ a = _af_invert(self._array_form) b = other._array_form return self._af_new(_af_rmul(a, b))
def __rmul__(self, other): """This is needed to coerce other to Permutation in rmul.""" cls = type(self) return cls(other)*self
def __mul__(self, other): """ Return the product a*b as a Permutation; the ith value is b(a(i)).
Examples ========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> a, b = [1, 0, 2], [0, 2, 1] >>> a = Permutation(a); b = Permutation(b) >>> list(a*b) [2, 0, 1] >>> [b(a(i)) for i in range(3)] [2, 0, 1]
This handles operands in reverse order compared to _af_rmul and rmul:
>>> al = list(a); bl = list(b) >>> _af_rmul(al, bl) [1, 2, 0] >>> [al[bl[i]] for i in range(3)] [1, 2, 0]
It is acceptable for the arrays to have different lengths; the shorter one will be padded to match the longer one:
>>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> b*Permutation([1, 0]) Permutation([1, 2, 0]) >>> Permutation([1, 0])*b Permutation([2, 0, 1])
It is also acceptable to allow coercion to handle conversion of a single list to the left of a Permutation:
>>> [0, 1]*a # no change: 2-element identity Permutation([1, 0, 2]) >>> [[0, 1]]*a # exchange first two elements Permutation([0, 1, 2])
You cannot use more than 1 cycle notation in a product of cycles since coercion can only handle one argument to the left. To handle multiple cycles it is convenient to use Cycle instead of Permutation:
>>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP >>> from sympy.combinatorics.permutations import Cycle >>> Cycle(1, 2)(2, 3) (1 3 2)
""" from sympy.combinatorics.perm_groups import PermutationGroup, Coset if isinstance(other, PermutationGroup): return Coset(self, other, dir='-') a = self.array_form # __rmul__ makes sure the other is a Permutation b = other.array_form if not b: perm = a else: b.extend(list(range(len(b), len(a)))) perm = [b[i] for i in a] + b[len(a):] return self._af_new(perm)
def commutes_with(self, other): """ Checks if the elements are commuting.
Examples ========
>>> from sympy.combinatorics import Permutation >>> a = Permutation([1, 4, 3, 0, 2, 5]) >>> b = Permutation([0, 1, 2, 3, 4, 5]) >>> a.commutes_with(b) True >>> b = Permutation([2, 3, 5, 4, 1, 0]) >>> a.commutes_with(b) False """ a = self.array_form b = other.array_form return _af_commutes_with(a, b)
def __pow__(self, n): """ Routine for finding powers of a permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([2, 0, 3, 1]) >>> p.order() 4 >>> p**4 Permutation([0, 1, 2, 3]) """ if isinstance(n, Permutation): raise NotImplementedError( 'p**p is not defined; do you mean p^p (conjugate)?') n = int(n) return self._af_new(_af_pow(self.array_form, n))
def __rxor__(self, i): """Return self(i) when ``i`` is an int.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation(1, 2, 9) >>> 2^p == p(2) == 9 True """ if int_valued(i): return self(i) else: raise NotImplementedError( "i^p = p(i) when i is an integer, not %s." % i)
def __xor__(self, h): """Return the conjugate permutation ``~h*self*h` `.
Explanation ===========
If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and ``b = ~h*a*h`` and both have the same cycle structure.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation(1, 2, 9) >>> q = Permutation(6, 9, 8) >>> p*q != q*p True
Calculate and check properties of the conjugate:
>>> c = p^q >>> c == ~q*p*q and p == q*c*~q True
The expression q^p^r is equivalent to q^(p*r):
>>> r = Permutation(9)(4, 6, 8) >>> q^p^r == q^(p*r) True
If the term to the left of the conjugate operator, i, is an integer then this is interpreted as selecting the ith element from the permutation to the right:
>>> all(i^p == p(i) for i in range(p.size)) True
Note that the * operator as higher precedence than the ^ operator:
>>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4) True
Notes =====
In Python the precedence rule is p^q^r = (p^q)^r which differs in general from p^(q^r)
>>> q^p^r (9)(1 4 8) >>> q^(p^r) (9)(1 8 6)
For a given r and p, both of the following are conjugates of p: ~r*p*r and r*p*~r. But these are not necessarily the same:
>>> ~r*p*r == r*p*~r True
>>> p = Permutation(1, 2, 9)(5, 6) >>> ~r*p*r == r*p*~r False
The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to this method:
>>> p^~r == r*p*~r True """
if self.size != h.size: raise ValueError("The permutations must be of equal size.") a = [None]*self.size h = h._array_form p = self._array_form for i in range(self.size): a[h[i]] = h[p[i]] return self._af_new(a)
def transpositions(self): """ Return the permutation decomposed into a list of transpositions.
Explanation ===========
It is always possible to express a permutation as the product of transpositions, see [1]
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]]) >>> t = p.transpositions() >>> t [(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)] >>> print(''.join(str(c) for c in t)) (0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2) >>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p True
References ==========
.. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties
""" a = self.cyclic_form res = [] for x in a: nx = len(x) if nx == 2: res.append(tuple(x)) elif nx > 2: first = x[0] for y in x[nx - 1:0:-1]: res.append((first, y)) return res
@classmethod def from_sequence(self, i, key=None): """Return the permutation needed to obtain ``i`` from the sorted elements of ``i``. If custom sorting is desired, a key can be given.
Examples ========
>>> from sympy.combinatorics import Permutation
>>> Permutation.from_sequence('SymPy') (4)(0 1 3) >>> _(sorted("SymPy")) ['S', 'y', 'm', 'P', 'y'] >>> Permutation.from_sequence('SymPy', key=lambda x: x.lower()) (4)(0 2)(1 3) """ ic = list(zip(i, list(range(len(i))))) if key: ic.sort(key=lambda x: key(x[0])) else: ic.sort() return ~Permutation([i[1] for i in ic])
def __invert__(self): """ Return the inverse of the permutation.
A permutation multiplied by its inverse is the identity permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([[2, 0], [3, 1]]) >>> ~p Permutation([2, 3, 0, 1]) >>> _ == p**-1 True >>> p*~p == ~p*p == Permutation([0, 1, 2, 3]) True """ return self._af_new(_af_invert(self._array_form))
def __iter__(self): """Yield elements from array form.
Examples ========
>>> from sympy.combinatorics import Permutation >>> list(Permutation(range(3))) [0, 1, 2] """ yield from self.array_form
def __repr__(self): return srepr(self)
def __call__(self, *i): """ Allows applying a permutation instance as a bijective function.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([[2, 0], [3, 1]]) >>> p.array_form [2, 3, 0, 1] >>> [p(i) for i in range(4)] [2, 3, 0, 1]
If an array is given then the permutation selects the items from the array (i.e. the permutation is applied to the array):
>>> from sympy.abc import x >>> p([x, 1, 0, x**2]) [0, x**2, x, 1] """ # list indices can be Integer or int; leave this # as it is (don't test or convert it) because this # gets called a lot and should be fast if len(i) == 1: i = i[0] if not isinstance(i, Iterable): i = as_int(i) if i < 0 or i > self.size: raise TypeError( "{} should be an integer between 0 and {}" .format(i, self.size-1)) return self._array_form[i] # P([a, b, c]) if len(i) != self.size: raise TypeError( "{} should have the length {}.".format(i, self.size)) return [i[j] for j in self._array_form] # P(1, 2, 3) return self*Permutation(Cycle(*i), size=self.size)
def atoms(self): """ Returns all the elements of a permutation
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation([0, 1, 2, 3, 4, 5]).atoms() {0, 1, 2, 3, 4, 5} >>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms() {0, 1, 2, 3, 4, 5} """ return set(self.array_form)
def apply(self, i): r"""Apply the permutation to an expression.
Parameters ==========
i : Expr It should be an integer between $0$ and $n-1$ where $n$ is the size of the permutation.
If it is a symbol or a symbolic expression that can have integer values, an ``AppliedPermutation`` object will be returned which can represent an unevaluated function.
Notes =====
Any permutation can be defined as a bijective function $\sigma : \{ 0, 1, \dots, n-1 \} \rightarrow \{ 0, 1, \dots, n-1 \}$ where $n$ denotes the size of the permutation.
The definition may even be extended for any set with distinctive elements, such that the permutation can even be applied for real numbers or such, however, it is not implemented for now for computational reasons and the integrity with the group theory module.
This function is similar to the ``__call__`` magic, however, ``__call__`` magic already has some other applications like permuting an array or attaching new cycles, which would not always be mathematically consistent.
This also guarantees that the return type is a SymPy integer, which guarantees the safety to use assumptions. """ i = _sympify(i) if i.is_integer is False: raise NotImplementedError("{} should be an integer.".format(i))
n = self.size if (i < 0) == True or (i >= n) == True: raise NotImplementedError( "{} should be an integer between 0 and {}".format(i, n-1))
if i.is_Integer: return Integer(self._array_form[i]) return AppliedPermutation(self, i)
def next_lex(self): """ Returns the next permutation in lexicographical order. If self is the last permutation in lexicographical order it returns None. See [4] section 2.4.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([2, 3, 1, 0]) >>> p = Permutation([2, 3, 1, 0]); p.rank() 17 >>> p = p.next_lex(); p.rank() 18
See Also ========
rank, unrank_lex """ perm = self.array_form[:] n = len(perm) i = n - 2 while perm[i + 1] < perm[i]: i -= 1 if i == -1: return None else: j = n - 1 while perm[j] < perm[i]: j -= 1 perm[j], perm[i] = perm[i], perm[j] i += 1 j = n - 1 while i < j: perm[j], perm[i] = perm[i], perm[j] i += 1 j -= 1 return self._af_new(perm)
@classmethod def unrank_nonlex(self, n, r): """ This is a linear time unranking algorithm that does not respect lexicographic order [3].
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.unrank_nonlex(4, 5) Permutation([2, 0, 3, 1]) >>> Permutation.unrank_nonlex(4, -1) Permutation([0, 1, 2, 3])
See Also ========
next_nonlex, rank_nonlex """ def _unrank1(n, r, a): if n > 0: a[n - 1], a[r % n] = a[r % n], a[n - 1] _unrank1(n - 1, r//n, a)
id_perm = list(range(n)) n = int(n) r = r % ifac(n) _unrank1(n, r, id_perm) return self._af_new(id_perm)
def rank_nonlex(self, inv_perm=None): """ This is a linear time ranking algorithm that does not enforce lexicographic order [3].
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank_nonlex() 23
See Also ========
next_nonlex, unrank_nonlex """ def _rank1(n, perm, inv_perm): if n == 1: return 0 s = perm[n - 1] t = inv_perm[n - 1] perm[n - 1], perm[t] = perm[t], s inv_perm[n - 1], inv_perm[s] = inv_perm[s], t return s + n*_rank1(n - 1, perm, inv_perm)
if inv_perm is None: inv_perm = (~self).array_form if not inv_perm: return 0 perm = self.array_form[:] r = _rank1(len(perm), perm, inv_perm) return r
def next_nonlex(self): """ Returns the next permutation in nonlex order [3]. If self is the last permutation in this order it returns None.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex() 5 >>> p = p.next_nonlex(); p Permutation([3, 0, 1, 2]) >>> p.rank_nonlex() 6
See Also ========
rank_nonlex, unrank_nonlex """ r = self.rank_nonlex() if r == ifac(self.size) - 1: return None return self.unrank_nonlex(self.size, r + 1)
def rank(self): """ Returns the lexicographic rank of the permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank() 0 >>> p = Permutation([3, 2, 1, 0]) >>> p.rank() 23
See Also ========
next_lex, unrank_lex, cardinality, length, order, size """ if self._rank is not None: return self._rank rank = 0 rho = self.array_form[:] n = self.size - 1 size = n + 1 psize = int(ifac(n)) for j in range(size - 1): rank += rho[j]*psize for i in range(j + 1, size): if rho[i] > rho[j]: rho[i] -= 1 psize //= n n -= 1 self._rank = rank return rank
@property def cardinality(self): """ Returns the number of all possible permutations.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.cardinality 24
See Also ========
length, order, rank, size """ return int(ifac(self.size))
def parity(self): """ Computes the parity of a permutation.
Explanation ===========
The parity of a permutation reflects the parity of the number of inversions in the permutation, i.e., the number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.parity() 0 >>> p = Permutation([3, 2, 0, 1]) >>> p.parity() 1
See Also ========
_af_parity """ if self._cyclic_form is not None: return (self.size - self.cycles) % 2
return _af_parity(self.array_form)
@property def is_even(self): """ Checks if a permutation is even.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.is_even True >>> p = Permutation([3, 2, 1, 0]) >>> p.is_even True
See Also ========
is_odd """ return not self.is_odd
@property def is_odd(self): """ Checks if a permutation is odd.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.is_odd False >>> p = Permutation([3, 2, 0, 1]) >>> p.is_odd True
See Also ========
is_even """ return bool(self.parity() % 2)
@property def is_Singleton(self): """ Checks to see if the permutation contains only one number and is thus the only possible permutation of this set of numbers
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation([0]).is_Singleton True >>> Permutation([0, 1]).is_Singleton False
See Also ========
is_Empty """ return self.size == 1
@property def is_Empty(self): """ Checks to see if the permutation is a set with zero elements
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation([]).is_Empty True >>> Permutation([0]).is_Empty False
See Also ========
is_Singleton """ return self.size == 0
@property def is_identity(self): return self.is_Identity
@property def is_Identity(self): """ Returns True if the Permutation is an identity permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([]) >>> p.is_Identity True >>> p = Permutation([[0], [1], [2]]) >>> p.is_Identity True >>> p = Permutation([0, 1, 2]) >>> p.is_Identity True >>> p = Permutation([0, 2, 1]) >>> p.is_Identity False
See Also ========
order """ af = self.array_form return not af or all(i == af[i] for i in range(self.size))
def ascents(self): """ Returns the positions of ascents in a permutation, ie, the location where p[i] < p[i+1]
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([4, 0, 1, 3, 2]) >>> p.ascents() [1, 2]
See Also ========
descents, inversions, min, max """ a = self.array_form pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]] return pos
def descents(self): """ Returns the positions of descents in a permutation, ie, the location where p[i] > p[i+1]
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([4, 0, 1, 3, 2]) >>> p.descents() [0, 3]
See Also ========
ascents, inversions, min, max """ a = self.array_form pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]] return pos
def max(self) -> int: """ The maximum element moved by the permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([1, 0, 2, 3, 4]) >>> p.max() 1
See Also ========
min, descents, ascents, inversions """ a = self.array_form if not a: return 0 return max(_a for i, _a in enumerate(a) if _a != i)
def min(self) -> int: """ The minimum element moved by the permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 4, 3, 2]) >>> p.min() 2
See Also ========
max, descents, ascents, inversions """ a = self.array_form if not a: return 0 return min(_a for i, _a in enumerate(a) if _a != i)
def inversions(self): """ Computes the number of inversions of a permutation.
Explanation ===========
An inversion is where i > j but p[i] < p[j].
For small length of p, it iterates over all i and j values and calculates the number of inversions. For large length of p, it uses a variation of merge sort to calculate the number of inversions.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2, 3, 4, 5]) >>> p.inversions() 0 >>> Permutation([3, 2, 1, 0]).inversions() 6
See Also ========
descents, ascents, min, max
References ==========
.. [1] https://www.cp.eng.chula.ac.th/~prabhas//teaching/algo/algo2008/count-inv.htm
""" inversions = 0 a = self.array_form n = len(a) if n < 130: for i in range(n - 1): b = a[i] for c in a[i + 1:]: if b > c: inversions += 1 else: k = 1 right = 0 arr = a[:] temp = a[:] while k < n: i = 0 while i + k < n: right = i + k * 2 - 1 if right >= n: right = n - 1 inversions += _merge(arr, temp, i, i + k, right) i = i + k * 2 k = k * 2 return inversions
def commutator(self, x): """Return the commutator of ``self`` and ``x``: ``~x*~self*x*self``
If f and g are part of a group, G, then the commutator of f and g is the group identity iff f and g commute, i.e. fg == gf.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([0, 2, 3, 1]) >>> x = Permutation([2, 0, 3, 1]) >>> c = p.commutator(x); c Permutation([2, 1, 3, 0]) >>> c == ~x*~p*x*p True
>>> I = Permutation(3) >>> p = [I + i for i in range(6)] >>> for i in range(len(p)): ... for j in range(len(p)): ... c = p[i].commutator(p[j]) ... if p[i]*p[j] == p[j]*p[i]: ... assert c == I ... else: ... assert c != I ...
References ==========
.. [1] https://en.wikipedia.org/wiki/Commutator """
a = self.array_form b = x.array_form n = len(a) if len(b) != n: raise ValueError("The permutations must be of equal size.") inva = [None]*n for i in range(n): inva[a[i]] = i invb = [None]*n for i in range(n): invb[b[i]] = i return self._af_new([a[b[inva[i]]] for i in invb])
def signature(self): """ Gives the signature of the permutation needed to place the elements of the permutation in canonical order.
The signature is calculated as (-1)^<number of inversions>
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2]) >>> p.inversions() 0 >>> p.signature() 1 >>> q = Permutation([0,2,1]) >>> q.inversions() 1 >>> q.signature() -1
See Also ========
inversions """ if self.is_even: return 1 return -1
def order(self): """ Computes the order of a permutation.
When the permutation is raised to the power of its order it equals the identity permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([3, 1, 5, 2, 4, 0]) >>> p.order() 4 >>> (p**(p.order())) Permutation([], size=6)
See Also ========
identity, cardinality, length, rank, size """
return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1)
def length(self): """ Returns the number of integers moved by a permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation([0, 3, 2, 1]).length() 2 >>> Permutation([[0, 1], [2, 3]]).length() 4
See Also ========
min, max, support, cardinality, order, rank, size """
return len(self.support())
@property def cycle_structure(self): """Return the cycle structure of the permutation as a dictionary indicating the multiplicity of each cycle length.
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation(3).cycle_structure {1: 4} >>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure {2: 2, 3: 1} """ if self._cycle_structure: rv = self._cycle_structure else: rv = defaultdict(int) singletons = self.size for c in self.cyclic_form: rv[len(c)] += 1 singletons -= len(c) if singletons: rv[1] = singletons self._cycle_structure = rv return dict(rv) # make a copy
@property def cycles(self): """ Returns the number of cycles contained in the permutation (including singletons).
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation([0, 1, 2]).cycles 3 >>> Permutation([0, 1, 2]).full_cyclic_form [[0], [1], [2]] >>> Permutation(0, 1)(2, 3).cycles 2
See Also ======== sympy.functions.combinatorial.numbers.stirling """ return len(self.full_cyclic_form)
def index(self): """ Returns the index of a permutation.
The index of a permutation is the sum of all subscripts j such that p[j] is greater than p[j+1].
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([3, 0, 2, 1, 4]) >>> p.index() 2 """ a = self.array_form
return sum(j for j in range(len(a) - 1) if a[j] > a[j + 1])
def runs(self): """ Returns the runs of a permutation.
An ascending sequence in a permutation is called a run [5].
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8]) >>> p.runs() [[2, 5, 7], [3, 6], [0, 1, 4, 8]] >>> q = Permutation([1,3,2,0]) >>> q.runs() [[1, 3], [2], [0]] """ return runs(self.array_form)
def inversion_vector(self): """Return the inversion vector of the permutation.
The inversion vector consists of elements whose value indicates the number of elements in the permutation that are lesser than it and lie on its right hand side.
The inversion vector is the same as the Lehmer encoding of a permutation.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2]) >>> p.inversion_vector() [4, 7, 0, 5, 0, 2, 1, 1] >>> p = Permutation([3, 2, 1, 0]) >>> p.inversion_vector() [3, 2, 1]
The inversion vector increases lexicographically with the rank of the permutation, the -ith element cycling through 0..i.
>>> p = Permutation(2) >>> while p: ... print('%s %s %s' % (p, p.inversion_vector(), p.rank())) ... p = p.next_lex() (2) [0, 0] 0 (1 2) [0, 1] 1 (2)(0 1) [1, 0] 2 (0 1 2) [1, 1] 3 (0 2 1) [2, 0] 4 (0 2) [2, 1] 5
See Also ========
from_inversion_vector """ self_array_form = self.array_form n = len(self_array_form) inversion_vector = [0] * (n - 1)
for i in range(n - 1): val = 0 for j in range(i + 1, n): if self_array_form[j] < self_array_form[i]: val += 1 inversion_vector[i] = val return inversion_vector
def rank_trotterjohnson(self): """ Returns the Trotter Johnson rank, which we get from the minimal change algorithm. See [4] section 2.4.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 1, 2, 3]) >>> p.rank_trotterjohnson() 0 >>> p = Permutation([0, 2, 1, 3]) >>> p.rank_trotterjohnson() 7
See Also ========
unrank_trotterjohnson, next_trotterjohnson """ if self.array_form == [] or self.is_Identity: return 0 if self.array_form == [1, 0]: return 1 perm = self.array_form n = self.size rank = 0 for j in range(1, n): k = 1 i = 0 while perm[i] != j: if perm[i] < j: k += 1 i += 1 j1 = j + 1 if rank % 2 == 0: rank = j1*rank + j1 - k else: rank = j1*rank + k - 1 return rank
@classmethod def unrank_trotterjohnson(cls, size, rank): """ Trotter Johnson permutation unranking. See [4] section 2.4.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.unrank_trotterjohnson(5, 10) Permutation([0, 3, 1, 2, 4])
See Also ========
rank_trotterjohnson, next_trotterjohnson """ perm = [0]*size r2 = 0 n = ifac(size) pj = 1 for j in range(2, size + 1): pj *= j r1 = (rank * pj) // n k = r1 - j*r2 if r2 % 2 == 0: for i in range(j - 1, j - k - 1, -1): perm[i] = perm[i - 1] perm[j - k - 1] = j - 1 else: for i in range(j - 1, k, -1): perm[i] = perm[i - 1] perm[k] = j - 1 r2 = r1 return cls._af_new(perm)
def next_trotterjohnson(self): """ Returns the next permutation in Trotter-Johnson order. If self is the last permutation it returns None. See [4] section 2.4. If it is desired to generate all such permutations, they can be generated in order more quickly with the ``generate_bell`` function.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation([3, 0, 2, 1]) >>> p.rank_trotterjohnson() 4 >>> p = p.next_trotterjohnson(); p Permutation([0, 3, 2, 1]) >>> p.rank_trotterjohnson() 5
See Also ========
rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell """ pi = self.array_form[:] n = len(pi) st = 0 rho = pi[:] done = False m = n-1 while m > 0 and not done: d = rho.index(m) for i in range(d, m): rho[i] = rho[i + 1] par = _af_parity(rho[:m]) if par == 1: if d == m: m -= 1 else: pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d] done = True else: if d == 0: m -= 1 st += 1 else: pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d] done = True if m == 0: return None return self._af_new(pi)
def get_precedence_matrix(self): """ Gets the precedence matrix. This is used for computing the distance between two permutations.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> p = Permutation.josephus(3, 6, 1) >>> p Permutation([2, 5, 3, 1, 4, 0]) >>> p.get_precedence_matrix() Matrix([ [0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0], [1, 1, 0, 1, 1, 1], [1, 1, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0], [1, 1, 0, 1, 1, 0]])
See Also ========
get_precedence_distance, get_adjacency_matrix, get_adjacency_distance """ m = zeros(self.size) perm = self.array_form for i in range(m.rows): for j in range(i + 1, m.cols): m[perm[i], perm[j]] = 1 return m
def get_precedence_distance(self, other): """ Computes the precedence distance between two permutations.
Explanation ===========
Suppose p and p' represent n jobs. The precedence metric counts the number of times a job j is preceded by job i in both p and p'. This metric is commutative.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([2, 0, 4, 3, 1]) >>> q = Permutation([3, 1, 2, 4, 0]) >>> p.get_precedence_distance(q) 7 >>> q.get_precedence_distance(p) 7
See Also ========
get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance """ if self.size != other.size: raise ValueError("The permutations must be of equal size.") self_prec_mat = self.get_precedence_matrix() other_prec_mat = other.get_precedence_matrix() n_prec = 0 for i in range(self.size): for j in range(self.size): if i == j: continue if self_prec_mat[i, j] * other_prec_mat[i, j] == 1: n_prec += 1 d = self.size * (self.size - 1)//2 - n_prec return d
def get_adjacency_matrix(self): """ Computes the adjacency matrix of a permutation.
Explanation ===========
If job i is adjacent to job j in a permutation p then we set m[i, j] = 1 where m is the adjacency matrix of p.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation.josephus(3, 6, 1) >>> p.get_adjacency_matrix() Matrix([ [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0]]) >>> q = Permutation([0, 1, 2, 3]) >>> q.get_adjacency_matrix() Matrix([ [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]])
See Also ========
get_precedence_matrix, get_precedence_distance, get_adjacency_distance """ m = zeros(self.size) perm = self.array_form for i in range(self.size - 1): m[perm[i], perm[i + 1]] = 1 return m
def get_adjacency_distance(self, other): """ Computes the adjacency distance between two permutations.
Explanation ===========
This metric counts the number of times a pair i,j of jobs is adjacent in both p and p'. If n_adj is this quantity then the adjacency distance is n - n_adj - 1 [1]
[1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals of Operational Research, 86, pp 473-490. (1999)
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 3, 1, 2, 4]) >>> q = Permutation.josephus(4, 5, 2) >>> p.get_adjacency_distance(q) 3 >>> r = Permutation([0, 2, 1, 4, 3]) >>> p.get_adjacency_distance(r) 4
See Also ========
get_precedence_matrix, get_precedence_distance, get_adjacency_matrix """ if self.size != other.size: raise ValueError("The permutations must be of the same size.") self_adj_mat = self.get_adjacency_matrix() other_adj_mat = other.get_adjacency_matrix() n_adj = 0 for i in range(self.size): for j in range(self.size): if i == j: continue if self_adj_mat[i, j] * other_adj_mat[i, j] == 1: n_adj += 1 d = self.size - n_adj - 1 return d
def get_positional_distance(self, other): """ Computes the positional distance between two permutations.
Examples ========
>>> from sympy.combinatorics import Permutation >>> p = Permutation([0, 3, 1, 2, 4]) >>> q = Permutation.josephus(4, 5, 2) >>> r = Permutation([3, 1, 4, 0, 2]) >>> p.get_positional_distance(q) 12 >>> p.get_positional_distance(r) 12
See Also ========
get_precedence_distance, get_adjacency_distance """ a = self.array_form b = other.array_form if len(a) != len(b): raise ValueError("The permutations must be of the same size.") return sum(abs(a[i] - b[i]) for i in range(len(a)))
@classmethod def josephus(cls, m, n, s=1): """Return as a permutation the shuffling of range(n) using the Josephus scheme in which every m-th item is selected until all have been chosen. The returned permutation has elements listed by the order in which they were selected.
The parameter ``s`` stops the selection process when there are ``s`` items remaining and these are selected by continuing the selection, counting by 1 rather than by ``m``.
Consider selecting every 3rd item from 6 until only 2 remain::
choices chosen ======== ====== 012345 01 345 2 01 34 25 01 4 253 0 4 2531 0 25314 253140
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation.josephus(3, 6, 2).array_form [2, 5, 3, 1, 4, 0]
References ==========
.. [1] https://en.wikipedia.org/wiki/Flavius_Josephus .. [2] https://en.wikipedia.org/wiki/Josephus_problem .. [3] https://web.archive.org/web/20171008094331/http://www.wou.edu/~burtonl/josephus.html
""" from collections import deque m -= 1 Q = deque(list(range(n))) perm = [] while len(Q) > max(s, 1): for dp in range(m): Q.append(Q.popleft()) perm.append(Q.popleft()) perm.extend(list(Q)) return cls(perm)
@classmethod def from_inversion_vector(cls, inversion): """ Calculates the permutation from the inversion vector.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> Permutation.from_inversion_vector([3, 2, 1, 0, 0]) Permutation([3, 2, 1, 0, 4, 5])
""" size = len(inversion) N = list(range(size + 1)) perm = [] try: for k in range(size): val = N[inversion[k]] perm.append(val) N.remove(val) except IndexError: raise ValueError("The inversion vector is not valid.") perm.extend(N) return cls._af_new(perm)
@classmethod def random(cls, n): """ Generates a random permutation of length ``n``.
Uses the underlying Python pseudo-random number generator.
Examples ========
>>> from sympy.combinatorics import Permutation >>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1])) True
""" perm_array = list(range(n)) random.shuffle(perm_array) return cls._af_new(perm_array)
@classmethod def unrank_lex(cls, size, rank): """ Lexicographic permutation unranking.
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy import init_printing >>> init_printing(perm_cyclic=False, pretty_print=False) >>> a = Permutation.unrank_lex(5, 10) >>> a.rank() 10 >>> a Permutation([0, 2, 4, 1, 3])
See Also ========
rank, next_lex """ perm_array = [0] * size psize = 1 for i in range(size): new_psize = psize*(i + 1) d = (rank % new_psize) // psize rank -= d*psize perm_array[size - i - 1] = d for j in range(size - i, size): if perm_array[j] > d - 1: perm_array[j] += 1 psize = new_psize return cls._af_new(perm_array)
def resize(self, n): """Resize the permutation to the new size ``n``.
Parameters ==========
n : int The new size of the permutation.
Raises ======
ValueError If the permutation cannot be resized to the given size. This may only happen when resized to a smaller size than the original.
Examples ========
>>> from sympy.combinatorics import Permutation
Increasing the size of a permutation:
>>> p = Permutation(0, 1, 2) >>> p = p.resize(5) >>> p (4)(0 1 2)
Decreasing the size of the permutation:
>>> p = p.resize(4) >>> p (3)(0 1 2)
If resizing to the specific size breaks the cycles:
>>> p.resize(2) Traceback (most recent call last): ... ValueError: The permutation cannot be resized to 2 because the cycle (0, 1, 2) may break. """ aform = self.array_form l = len(aform) if n > l: aform += list(range(l, n)) return Permutation._af_new(aform)
elif n < l: cyclic_form = self.full_cyclic_form new_cyclic_form = [] for cycle in cyclic_form: cycle_min = min(cycle) cycle_max = max(cycle) if cycle_min <= n-1: if cycle_max > n-1: raise ValueError( "The permutation cannot be resized to {} " "because the cycle {} may break." .format(n, tuple(cycle)))
new_cyclic_form.append(cycle) return Permutation(new_cyclic_form)
return self
# XXX Deprecated flag print_cyclic = None
def _merge(arr, temp, left, mid, right): """ Merges two sorted arrays and calculates the inversion count.
Helper function for calculating inversions. This method is for internal use only. """ i = k = left j = mid inv_count = 0 while i < mid and j <= right: if arr[i] < arr[j]: temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 inv_count += (mid -i) while i < mid: temp[k] = arr[i] k += 1 i += 1 if j <= right: k += right - j + 1 j += right - j + 1 arr[left:k + 1] = temp[left:k + 1] else: arr[left:right + 1] = temp[left:right + 1] return inv_count
Perm = Permutation_af_new = Perm._af_new
class AppliedPermutation(Expr): """A permutation applied to a symbolic variable.
Parameters ==========
perm : Permutation x : Expr
Examples ========
>>> from sympy import Symbol >>> from sympy.combinatorics import Permutation
Creating a symbolic permutation function application:
>>> x = Symbol('x') >>> p = Permutation(0, 1, 2) >>> p.apply(x) AppliedPermutation((0 1 2), x) >>> _.subs(x, 1) 2 """ def __new__(cls, perm, x, evaluate=None): if evaluate is None: evaluate = global_parameters.evaluate
perm = _sympify(perm) x = _sympify(x)
if not isinstance(perm, Permutation): raise ValueError("{} must be a Permutation instance." .format(perm))
if evaluate: if x.is_Integer: return perm.apply(x)
obj = super().__new__(cls, perm, x) return obj
@dispatch(Permutation, Permutation)def _eval_is_eq(lhs, rhs): if lhs._size != rhs._size: return None return lhs._array_form == rhs._array_form12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019from sympy.combinatorics import Permutation as Permfrom sympy.combinatorics.perm_groups import PermutationGroupfrom sympy.core import Basic, Tuple, default_sort_keyfrom sympy.sets import FiniteSetfrom sympy.utilities.iterables import (minlex, unflatten, flatten)from sympy.utilities.misc import as_int
rmul = Perm.rmul
class Polyhedron(Basic): """ Represents the polyhedral symmetry group (PSG).
Explanation ===========
The PSG is one of the symmetry groups of the Platonic solids. There are three polyhedral groups: the tetrahedral group of order 12, the octahedral group of order 24, and the icosahedral group of order 60.
All doctests have been given in the docstring of the constructor of the object.
References ==========
.. [1] https://mathworld.wolfram.com/PolyhedralGroup.html
""" _edges = None
def __new__(cls, corners, faces=(), pgroup=()): """ The constructor of the Polyhedron group object.
Explanation ===========
It takes up to three parameters: the corners, faces, and allowed transformations.
The corners/vertices are entered as a list of arbitrary expressions that are used to identify each vertex.
The faces are entered as a list of tuples of indices; a tuple of indices identifies the vertices which define the face. They should be entered in a cw or ccw order; they will be standardized by reversal and rotation to be give the lowest lexical ordering. If no faces are given then no edges will be computed.
>>> from sympy.combinatorics.polyhedron import Polyhedron >>> Polyhedron(list('abc'), [(1, 2, 0)]).faces {(0, 1, 2)} >>> Polyhedron(list('abc'), [(1, 0, 2)]).faces {(0, 1, 2)}
The allowed transformations are entered as allowable permutations of the vertices for the polyhedron. Instance of Permutations (as with faces) should refer to the supplied vertices by index. These permutation are stored as a PermutationGroup.
Examples ========
>>> from sympy.combinatorics.permutations import Permutation >>> from sympy import init_printing >>> from sympy.abc import w, x, y, z >>> init_printing(pretty_print=False, perm_cyclic=False)
Here we construct the Polyhedron object for a tetrahedron.
>>> corners = [w, x, y, z] >>> faces = [(0, 1, 2), (0, 2, 3), (0, 3, 1), (1, 2, 3)]
Next, allowed transformations of the polyhedron must be given. This is given as permutations of vertices.
Although the vertices of a tetrahedron can be numbered in 24 (4!) different ways, there are only 12 different orientations for a physical tetrahedron. The following permutations, applied once or twice, will generate all 12 of the orientations. (The identity permutation, Permutation(range(4)), is not included since it does not change the orientation of the vertices.)
>>> pgroup = [Permutation([[0, 1, 2], [3]]), \ Permutation([[0, 1, 3], [2]]), \ Permutation([[0, 2, 3], [1]]), \ Permutation([[1, 2, 3], [0]]), \ Permutation([[0, 1], [2, 3]]), \ Permutation([[0, 2], [1, 3]]), \ Permutation([[0, 3], [1, 2]])]
The Polyhedron is now constructed and demonstrated:
>>> tetra = Polyhedron(corners, faces, pgroup) >>> tetra.size 4 >>> tetra.edges {(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)} >>> tetra.corners (w, x, y, z)
It can be rotated with an arbitrary permutation of vertices, e.g. the following permutation is not in the pgroup:
>>> tetra.rotate(Permutation([0, 1, 3, 2])) >>> tetra.corners (w, x, z, y)
An allowed permutation of the vertices can be constructed by repeatedly applying permutations from the pgroup to the vertices. Here is a demonstration that applying p and p**2 for every p in pgroup generates all the orientations of a tetrahedron and no others:
>>> all = ( (w, x, y, z), \ (x, y, w, z), \ (y, w, x, z), \ (w, z, x, y), \ (z, w, y, x), \ (w, y, z, x), \ (y, z, w, x), \ (x, z, y, w), \ (z, y, x, w), \ (y, x, z, w), \ (x, w, z, y), \ (z, x, w, y) )
>>> got = [] >>> for p in (pgroup + [p**2 for p in pgroup]): ... h = Polyhedron(corners) ... h.rotate(p) ... got.append(h.corners) ... >>> set(got) == set(all) True
The make_perm method of a PermutationGroup will randomly pick permutations, multiply them together, and return the permutation that can be applied to the polyhedron to give the orientation produced by those individual permutations.
Here, 3 permutations are used:
>>> tetra.pgroup.make_perm(3) # doctest: +SKIP Permutation([0, 3, 1, 2])
To select the permutations that should be used, supply a list of indices to the permutations in pgroup in the order they should be applied:
>>> use = [0, 0, 2] >>> p002 = tetra.pgroup.make_perm(3, use) >>> p002 Permutation([1, 0, 3, 2])
Apply them one at a time:
>>> tetra.reset() >>> for i in use: ... tetra.rotate(pgroup[i]) ... >>> tetra.vertices (x, w, z, y) >>> sequentially = tetra.vertices
Apply the composite permutation:
>>> tetra.reset() >>> tetra.rotate(p002) >>> tetra.corners (x, w, z, y) >>> tetra.corners in all and tetra.corners == sequentially True
Notes =====
Defining permutation groups ---------------------------
It is not necessary to enter any permutations, nor is necessary to enter a complete set of transformations. In fact, for a polyhedron, all configurations can be constructed from just two permutations. For example, the orientations of a tetrahedron can be generated from an axis passing through a vertex and face and another axis passing through a different vertex or from an axis passing through the midpoints of two edges opposite of each other.
For simplicity of presentation, consider a square -- not a cube -- with vertices 1, 2, 3, and 4:
1-----2 We could think of axes of rotation being: | | 1) through the face | | 2) from midpoint 1-2 to 3-4 or 1-3 to 2-4 3-----4 3) lines 1-4 or 2-3
To determine how to write the permutations, imagine 4 cameras, one at each corner, labeled A-D:
A B A B 1-----2 1-----3 vertex index: | | | | 1 0 | | | | 2 1 3-----4 2-----4 3 2 C D C D 4 3
original after rotation along 1-4
A diagonal and a face axis will be chosen for the "permutation group" from which any orientation can be constructed.
>>> pgroup = []
Imagine a clockwise rotation when viewing 1-4 from camera A. The new orientation is (in camera-order): 1, 3, 2, 4 so the permutation is given using the *indices* of the vertices as:
>>> pgroup.append(Permutation((0, 2, 1, 3)))
Now imagine rotating clockwise when looking down an axis entering the center of the square as viewed. The new camera-order would be 3, 1, 4, 2 so the permutation is (using indices):
>>> pgroup.append(Permutation((2, 0, 3, 1)))
The square can now be constructed: ** use real-world labels for the vertices, entering them in camera order ** for the faces we use zero-based indices of the vertices in *edge-order* as the face is traversed; neither the direction nor the starting point matter -- the faces are only used to define edges (if so desired).
>>> square = Polyhedron((1, 2, 3, 4), [(0, 1, 3, 2)], pgroup)
To rotate the square with a single permutation we can do:
>>> square.rotate(square.pgroup[0]) >>> square.corners (1, 3, 2, 4)
To use more than one permutation (or to use one permutation more than once) it is more convenient to use the make_perm method:
>>> p011 = square.pgroup.make_perm([0, 1, 1]) # diag flip + 2 rotations >>> square.reset() # return to initial orientation >>> square.rotate(p011) >>> square.corners (4, 2, 3, 1)
Thinking outside the box ------------------------
Although the Polyhedron object has a direct physical meaning, it actually has broader application. In the most general sense it is just a decorated PermutationGroup, allowing one to connect the permutations to something physical. For example, a Rubik's cube is not a proper polyhedron, but the Polyhedron class can be used to represent it in a way that helps to visualize the Rubik's cube.
>>> from sympy import flatten, unflatten, symbols >>> from sympy.combinatorics import RubikGroup >>> facelets = flatten([symbols(s+'1:5') for s in 'UFRBLD']) >>> def show(): ... pairs = unflatten(r2.corners, 2) ... print(pairs[::2]) ... print(pairs[1::2]) ... >>> r2 = Polyhedron(facelets, pgroup=RubikGroup(2)) >>> show() [(U1, U2), (F1, F2), (R1, R2), (B1, B2), (L1, L2), (D1, D2)] [(U3, U4), (F3, F4), (R3, R4), (B3, B4), (L3, L4), (D3, D4)] >>> r2.rotate(0) # cw rotation of F >>> show() [(U1, U2), (F3, F1), (U3, R2), (B1, B2), (L1, D1), (R3, R1)] [(L4, L2), (F4, F2), (U4, R4), (B3, B4), (L3, D2), (D3, D4)]
Predefined Polyhedra ====================
For convenience, the vertices and faces are defined for the following standard solids along with a permutation group for transformations. When the polyhedron is oriented as indicated below, the vertices in a given horizontal plane are numbered in ccw direction, starting from the vertex that will give the lowest indices in a given face. (In the net of the vertices, indices preceded by "-" indicate replication of the lhs index in the net.)
tetrahedron, tetrahedron_faces ------------------------------
4 vertices (vertex up) net:
0 0-0 1 2 3-1
4 faces:
(0, 1, 2) (0, 2, 3) (0, 3, 1) (1, 2, 3)
cube, cube_faces ----------------
8 vertices (face up) net:
0 1 2 3-0 4 5 6 7-4
6 faces:
(0, 1, 2, 3) (0, 1, 5, 4) (1, 2, 6, 5) (2, 3, 7, 6) (0, 3, 7, 4) (4, 5, 6, 7)
octahedron, octahedron_faces ----------------------------
6 vertices (vertex up) net:
0 0 0-0 1 2 3 4-1 5 5 5-5
8 faces:
(0, 1, 2) (0, 2, 3) (0, 3, 4) (0, 1, 4) (1, 2, 5) (2, 3, 5) (3, 4, 5) (1, 4, 5)
dodecahedron, dodecahedron_faces --------------------------------
20 vertices (vertex up) net:
0 1 2 3 4 -0 5 6 7 8 9 -5 14 10 11 12 13-14 15 16 17 18 19-15
12 faces:
(0, 1, 2, 3, 4) (0, 1, 6, 10, 5) (1, 2, 7, 11, 6) (2, 3, 8, 12, 7) (3, 4, 9, 13, 8) (0, 4, 9, 14, 5) (5, 10, 16, 15, 14) (6, 10, 16, 17, 11) (7, 11, 17, 18, 12) (8, 12, 18, 19, 13) (9, 13, 19, 15, 14)(15, 16, 17, 18, 19)
icosahedron, icosahedron_faces ------------------------------
12 vertices (face up) net:
0 0 0 0 -0 1 2 3 4 5 -1 6 7 8 9 10 -6 11 11 11 11 -11
20 faces:
(0, 1, 2) (0, 2, 3) (0, 3, 4) (0, 4, 5) (0, 1, 5) (1, 2, 6) (2, 3, 7) (3, 4, 8) (4, 5, 9) (1, 5, 10) (2, 6, 7) (3, 7, 8) (4, 8, 9) (5, 9, 10) (1, 6, 10) (6, 7, 11) (7, 8, 11) (8, 9, 11) (9, 10, 11) (6, 10, 11)
>>> from sympy.combinatorics.polyhedron import cube >>> cube.edges {(0, 1), (0, 3), (0, 4), (1, 2), (1, 5), (2, 3), (2, 6), (3, 7), (4, 5), (4, 7), (5, 6), (6, 7)}
If you want to use letters or other names for the corners you can still use the pre-calculated faces:
>>> corners = list('abcdefgh') >>> Polyhedron(corners, cube.faces).corners (a, b, c, d, e, f, g, h)
References ==========
.. [1] www.ocf.berkeley.edu/~wwu/articles/platonicsolids.pdf
""" faces = [minlex(f, directed=False, key=default_sort_key) for f in faces] corners, faces, pgroup = args = \ [Tuple(*a) for a in (corners, faces, pgroup)] obj = Basic.__new__(cls, *args) obj._corners = tuple(corners) # in order given obj._faces = FiniteSet(*faces) if pgroup and pgroup[0].size != len(corners): raise ValueError("Permutation size unequal to number of corners.") # use the identity permutation if none are given obj._pgroup = PermutationGroup( pgroup or [Perm(range(len(corners)))] ) return obj
@property def corners(self): """ Get the corners of the Polyhedron.
The method ``vertices`` is an alias for ``corners``.
Examples ========
>>> from sympy.combinatorics import Polyhedron >>> from sympy.abc import a, b, c, d >>> p = Polyhedron(list('abcd')) >>> p.corners == p.vertices == (a, b, c, d) True
See Also ========
array_form, cyclic_form """ return self._corners vertices = corners
@property def array_form(self): """Return the indices of the corners.
The indices are given relative to the original position of corners.
Examples ========
>>> from sympy.combinatorics.polyhedron import tetrahedron >>> tetrahedron = tetrahedron.copy() >>> tetrahedron.array_form [0, 1, 2, 3]
>>> tetrahedron.rotate(0) >>> tetrahedron.array_form [0, 2, 3, 1] >>> tetrahedron.pgroup[0].array_form [0, 2, 3, 1]
See Also ========
corners, cyclic_form """ corners = list(self.args[0]) return [corners.index(c) for c in self.corners]
@property def cyclic_form(self): """Return the indices of the corners in cyclic notation.
The indices are given relative to the original position of corners.
See Also ========
corners, array_form """ return Perm._af_new(self.array_form).cyclic_form
@property def size(self): """ Get the number of corners of the Polyhedron. """ return len(self._corners)
@property def faces(self): """ Get the faces of the Polyhedron. """ return self._faces
@property def pgroup(self): """ Get the permutations of the Polyhedron. """ return self._pgroup
@property def edges(self): """ Given the faces of the polyhedra we can get the edges.
Examples ========
>>> from sympy.combinatorics import Polyhedron >>> from sympy.abc import a, b, c >>> corners = (a, b, c) >>> faces = [(0, 1, 2)] >>> Polyhedron(corners, faces).edges {(0, 1), (0, 2), (1, 2)}
""" if self._edges is None: output = set() for face in self.faces: for i in range(len(face)): edge = tuple(sorted([face[i], face[i - 1]])) output.add(edge) self._edges = FiniteSet(*output) return self._edges
def rotate(self, perm): """ Apply a permutation to the polyhedron *in place*. The permutation may be given as a Permutation instance or an integer indicating which permutation from pgroup of the Polyhedron should be applied.
This is an operation that is analogous to rotation about an axis by a fixed increment.
Notes =====
When a Permutation is applied, no check is done to see if that is a valid permutation for the Polyhedron. For example, a cube could be given a permutation which effectively swaps only 2 vertices. A valid permutation (that rotates the object in a physical way) will be obtained if one only uses permutations from the ``pgroup`` of the Polyhedron. On the other hand, allowing arbitrary rotations (applications of permutations) gives a way to follow named elements rather than indices since Polyhedron allows vertices to be named while Permutation works only with indices.
Examples ========
>>> from sympy.combinatorics import Polyhedron, Permutation >>> from sympy.combinatorics.polyhedron import cube >>> cube = cube.copy() >>> cube.corners (0, 1, 2, 3, 4, 5, 6, 7) >>> cube.rotate(0) >>> cube.corners (1, 2, 3, 0, 5, 6, 7, 4)
A non-physical "rotation" that is not prohibited by this method:
>>> cube.reset() >>> cube.rotate(Permutation([[1, 2]], size=8)) >>> cube.corners (0, 2, 1, 3, 4, 5, 6, 7)
Polyhedron can be used to follow elements of set that are identified by letters instead of integers:
>>> shadow = h5 = Polyhedron(list('abcde')) >>> p = Permutation([3, 0, 1, 2, 4]) >>> h5.rotate(p) >>> h5.corners (d, a, b, c, e) >>> _ == shadow.corners True >>> copy = h5.copy() >>> h5.rotate(p) >>> h5.corners == copy.corners False """ if not isinstance(perm, Perm): perm = self.pgroup[perm] # and we know it's valid else: if perm.size != self.size: raise ValueError('Polyhedron and Permutation sizes differ.') a = perm.array_form corners = [self.corners[a[i]] for i in range(len(self.corners))] self._corners = tuple(corners)
def reset(self): """Return corners to their original positions.
Examples ========
>>> from sympy.combinatorics.polyhedron import tetrahedron as T >>> T = T.copy() >>> T.corners (0, 1, 2, 3) >>> T.rotate(0) >>> T.corners (0, 2, 3, 1) >>> T.reset() >>> T.corners (0, 1, 2, 3) """ self._corners = self.args[0]
def _pgroup_calcs(): """Return the permutation groups for each of the polyhedra and the face definitions: tetrahedron, cube, octahedron, dodecahedron, icosahedron, tetrahedron_faces, cube_faces, octahedron_faces, dodecahedron_faces, icosahedron_faces
Explanation ===========
(This author did not find and did not know of a better way to do it though there likely is such a way.)
Although only 2 permutations are needed for a polyhedron in order to generate all the possible orientations, a group of permutations is provided instead. A set of permutations is called a "group" if::
a*b = c (for any pair of permutations in the group, a and b, their product, c, is in the group)
a*(b*c) = (a*b)*c (for any 3 permutations in the group associativity holds)
there is an identity permutation, I, such that I*a = a*I for all elements in the group
a*b = I (the inverse of each permutation is also in the group)
None of the polyhedron groups defined follow these definitions of a group. Instead, they are selected to contain those permutations whose powers alone will construct all orientations of the polyhedron, i.e. for permutations ``a``, ``b``, etc... in the group, ``a, a**2, ..., a**o_a``, ``b, b**2, ..., b**o_b``, etc... (where ``o_i`` is the order of permutation ``i``) generate all permutations of the polyhedron instead of mixed products like ``a*b``, ``a*b**2``, etc....
Note that for a polyhedron with n vertices, the valid permutations of the vertices exclude those that do not maintain its faces. e.g. the permutation BCDE of a square's four corners, ABCD, is a valid permutation while CBDE is not (because this would twist the square).
Examples ========
The is_group checks for: closure, the presence of the Identity permutation, and the presence of the inverse for each of the elements in the group. This confirms that none of the polyhedra are true groups:
>>> from sympy.combinatorics.polyhedron import ( ... tetrahedron, cube, octahedron, dodecahedron, icosahedron) ... >>> polyhedra = (tetrahedron, cube, octahedron, dodecahedron, icosahedron) >>> [h.pgroup.is_group for h in polyhedra] ... [True, True, True, True, True]
Although tests in polyhedron's test suite check that powers of the permutations in the groups generate all permutations of the vertices of the polyhedron, here we also demonstrate the powers of the given permutations create a complete group for the tetrahedron:
>>> from sympy.combinatorics import Permutation, PermutationGroup >>> for h in polyhedra[:1]: ... G = h.pgroup ... perms = set() ... for g in G: ... for e in range(g.order()): ... p = tuple((g**e).array_form) ... perms.add(p) ... ... perms = [Permutation(p) for p in perms] ... assert PermutationGroup(perms).is_group
In addition to doing the above, the tests in the suite confirm that the faces are all present after the application of each permutation.
References ==========
.. [1] https://dogschool.tripod.com/trianglegroup.html
""" def _pgroup_of_double(polyh, ordered_faces, pgroup): n = len(ordered_faces[0]) # the vertices of the double which sits inside a give polyhedron # can be found by tracking the faces of the outer polyhedron. # A map between face and the vertex of the double is made so that # after rotation the position of the vertices can be located fmap = dict(zip(ordered_faces, range(len(ordered_faces)))) flat_faces = flatten(ordered_faces) new_pgroup = [] for p in pgroup: h = polyh.copy() h.rotate(p) c = h.corners # reorder corners in the order they should appear when # enumerating the faces reorder = unflatten([c[j] for j in flat_faces], n) # make them canonical reorder = [tuple(map(as_int, minlex(f, directed=False))) for f in reorder] # map face to vertex: the resulting list of vertices are the # permutation that we seek for the double new_pgroup.append(Perm([fmap[f] for f in reorder])) return new_pgroup
tetrahedron_faces = [ (0, 1, 2), (0, 2, 3), (0, 3, 1), # upper 3 (1, 2, 3), # bottom ]
# cw from top # _t_pgroup = [ Perm([[1, 2, 3], [0]]), # cw from top Perm([[0, 1, 2], [3]]), # cw from front face Perm([[0, 3, 2], [1]]), # cw from back right face Perm([[0, 3, 1], [2]]), # cw from back left face Perm([[0, 1], [2, 3]]), # through front left edge Perm([[0, 2], [1, 3]]), # through front right edge Perm([[0, 3], [1, 2]]), # through back edge ]
tetrahedron = Polyhedron( range(4), tetrahedron_faces, _t_pgroup)
cube_faces = [ (0, 1, 2, 3), # upper (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (0, 3, 7, 4), # middle 4 (4, 5, 6, 7), # lower ]
# U, D, F, B, L, R = up, down, front, back, left, right _c_pgroup = [Perm(p) for p in [ [1, 2, 3, 0, 5, 6, 7, 4], # cw from top, U [4, 0, 3, 7, 5, 1, 2, 6], # cw from F face [4, 5, 1, 0, 7, 6, 2, 3], # cw from R face
[1, 0, 4, 5, 2, 3, 7, 6], # cw through UF edge [6, 2, 1, 5, 7, 3, 0, 4], # cw through UR edge [6, 7, 3, 2, 5, 4, 0, 1], # cw through UB edge [3, 7, 4, 0, 2, 6, 5, 1], # cw through UL edge [4, 7, 6, 5, 0, 3, 2, 1], # cw through FL edge [6, 5, 4, 7, 2, 1, 0, 3], # cw through FR edge
[0, 3, 7, 4, 1, 2, 6, 5], # cw through UFL vertex [5, 1, 0, 4, 6, 2, 3, 7], # cw through UFR vertex [5, 6, 2, 1, 4, 7, 3, 0], # cw through UBR vertex [7, 4, 0, 3, 6, 5, 1, 2], # cw through UBL ]]
cube = Polyhedron( range(8), cube_faces, _c_pgroup)
octahedron_faces = [ (0, 1, 2), (0, 2, 3), (0, 3, 4), (0, 1, 4), # top 4 (1, 2, 5), (2, 3, 5), (3, 4, 5), (1, 4, 5), # bottom 4 ]
octahedron = Polyhedron( range(6), octahedron_faces, _pgroup_of_double(cube, cube_faces, _c_pgroup))
dodecahedron_faces = [ (0, 1, 2, 3, 4), # top (0, 1, 6, 10, 5), (1, 2, 7, 11, 6), (2, 3, 8, 12, 7), # upper 5 (3, 4, 9, 13, 8), (0, 4, 9, 14, 5), (5, 10, 16, 15, 14), (6, 10, 16, 17, 11), (7, 11, 17, 18, 12), # lower 5 (8, 12, 18, 19, 13), (9, 13, 19, 15, 14), (15, 16, 17, 18, 19) # bottom ]
def _string_to_perm(s): rv = [Perm(range(20))] p = None for si in s: if si not in '01': count = int(si) - 1 else: count = 1 if si == '0': p = _f0 elif si == '1': p = _f1 rv.extend([p]*count) return Perm.rmul(*rv)
# top face cw _f0 = Perm([ 1, 2, 3, 4, 0, 6, 7, 8, 9, 5, 11, 12, 13, 14, 10, 16, 17, 18, 19, 15]) # front face cw _f1 = Perm([ 5, 0, 4, 9, 14, 10, 1, 3, 13, 15, 6, 2, 8, 19, 16, 17, 11, 7, 12, 18]) # the strings below, like 0104 are shorthand for F0*F1*F0**4 and are # the remaining 4 face rotations, 15 edge permutations, and the # 10 vertex rotations. _dodeca_pgroup = [_f0, _f1] + [_string_to_perm(s) for s in ''' 0104 140 014 0410 010 1403 03104 04103 102 120 1304 01303 021302 03130 0412041 041204103 04120410 041204104 041204102 10 01 1402 0140 04102 0412 1204 1302 0130 03120'''.strip().split()]
dodecahedron = Polyhedron( range(20), dodecahedron_faces, _dodeca_pgroup)
icosahedron_faces = [ (0, 1, 2), (0, 2, 3), (0, 3, 4), (0, 4, 5), (0, 1, 5), (1, 6, 7), (1, 2, 7), (2, 7, 8), (2, 3, 8), (3, 8, 9), (3, 4, 9), (4, 9, 10), (4, 5, 10), (5, 6, 10), (1, 5, 6), (6, 7, 11), (7, 8, 11), (8, 9, 11), (9, 10, 11), (6, 10, 11)]
icosahedron = Polyhedron( range(12), icosahedron_faces, _pgroup_of_double( dodecahedron, dodecahedron_faces, _dodeca_pgroup))
return (tetrahedron, cube, octahedron, dodecahedron, icosahedron, tetrahedron_faces, cube_faces, octahedron_faces, dodecahedron_faces, icosahedron_faces)
# -----------------------------------------------------------------------# Standard Polyhedron groups## These are generated using _pgroup_calcs() above. However to save# import time we encode them explicitly here.# -----------------------------------------------------------------------
tetrahedron = Polyhedron( Tuple(0, 1, 2, 3), Tuple( Tuple(0, 1, 2), Tuple(0, 2, 3), Tuple(0, 1, 3), Tuple(1, 2, 3)), Tuple( Perm(1, 2, 3), Perm(3)(0, 1, 2), Perm(0, 3, 2), Perm(0, 3, 1), Perm(0, 1)(2, 3), Perm(0, 2)(1, 3), Perm(0, 3)(1, 2) ))
cube = Polyhedron( Tuple(0, 1, 2, 3, 4, 5, 6, 7), Tuple( Tuple(0, 1, 2, 3), Tuple(0, 1, 5, 4), Tuple(1, 2, 6, 5), Tuple(2, 3, 7, 6), Tuple(0, 3, 7, 4), Tuple(4, 5, 6, 7)), Tuple( Perm(0, 1, 2, 3)(4, 5, 6, 7), Perm(0, 4, 5, 1)(2, 3, 7, 6), Perm(0, 4, 7, 3)(1, 5, 6, 2), Perm(0, 1)(2, 4)(3, 5)(6, 7), Perm(0, 6)(1, 2)(3, 5)(4, 7), Perm(0, 6)(1, 7)(2, 3)(4, 5), Perm(0, 3)(1, 7)(2, 4)(5, 6), Perm(0, 4)(1, 7)(2, 6)(3, 5), Perm(0, 6)(1, 5)(2, 4)(3, 7), Perm(1, 3, 4)(2, 7, 5), Perm(7)(0, 5, 2)(3, 4, 6), Perm(0, 5, 7)(1, 6, 3), Perm(0, 7, 2)(1, 4, 6)))
octahedron = Polyhedron( Tuple(0, 1, 2, 3, 4, 5), Tuple( Tuple(0, 1, 2), Tuple(0, 2, 3), Tuple(0, 3, 4), Tuple(0, 1, 4), Tuple(1, 2, 5), Tuple(2, 3, 5), Tuple(3, 4, 5), Tuple(1, 4, 5)), Tuple( Perm(5)(1, 2, 3, 4), Perm(0, 4, 5, 2), Perm(0, 1, 5, 3), Perm(0, 1)(2, 4)(3, 5), Perm(0, 2)(1, 3)(4, 5), Perm(0, 3)(1, 5)(2, 4), Perm(0, 4)(1, 3)(2, 5), Perm(0, 5)(1, 4)(2, 3), Perm(0, 5)(1, 2)(3, 4), Perm(0, 4, 1)(2, 3, 5), Perm(0, 1, 2)(3, 4, 5), Perm(0, 2, 3)(1, 5, 4), Perm(0, 4, 3)(1, 5, 2)))
dodecahedron = Polyhedron( Tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19), Tuple( Tuple(0, 1, 2, 3, 4), Tuple(0, 1, 6, 10, 5), Tuple(1, 2, 7, 11, 6), Tuple(2, 3, 8, 12, 7), Tuple(3, 4, 9, 13, 8), Tuple(0, 4, 9, 14, 5), Tuple(5, 10, 16, 15, 14), Tuple(6, 10, 16, 17, 11), Tuple(7, 11, 17, 18, 12), Tuple(8, 12, 18, 19, 13), Tuple(9, 13, 19, 15, 14), Tuple(15, 16, 17, 18, 19)), Tuple( Perm(0, 1, 2, 3, 4)(5, 6, 7, 8, 9)(10, 11, 12, 13, 14)(15, 16, 17, 18, 19), Perm(0, 5, 10, 6, 1)(2, 4, 14, 16, 11)(3, 9, 15, 17, 7)(8, 13, 19, 18, 12), Perm(0, 10, 17, 12, 3)(1, 6, 11, 7, 2)(4, 5, 16, 18, 8)(9, 14, 15, 19, 13), Perm(0, 6, 17, 19, 9)(1, 11, 18, 13, 4)(2, 7, 12, 8, 3)(5, 10, 16, 15, 14), Perm(0, 2, 12, 19, 14)(1, 7, 18, 15, 5)(3, 8, 13, 9, 4)(6, 11, 17, 16, 10), Perm(0, 4, 9, 14, 5)(1, 3, 13, 15, 10)(2, 8, 19, 16, 6)(7, 12, 18, 17, 11), Perm(0, 1)(2, 5)(3, 10)(4, 6)(7, 14)(8, 16)(9, 11)(12, 15)(13, 17)(18, 19), Perm(0, 7)(1, 2)(3, 6)(4, 11)(5, 12)(8, 10)(9, 17)(13, 16)(14, 18)(15, 19), Perm(0, 12)(1, 8)(2, 3)(4, 7)(5, 18)(6, 13)(9, 11)(10, 19)(14, 17)(15, 16), Perm(0, 8)(1, 13)(2, 9)(3, 4)(5, 12)(6, 19)(7, 14)(10, 18)(11, 15)(16, 17), Perm(0, 4)(1, 9)(2, 14)(3, 5)(6, 13)(7, 15)(8, 10)(11, 19)(12, 16)(17, 18), Perm(0, 5)(1, 14)(2, 15)(3, 16)(4, 10)(6, 9)(7, 19)(8, 17)(11, 13)(12, 18), Perm(0, 11)(1, 6)(2, 10)(3, 16)(4, 17)(5, 7)(8, 15)(9, 18)(12, 14)(13, 19), Perm(0, 18)(1, 12)(2, 7)(3, 11)(4, 17)(5, 19)(6, 8)(9, 16)(10, 13)(14, 15), Perm(0, 18)(1, 19)(2, 13)(3, 8)(4, 12)(5, 17)(6, 15)(7, 9)(10, 16)(11, 14), Perm(0, 13)(1, 19)(2, 15)(3, 14)(4, 9)(5, 8)(6, 18)(7, 16)(10, 12)(11, 17), Perm(0, 16)(1, 15)(2, 19)(3, 18)(4, 17)(5, 10)(6, 14)(7, 13)(8, 12)(9, 11), Perm(0, 18)(1, 17)(2, 16)(3, 15)(4, 19)(5, 12)(6, 11)(7, 10)(8, 14)(9, 13), Perm(0, 15)(1, 19)(2, 18)(3, 17)(4, 16)(5, 14)(6, 13)(7, 12)(8, 11)(9, 10), Perm(0, 17)(1, 16)(2, 15)(3, 19)(4, 18)(5, 11)(6, 10)(7, 14)(8, 13)(9, 12), Perm(0, 19)(1, 18)(2, 17)(3, 16)(4, 15)(5, 13)(6, 12)(7, 11)(8, 10)(9, 14), Perm(1, 4, 5)(2, 9, 10)(3, 14, 6)(7, 13, 16)(8, 15, 11)(12, 19, 17), Perm(19)(0, 6, 2)(3, 5, 11)(4, 10, 7)(8, 14, 17)(9, 16, 12)(13, 15, 18), Perm(0, 11, 8)(1, 7, 3)(4, 6, 12)(5, 17, 13)(9, 10, 18)(14, 16, 19), Perm(0, 7, 13)(1, 12, 9)(2, 8, 4)(5, 11, 19)(6, 18, 14)(10, 17, 15), Perm(0, 3, 9)(1, 8, 14)(2, 13, 5)(6, 12, 15)(7, 19, 10)(11, 18, 16), Perm(0, 14, 10)(1, 9, 16)(2, 13, 17)(3, 19, 11)(4, 15, 6)(7, 8, 18), Perm(0, 16, 7)(1, 10, 11)(2, 5, 17)(3, 14, 18)(4, 15, 12)(8, 9, 19), Perm(0, 16, 13)(1, 17, 8)(2, 11, 12)(3, 6, 18)(4, 10, 19)(5, 15, 9), Perm(0, 11, 15)(1, 17, 14)(2, 18, 9)(3, 12, 13)(4, 7, 19)(5, 6, 16), Perm(0, 8, 15)(1, 12, 16)(2, 18, 10)(3, 19, 5)(4, 13, 14)(6, 7, 17)))
icosahedron = Polyhedron( Tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), Tuple( Tuple(0, 1, 2), Tuple(0, 2, 3), Tuple(0, 3, 4), Tuple(0, 4, 5), Tuple(0, 1, 5), Tuple(1, 6, 7), Tuple(1, 2, 7), Tuple(2, 7, 8), Tuple(2, 3, 8), Tuple(3, 8, 9), Tuple(3, 4, 9), Tuple(4, 9, 10), Tuple(4, 5, 10), Tuple(5, 6, 10), Tuple(1, 5, 6), Tuple(6, 7, 11), Tuple(7, 8, 11), Tuple(8, 9, 11), Tuple(9, 10, 11), Tuple(6, 10, 11)), Tuple( Perm(11)(1, 2, 3, 4, 5)(6, 7, 8, 9, 10), Perm(0, 5, 6, 7, 2)(3, 4, 10, 11, 8), Perm(0, 1, 7, 8, 3)(4, 5, 6, 11, 9), Perm(0, 2, 8, 9, 4)(1, 7, 11, 10, 5), Perm(0, 3, 9, 10, 5)(1, 2, 8, 11, 6), Perm(0, 4, 10, 6, 1)(2, 3, 9, 11, 7), Perm(0, 1)(2, 5)(3, 6)(4, 7)(8, 10)(9, 11), Perm(0, 2)(1, 3)(4, 7)(5, 8)(6, 9)(10, 11), Perm(0, 3)(1, 9)(2, 4)(5, 8)(6, 11)(7, 10), Perm(0, 4)(1, 9)(2, 10)(3, 5)(6, 8)(7, 11), Perm(0, 5)(1, 4)(2, 10)(3, 6)(7, 9)(8, 11), Perm(0, 6)(1, 5)(2, 10)(3, 11)(4, 7)(8, 9), Perm(0, 7)(1, 2)(3, 6)(4, 11)(5, 8)(9, 10), Perm(0, 8)(1, 9)(2, 3)(4, 7)(5, 11)(6, 10), Perm(0, 9)(1, 11)(2, 10)(3, 4)(5, 8)(6, 7), Perm(0, 10)(1, 9)(2, 11)(3, 6)(4, 5)(7, 8), Perm(0, 11)(1, 6)(2, 10)(3, 9)(4, 8)(5, 7), Perm(0, 11)(1, 8)(2, 7)(3, 6)(4, 10)(5, 9), Perm(0, 11)(1, 10)(2, 9)(3, 8)(4, 7)(5, 6), Perm(0, 11)(1, 7)(2, 6)(3, 10)(4, 9)(5, 8), Perm(0, 11)(1, 9)(2, 8)(3, 7)(4, 6)(5, 10), Perm(0, 5, 1)(2, 4, 6)(3, 10, 7)(8, 9, 11), Perm(0, 1, 2)(3, 5, 7)(4, 6, 8)(9, 10, 11), Perm(0, 2, 3)(1, 8, 4)(5, 7, 9)(6, 11, 10), Perm(0, 3, 4)(1, 8, 10)(2, 9, 5)(6, 7, 11), Perm(0, 4, 5)(1, 3, 10)(2, 9, 6)(7, 8, 11), Perm(0, 10, 7)(1, 5, 6)(2, 4, 11)(3, 9, 8), Perm(0, 6, 8)(1, 7, 2)(3, 5, 11)(4, 10, 9), Perm(0, 7, 9)(1, 11, 4)(2, 8, 3)(5, 6, 10), Perm(0, 8, 10)(1, 7, 6)(2, 11, 5)(3, 9, 4), Perm(0, 9, 6)(1, 3, 11)(2, 8, 7)(4, 10, 5)))
tetrahedron_faces = [tuple(arg) for arg in tetrahedron.faces]
cube_faces = [tuple(arg) for arg in cube.faces]
octahedron_faces = [tuple(arg) for arg in octahedron.faces]
dodecahedron_faces = [tuple(arg) for arg in dodecahedron.faces]
icosahedron_faces = [tuple(arg) for arg in icosahedron.faces]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453from collections import dequefrom sympy.combinatorics.rewritingsystem_fsm import StateMachine
class RewritingSystem: ''' A class implementing rewriting systems for `FpGroup`s.
References ========== .. [1] Epstein, D., Holt, D. and Rees, S. (1991). The use of Knuth-Bendix methods to solve the word problem in automatic groups. Journal of Symbolic Computation, 12(4-5), pp.397-414.
.. [2] GAP's Manual on its KBMAG package https://www.gap-system.org/Manuals/pkg/kbmag-1.5.3/doc/manual.pdf
''' def __init__(self, group): self.group = group self.alphabet = group.generators self._is_confluent = None
# these values are taken from [2] self.maxeqns = 32767 # max rules self.tidyint = 100 # rules before tidying
# _max_exceeded is True if maxeqns is exceeded # at any point self._max_exceeded = False
# Reduction automaton self.reduction_automaton = None self._new_rules = {}
# dictionary of reductions self.rules = {} self.rules_cache = deque([], 50) self._init_rules()
# All the transition symbols in the automaton generators = list(self.alphabet) generators += [gen**-1 for gen in generators] # Create a finite state machine as an instance of the StateMachine object self.reduction_automaton = StateMachine('Reduction automaton for '+ repr(self.group), generators) self.construct_automaton()
def set_max(self, n): ''' Set the maximum number of rules that can be defined
''' if n > self.maxeqns: self._max_exceeded = False self.maxeqns = n return
@property def is_confluent(self): ''' Return `True` if the system is confluent
''' if self._is_confluent is None: self._is_confluent = self._check_confluence() return self._is_confluent
def _init_rules(self): identity = self.group.free_group.identity for r in self.group.relators: self.add_rule(r, identity) self._remove_redundancies() return
def _add_rule(self, r1, r2): ''' Add the rule r1 -> r2 with no checking or further deductions
''' if len(self.rules) + 1 > self.maxeqns: self._is_confluent = self._check_confluence() self._max_exceeded = True raise RuntimeError("Too many rules were defined.") self.rules[r1] = r2 # Add the newly added rule to the `new_rules` dictionary. if self.reduction_automaton: self._new_rules[r1] = r2
def add_rule(self, w1, w2, check=False): new_keys = set()
if w1 == w2: return new_keys
if w1 < w2: w1, w2 = w2, w1
if (w1, w2) in self.rules_cache: return new_keys self.rules_cache.append((w1, w2))
s1, s2 = w1, w2
# The following is the equivalent of checking # s1 for overlaps with the implicit reductions # {g*g**-1 -> <identity>} and {g**-1*g -> <identity>} # for any generator g without installing the # redundant rules that would result from processing # the overlaps. See [1], Section 3 for details.
if len(s1) - len(s2) < 3: if s1 not in self.rules: new_keys.add(s1) if not check: self._add_rule(s1, s2) if s2**-1 > s1**-1 and s2**-1 not in self.rules: new_keys.add(s2**-1) if not check: self._add_rule(s2**-1, s1**-1)
# overlaps on the right while len(s1) - len(s2) > -1: g = s1[len(s1)-1] s1 = s1.subword(0, len(s1)-1) s2 = s2*g**-1 if len(s1) - len(s2) < 0: if s2 not in self.rules: if not check: self._add_rule(s2, s1) new_keys.add(s2) elif len(s1) - len(s2) < 3: new = self.add_rule(s1, s2, check) new_keys.update(new)
# overlaps on the left while len(w1) - len(w2) > -1: g = w1[0] w1 = w1.subword(1, len(w1)) w2 = g**-1*w2 if len(w1) - len(w2) < 0: if w2 not in self.rules: if not check: self._add_rule(w2, w1) new_keys.add(w2) elif len(w1) - len(w2) < 3: new = self.add_rule(w1, w2, check) new_keys.update(new)
return new_keys
def _remove_redundancies(self, changes=False): ''' Reduce left- and right-hand sides of reduction rules and remove redundant equations (i.e. those for which lhs == rhs). If `changes` is `True`, return a set containing the removed keys and a set containing the added keys
''' removed = set() added = set() rules = self.rules.copy() for r in rules: v = self.reduce(r, exclude=r) w = self.reduce(rules[r]) if v != r: del self.rules[r] removed.add(r) if v > w: added.add(v) self.rules[v] = w elif v < w: added.add(w) self.rules[w] = v else: self.rules[v] = w if changes: return removed, added return
def make_confluent(self, check=False): ''' Try to make the system confluent using the Knuth-Bendix completion algorithm
''' if self._max_exceeded: return self._is_confluent lhs = list(self.rules.keys())
def _overlaps(r1, r2): len1 = len(r1) len2 = len(r2) result = [] for j in range(1, len1 + len2): if (r1.subword(len1 - j, len1 + len2 - j, strict=False) == r2.subword(j - len1, j, strict=False)): a = r1.subword(0, len1-j, strict=False) a = a*r2.subword(0, j-len1, strict=False) b = r2.subword(j-len1, j, strict=False) c = r2.subword(j, len2, strict=False) c = c*r1.subword(len1 + len2 - j, len1, strict=False) result.append(a*b*c) return result
def _process_overlap(w, r1, r2, check): s = w.eliminate_word(r1, self.rules[r1]) s = self.reduce(s) t = w.eliminate_word(r2, self.rules[r2]) t = self.reduce(t) if s != t: if check: # system not confluent return [0] try: new_keys = self.add_rule(t, s, check) return new_keys except RuntimeError: return False return
added = 0 i = 0 while i < len(lhs): r1 = lhs[i] i += 1 # j could be i+1 to not # check each pair twice but lhs # is extended in the loop and the new # elements have to be checked with the # preceding ones. there is probably a better way # to handle this j = 0 while j < len(lhs): r2 = lhs[j] j += 1 if r1 == r2: continue overlaps = _overlaps(r1, r2) overlaps.extend(_overlaps(r1**-1, r2)) if not overlaps: continue for w in overlaps: new_keys = _process_overlap(w, r1, r2, check) if new_keys: if check: return False lhs.extend(new_keys) added += len(new_keys) elif new_keys == False: # too many rules were added so the process # couldn't complete return self._is_confluent
if added > self.tidyint and not check: # tidy up r, a = self._remove_redundancies(changes=True) added = 0 if r: # reset i since some elements were removed i = min(lhs.index(s) for s in r) lhs = [l for l in lhs if l not in r] lhs.extend(a) if r1 in r: # r1 was removed as redundant break
self._is_confluent = True if not check: self._remove_redundancies() return True
def _check_confluence(self): return self.make_confluent(check=True)
def reduce(self, word, exclude=None): ''' Apply reduction rules to `word` excluding the reduction rule for the lhs equal to `exclude`
''' rules = {r: self.rules[r] for r in self.rules if r != exclude} # the following is essentially `eliminate_words()` code from the # `FreeGroupElement` class, the only difference being the first # "if" statement again = True new = word while again: again = False for r in rules: prev = new if rules[r]**-1 > r**-1: new = new.eliminate_word(r, rules[r], _all=True, inverse=False) else: new = new.eliminate_word(r, rules[r], _all=True) if new != prev: again = True return new
def _compute_inverse_rules(self, rules): ''' Compute the inverse rules for a given set of rules. The inverse rules are used in the automaton for word reduction.
Arguments: rules (dictionary): Rules for which the inverse rules are to computed.
Returns: Dictionary of inverse_rules.
''' inverse_rules = {} for r in rules: rule_key_inverse = r**-1 rule_value_inverse = (rules[r])**-1 if (rule_value_inverse < rule_key_inverse): inverse_rules[rule_key_inverse] = rule_value_inverse else: inverse_rules[rule_value_inverse] = rule_key_inverse return inverse_rules
def construct_automaton(self): ''' Construct the automaton based on the set of reduction rules of the system.
Automata Design: The accept states of the automaton are the proper prefixes of the left hand side of the rules. The complete left hand side of the rules are the dead states of the automaton.
''' self._add_to_automaton(self.rules)
def _add_to_automaton(self, rules): ''' Add new states and transitions to the automaton.
Summary: States corresponding to the new rules added to the system are computed and added to the automaton. Transitions in the previously added states are also modified if necessary.
Arguments: rules (dictionary) -- Dictionary of the newly added rules.
''' # Automaton variables automaton_alphabet = [] proper_prefixes = {}
# compute the inverses of all the new rules added all_rules = rules inverse_rules = self._compute_inverse_rules(all_rules) all_rules.update(inverse_rules)
# Keep track of the accept_states. accept_states = []
for rule in all_rules: # The symbols present in the new rules are the symbols to be verified at each state. # computes the automaton_alphabet, as the transitions solely depend upon the new states. automaton_alphabet += rule.letter_form_elm # Compute the proper prefixes for every rule. proper_prefixes[rule] = [] letter_word_array = list(rule.letter_form_elm) len_letter_word_array = len(letter_word_array) for i in range (1, len_letter_word_array): letter_word_array[i] = letter_word_array[i-1]*letter_word_array[i] # Add accept states. elem = letter_word_array[i-1] if elem not in self.reduction_automaton.states: self.reduction_automaton.add_state(elem, state_type='a') accept_states.append(elem) proper_prefixes[rule] = letter_word_array # Check for overlaps between dead and accept states. if rule in accept_states: self.reduction_automaton.states[rule].state_type = 'd' self.reduction_automaton.states[rule].rh_rule = all_rules[rule] accept_states.remove(rule) # Add dead states if rule not in self.reduction_automaton.states: self.reduction_automaton.add_state(rule, state_type='d', rh_rule=all_rules[rule])
automaton_alphabet = set(automaton_alphabet)
# Add new transitions for every state. for state in self.reduction_automaton.states: current_state_name = state current_state_type = self.reduction_automaton.states[state].state_type # Transitions will be modified only when suffixes of the current_state # belongs to the proper_prefixes of the new rules. # The rest are ignored if they cannot lead to a dead state after a finite number of transisitons. if current_state_type == 's': for letter in automaton_alphabet: if letter in self.reduction_automaton.states: self.reduction_automaton.states[state].add_transition(letter, letter) else: self.reduction_automaton.states[state].add_transition(letter, current_state_name) elif current_state_type == 'a': # Check if the transition to any new state in possible. for letter in automaton_alphabet: _next = current_state_name*letter while len(_next) and _next not in self.reduction_automaton.states: _next = _next.subword(1, len(_next)) if not len(_next): _next = 'start' self.reduction_automaton.states[state].add_transition(letter, _next)
# Add transitions for new states. All symbols used in the automaton are considered here. # Ignore this if `reduction_automaton.automaton_alphabet` = `automaton_alphabet`. if len(self.reduction_automaton.automaton_alphabet) != len(automaton_alphabet): for state in accept_states: current_state_name = state for letter in self.reduction_automaton.automaton_alphabet: _next = current_state_name*letter while len(_next) and _next not in self.reduction_automaton.states: _next = _next.subword(1, len(_next)) if not len(_next): _next = 'start' self.reduction_automaton.states[state].add_transition(letter, _next)
def reduce_using_automaton(self, word): ''' Reduce a word using an automaton.
Summary: All the symbols of the word are stored in an array and are given as the input to the automaton. If the automaton reaches a dead state that subword is replaced and the automaton is run from the beginning. The complete word has to be replaced when the word is read and the automaton reaches a dead state. So, this process is repeated until the word is read completely and the automaton reaches the accept state.
Arguments: word (instance of FreeGroupElement) -- Word that needs to be reduced.
''' # Modify the automaton if new rules are found. if self._new_rules: self._add_to_automaton(self._new_rules) self._new_rules = {}
flag = 1 while flag: flag = 0 current_state = self.reduction_automaton.states['start'] for i, s in enumerate(word.letter_form_elm): next_state_name = current_state.transitions[s] next_state = self.reduction_automaton.states[next_state_name] if next_state.state_type == 'd': subst = next_state.rh_rule word = word.substituted_word(i - len(next_state_name) + 1, i+1, subst) flag = 1 break current_state = next_state return word123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960class State: ''' A representation of a state managed by a ``StateMachine``.
Attributes: name (instance of FreeGroupElement or string) -- State name which is also assigned to the Machine. transisitons (OrderedDict) -- Represents all the transitions of the state object. state_type (string) -- Denotes the type (accept/start/dead) of the state. rh_rule (instance of FreeGroupElement) -- right hand rule for dead state. state_machine (instance of StateMachine object) -- The finite state machine that the state belongs to. '''
def __init__(self, name, state_machine, state_type=None, rh_rule=None): self.name = name self.transitions = {} self.state_machine = state_machine self.state_type = state_type[0] self.rh_rule = rh_rule
def add_transition(self, letter, state): ''' Add a transition from the current state to a new state.
Keyword Arguments: letter -- The alphabet element the current state reads to make the state transition. state -- This will be an instance of the State object which represents a new state after in the transition after the alphabet is read.
''' self.transitions[letter] = state
class StateMachine: ''' Representation of a finite state machine the manages the states and the transitions of the automaton.
Attributes: states (dictionary) -- Collection of all registered `State` objects. name (str) -- Name of the state machine. '''
def __init__(self, name, automaton_alphabet): self.name = name self.automaton_alphabet = automaton_alphabet self.states = {} # Contains all the states in the machine. self.add_state('start', state_type='s')
def add_state(self, state_name, state_type=None, rh_rule=None): ''' Instantiate a state object and stores it in the 'states' dictionary.
Arguments: state_name (instance of FreeGroupElement or string) -- name of the new states. state_type (string) -- Denotes the type (accept/start/dead) of the state added. rh_rule (instance of FreeGroupElement) -- right hand rule for dead state.
''' new_state = State(state_name, self, state_type, rh_rule) self.states[state_name] = new_state
def __repr__(self): return "%s" % (self.name)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""The Schur number S(k) is the largest integer n for which the interval [1,n]can be partitioned into k sum-free sets.(https://mathworld.wolfram.com/SchurNumber.html)"""import mathfrom sympy.core import Sfrom sympy.core.basic import Basicfrom sympy.core.function import Functionfrom sympy.core.numbers import Integer
class SchurNumber(Function): r""" This function creates a SchurNumber object which is evaluated for `k \le 5` otherwise only the lower bound information can be retrieved.
Examples ========
>>> from sympy.combinatorics.schur_number import SchurNumber
Since S(3) = 13, hence the output is a number >>> SchurNumber(3) 13
We do not know the Schur number for values greater than 5, hence only the object is returned >>> SchurNumber(6) SchurNumber(6)
Now, the lower bound information can be retrieved using lower_bound() method >>> SchurNumber(6).lower_bound() 536
"""
@classmethod def eval(cls, k): if k.is_Number: if k is S.Infinity: return S.Infinity if k.is_zero: return S.Zero if not k.is_integer or k.is_negative: raise ValueError("k should be a positive integer") first_known_schur_numbers = {1: 1, 2: 4, 3: 13, 4: 44, 5: 160} if k <= 5: return Integer(first_known_schur_numbers[k])
def lower_bound(self): f_ = self.args[0] # Improved lower bounds known for S(6) and S(7) if f_ == 6: return Integer(536) if f_ == 7: return Integer(1680) # For other cases, use general expression if f_.is_Integer: return 3*self.func(f_ - 1).lower_bound() - 1 return (3**f_ - 1)/2
def _schur_subsets_number(n):
if n is S.Infinity: raise ValueError("Input must be finite") if n <= 0: raise ValueError("n must be a non-zero positive integer.") elif n <= 3: min_k = 1 else: min_k = math.ceil(math.log(2*n + 1, 3))
return Integer(min_k)
def schur_partition(n): """
This function returns the partition in the minimum number of sum-free subsets according to the lower bound given by the Schur Number.
Parameters ==========
n: a number n is the upper limit of the range [1, n] for which we need to find and return the minimum number of free subsets according to the lower bound of schur number
Returns =======
List of lists List of the minimum number of sum-free subsets
Notes =====
It is possible for some n to make the partition into less subsets since the only known Schur numbers are: S(1) = 1, S(2) = 4, S(3) = 13, S(4) = 44. e.g for n = 44 the lower bound from the function above is 5 subsets but it has been proven that can be done with 4 subsets.
Examples ========
For n = 1, 2, 3 the answer is the set itself
>>> from sympy.combinatorics.schur_number import schur_partition >>> schur_partition(2) [[1, 2]]
For n > 3, the answer is the minimum number of sum-free subsets:
>>> schur_partition(5) [[3, 2], [5], [1, 4]]
>>> schur_partition(8) [[3, 2], [6, 5, 8], [1, 4, 7]] """
if isinstance(n, Basic) and not n.is_Number: raise ValueError("Input value must be a number")
number_of_subsets = _schur_subsets_number(n) if n == 1: sum_free_subsets = [[1]] elif n == 2: sum_free_subsets = [[1, 2]] elif n == 3: sum_free_subsets = [[1, 2, 3]] else: sum_free_subsets = [[1, 4], [2, 3]]
while len(sum_free_subsets) < number_of_subsets: sum_free_subsets = _generate_next_list(sum_free_subsets, n) missed_elements = [3*k + 1 for k in range(len(sum_free_subsets), (n-1)//3 + 1)] sum_free_subsets[-1] += missed_elements
return sum_free_subsets
def _generate_next_list(current_list, n): new_list = []
for item in current_list: temp_1 = [number*3 for number in item if number*3 <= n] temp_2 = [number*3 - 1 for number in item if number*3 - 1 <= n] new_item = temp_1 + temp_2 new_list.append(new_item)
last_list = [3*k + 1 for k in range(len(current_list)+1) if 3*k + 1 <= n] new_list.append(last_list) current_list = new_list
return current_list123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619from itertools import combinations
from sympy.combinatorics.graycode import GrayCode
class Subset(): """ Represents a basic subset object.
Explanation ===========
We generate subsets using essentially two techniques, binary enumeration and lexicographic enumeration. The Subset class takes two arguments, the first one describes the initial subset to consider and the second describes the superset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset ['b'] >>> a.prev_binary().subset ['c'] """
_rank_binary = None _rank_lex = None _rank_graycode = None _subset = None _superset = None
def __new__(cls, subset, superset): """ Default constructor.
It takes the ``subset`` and its ``superset`` as its parameters.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.subset ['c', 'd'] >>> a.superset ['a', 'b', 'c', 'd'] >>> a.size 2 """ if len(subset) > len(superset): raise ValueError('Invalid arguments have been provided. The ' 'superset must be larger than the subset.') for elem in subset: if elem not in superset: raise ValueError('The superset provided is invalid as it does ' 'not contain the element {}'.format(elem)) obj = object.__new__(cls) obj._subset = subset obj._superset = superset return obj
def __eq__(self, other): """Return a boolean indicating whether a == b on the basis of whether both objects are of the class Subset and if the values of the subset and superset attributes are the same. """ if not isinstance(other, Subset): return NotImplemented return self.subset == other.subset and self.superset == other.superset
def iterate_binary(self, k): """ This is a helper function. It iterates over the binary subsets by ``k`` steps. This variable can be both positive or negative.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.iterate_binary(-2).subset ['d'] >>> a = Subset(['a', 'b', 'c'], ['a', 'b', 'c', 'd']) >>> a.iterate_binary(2).subset []
See Also ========
next_binary, prev_binary """ bin_list = Subset.bitlist_from_subset(self.subset, self.superset) n = (int(''.join(bin_list), 2) + k) % 2**self.superset_size bits = bin(n)[2:].rjust(self.superset_size, '0') return Subset.subset_from_bitlist(self.superset, bits)
def next_binary(self): """ Generates the next binary ordered subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset ['b'] >>> a = Subset(['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_binary().subset []
See Also ========
prev_binary, iterate_binary """ return self.iterate_binary(1)
def prev_binary(self): """ Generates the previous binary ordered subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset([], ['a', 'b', 'c', 'd']) >>> a.prev_binary().subset ['a', 'b', 'c', 'd'] >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.prev_binary().subset ['c']
See Also ========
next_binary, iterate_binary """ return self.iterate_binary(-1)
def next_lexicographic(self): """ Generates the next lexicographically ordered subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.next_lexicographic().subset ['d'] >>> a = Subset(['d'], ['a', 'b', 'c', 'd']) >>> a.next_lexicographic().subset []
See Also ========
prev_lexicographic """ i = self.superset_size - 1 indices = Subset.subset_indices(self.subset, self.superset)
if i in indices: if i - 1 in indices: indices.remove(i - 1) else: indices.remove(i) i = i - 1 while i >= 0 and i not in indices: i = i - 1 if i >= 0: indices.remove(i) indices.append(i+1) else: while i not in indices and i >= 0: i = i - 1 indices.append(i + 1)
ret_set = [] super_set = self.superset for i in indices: ret_set.append(super_set[i]) return Subset(ret_set, super_set)
def prev_lexicographic(self): """ Generates the previous lexicographically ordered subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset([], ['a', 'b', 'c', 'd']) >>> a.prev_lexicographic().subset ['d'] >>> a = Subset(['c','d'], ['a', 'b', 'c', 'd']) >>> a.prev_lexicographic().subset ['c']
See Also ========
next_lexicographic """ i = self.superset_size - 1 indices = Subset.subset_indices(self.subset, self.superset)
while i >= 0 and i not in indices: i = i - 1
if i == 0 or i - 1 in indices: indices.remove(i) else: if i >= 0: indices.remove(i) indices.append(i - 1) indices.append(self.superset_size - 1)
ret_set = [] super_set = self.superset for i in indices: ret_set.append(super_set[i]) return Subset(ret_set, super_set)
def iterate_graycode(self, k): """ Helper function used for prev_gray and next_gray. It performs ``k`` step overs to get the respective Gray codes.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) >>> a.iterate_graycode(3).subset [1, 4] >>> a.iterate_graycode(-2).subset [1, 2, 4]
See Also ========
next_gray, prev_gray """ unranked_code = GrayCode.unrank(self.superset_size, (self.rank_gray + k) % self.cardinality) return Subset.subset_from_bitlist(self.superset, unranked_code)
def next_gray(self): """ Generates the next Gray code ordered subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset([1, 2, 3], [1, 2, 3, 4]) >>> a.next_gray().subset [1, 3]
See Also ========
iterate_graycode, prev_gray """ return self.iterate_graycode(1)
def prev_gray(self): """ Generates the previous Gray code ordered subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset([2, 3, 4], [1, 2, 3, 4, 5]) >>> a.prev_gray().subset [2, 3, 4, 5]
See Also ========
iterate_graycode, next_gray """ return self.iterate_graycode(-1)
@property def rank_binary(self): """ Computes the binary ordered rank.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset([], ['a','b','c','d']) >>> a.rank_binary 0 >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.rank_binary 3
See Also ========
iterate_binary, unrank_binary """ if self._rank_binary is None: self._rank_binary = int("".join( Subset.bitlist_from_subset(self.subset, self.superset)), 2) return self._rank_binary
@property def rank_lexicographic(self): """ Computes the lexicographic ranking of the subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.rank_lexicographic 14 >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6]) >>> a.rank_lexicographic 43 """ if self._rank_lex is None: def _ranklex(self, subset_index, i, n): if subset_index == [] or i > n: return 0 if i in subset_index: subset_index.remove(i) return 1 + _ranklex(self, subset_index, i + 1, n) return 2**(n - i - 1) + _ranklex(self, subset_index, i + 1, n) indices = Subset.subset_indices(self.subset, self.superset) self._rank_lex = _ranklex(self, indices, 0, self.superset_size) return self._rank_lex
@property def rank_gray(self): """ Computes the Gray code ranking of the subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c','d'], ['a','b','c','d']) >>> a.rank_gray 2 >>> a = Subset([2, 4, 5], [1, 2, 3, 4, 5, 6]) >>> a.rank_gray 27
See Also ========
iterate_graycode, unrank_gray """ if self._rank_graycode is None: bits = Subset.bitlist_from_subset(self.subset, self.superset) self._rank_graycode = GrayCode(len(bits), start=bits).rank return self._rank_graycode
@property def subset(self): """ Gets the subset represented by the current instance.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.subset ['c', 'd']
See Also ========
superset, size, superset_size, cardinality """ return self._subset
@property def size(self): """ Gets the size of the subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.size 2
See Also ========
subset, superset, superset_size, cardinality """ return len(self.subset)
@property def superset(self): """ Gets the superset of the subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.superset ['a', 'b', 'c', 'd']
See Also ========
subset, size, superset_size, cardinality """ return self._superset
@property def superset_size(self): """ Returns the size of the superset.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.superset_size 4
See Also ========
subset, superset, size, cardinality """ return len(self.superset)
@property def cardinality(self): """ Returns the number of all possible subsets.
Examples ========
>>> from sympy.combinatorics import Subset >>> a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) >>> a.cardinality 16
See Also ========
subset, superset, size, superset_size """ return 2**(self.superset_size)
@classmethod def subset_from_bitlist(self, super_set, bitlist): """ Gets the subset defined by the bitlist.
Examples ========
>>> from sympy.combinatorics import Subset >>> Subset.subset_from_bitlist(['a', 'b', 'c', 'd'], '0011').subset ['c', 'd']
See Also ========
bitlist_from_subset """ if len(super_set) != len(bitlist): raise ValueError("The sizes of the lists are not equal") ret_set = [] for i in range(len(bitlist)): if bitlist[i] == '1': ret_set.append(super_set[i]) return Subset(ret_set, super_set)
@classmethod def bitlist_from_subset(self, subset, superset): """ Gets the bitlist corresponding to a subset.
Examples ========
>>> from sympy.combinatorics import Subset >>> Subset.bitlist_from_subset(['c', 'd'], ['a', 'b', 'c', 'd']) '0011'
See Also ========
subset_from_bitlist """ bitlist = ['0'] * len(superset) if isinstance(subset, Subset): subset = subset.subset for i in Subset.subset_indices(subset, superset): bitlist[i] = '1' return ''.join(bitlist)
@classmethod def unrank_binary(self, rank, superset): """ Gets the binary ordered subset of the specified rank.
Examples ========
>>> from sympy.combinatorics import Subset >>> Subset.unrank_binary(4, ['a', 'b', 'c', 'd']).subset ['b']
See Also ========
iterate_binary, rank_binary """ bits = bin(rank)[2:].rjust(len(superset), '0') return Subset.subset_from_bitlist(superset, bits)
@classmethod def unrank_gray(self, rank, superset): """ Gets the Gray code ordered subset of the specified rank.
Examples ========
>>> from sympy.combinatorics import Subset >>> Subset.unrank_gray(4, ['a', 'b', 'c']).subset ['a', 'b'] >>> Subset.unrank_gray(0, ['a', 'b', 'c']).subset []
See Also ========
iterate_graycode, rank_gray """ graycode_bitlist = GrayCode.unrank(len(superset), rank) return Subset.subset_from_bitlist(superset, graycode_bitlist)
@classmethod def subset_indices(self, subset, superset): """Return indices of subset in superset in a list; the list is empty if all elements of ``subset`` are not in ``superset``.
Examples ========
>>> from sympy.combinatorics import Subset >>> superset = [1, 3, 2, 5, 4] >>> Subset.subset_indices([3, 2, 1], superset) [1, 2, 0] >>> Subset.subset_indices([1, 6], superset) [] >>> Subset.subset_indices([], superset) []
""" a, b = superset, subset sb = set(b) d = {} for i, ai in enumerate(a): if ai in sb: d[ai] = i sb.remove(ai) if not sb: break else: return [] return [d[bi] for bi in b]
def ksubsets(superset, k): """ Finds the subsets of size ``k`` in lexicographic order.
This uses the itertools generator.
Examples ========
>>> from sympy.combinatorics.subsets import ksubsets >>> list(ksubsets([1, 2, 3], 2)) [(1, 2), (1, 3), (2, 3)] >>> list(ksubsets([1, 2, 3, 4, 5], 2)) [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), \ (2, 5), (3, 4), (3, 5), (4, 5)]
See Also ========
Subset """ return combinations(superset, k)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190from sympy.combinatorics.permutations import Permutation, _af_rmul, \ _af_invert, _af_newfrom sympy.combinatorics.perm_groups import PermutationGroup, _orbit, \ _orbit_transversalfrom sympy.combinatorics.util import _distribute_gens_by_base, \ _orbits_transversals_from_bsgs
""" References for tensor canonicalization:
[1] R. Portugal "Algorithmic simplification of tensor expressions", J. Phys. A 32 (1999) 7779-7789
[2] R. Portugal, B.F. Svaiter "Group-theoretic Approach for Symbolic Tensor Manipulation: I. Free Indices" arXiv:math-ph/0107031v1
[3] L.R.U. Manssur, R. Portugal "Group-theoretic Approach for Symbolic Tensor Manipulation: II. Dummy Indices" arXiv:math-ph/0107032v1
[4] xperm.c part of XPerm written by J. M. Martin-Garcia http://www.xact.es/index.html"""
def dummy_sgs(dummies, sym, n): """ Return the strong generators for dummy indices.
Parameters ==========
dummies : List of dummy indices. `dummies[2k], dummies[2k+1]` are paired indices. In base form, the dummy indices are always in consecutive positions. sym : symmetry under interchange of contracted dummies:: * None no symmetry * 0 commuting * 1 anticommuting
n : number of indices
Examples ========
>>> from sympy.combinatorics.tensor_can import dummy_sgs >>> dummy_sgs(list(range(2, 8)), 0, 8) [[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9], [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]] """ if len(dummies) > n: raise ValueError("List too large") res = [] # exchange of contravariant and covariant indices if sym is not None: for j in dummies[::2]: a = list(range(n + 2)) if sym == 1: a[n] = n + 1 a[n + 1] = n a[j], a[j + 1] = a[j + 1], a[j] res.append(a) # rename dummy indices for j in dummies[:-3:2]: a = list(range(n + 2)) a[j:j + 4] = a[j + 2], a[j + 3], a[j], a[j + 1] res.append(a) return res
def _min_dummies(dummies, sym, indices): """ Return list of minima of the orbits of indices in group of dummies. See ``double_coset_can_rep`` for the description of ``dummies`` and ``sym``. ``indices`` is the initial list of dummy indices.
Examples ========
>>> from sympy.combinatorics.tensor_can import _min_dummies >>> _min_dummies([list(range(2, 8))], [0], list(range(10))) [0, 1, 2, 2, 2, 2, 2, 2, 8, 9] """ num_types = len(sym) m = [min(dx) if dx else None for dx in dummies] res = indices[:] for i in range(num_types): for c, i in enumerate(indices): for j in range(num_types): if i in dummies[j]: res[c] = m[j] break return res
def _trace_S(s, j, b, S_cosets): """ Return the representative h satisfying s[h[b]] == j
If there is not such a representative return None """ for h in S_cosets[b]: if s[h[b]] == j: return h return None
def _trace_D(gj, p_i, Dxtrav): """ Return the representative h satisfying h[gj] == p_i
If there is not such a representative return None """ for h in Dxtrav: if h[gj] == p_i: return h return None
def _dumx_remove(dumx, dumx_flat, p0): """ remove p0 from dumx """ res = [] for dx in dumx: if p0 not in dx: res.append(dx) continue k = dx.index(p0) if k % 2 == 0: p0_paired = dx[k + 1] else: p0_paired = dx[k - 1] dx.remove(p0) dx.remove(p0_paired) dumx_flat.remove(p0) dumx_flat.remove(p0_paired) res.append(dx)
def transversal2coset(size, base, transversal): a = [] j = 0 for i in range(size): if i in base: a.append(sorted(transversal[j].values())) j += 1 else: a.append([list(range(size))]) j = len(a) - 1 while a[j] == [list(range(size))]: j -= 1 return a[:j + 1]
def double_coset_can_rep(dummies, sym, b_S, sgens, S_transversals, g): r""" Butler-Portugal algorithm for tensor canonicalization with dummy indices.
Parameters ==========
dummies list of lists of dummy indices, one list for each type of index; the dummy indices are put in order contravariant, covariant [d0, -d0, d1, -d1, ...].
sym list of the symmetries of the index metric for each type.
possible symmetries of the metrics * 0 symmetric * 1 antisymmetric * None no symmetry
b_S base of a minimal slot symmetry BSGS.
sgens generators of the slot symmetry BSGS.
S_transversals transversals for the slot BSGS.
g permutation representing the tensor.
Returns =======
Return 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor.
Notes =====
A tensor with dummy indices can be represented in a number of equivalent ways which typically grows exponentially with the number of indices. To be able to establish if two tensors with many indices are equal becomes computationally very slow in absence of an efficient algorithm.
The Butler-Portugal algorithm [3] is an efficient algorithm to put tensors in canonical form, solving the above problem.
Portugal observed that a tensor can be represented by a permutation, and that the class of tensors equivalent to it under slot and dummy symmetries is equivalent to the double coset `D*g*S` (Note: in this documentation we use the conventions for multiplication of permutations p, q with (p*q)(i) = p[q[i]] which is opposite to the one used in the Permutation class)
Using the algorithm by Butler to find a representative of the double coset one can find a canonical form for the tensor.
To see this correspondence, let `g` be a permutation in array form; a tensor with indices `ind` (the indices including both the contravariant and the covariant ones) can be written as
`t = T(ind[g[0]], \dots, ind[g[n-1]])`,
where `n = len(ind)`; `g` has size `n + 2`, the last two indices for the sign of the tensor (trick introduced in [4]).
A slot symmetry transformation `s` is a permutation acting on the slots `t \rightarrow T(ind[(g*s)[0]], \dots, ind[(g*s)[n-1]])`
A dummy symmetry transformation acts on `ind` `t \rightarrow T(ind[(d*g)[0]], \dots, ind[(d*g)[n-1]])`
Being interested only in the transformations of the tensor under these symmetries, one can represent the tensor by `g`, which transforms as
`g -> d*g*s`, so it belongs to the coset `D*g*S`, or in other words to the set of all permutations allowed by the slot and dummy symmetries.
Let us explain the conventions by an example.
Given a tensor `T^{d3 d2 d1}{}_{d1 d2 d3}` with the slot symmetries `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`
`T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}`
and symmetric metric, find the tensor equivalent to it which is the lowest under the ordering of indices: lexicographic ordering `d1, d2, d3` and then contravariant before covariant index; that is the canonical form of the tensor.
The canonical form is `-T^{d1 d2 d3}{}_{d1 d2 d3}` obtained using `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`.
To convert this problem in the input for this function, use the following ordering of the index names (- for covariant for short) `d1, -d1, d2, -d2, d3, -d3`
`T^{d3 d2 d1}{}_{d1 d2 d3}` corresponds to `g = [4, 2, 0, 1, 3, 5, 6, 7]` where the last two indices are for the sign
`sgens = [Permutation(0, 2)(6, 7), Permutation(0, 4)(6, 7)]`
sgens[0] is the slot symmetry `-(0, 2)` `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`
sgens[1] is the slot symmetry `-(0, 4)` `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}`
The dummy symmetry group D is generated by the strong base generators `[(0, 1), (2, 3), (4, 5), (0, 2)(1, 3), (0, 4)(1, 5)]` where the first three interchange covariant and contravariant positions of the same index (d1 <-> -d1) and the last two interchange the dummy indices themselves (d1 <-> d2).
The dummy symmetry acts from the left `d = [1, 0, 2, 3, 4, 5, 6, 7]` exchange `d1 \leftrightarrow -d1` `T^{d3 d2 d1}{}_{d1 d2 d3} == T^{d3 d2}{}_{d1}{}^{d1}{}_{d2 d3}`
`g=[4, 2, 0, 1, 3, 5, 6, 7] -> [4, 2, 1, 0, 3, 5, 6, 7] = _af_rmul(d, g)` which differs from `_af_rmul(g, d)`.
The slot symmetry acts from the right `s = [2, 1, 0, 3, 4, 5, 7, 6]` exchanges slots 0 and 2 and changes sign `T^{d3 d2 d1}{}_{d1 d2 d3} == -T^{d1 d2 d3}{}_{d1 d2 d3}`
`g=[4,2,0,1,3,5,6,7] -> [0, 2, 4, 1, 3, 5, 7, 6] = _af_rmul(g, s)`
Example in which the tensor is zero, same slot symmetries as above: `T^{d2}{}_{d1 d3}{}^{d1 d3}{}_{d2}`
`= -T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,4)`;
`= T_{d3 d1}{}^{d3}{}^{d1 d2}{}_{d2}` under slot symmetry `-(0,2)`;
`= T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}` symmetric metric;
`= 0` since two of these lines have tensors differ only for the sign.
The double coset D*g*S consists of permutations `h = d*g*s` corresponding to equivalent tensors; if there are two `h` which are the same apart from the sign, return zero; otherwise choose as representative the tensor with indices ordered lexicographically according to `[d1, -d1, d2, -d2, d3, -d3]` that is ``rep = min(D*g*S) = min([d*g*s for d in D for s in S])``
The indices are fixed one by one; first choose the lowest index for slot 0, then the lowest remaining index for slot 1, etc. Doing this one obtains a chain of stabilizers
`S \rightarrow S_{b0} \rightarrow S_{b0,b1} \rightarrow \dots` and `D \rightarrow D_{p0} \rightarrow D_{p0,p1} \rightarrow \dots`
where ``[b0, b1, ...] = range(b)`` is a base of the symmetric group; the strong base `b_S` of S is an ordered sublist of it; therefore it is sufficient to compute once the strong base generators of S using the Schreier-Sims algorithm; the stabilizers of the strong base generators are the strong base generators of the stabilizer subgroup.
``dbase = [p0, p1, ...]`` is not in general in lexicographic order, so that one must recompute the strong base generators each time; however this is trivial, there is no need to use the Schreier-Sims algorithm for D.
The algorithm keeps a TAB of elements `(s_i, d_i, h_i)` where `h_i = d_i \times g \times s_i` satisfying `h_i[j] = p_j` for `0 \le j < i` starting from `s_0 = id, d_0 = id, h_0 = g`.
The equations `h_0[0] = p_0, h_1[1] = p_1, \dots` are solved in this order, choosing each time the lowest possible value of p_i
For `j < i` `d_i*g*s_i*S_{b_0, \dots, b_{i-1}}*b_j = D_{p_0, \dots, p_{i-1}}*p_j` so that for dx in `D_{p_0,\dots,p_{i-1}}` and sx in `S_{base[0], \dots, base[i-1]}` one has `dx*d_i*g*s_i*sx*b_j = p_j`
Search for dx, sx such that this equation holds for `j = i`; it can be written as `s_i*sx*b_j = J, dx*d_i*g*J = p_j` `sx*b_j = s_i**-1*J; sx = trace(s_i**-1, S_{b_0,...,b_{i-1}})` `dx**-1*p_j = d_i*g*J; dx = trace(d_i*g*J, D_{p_0,...,p_{i-1}})`
`s_{i+1} = s_i*trace(s_i**-1*J, S_{b_0,...,b_{i-1}})` `d_{i+1} = trace(d_i*g*J, D_{p_0,...,p_{i-1}})**-1*d_i` `h_{i+1}*b_i = d_{i+1}*g*s_{i+1}*b_i = p_i`
`h_n*b_j = p_j` for all j, so that `h_n` is the solution.
Add the found `(s, d, h)` to TAB1.
At the end of the iteration sort TAB1 with respect to the `h`; if there are two consecutive `h` in TAB1 which differ only for the sign, the tensor is zero, so return 0; if there are two consecutive `h` which are equal, keep only one.
Then stabilize the slot generators under `i` and the dummy generators under `p_i`.
Assign `TAB = TAB1` at the end of the iteration step.
At the end `TAB` contains a unique `(s, d, h)`, since all the slots of the tensor `h` have been fixed to have the minimum value according to the symmetries. The algorithm returns `h`.
It is important that the slot BSGS has lexicographic minimal base, otherwise there is an `i` which does not belong to the slot base for which `p_i` is fixed by the dummy symmetry only, while `i` is not invariant from the slot stabilizer, so `p_i` is not in general the minimal value.
This algorithm differs slightly from the original algorithm [3]: the canonical form is minimal lexicographically, and the BSGS has minimal base under lexicographic order. Equal tensors `h` are eliminated from TAB.
Examples ========
>>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.tensor_can import double_coset_can_rep, get_transversals >>> gens = [Permutation(x) for x in [[2, 1, 0, 3, 4, 5, 7, 6], [4, 1, 2, 3, 0, 5, 7, 6]]] >>> base = [0, 2] >>> g = Permutation([4, 2, 0, 1, 3, 5, 6, 7]) >>> transversals = get_transversals(base, gens) >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) [0, 1, 2, 3, 4, 5, 7, 6]
>>> g = Permutation([4, 1, 3, 0, 5, 2, 6, 7]) >>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g) 0 """ size = g.size g = g.array_form num_dummies = size - 2 indices = list(range(num_dummies)) all_metrics_with_sym = not any(_ is None for _ in sym) num_types = len(sym) dumx = dummies[:] dumx_flat = [] for dx in dumx: dumx_flat.extend(dx) b_S = b_S[:] sgensx = [h._array_form for h in sgens] if b_S: S_transversals = transversal2coset(size, b_S, S_transversals) # strong generating set for D dsgsx = [] for i in range(num_types): dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) idn = list(range(size)) # TAB = list of entries (s, d, h) where h = _af_rmuln(d,g,s) # for short, in the following d*g*s means _af_rmuln(d,g,s) TAB = [(idn, idn, g)] for i in range(size - 2): b = i testb = b in b_S and sgensx if testb: sgensx1 = [_af_new(_) for _ in sgensx] deltab = _orbit(size, sgensx1, b) else: deltab = {b} # p1 = min(IMAGES) = min(Union D_p*h*deltab for h in TAB) if all_metrics_with_sym: md = _min_dummies(dumx, sym, indices) else: md = [min(_orbit(size, [_af_new( ddx) for ddx in dsgsx], ii)) for ii in range(size - 2)]
p_i = min(min(md[h[x]] for x in deltab) for s, d, h in TAB) dsgsx1 = [_af_new(_) for _ in dsgsx] Dxtrav = _orbit_transversal(size, dsgsx1, p_i, False, af=True) \ if dsgsx else None if Dxtrav: Dxtrav = [_af_invert(x) for x in Dxtrav] # compute the orbit of p_i for ii in range(num_types): if p_i in dumx[ii]: # the orbit is made by all the indices in dum[ii] if sym[ii] is not None: deltap = dumx[ii] else: # the orbit is made by all the even indices if p_i # is even, by all the odd indices if p_i is odd p_i_index = dumx[ii].index(p_i) % 2 deltap = dumx[ii][p_i_index::2] break else: deltap = [p_i] TAB1 = [] while TAB: s, d, h = TAB.pop() if min(md[h[x]] for x in deltab) != p_i: continue deltab1 = [x for x in deltab if md[h[x]] == p_i] # NEXT = s*deltab1 intersection (d*g)**-1*deltap dg = _af_rmul(d, g) dginv = _af_invert(dg) sdeltab = [s[x] for x in deltab1] gdeltap = [dginv[x] for x in deltap] NEXT = [x for x in sdeltab if x in gdeltap] # d, s satisfy # d*g*s*base[i-1] = p_{i-1}; using the stabilizers # d*g*s*S_{base[0],...,base[i-1]}*base[i-1] = # D_{p_0,...,p_{i-1}}*p_{i-1} # so that to find d1, s1 satisfying d1*g*s1*b = p_i # one can look for dx in D_{p_0,...,p_{i-1}} and # sx in S_{base[0],...,base[i-1]} # d1 = dx*d; s1 = s*sx # d1*g*s1*b = dx*d*g*s*sx*b = p_i for j in NEXT: if testb: # solve s1*b = j with s1 = s*sx for some element sx # of the stabilizer of ..., base[i-1] # sx*b = s**-1*j; sx = _trace_S(s, j,...) # s1 = s*trace_S(s**-1*j,...) s1 = _trace_S(s, j, b, S_transversals) if not s1: continue else: s1 = [s[ix] for ix in s1] else: s1 = s # assert s1[b] == j # invariant # solve d1*g*j = p_i with d1 = dx*d for some element dg # of the stabilizer of ..., p_{i-1} # dx**-1*p_i = d*g*j; dx**-1 = trace_D(d*g*j,...) # d1 = trace_D(d*g*j,...)**-1*d # to save an inversion in the inner loop; notice we did # Dxtrav = [perm_af_invert(x) for x in Dxtrav] out of the loop if Dxtrav: d1 = _trace_D(dg[j], p_i, Dxtrav) if not d1: continue else: if p_i != dg[j]: continue d1 = idn assert d1[dg[j]] == p_i # invariant d1 = [d1[ix] for ix in d] h1 = [d1[g[ix]] for ix in s1] # assert h1[b] == p_i # invariant TAB1.append((s1, d1, h1))
# if TAB contains equal permutations, keep only one of them; # if TAB contains equal permutations up to the sign, return 0 TAB1.sort(key=lambda x: x[-1]) prev = [0] * size while TAB1: s, d, h = TAB1.pop() if h[:-2] == prev[:-2]: if h[-1] != prev[-1]: return 0 else: TAB.append((s, d, h)) prev = h
# stabilize the SGS sgensx = [h for h in sgensx if h[b] == b] if b in b_S: b_S.remove(b) _dumx_remove(dumx, dumx_flat, p_i) dsgsx = [] for i in range(num_types): dsgsx.extend(dummy_sgs(dumx[i], sym[i], num_dummies)) return TAB[0][-1]
def canonical_free(base, gens, g, num_free): """ Canonicalization of a tensor with respect to free indices choosing the minimum with respect to lexicographical ordering in the free indices.
Explanation ===========
``base``, ``gens`` BSGS for slot permutation group ``g`` permutation representing the tensor ``num_free`` number of free indices The indices must be ordered with first the free indices
See explanation in double_coset_can_rep The algorithm is a variation of the one given in [2].
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import canonical_free >>> gens = [[1, 0, 2, 3, 5, 4], [2, 3, 0, 1, 4, 5],[0, 1, 3, 2, 5, 4]] >>> gens = [Permutation(h) for h in gens] >>> base = [0, 2] >>> g = Permutation([2, 1, 0, 3, 4, 5]) >>> canonical_free(base, gens, g, 4) [0, 3, 1, 2, 5, 4]
Consider the product of Riemann tensors ``T = R^{a}_{d0}^{d1,d2}*R_{d2,d1}^{d0,b}`` The order of the indices is ``[a, b, d0, -d0, d1, -d1, d2, -d2]`` The permutation corresponding to the tensor is ``g = [0, 3, 4, 6, 7, 5, 2, 1, 8, 9]``
In particular ``a`` is position ``0``, ``b`` is in position ``9``. Use the slot symmetries to get `T` is a form which is the minimal in lexicographic order in the free indices ``a`` and ``b``, e.g. ``-R^{a}_{d0}^{d1,d2}*R^{b,d0}_{d2,d1}`` corresponding to ``[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]``
>>> from sympy.combinatorics.tensor_can import riemann_bsgs, tensor_gens >>> base, gens = riemann_bsgs >>> size, sbase, sgens = tensor_gens(base, gens, [[], []], 0) >>> g = Permutation([0, 3, 4, 6, 7, 5, 2, 1, 8, 9]) >>> canonical_free(sbase, [Permutation(h) for h in sgens], g, 2) [0, 3, 4, 6, 1, 2, 7, 5, 9, 8] """ g = g.array_form size = len(g) if not base: return g[:]
transversals = get_transversals(base, gens) for x in sorted(g[:-2]): if x not in base: base.append(x) h = g for transv in transversals: h_i = [size]*num_free # find the element s in transversals[i] such that # _af_rmul(h, s) has its free elements with the lowest position in h s = None for sk in transv.values(): h1 = _af_rmul(h, sk) hi = [h1.index(ix) for ix in range(num_free)] if hi < h_i: h_i = hi s = sk if s: h = _af_rmul(h, s) return h
def _get_map_slots(size, fixed_slots): res = list(range(size)) pos = 0 for i in range(size): if i in fixed_slots: continue res[i] = pos pos += 1 return res
def _lift_sgens(size, fixed_slots, free, s): a = [] j = k = 0 fd = list(zip(fixed_slots, free)) fd = [y for x, y in sorted(fd)] num_free = len(free) for i in range(size): if i in fixed_slots: a.append(fd[k]) k += 1 else: a.append(s[j] + num_free) j += 1 return a
def canonicalize(g, dummies, msym, *v): """ canonicalize tensor formed by tensors
Parameters ==========
g : permutation representing the tensor
dummies : list representing the dummy indices it can be a list of dummy indices of the same type or a list of lists of dummy indices, one list for each type of index; the dummy indices must come after the free indices, and put in order contravariant, covariant [d0, -d0, d1,-d1,...]
msym : symmetry of the metric(s) it can be an integer or a list; in the first case it is the symmetry of the dummy index metric; in the second case it is the list of the symmetries of the index metric for each type
v : list, (base_i, gens_i, n_i, sym_i) for tensors of type `i`
base_i, gens_i : BSGS for tensors of this type. The BSGS should have minimal base under lexicographic ordering; if not, an attempt is made do get the minimal BSGS; in case of failure, canonicalize_naive is used, which is much slower.
n_i : number of tensors of type `i`.
sym_i : symmetry under exchange of component tensors of type `i`.
Both for msym and sym_i the cases are * None no symmetry * 0 commuting * 1 anticommuting
Returns =======
0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor.
Algorithm =========
First one uses canonical_free to get the minimum tensor under lexicographic order, using only the slot symmetries. If the component tensors have not minimal BSGS, it is attempted to find it; if the attempt fails canonicalize_naive is used instead.
Compute the residual slot symmetry keeping fixed the free indices using tensor_gens(base, gens, list_free_indices, sym).
Reduce the problem eliminating the free indices.
Then use double_coset_can_rep and lift back the result reintroducing the free indices.
Examples ========
one type of index with commuting metric;
`A_{a b}` and `B_{a b}` antisymmetric and commuting
`T = A_{d0 d1} * B^{d0}{}_{d2} * B^{d2 d1}`
`ord = [d0,-d0,d1,-d1,d2,-d2]` order of the indices
g = [1, 3, 0, 5, 4, 2, 6, 7]
`T_c = 0`
>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize, bsgs_direct_product >>> from sympy.combinatorics import Permutation >>> base2a, gens2a = get_symmetric_group_sgs(2, 1) >>> t0 = (base2a, gens2a, 1, 0) >>> t1 = (base2a, gens2a, 2, 0) >>> g = Permutation([1, 3, 0, 5, 4, 2, 6, 7]) >>> canonicalize(g, range(6), 0, t0, t1) 0
same as above, but with `B_{a b}` anticommuting
`T_c = -A^{d0 d1} * B_{d0}{}^{d2} * B_{d1 d2}`
can = [0,2,1,4,3,5,7,6]
>>> t1 = (base2a, gens2a, 2, 1) >>> canonicalize(g, range(6), 0, t0, t1) [0, 2, 1, 4, 3, 5, 7, 6]
two types of indices `[a,b,c,d,e,f]` and `[m,n]`, in this order, both with commuting metric
`f^{a b c}` antisymmetric, commuting
`A_{m a}` no symmetry, commuting
`T = f^c{}_{d a} * f^f{}_{e b} * A_m{}^d * A^{m b} * A_n{}^a * A^{n e}`
ord = [c,f,a,-a,b,-b,d,-d,e,-e,m,-m,n,-n]
g = [0,7,3, 1,9,5, 11,6, 10,4, 13,2, 12,8, 14,15]
The canonical tensor is `T_c = -f^{c a b} * f^{f d e} * A^m{}_a * A_{m d} * A^n{}_b * A_{n e}`
can = [0,2,4, 1,6,8, 10,3, 11,7, 12,5, 13,9, 15,14]
>>> base_f, gens_f = get_symmetric_group_sgs(3, 1) >>> base1, gens1 = get_symmetric_group_sgs(1) >>> base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1) >>> t0 = (base_f, gens_f, 2, 0) >>> t1 = (base_A, gens_A, 4, 0) >>> dummies = [range(2, 10), range(10, 14)] >>> g = Permutation([0, 7, 3, 1, 9, 5, 11, 6, 10, 4, 13, 2, 12, 8, 14, 15]) >>> canonicalize(g, dummies, [0, 0], t0, t1) [0, 2, 4, 1, 6, 8, 10, 3, 11, 7, 12, 5, 13, 9, 15, 14] """ from sympy.combinatorics.testutil import canonicalize_naive if not isinstance(msym, list): if msym not in (0, 1, None): raise ValueError('msym must be 0, 1 or None') num_types = 1 else: num_types = len(msym) if not all(msymx in (0, 1, None) for msymx in msym): raise ValueError('msym entries must be 0, 1 or None') if len(dummies) != num_types: raise ValueError( 'dummies and msym must have the same number of elements') size = g.size num_tensors = 0 v1 = [] for base_i, gens_i, n_i, sym_i in v: # check that the BSGS is minimal; # this property is used in double_coset_can_rep; # if it is not minimal use canonicalize_naive if not _is_minimal_bsgs(base_i, gens_i): mbsgs = get_minimal_bsgs(base_i, gens_i) if not mbsgs: can = canonicalize_naive(g, dummies, msym, *v) return can base_i, gens_i = mbsgs v1.append((base_i, gens_i, [[]] * n_i, sym_i)) num_tensors += n_i
if num_types == 1 and not isinstance(msym, list): dummies = [dummies] msym = [msym] flat_dummies = [] for dumx in dummies: flat_dummies.extend(dumx)
if flat_dummies and flat_dummies != list(range(flat_dummies[0], flat_dummies[-1] + 1)): raise ValueError('dummies is not valid')
# slot symmetry of the tensor size1, sbase, sgens = gens_products(*v1) if size != size1: raise ValueError( 'g has size %d, generators have size %d' % (size, size1)) free = [i for i in range(size - 2) if i not in flat_dummies] num_free = len(free)
# g1 minimal tensor under slot symmetry g1 = canonical_free(sbase, sgens, g, num_free) if not flat_dummies: return g1 # save the sign of g1 sign = 0 if g1[-1] == size - 1 else 1
# the free indices are kept fixed. # Determine free_i, the list of slots of tensors which are fixed # since they are occupied by free indices, which are fixed. start = 0 for i, (base_i, gens_i, n_i, sym_i) in enumerate(v): free_i = [] len_tens = gens_i[0].size - 2 # for each component tensor get a list od fixed islots for j in range(n_i): # get the elements corresponding to the component tensor h = g1[start:(start + len_tens)] fr = [] # get the positions of the fixed elements in h for k in free: if k in h: fr.append(h.index(k)) free_i.append(fr) start += len_tens v1[i] = (base_i, gens_i, free_i, sym_i) # BSGS of the tensor with fixed free indices # if tensor_gens fails in gens_product, use canonicalize_naive size, sbase, sgens = gens_products(*v1)
# reduce the permutations getting rid of the free indices pos_free = [g1.index(x) for x in range(num_free)] size_red = size - num_free g1_red = [x - num_free for x in g1 if x in flat_dummies] if sign: g1_red.extend([size_red - 1, size_red - 2]) else: g1_red.extend([size_red - 2, size_red - 1]) map_slots = _get_map_slots(size, pos_free) sbase_red = [map_slots[i] for i in sbase if i not in pos_free] sgens_red = [_af_new([map_slots[i] for i in y._array_form if i not in pos_free]) for y in sgens] dummies_red = [[x - num_free for x in y] for y in dummies] transv_red = get_transversals(sbase_red, sgens_red) g1_red = _af_new(g1_red) g2 = double_coset_can_rep( dummies_red, msym, sbase_red, sgens_red, transv_red, g1_red) if g2 == 0: return 0 # lift to the case with the free indices g3 = _lift_sgens(size, pos_free, free, g2) return g3
def perm_af_direct_product(gens1, gens2, signed=True): """ Direct products of the generators gens1 and gens2.
Examples ========
>>> from sympy.combinatorics.tensor_can import perm_af_direct_product >>> gens1 = [[1, 0, 2, 3], [0, 1, 3, 2]] >>> gens2 = [[1, 0]] >>> perm_af_direct_product(gens1, gens2, False) [[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]] >>> gens1 = [[1, 0, 2, 3, 5, 4], [0, 1, 3, 2, 4, 5]] >>> gens2 = [[1, 0, 2, 3]] >>> perm_af_direct_product(gens1, gens2, True) [[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]] """ gens1 = [list(x) for x in gens1] gens2 = [list(x) for x in gens2] s = 2 if signed else 0 n1 = len(gens1[0]) - s n2 = len(gens2[0]) - s start = list(range(n1)) end = list(range(n1, n1 + n2)) if signed: gens1 = [gen[:-2] + end + [gen[-2] + n2, gen[-1] + n2] for gen in gens1] gens2 = [start + [x + n1 for x in gen] for gen in gens2] else: gens1 = [gen + end for gen in gens1] gens2 = [start + [x + n1 for x in gen] for gen in gens2]
res = gens1 + gens2
return res
def bsgs_direct_product(base1, gens1, base2, gens2, signed=True): """ Direct product of two BSGS.
Parameters ==========
base1 : base of the first BSGS.
gens1 : strong generating sequence of the first BSGS.
base2, gens2 : similarly for the second BSGS.
signed : flag for signed permutations.
Examples ========
>>> from sympy.combinatorics.tensor_can import (get_symmetric_group_sgs, bsgs_direct_product) >>> base1, gens1 = get_symmetric_group_sgs(1) >>> base2, gens2 = get_symmetric_group_sgs(2) >>> bsgs_direct_product(base1, gens1, base2, gens2) ([1], [(4)(1 2)]) """ s = 2 if signed else 0 n1 = gens1[0].size - s base = list(base1) base += [x + n1 for x in base2] gens1 = [h._array_form for h in gens1] gens2 = [h._array_form for h in gens2] gens = perm_af_direct_product(gens1, gens2, signed) size = len(gens[0]) id_af = list(range(size)) gens = [h for h in gens if h != id_af] if not gens: gens = [id_af] return base, [_af_new(h) for h in gens]
def get_symmetric_group_sgs(n, antisym=False): """ Return base, gens of the minimal BSGS for (anti)symmetric tensor
Parameters ==========
n : rank of the tensor antisym : bool ``antisym = False`` symmetric tensor ``antisym = True`` antisymmetric tensor
Examples ========
>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs >>> get_symmetric_group_sgs(3) ([0, 1], [(4)(0 1), (4)(1 2)]) """ if n == 1: return [], [_af_new(list(range(3)))] gens = [Permutation(n - 1)(i, i + 1)._array_form for i in range(n - 1)] if antisym == 0: gens = [x + [n, n + 1] for x in gens] else: gens = [x + [n + 1, n] for x in gens] base = list(range(n - 1)) return base, [_af_new(h) for h in gens]
riemann_bsgs = [0, 2], [Permutation(0, 1)(4, 5), Permutation(2, 3)(4, 5), Permutation(5)(0, 2)(1, 3)]
def get_transversals(base, gens): """ Return transversals for the group with BSGS base, gens """ if not base: return [] stabs = _distribute_gens_by_base(base, gens) orbits, transversals = _orbits_transversals_from_bsgs(base, stabs) transversals = [{x: h._array_form for x, h in y.items()} for y in transversals] return transversals
def _is_minimal_bsgs(base, gens): """ Check if the BSGS has minimal base under lexigographic order.
base, gens BSGS
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import riemann_bsgs, _is_minimal_bsgs >>> _is_minimal_bsgs(*riemann_bsgs) True >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) >>> _is_minimal_bsgs(*riemann_bsgs1) False """ base1 = [] sgs1 = gens[:] size = gens[0].size for i in range(size): if not all(h._array_form[i] == i for h in sgs1): base1.append(i) sgs1 = [h for h in sgs1 if h._array_form[i] == i] return base1 == base
def get_minimal_bsgs(base, gens): """ Compute a minimal GSGS
base, gens BSGS
If base, gens is a minimal BSGS return it; else return a minimal BSGS if it fails in finding one, it returns None
TODO: use baseswap in the case in which if it fails in finding a minimal BSGS
Examples ========
>>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.tensor_can import get_minimal_bsgs >>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)])) >>> get_minimal_bsgs(*riemann_bsgs1) ([0, 2], [(0 1)(4 5), (5)(0 2)(1 3), (2 3)(4 5)]) """ G = PermutationGroup(gens) base, gens = G.schreier_sims_incremental() if not _is_minimal_bsgs(base, gens): return None return base, gens
def tensor_gens(base, gens, list_free_indices, sym=0): """ Returns size, res_base, res_gens BSGS for n tensors of the same type.
Explanation ===========
base, gens BSGS for tensors of this type list_free_indices list of the slots occupied by fixed indices for each of the tensors
sym symmetry under commutation of two tensors sym None no symmetry sym 0 commuting sym 1 anticommuting
Examples ========
>>> from sympy.combinatorics.tensor_can import tensor_gens, get_symmetric_group_sgs
two symmetric tensors with 3 indices without free indices
>>> base, gens = get_symmetric_group_sgs(3) >>> tensor_gens(base, gens, [[], []]) (8, [0, 1, 3, 4], [(7)(0 1), (7)(1 2), (7)(3 4), (7)(4 5), (7)(0 3)(1 4)(2 5)])
two symmetric tensors with 3 indices with free indices in slot 1 and 0
>>> tensor_gens(base, gens, [[1], [0]]) (8, [0, 4], [(7)(0 2), (7)(4 5)])
four symmetric tensors with 3 indices, two of which with free indices
""" def _get_bsgs(G, base, gens, free_indices): """ return the BSGS for G.pointwise_stabilizer(free_indices) """ if not free_indices: return base[:], gens[:] else: H = G.pointwise_stabilizer(free_indices) base, sgs = H.schreier_sims_incremental() return base, sgs
# if not base there is no slot symmetry for the component tensors # if list_free_indices.count([]) < 2 there is no commutation symmetry # so there is no resulting slot symmetry if not base and list_free_indices.count([]) < 2: n = len(list_free_indices) size = gens[0].size size = n * (size - 2) + 2 return size, [], [_af_new(list(range(size)))]
# if any(list_free_indices) one needs to compute the pointwise # stabilizer, so G is needed if any(list_free_indices): G = PermutationGroup(gens) else: G = None
# no_free list of lists of indices for component tensors without fixed # indices no_free = [] size = gens[0].size id_af = list(range(size)) num_indices = size - 2 if not list_free_indices[0]: no_free.append(list(range(num_indices))) res_base, res_gens = _get_bsgs(G, base, gens, list_free_indices[0]) for i in range(1, len(list_free_indices)): base1, gens1 = _get_bsgs(G, base, gens, list_free_indices[i]) res_base, res_gens = bsgs_direct_product(res_base, res_gens, base1, gens1, 1) if not list_free_indices[i]: no_free.append(list(range(size - 2, size - 2 + num_indices))) size += num_indices nr = size - 2 res_gens = [h for h in res_gens if h._array_form != id_af] # if sym there are no commuting tensors stop here if sym is None or not no_free: if not res_gens: res_gens = [_af_new(id_af)] return size, res_base, res_gens
# if the component tensors have moinimal BSGS, so is their direct # product P; the slot symmetry group is S = P*C, where C is the group # to (anti)commute the component tensors with no free indices # a stabilizer has the property S_i = P_i*C_i; # the BSGS of P*C has SGS_P + SGS_C and the base is # the ordered union of the bases of P and C. # If P has minimal BSGS, so has S with this base. base_comm = [] for i in range(len(no_free) - 1): ind1 = no_free[i] ind2 = no_free[i + 1] a = list(range(ind1[0])) a.extend(ind2) a.extend(ind1) base_comm.append(ind1[0]) a.extend(list(range(ind2[-1] + 1, nr))) if sym == 0: a.extend([nr, nr + 1]) else: a.extend([nr + 1, nr]) res_gens.append(_af_new(a)) res_base = list(res_base) # each base is ordered; order the union of the two bases for i in base_comm: if i not in res_base: res_base.append(i) res_base.sort() if not res_gens: res_gens = [_af_new(id_af)]
return size, res_base, res_gens
def gens_products(*v): """ Returns size, res_base, res_gens BSGS for n tensors of different types.
Explanation ===========
v is a sequence of (base_i, gens_i, free_i, sym_i) where base_i, gens_i BSGS of tensor of type `i` free_i list of the fixed slots for each of the tensors of type `i`; if there are `n_i` tensors of type `i` and none of them have fixed slots, `free = [[]]*n_i` sym 0 (1) if the tensors of type `i` (anti)commute among themselves
Examples ========
>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, gens_products >>> base, gens = get_symmetric_group_sgs(2) >>> gens_products((base, gens, [[], []], 0)) (6, [0, 2], [(5)(0 1), (5)(2 3), (5)(0 2)(1 3)]) >>> gens_products((base, gens, [[1], []], 0)) (6, [2], [(5)(2 3)]) """ res_size, res_base, res_gens = tensor_gens(*v[0]) for i in range(1, len(v)): size, base, gens = tensor_gens(*v[i]) res_base, res_gens = bsgs_direct_product(res_base, res_gens, base, gens, 1) res_size = res_gens[0].size id_af = list(range(res_size)) res_gens = [h for h in res_gens if h != id_af] if not res_gens: res_gens = [id_af] return res_size, res_base, res_gens123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221from sympy.combinatorics.free_groups import free_group, FreeGroupfrom sympy.core import Symbolfrom sympy.testing.pytest import raisesfrom sympy.core.numbers import oo
F, x, y, z = free_group("x, y, z")
def test_FreeGroup__init__(): x, y, z = map(Symbol, "xyz")
assert len(FreeGroup("x, y, z").generators) == 3 assert len(FreeGroup(x).generators) == 1 assert len(FreeGroup(("x", "y", "z"))) == 3 assert len(FreeGroup((x, y, z)).generators) == 3
def test_free_group(): G, a, b, c = free_group("a, b, c") assert F.generators == (x, y, z) assert x*z**2 in F assert x in F assert y*z**-1 in F assert (y*z)**0 in F assert a not in F assert a**0 not in F assert len(F) == 3 assert str(F) == '<free group on the generators (x, y, z)>' assert not F == G assert F.order() is oo assert F.is_abelian == False assert F.center() == {F.identity}
(e,) = free_group("") assert e.order() == 1 assert e.generators == () assert e.elements == {e.identity} assert e.is_abelian == True
def test_FreeGroup__hash__(): assert hash(F)
def test_FreeGroup__eq__(): assert free_group("x, y, z")[0] == free_group("x, y, z")[0] assert free_group("x, y, z")[0] is free_group("x, y, z")[0]
assert free_group("x, y, z")[0] != free_group("a, x, y")[0] assert free_group("x, y, z")[0] is not free_group("a, x, y")[0]
assert free_group("x, y")[0] != free_group("x, y, z")[0] assert free_group("x, y")[0] is not free_group("x, y, z")[0]
assert free_group("x, y, z")[0] != free_group("x, y")[0] assert free_group("x, y, z")[0] is not free_group("x, y")[0]
def test_FreeGroup__getitem__(): assert F[0:] == FreeGroup("x, y, z") assert F[1:] == FreeGroup("y, z") assert F[2:] == FreeGroup("z")
def test_FreeGroupElm__hash__(): assert hash(x*y*z)
def test_FreeGroupElm_copy(): f = x*y*z**3 g = f.copy() h = x*y*z**7
assert f == g assert f != h
def test_FreeGroupElm_inverse(): assert x.inverse() == x**-1 assert (x*y).inverse() == y**-1*x**-1 assert (y*x*y**-1).inverse() == y*x**-1*y**-1 assert (y**2*x**-1).inverse() == x*y**-2
def test_FreeGroupElm_type_error(): raises(TypeError, lambda: 2/x) raises(TypeError, lambda: x**2 + y**2) raises(TypeError, lambda: x/2)
def test_FreeGroupElm_methods(): assert (x**0).order() == 1 assert (y**2).order() is oo assert (x**-1*y).commutator(x) == y**-1*x**-1*y*x assert len(x**2*y**-1) == 3 assert len(x**-1*y**3*z) == 5
def test_FreeGroupElm_eliminate_word(): w = x**5*y*x**2*y**-4*x assert w.eliminate_word( x, x**2 ) == x**10*y*x**4*y**-4*x**2 w3 = x**2*y**3*x**-1*y assert w3.eliminate_word(x, x**2) == x**4*y**3*x**-2*y assert w3.eliminate_word(x, y) == y**5 assert w3.eliminate_word(x, y**4) == y**8 assert w3.eliminate_word(y, x**-1) == x**-3 assert w3.eliminate_word(x, y*z) == y*z*y*z*y**3*z**-1 assert (y**-3).eliminate_word(y, x**-1*z**-1) == z*x*z*x*z*x #assert w3.eliminate_word(x, y*x) == y*x*y*x**2*y*x*y*x*y*x*z**3 #assert w3.eliminate_word(x, x*y) == x*y*x**2*y*x*y*x*y*x*y*z**3
def test_FreeGroupElm_array_form(): assert (x*z).array_form == ((Symbol('x'), 1), (Symbol('z'), 1)) assert (x**2*z*y*x**-2).array_form == \ ((Symbol('x'), 2), (Symbol('z'), 1), (Symbol('y'), 1), (Symbol('x'), -2)) assert (x**-2*y**-1).array_form == ((Symbol('x'), -2), (Symbol('y'), -1))
def test_FreeGroupElm_letter_form(): assert (x**3).letter_form == (Symbol('x'), Symbol('x'), Symbol('x')) assert (x**2*z**-2*x).letter_form == \ (Symbol('x'), Symbol('x'), -Symbol('z'), -Symbol('z'), Symbol('x'))
def test_FreeGroupElm_ext_rep(): assert (x**2*z**-2*x).ext_rep == \ (Symbol('x'), 2, Symbol('z'), -2, Symbol('x'), 1) assert (x**-2*y**-1).ext_rep == (Symbol('x'), -2, Symbol('y'), -1) assert (x*z).ext_rep == (Symbol('x'), 1, Symbol('z'), 1)
def test_FreeGroupElm__mul__pow__(): x1 = x.group.dtype(((Symbol('x'), 1),)) assert x**2 == x1*x
assert (x**2*y*x**-2)**4 == x**2*y**4*x**-2 assert (x**2)**2 == x**4 assert (x**-1)**-1 == x assert (x**-1)**0 == F.identity assert (y**2)**-2 == y**-4
assert x**2*x**-1 == x assert x**2*y**2*y**-1 == x**2*y assert x*x**-1 == F.identity
assert x/x == F.identity assert x/x**2 == x**-1 assert (x**2*y)/(x**2*y**-1) == x**2*y**2*x**-2 assert (x**2*y)/(y**-1*x**2) == x**2*y*x**-2*y
assert x*(x**-1*y*z*y**-1) == y*z*y**-1 assert x**2*(x**-2*y**-1*z**2*y) == y**-1*z**2*y
a = F.identity for n in range(10): assert a == x**n assert a**-1 == x**-n a *= x
def test_FreeGroupElm__len__(): assert len(x**5*y*x**2*y**-4*x) == 13 assert len(x**17) == 17 assert len(y**0) == 0
def test_FreeGroupElm_comparison(): assert not (x*y == y*x) assert x**0 == y**0
assert x**2 < y**3 assert not x**3 < y**2 assert x*y < x**2*y assert x**2*y**2 < y**4 assert not y**4 < y**-4 assert not y**4 < x**-4 assert y**-2 < y**2
assert x**2 <= y**2 assert x**2 <= x**2
assert not y*z > z*y assert x > x**-1
assert not x**2 >= y**2
def test_FreeGroupElm_syllables(): w = x**5*y*x**2*y**-4*x assert w.number_syllables() == 5 assert w.exponent_syllable(2) == 2 assert w.generator_syllable(3) == Symbol('y') assert w.sub_syllables(1, 2) == y assert w.sub_syllables(3, 3) == F.identity
def test_FreeGroup_exponents(): w1 = x**2*y**3 assert w1.exponent_sum(x) == 2 assert w1.exponent_sum(x**-1) == -2 assert w1.generator_count(x) == 2
w2 = x**2*y**4*x**-3 assert w2.exponent_sum(x) == -1 assert w2.generator_count(x) == 5
def test_FreeGroup_generators(): assert (x**2*y**4*z**-1).contains_generators() == {x, y, z} assert (x**-1*y**3).contains_generators() == {x, y}
def test_FreeGroupElm_words(): w = x**5*y*x**2*y**-4*x assert w.subword(2, 6) == x**3*y assert w.subword(3, 2) == F.identity assert w.subword(6, 10) == x**2*y**-2
assert w.substituted_word(0, 7, y**-1) == y**-1*x*y**-4*x assert w.substituted_word(0, 7, y**2*x) == y**2*x**2*y**-4*x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105from sympy.combinatorics.generators import symmetric, cyclic, alternating, \ dihedral, rubikfrom sympy.combinatorics.permutations import Permutationfrom sympy.testing.pytest import raises
def test_generators():
assert list(cyclic(6)) == [ Permutation([0, 1, 2, 3, 4, 5]), Permutation([1, 2, 3, 4, 5, 0]), Permutation([2, 3, 4, 5, 0, 1]), Permutation([3, 4, 5, 0, 1, 2]), Permutation([4, 5, 0, 1, 2, 3]), Permutation([5, 0, 1, 2, 3, 4])]
assert list(cyclic(10)) == [ Permutation([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), Permutation([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]), Permutation([2, 3, 4, 5, 6, 7, 8, 9, 0, 1]), Permutation([3, 4, 5, 6, 7, 8, 9, 0, 1, 2]), Permutation([4, 5, 6, 7, 8, 9, 0, 1, 2, 3]), Permutation([5, 6, 7, 8, 9, 0, 1, 2, 3, 4]), Permutation([6, 7, 8, 9, 0, 1, 2, 3, 4, 5]), Permutation([7, 8, 9, 0, 1, 2, 3, 4, 5, 6]), Permutation([8, 9, 0, 1, 2, 3, 4, 5, 6, 7]), Permutation([9, 0, 1, 2, 3, 4, 5, 6, 7, 8])]
assert list(alternating(4)) == [ Permutation([0, 1, 2, 3]), Permutation([0, 2, 3, 1]), Permutation([0, 3, 1, 2]), Permutation([1, 0, 3, 2]), Permutation([1, 2, 0, 3]), Permutation([1, 3, 2, 0]), Permutation([2, 0, 1, 3]), Permutation([2, 1, 3, 0]), Permutation([2, 3, 0, 1]), Permutation([3, 0, 2, 1]), Permutation([3, 1, 0, 2]), Permutation([3, 2, 1, 0])]
assert list(symmetric(3)) == [ Permutation([0, 1, 2]), Permutation([0, 2, 1]), Permutation([1, 0, 2]), Permutation([1, 2, 0]), Permutation([2, 0, 1]), Permutation([2, 1, 0])]
assert list(symmetric(4)) == [ Permutation([0, 1, 2, 3]), Permutation([0, 1, 3, 2]), Permutation([0, 2, 1, 3]), Permutation([0, 2, 3, 1]), Permutation([0, 3, 1, 2]), Permutation([0, 3, 2, 1]), Permutation([1, 0, 2, 3]), Permutation([1, 0, 3, 2]), Permutation([1, 2, 0, 3]), Permutation([1, 2, 3, 0]), Permutation([1, 3, 0, 2]), Permutation([1, 3, 2, 0]), Permutation([2, 0, 1, 3]), Permutation([2, 0, 3, 1]), Permutation([2, 1, 0, 3]), Permutation([2, 1, 3, 0]), Permutation([2, 3, 0, 1]), Permutation([2, 3, 1, 0]), Permutation([3, 0, 1, 2]), Permutation([3, 0, 2, 1]), Permutation([3, 1, 0, 2]), Permutation([3, 1, 2, 0]), Permutation([3, 2, 0, 1]), Permutation([3, 2, 1, 0])]
assert list(dihedral(1)) == [ Permutation([0, 1]), Permutation([1, 0])]
assert list(dihedral(2)) == [ Permutation([0, 1, 2, 3]), Permutation([1, 0, 3, 2]), Permutation([2, 3, 0, 1]), Permutation([3, 2, 1, 0])]
assert list(dihedral(3)) == [ Permutation([0, 1, 2]), Permutation([2, 1, 0]), Permutation([1, 2, 0]), Permutation([0, 2, 1]), Permutation([2, 0, 1]), Permutation([1, 0, 2])]
assert list(dihedral(5)) == [ Permutation([0, 1, 2, 3, 4]), Permutation([4, 3, 2, 1, 0]), Permutation([1, 2, 3, 4, 0]), Permutation([0, 4, 3, 2, 1]), Permutation([2, 3, 4, 0, 1]), Permutation([1, 0, 4, 3, 2]), Permutation([3, 4, 0, 1, 2]), Permutation([2, 1, 0, 4, 3]), Permutation([4, 0, 1, 2, 3]), Permutation([3, 2, 1, 0, 4])]
raises(ValueError, lambda: rubik(1))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from sympy.combinatorics.graycode import (GrayCode, bin_to_gray, random_bitstring, get_subset_from_bitstring, graycode_subsets, gray_to_bin)from sympy.testing.pytest import raises
def test_graycode(): g = GrayCode(2) got = [] for i in g.generate_gray(): if i.startswith('0'): g.skip() got.append(i) assert got == '00 11 10'.split() a = GrayCode(6) assert a.current == '0'*6 assert a.rank == 0 assert len(list(a.generate_gray())) == 64 codes = ['011001', '011011', '011010', '011110', '011111', '011101', '011100', '010100', '010101', '010111', '010110', '010010', '010011', '010001', '010000', '110000', '110001', '110011', '110010', '110110', '110111', '110101', '110100', '111100', '111101', '111111', '111110', '111010', '111011', '111001', '111000', '101000', '101001', '101011', '101010', '101110', '101111', '101101', '101100', '100100', '100101', '100111', '100110', '100010', '100011', '100001', '100000'] assert list(a.generate_gray(start='011001')) == codes assert list( a.generate_gray(rank=GrayCode(6, start='011001').rank)) == codes assert a.next().current == '000001' assert a.next(2).current == '000011' assert a.next(-1).current == '100000'
a = GrayCode(5, start='10010') assert a.rank == 28 a = GrayCode(6, start='101000') assert a.rank == 48
assert GrayCode(6, rank=4).current == '000110' assert GrayCode(6, rank=4).rank == 4 assert [GrayCode(4, start=s).rank for s in GrayCode(4).generate_gray()] == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] a = GrayCode(15, rank=15) assert a.current == '000000000001000'
assert bin_to_gray('111') == '100'
a = random_bitstring(5) assert type(a) is str assert len(a) == 5 assert all(i in ['0', '1'] for i in a)
assert get_subset_from_bitstring( ['a', 'b', 'c', 'd'], '0011') == ['c', 'd'] assert get_subset_from_bitstring('abcd', '1001') == ['a', 'd'] assert list(graycode_subsets(['a', 'b', 'c'])) == \ [[], ['c'], ['b', 'c'], ['b'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'c'], ['a']]
raises(ValueError, lambda: GrayCode(0)) raises(ValueError, lambda: GrayCode(2.2)) raises(ValueError, lambda: GrayCode(2, start=[1, 1, 0])) raises(ValueError, lambda: GrayCode(2, rank=2.5)) raises(ValueError, lambda: get_subset_from_bitstring(['c', 'a', 'c'], '1100')) raises(ValueError, lambda: list(GrayCode(3).generate_gray(start="1111")))
def test_live_issue_117(): assert bin_to_gray('0100') == '0110' assert bin_to_gray('0101') == '0111' for bits in ('0100', '0101'): assert gray_to_bin(bin_to_gray(bits)) == bits123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110from sympy.combinatorics.group_numbers import (is_nilpotent_number, is_abelian_number, is_cyclic_number, _holder_formula, groups_count)from sympy.ntheory.factor_ import factorintfrom sympy.ntheory.generate import primefrom sympy.testing.pytest import raisesfrom sympy import randprime
def test_is_nilpotent_number(): assert is_nilpotent_number(21) == False assert is_nilpotent_number(randprime(1, 30)**12) == True raises(ValueError, lambda: is_nilpotent_number(-5))
A056867 = [1, 2, 3, 4, 5, 7, 8, 9, 11, 13, 15, 16, 17, 19, 23, 25, 27, 29, 31, 32, 33, 35, 37, 41, 43, 45, 47, 49, 51, 53, 59, 61, 64, 65, 67, 69, 71, 73, 77, 79, 81, 83, 85, 87, 89, 91, 95, 97, 99] for n in range(1, 100): assert is_nilpotent_number(n) == (n in A056867)
def test_is_abelian_number(): assert is_abelian_number(4) == True assert is_abelian_number(randprime(1, 2000)**2) == True assert is_abelian_number(randprime(1000, 100000)) == True assert is_abelian_number(60) == False assert is_abelian_number(24) == False raises(ValueError, lambda: is_abelian_number(-5))
A051532 = [1, 2, 3, 4, 5, 7, 9, 11, 13, 15, 17, 19, 23, 25, 29, 31, 33, 35, 37, 41, 43, 45, 47, 49, 51, 53, 59, 61, 65, 67, 69, 71, 73, 77, 79, 83, 85, 87, 89, 91, 95, 97, 99] for n in range(1, 100): assert is_abelian_number(n) == (n in A051532)
A003277 = [1, 2, 3, 5, 7, 11, 13, 15, 17, 19, 23, 29, 31, 33, 35, 37, 41, 43, 47, 51, 53, 59, 61, 65, 67, 69, 71, 73, 77, 79, 83, 85, 87, 89, 91, 95, 97]
def test_is_cyclic_number(): assert is_cyclic_number(15) == True assert is_cyclic_number(randprime(1, 2000)**2) == False assert is_cyclic_number(randprime(1000, 100000)) == True assert is_cyclic_number(4) == False raises(ValueError, lambda: is_cyclic_number(-5))
for n in range(1, 100): assert is_cyclic_number(n) == (n in A003277)
def test_holder_formula(): # semiprime assert _holder_formula({3, 5}) == 1 assert _holder_formula({5, 11}) == 2 # n in A003277 is always 1 for n in A003277: assert _holder_formula(set(factorint(n).keys())) == 1 # otherwise assert _holder_formula({2, 3, 5, 7}) == 12
def test_groups_count(): A000001 = [0, 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51, 1, 2, 1, 14, 1, 2, 2, 14, 1, 6, 1, 4, 2, 2, 1, 52, 2, 5, 1, 5, 1, 15, 2, 13, 2, 2, 1, 13, 1, 2, 4, 267, 1, 4, 1, 5, 1, 4, 1, 50, 1, 2, 3, 4, 1, 6, 1, 52, 15, 2, 1, 15, 1, 2, 1, 12, 1, 10, 1, 4, 2] for n in range(1, len(A000001)): try: assert groups_count(n) == A000001[n] except ValueError: pass
A000679 = [1, 1, 2, 5, 14, 51, 267, 2328, 56092, 10494213, 49487367289] for e in range(1, len(A000679)): assert groups_count(2**e) == A000679[e]
A090091 = [1, 1, 2, 5, 15, 67, 504, 9310, 1396077, 5937876645] for e in range(1, len(A090091)): assert groups_count(3**e) == A090091[e]
A090130 = [1, 1, 2, 5, 15, 77, 684, 34297] for e in range(1, len(A090130)): assert groups_count(5**e) == A090130[e]
A090140 = [1, 1, 2, 5, 15, 83, 860, 113147] for e in range(1, len(A090140)): assert groups_count(7**e) == A090140[e]
A232105 = [51, 67, 77, 83, 87, 97, 101, 107, 111, 125, 131, 145, 149, 155, 159, 173, 183, 193, 203, 207, 217] for i in range(len(A232105)): assert groups_count(prime(i+1)**5) == A232105[i]
A232106 = [267, 504, 684, 860, 1192, 1476, 1944, 2264, 2876, 4068, 4540, 6012, 7064, 7664, 8852, 10908, 13136] for i in range(len(A232106)): assert groups_count(prime(i+1)**6) == A232106[i]
A232107 = [2328, 9310, 34297, 113147, 750735, 1600573, 5546909, 9380741, 23316851, 71271069, 98488755] for i in range(len(A232107)): assert groups_count(prime(i+1)**7) == A232107[i]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114from sympy.combinatorics import Permutationfrom sympy.combinatorics.perm_groups import PermutationGroupfrom sympy.combinatorics.homomorphisms import homomorphism, group_isomorphism, is_isomorphicfrom sympy.combinatorics.free_groups import free_groupfrom sympy.combinatorics.fp_groups import FpGroupfrom sympy.combinatorics.named_groups import AlternatingGroup, DihedralGroup, CyclicGroupfrom sympy.testing.pytest import raises
def test_homomorphism(): # FpGroup -> PermutationGroup F, a, b = free_group("a, b") G = FpGroup(F, [a**3, b**3, (a*b)**2])
c = Permutation(3)(0, 1, 2) d = Permutation(3)(1, 2, 3) A = AlternatingGroup(4) T = homomorphism(G, A, [a, b], [c, d]) assert T(a*b**2*a**-1) == c*d**2*c**-1 assert T.is_isomorphism() assert T(T.invert(Permutation(3)(0, 2, 3))) == Permutation(3)(0, 2, 3)
T = homomorphism(G, AlternatingGroup(4), G.generators) assert T.is_trivial() assert T.kernel().order() == G.order()
E, e = free_group("e") G = FpGroup(E, [e**8]) P = PermutationGroup([Permutation(0, 1, 2, 3), Permutation(0, 2)]) T = homomorphism(G, P, [e], [Permutation(0, 1, 2, 3)]) assert T.image().order() == 4 assert T(T.invert(Permutation(0, 2)(1, 3))) == Permutation(0, 2)(1, 3)
T = homomorphism(E, AlternatingGroup(4), E.generators, [c]) assert T.invert(c**2) == e**-1 #order(c) == 3 so c**2 == c**-1
# FreeGroup -> FreeGroup T = homomorphism(F, E, [a], [e]) assert T(a**-2*b**4*a**2).is_identity
# FreeGroup -> FpGroup G = FpGroup(F, [a*b*a**-1*b**-1]) T = homomorphism(F, G, F.generators, G.generators) assert T.invert(a**-1*b**-1*a**2) == a*b**-1
# PermutationGroup -> PermutationGroup D = DihedralGroup(8) p = Permutation(0, 1, 2, 3, 4, 5, 6, 7) P = PermutationGroup(p) T = homomorphism(P, D, [p], [p]) assert T.is_injective() assert not T.is_isomorphism() assert T.invert(p**3) == p**3
T2 = homomorphism(F, P, [F.generators[0]], P.generators) T = T.compose(T2) assert T.domain == F assert T.codomain == D assert T(a*b) == p
D3 = DihedralGroup(3) T = homomorphism(D3, D3, D3.generators, D3.generators) assert T.is_isomorphism()
def test_isomorphisms():
F, a, b = free_group("a, b") E, c, d = free_group("c, d") # Infinite groups with differently ordered relators. G = FpGroup(F, [a**2, b**3]) H = FpGroup(F, [b**3, a**2]) assert is_isomorphic(G, H)
# Trivial Case # FpGroup -> FpGroup H = FpGroup(F, [a**3, b**3, (a*b)**2]) F, c, d = free_group("c, d") G = FpGroup(F, [c**3, d**3, (c*d)**2]) check, T = group_isomorphism(G, H) assert check assert T(c**3*d**2) == a**3*b**2
# FpGroup -> PermutationGroup # FpGroup is converted to the equivalent isomorphic group. F, a, b = free_group("a, b") G = FpGroup(F, [a**3, b**3, (a*b)**2]) H = AlternatingGroup(4) check, T = group_isomorphism(G, H) assert check assert T(b*a*b**-1*a**-1*b**-1) == Permutation(0, 2, 3) assert T(b*a*b*a**-1*b**-1) == Permutation(0, 3, 2)
# PermutationGroup -> PermutationGroup D = DihedralGroup(8) p = Permutation(0, 1, 2, 3, 4, 5, 6, 7) P = PermutationGroup(p) assert not is_isomorphic(D, P)
A = CyclicGroup(5) B = CyclicGroup(7) assert not is_isomorphic(A, B)
# Two groups of the same prime order are isomorphic to each other. G = FpGroup(F, [a, b**5]) H = CyclicGroup(5) assert G.order() == H.order() assert is_isomorphic(G, H)
def test_check_homomorphism(): a = Permutation(1,2,3,4) b = Permutation(1,3) G = PermutationGroup([a, b]) raises(ValueError, lambda: homomorphism(G, G, [a], [a]))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243from sympy.core.containers import Tuplefrom sympy.combinatorics.generators import rubik_cube_generatorsfrom sympy.combinatorics.homomorphisms import is_isomorphicfrom sympy.combinatorics.named_groups import SymmetricGroup, CyclicGroup,\ DihedralGroup, AlternatingGroup, AbelianGroup, RubikGroupfrom sympy.combinatorics.perm_groups import (PermutationGroup, _orbit_transversal, Coset, SymmetricPermutationGroup)from sympy.combinatorics.permutations import Permutationfrom sympy.combinatorics.polyhedron import tetrahedron as Tetra, cubefrom sympy.combinatorics.testutil import _verify_bsgs, _verify_centralizer,\ _verify_normal_closurefrom sympy.testing.pytest import skip, XFAIL, slow
rmul = Permutation.rmul
def test_has(): a = Permutation([1, 0]) G = PermutationGroup([a]) assert G.is_abelian a = Permutation([2, 0, 1]) b = Permutation([2, 1, 0]) G = PermutationGroup([a, b]) assert not G.is_abelian
G = PermutationGroup([a]) assert G.has(a) assert not G.has(b)
a = Permutation([2, 0, 1, 3, 4, 5]) b = Permutation([0, 2, 1, 3, 4]) assert PermutationGroup(a, b).degree == \ PermutationGroup(a, b).degree == 6
g = PermutationGroup(Permutation(0, 2, 1)) assert Tuple(1, g).has(g)
def test_generate(): a = Permutation([1, 0]) g = list(PermutationGroup([a]).generate()) assert g == [Permutation([0, 1]), Permutation([1, 0])] assert len(list(PermutationGroup(Permutation((0, 1))).generate())) == 1 g = PermutationGroup([a]).generate(method='dimino') assert list(g) == [Permutation([0, 1]), Permutation([1, 0])] a = Permutation([2, 0, 1]) b = Permutation([2, 1, 0]) G = PermutationGroup([a, b]) g = G.generate() v1 = [p.array_form for p in list(g)] v1.sort() assert v1 == [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] v2 = list(G.generate(method='dimino', af=True)) assert v1 == sorted(v2) a = Permutation([2, 0, 1, 3, 4, 5]) b = Permutation([2, 1, 3, 4, 5, 0]) g = PermutationGroup([a, b]).generate(af=True) assert len(list(g)) == 360
def test_order(): a = Permutation([2, 0, 1, 3, 4, 5, 6, 7, 8, 9]) b = Permutation([2, 1, 3, 4, 5, 6, 7, 8, 9, 0]) g = PermutationGroup([a, b]) assert g.order() == 1814400 assert PermutationGroup().order() == 1
def test_equality(): p_1 = Permutation(0, 1, 3) p_2 = Permutation(0, 2, 3) p_3 = Permutation(0, 1, 2) p_4 = Permutation(0, 1, 3) g_1 = PermutationGroup(p_1, p_2) g_2 = PermutationGroup(p_3, p_4) g_3 = PermutationGroup(p_2, p_1) g_4 = PermutationGroup(p_1, p_2)
assert g_1 != g_2 assert g_1.generators != g_2.generators assert g_1.equals(g_2) assert g_1 != g_3 assert g_1.equals(g_3) assert g_1 == g_4
def test_stabilizer(): S = SymmetricGroup(2) H = S.stabilizer(0) assert H.generators == [Permutation(1)] a = Permutation([2, 0, 1, 3, 4, 5]) b = Permutation([2, 1, 3, 4, 5, 0]) G = PermutationGroup([a, b]) G0 = G.stabilizer(0) assert G0.order() == 60
gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] gens = [Permutation(p) for p in gens_cube] G = PermutationGroup(gens) G2 = G.stabilizer(2) assert G2.order() == 6 G2_1 = G2.stabilizer(1) v = list(G2_1.generate(af=True)) assert v == [[0, 1, 2, 3, 4, 5, 6, 7], [3, 1, 2, 0, 7, 5, 6, 4]]
gens = ( (1, 2, 0, 4, 5, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19), (0, 1, 2, 3, 4, 5, 19, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 7, 17, 18), (0, 1, 2, 3, 4, 5, 6, 7, 9, 18, 16, 11, 12, 13, 14, 15, 8, 17, 10, 19)) gens = [Permutation(p) for p in gens] G = PermutationGroup(gens) G2 = G.stabilizer(2) assert G2.order() == 181440 S = SymmetricGroup(3) assert [G.order() for G in S.basic_stabilizers] == [6, 2]
def test_center(): # the center of the dihedral group D_n is of order 2 for even n for i in (4, 6, 10): D = DihedralGroup(i) assert (D.center()).order() == 2 # the center of the dihedral group D_n is of order 1 for odd n>2 for i in (3, 5, 7): D = DihedralGroup(i) assert (D.center()).order() == 1 # the center of an abelian group is the group itself for i in (2, 3, 5): for j in (1, 5, 7): for k in (1, 1, 11): G = AbelianGroup(i, j, k) assert G.center().is_subgroup(G) # the center of a nonabelian simple group is trivial for i in(1, 5, 9): A = AlternatingGroup(i) assert (A.center()).order() == 1 # brute-force verifications D = DihedralGroup(5) A = AlternatingGroup(3) C = CyclicGroup(4) G.is_subgroup(D*A*C) assert _verify_centralizer(G, G)
def test_centralizer(): # the centralizer of the trivial group is the entire group S = SymmetricGroup(2) assert S.centralizer(Permutation(list(range(2)))).is_subgroup(S) A = AlternatingGroup(5) assert A.centralizer(Permutation(list(range(5)))).is_subgroup(A) # a centralizer in the trivial group is the trivial group itself triv = PermutationGroup([Permutation([0, 1, 2, 3])]) D = DihedralGroup(4) assert triv.centralizer(D).is_subgroup(triv) # brute-force verifications for centralizers of groups for i in (4, 5, 6): S = SymmetricGroup(i) A = AlternatingGroup(i) C = CyclicGroup(i) D = DihedralGroup(i) for gp in (S, A, C, D): for gp2 in (S, A, C, D): if not gp2.is_subgroup(gp): assert _verify_centralizer(gp, gp2) # verify the centralizer for all elements of several groups S = SymmetricGroup(5) elements = list(S.generate_dimino()) for element in elements: assert _verify_centralizer(S, element) A = AlternatingGroup(5) elements = list(A.generate_dimino()) for element in elements: assert _verify_centralizer(A, element) D = DihedralGroup(7) elements = list(D.generate_dimino()) for element in elements: assert _verify_centralizer(D, element) # verify centralizers of small groups within small groups small = [] for i in (1, 2, 3): small.append(SymmetricGroup(i)) small.append(AlternatingGroup(i)) small.append(DihedralGroup(i)) small.append(CyclicGroup(i)) for gp in small: for gp2 in small: if gp.degree == gp2.degree: assert _verify_centralizer(gp, gp2)
def test_coset_rank(): gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] gens = [Permutation(p) for p in gens_cube] G = PermutationGroup(gens) i = 0 for h in G.generate(af=True): rk = G.coset_rank(h) assert rk == i h1 = G.coset_unrank(rk, af=True) assert h == h1 i += 1 assert G.coset_unrank(48) is None assert G.coset_unrank(G.coset_rank(gens[0])) == gens[0]
def test_coset_factor(): a = Permutation([0, 2, 1]) G = PermutationGroup([a]) c = Permutation([2, 1, 0]) assert not G.coset_factor(c) assert G.coset_rank(c) is None
a = Permutation([2, 0, 1, 3, 4, 5]) b = Permutation([2, 1, 3, 4, 5, 0]) g = PermutationGroup([a, b]) assert g.order() == 360 d = Permutation([1, 0, 2, 3, 4, 5]) assert not g.coset_factor(d.array_form) assert not g.contains(d) assert Permutation(2) in G c = Permutation([1, 0, 2, 3, 5, 4]) v = g.coset_factor(c, True) tr = g.basic_transversals p = Permutation.rmul(*[tr[i][v[i]] for i in range(len(g.base))]) assert p == c v = g.coset_factor(c) p = Permutation.rmul(*v) assert p == c assert g.contains(c) G = PermutationGroup([Permutation([2, 1, 0])]) p = Permutation([1, 0, 2]) assert G.coset_factor(p) == []
def test_orbits(): a = Permutation([2, 0, 1]) b = Permutation([2, 1, 0]) g = PermutationGroup([a, b]) assert g.orbit(0) == {0, 1, 2} assert g.orbits() == [{0, 1, 2}] assert g.is_transitive() and g.is_transitive(strict=False) assert g.orbit_transversal(0) == \ [Permutation( [0, 1, 2]), Permutation([2, 0, 1]), Permutation([1, 2, 0])] assert g.orbit_transversal(0, True) == \ [(0, Permutation([0, 1, 2])), (2, Permutation([2, 0, 1])), (1, Permutation([1, 2, 0]))]
G = DihedralGroup(6) transversal, slps = _orbit_transversal(G.degree, G.generators, 0, True, slp=True) for i, t in transversal: slp = slps[i] w = G.identity for s in slp: w = G.generators[s]*w assert w == t
a = Permutation(list(range(1, 100)) + [0]) G = PermutationGroup([a]) assert [min(o) for o in G.orbits()] == [0] G = PermutationGroup(rubik_cube_generators()) assert [min(o) for o in G.orbits()] == [0, 1] assert not G.is_transitive() and not G.is_transitive(strict=False) G = PermutationGroup([Permutation(0, 1, 3), Permutation(3)(0, 1)]) assert not G.is_transitive() and G.is_transitive(strict=False) assert PermutationGroup( Permutation(3)).is_transitive(strict=False) is False
def test_is_normal(): gens_s5 = [Permutation(p) for p in [[1, 2, 3, 4, 0], [2, 1, 4, 0, 3]]] G1 = PermutationGroup(gens_s5) assert G1.order() == 120 gens_a5 = [Permutation(p) for p in [[1, 0, 3, 2, 4], [2, 1, 4, 3, 0]]] G2 = PermutationGroup(gens_a5) assert G2.order() == 60 assert G2.is_normal(G1) gens3 = [Permutation(p) for p in [[2, 1, 3, 0, 4], [1, 2, 0, 3, 4]]] G3 = PermutationGroup(gens3) assert not G3.is_normal(G1) assert G3.order() == 12 G4 = G1.normal_closure(G3.generators) assert G4.order() == 60 gens5 = [Permutation(p) for p in [[1, 2, 3, 0, 4], [1, 2, 0, 3, 4]]] G5 = PermutationGroup(gens5) assert G5.order() == 24 G6 = G1.normal_closure(G5.generators) assert G6.order() == 120 assert G1.is_subgroup(G6) assert not G1.is_subgroup(G4) assert G2.is_subgroup(G4) I5 = PermutationGroup(Permutation(4)) assert I5.is_normal(G5) assert I5.is_normal(G6, strict=False) p1 = Permutation([1, 0, 2, 3, 4]) p2 = Permutation([0, 1, 2, 4, 3]) p3 = Permutation([3, 4, 2, 1, 0]) id_ = Permutation([0, 1, 2, 3, 4]) H = PermutationGroup([p1, p3]) H_n1 = PermutationGroup([p1, p2]) H_n2_1 = PermutationGroup(p1) H_n2_2 = PermutationGroup(p2) H_id = PermutationGroup(id_) assert H_n1.is_normal(H) assert H_n2_1.is_normal(H_n1) assert H_n2_2.is_normal(H_n1) assert H_id.is_normal(H_n2_1) assert H_id.is_normal(H_n1) assert H_id.is_normal(H) assert not H_n2_1.is_normal(H) assert not H_n2_2.is_normal(H)
def test_eq(): a = [[1, 2, 0, 3, 4, 5], [1, 0, 2, 3, 4, 5], [2, 1, 0, 3, 4, 5], [ 1, 2, 0, 3, 4, 5]] a = [Permutation(p) for p in a + [[1, 2, 3, 4, 5, 0]]] g = Permutation([1, 2, 3, 4, 5, 0]) G1, G2, G3 = [PermutationGroup(x) for x in [a[:2], a[2:4], [g, g**2]]] assert G1.order() == G2.order() == G3.order() == 6 assert G1.is_subgroup(G2) assert not G1.is_subgroup(G3) G4 = PermutationGroup([Permutation([0, 1])]) assert not G1.is_subgroup(G4) assert G4.is_subgroup(G1, 0) assert PermutationGroup(g, g).is_subgroup(PermutationGroup(g)) assert SymmetricGroup(3).is_subgroup(SymmetricGroup(4), 0) assert SymmetricGroup(3).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0) assert not CyclicGroup(5).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0) assert CyclicGroup(3).is_subgroup(SymmetricGroup(3)*CyclicGroup(5), 0)
def test_derived_subgroup(): a = Permutation([1, 0, 2, 4, 3]) b = Permutation([0, 1, 3, 2, 4]) G = PermutationGroup([a, b]) C = G.derived_subgroup() assert C.order() == 3 assert C.is_normal(G) assert C.is_subgroup(G, 0) assert not G.is_subgroup(C, 0) gens_cube = [[1, 3, 5, 7, 0, 2, 4, 6], [1, 3, 0, 2, 5, 7, 4, 6]] gens = [Permutation(p) for p in gens_cube] G = PermutationGroup(gens) C = G.derived_subgroup() assert C.order() == 12
def test_is_solvable(): a = Permutation([1, 2, 0]) b = Permutation([1, 0, 2]) G = PermutationGroup([a, b]) assert G.is_solvable G = PermutationGroup([a]) assert G.is_solvable a = Permutation([1, 2, 3, 4, 0]) b = Permutation([1, 0, 2, 3, 4]) G = PermutationGroup([a, b]) assert not G.is_solvable P = SymmetricGroup(10) S = P.sylow_subgroup(3) assert S.is_solvable
def test_rubik1(): gens = rubik_cube_generators() gens1 = [gens[-1]] + [p**2 for p in gens[1:]] G1 = PermutationGroup(gens1) assert G1.order() == 19508428800 gens2 = [p**2 for p in gens] G2 = PermutationGroup(gens2) assert G2.order() == 663552 assert G2.is_subgroup(G1, 0) C1 = G1.derived_subgroup() assert C1.order() == 4877107200 assert C1.is_subgroup(G1, 0) assert not G2.is_subgroup(C1, 0)
G = RubikGroup(2) assert G.order() == 3674160
@XFAILdef test_rubik(): skip('takes too much time') G = PermutationGroup(rubik_cube_generators()) assert G.order() == 43252003274489856000 G1 = PermutationGroup(G[:3]) assert G1.order() == 170659735142400 assert not G1.is_normal(G) G2 = G.normal_closure(G1.generators) assert G2.is_subgroup(G)
def test_direct_product(): C = CyclicGroup(4) D = DihedralGroup(4) G = C*C*C assert G.order() == 64 assert G.degree == 12 assert len(G.orbits()) == 3 assert G.is_abelian is True H = D*C assert H.order() == 32 assert H.is_abelian is False
def test_orbit_rep(): G = DihedralGroup(6) assert G.orbit_rep(1, 3) in [Permutation([2, 3, 4, 5, 0, 1]), Permutation([4, 3, 2, 1, 0, 5])] H = CyclicGroup(4)*G assert H.orbit_rep(1, 5) is False
def test_schreier_vector(): G = CyclicGroup(50) v = [0]*50 v[23] = -1 assert G.schreier_vector(23) == v H = DihedralGroup(8) assert H.schreier_vector(2) == [0, 1, -1, 0, 0, 1, 0, 0] L = SymmetricGroup(4) assert L.schreier_vector(1) == [1, -1, 0, 0]
def test_random_pr(): D = DihedralGroup(6) r = 11 n = 3 _random_prec_n = {} _random_prec_n[0] = {'s': 7, 't': 3, 'x': 2, 'e': -1} _random_prec_n[1] = {'s': 5, 't': 5, 'x': 1, 'e': -1} _random_prec_n[2] = {'s': 3, 't': 4, 'x': 2, 'e': 1} D._random_pr_init(r, n, _random_prec_n=_random_prec_n) assert D._random_gens[11] == [0, 1, 2, 3, 4, 5] _random_prec = {'s': 2, 't': 9, 'x': 1, 'e': -1} assert D.random_pr(_random_prec=_random_prec) == \ Permutation([0, 5, 4, 3, 2, 1])
def test_is_alt_sym(): G = DihedralGroup(10) assert G.is_alt_sym() is False assert G._eval_is_alt_sym_naive() is False assert G._eval_is_alt_sym_naive(only_alt=True) is False assert G._eval_is_alt_sym_naive(only_sym=True) is False
S = SymmetricGroup(10) assert S._eval_is_alt_sym_naive() is True assert S._eval_is_alt_sym_naive(only_alt=True) is False assert S._eval_is_alt_sym_naive(only_sym=True) is True
N_eps = 10 _random_prec = {'N_eps': N_eps, 0: Permutation([[2], [1, 4], [0, 6, 7, 8, 9, 3, 5]]), 1: Permutation([[1, 8, 7, 6, 3, 5, 2, 9], [0, 4]]), 2: Permutation([[5, 8], [4, 7], [0, 1, 2, 3, 6, 9]]), 3: Permutation([[3], [0, 8, 2, 7, 4, 1, 6, 9, 5]]), 4: Permutation([[8], [4, 7, 9], [3, 6], [0, 5, 1, 2]]), 5: Permutation([[6], [0, 2, 4, 5, 1, 8, 3, 9, 7]]), 6: Permutation([[6, 9, 8], [4, 5], [1, 3, 7], [0, 2]]), 7: Permutation([[4], [0, 2, 9, 1, 3, 8, 6, 5, 7]]), 8: Permutation([[1, 5, 6, 3], [0, 2, 7, 8, 4, 9]]), 9: Permutation([[8], [6, 7], [2, 3, 4, 5], [0, 1, 9]])} assert S.is_alt_sym(_random_prec=_random_prec) is True
A = AlternatingGroup(10) assert A._eval_is_alt_sym_naive() is True assert A._eval_is_alt_sym_naive(only_alt=True) is True assert A._eval_is_alt_sym_naive(only_sym=True) is False
_random_prec = {'N_eps': N_eps, 0: Permutation([[1, 6, 4, 2, 7, 8, 5, 9, 3], [0]]), 1: Permutation([[1], [0, 5, 8, 4, 9, 2, 3, 6, 7]]), 2: Permutation([[1, 9, 8, 3, 2, 5], [0, 6, 7, 4]]), 3: Permutation([[6, 8, 9], [4, 5], [1, 3, 7, 2], [0]]), 4: Permutation([[8], [5], [4], [2, 6, 9, 3], [1], [0, 7]]), 5: Permutation([[3, 6], [0, 8, 1, 7, 5, 9, 4, 2]]), 6: Permutation([[5], [2, 9], [1, 8, 3], [0, 4, 7, 6]]), 7: Permutation([[1, 8, 4, 7, 2, 3], [0, 6, 9, 5]]), 8: Permutation([[5, 8, 7], [3], [1, 4, 2, 6], [0, 9]]), 9: Permutation([[4, 9, 6], [3, 8], [1, 2], [0, 5, 7]])} assert A.is_alt_sym(_random_prec=_random_prec) is False
G = PermutationGroup( Permutation(1, 3, size=8)(0, 2, 4, 6), Permutation(5, 7, size=8)(0, 2, 4, 6)) assert G.is_alt_sym() is False
# Tests for monte-carlo c_n parameter setting, and which guarantees # to give False. G = DihedralGroup(10) assert G._eval_is_alt_sym_monte_carlo() is False G = DihedralGroup(20) assert G._eval_is_alt_sym_monte_carlo() is False
# A dry-running test to check if it looks up for the updated cache. G = DihedralGroup(6) G.is_alt_sym() assert G.is_alt_sym() is False
def test_minimal_block(): D = DihedralGroup(6) block_system = D.minimal_block([0, 3]) for i in range(3): assert block_system[i] == block_system[i + 3] S = SymmetricGroup(6) assert S.minimal_block([0, 1]) == [0, 0, 0, 0, 0, 0]
assert Tetra.pgroup.minimal_block([0, 1]) == [0, 0, 0, 0]
P1 = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) P2 = PermutationGroup(Permutation(0, 1, 2, 3, 4, 5), Permutation(1, 5)(2, 4)) assert P1.minimal_block([0, 2]) == [0, 1, 0, 1, 0, 1] assert P2.minimal_block([0, 2]) == [0, 1, 0, 1, 0, 1]
def test_minimal_blocks(): P = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) assert P.minimal_blocks() == [[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]]
P = SymmetricGroup(5) assert P.minimal_blocks() == [[0]*5]
P = PermutationGroup(Permutation(0, 3)) assert P.minimal_blocks() is False
def test_max_div(): S = SymmetricGroup(10) assert S.max_div == 5
def test_is_primitive(): S = SymmetricGroup(5) assert S.is_primitive() is True C = CyclicGroup(7) assert C.is_primitive() is True
a = Permutation(0, 1, 2, size=6) b = Permutation(3, 4, 5, size=6) G = PermutationGroup(a, b) assert G.is_primitive() is False
def test_random_stab(): S = SymmetricGroup(5) _random_el = Permutation([1, 3, 2, 0, 4]) _random_prec = {'rand': _random_el} g = S.random_stab(2, _random_prec=_random_prec) assert g == Permutation([1, 3, 2, 0, 4]) h = S.random_stab(1) assert h(1) == 1
def test_transitivity_degree(): perm = Permutation([1, 2, 0]) C = PermutationGroup([perm]) assert C.transitivity_degree == 1 gen1 = Permutation([1, 2, 0, 3, 4]) gen2 = Permutation([1, 2, 3, 4, 0]) # alternating group of degree 5 Alt = PermutationGroup([gen1, gen2]) assert Alt.transitivity_degree == 3
def test_schreier_sims_random(): assert sorted(Tetra.pgroup.base) == [0, 1]
S = SymmetricGroup(3) base = [0, 1] strong_gens = [Permutation([1, 2, 0]), Permutation([1, 0, 2]), Permutation([0, 2, 1])] assert S.schreier_sims_random(base, strong_gens, 5) == (base, strong_gens) D = DihedralGroup(3) _random_prec = {'g': [Permutation([2, 0, 1]), Permutation([1, 2, 0]), Permutation([1, 0, 2])]} base = [0, 1] strong_gens = [Permutation([1, 2, 0]), Permutation([2, 1, 0]), Permutation([0, 2, 1])] assert D.schreier_sims_random([], D.generators, 2, _random_prec=_random_prec) == (base, strong_gens)
def test_baseswap(): S = SymmetricGroup(4) S.schreier_sims() base = S.base strong_gens = S.strong_gens assert base == [0, 1, 2] deterministic = S.baseswap(base, strong_gens, 1, randomized=False) randomized = S.baseswap(base, strong_gens, 1) assert deterministic[0] == [0, 2, 1] assert _verify_bsgs(S, deterministic[0], deterministic[1]) is True assert randomized[0] == [0, 2, 1] assert _verify_bsgs(S, randomized[0], randomized[1]) is True
def test_schreier_sims_incremental(): identity = Permutation([0, 1, 2, 3, 4]) TrivialGroup = PermutationGroup([identity]) base, strong_gens = TrivialGroup.schreier_sims_incremental(base=[0, 1, 2]) assert _verify_bsgs(TrivialGroup, base, strong_gens) is True S = SymmetricGroup(5) base, strong_gens = S.schreier_sims_incremental(base=[0, 1, 2]) assert _verify_bsgs(S, base, strong_gens) is True D = DihedralGroup(2) base, strong_gens = D.schreier_sims_incremental(base=[1]) assert _verify_bsgs(D, base, strong_gens) is True A = AlternatingGroup(7) gens = A.generators[:] gen0 = gens[0] gen1 = gens[1] gen1 = rmul(gen1, ~gen0) gen0 = rmul(gen0, gen1) gen1 = rmul(gen0, gen1) base, strong_gens = A.schreier_sims_incremental(base=[0, 1], gens=gens) assert _verify_bsgs(A, base, strong_gens) is True C = CyclicGroup(11) gen = C.generators[0] base, strong_gens = C.schreier_sims_incremental(gens=[gen**3]) assert _verify_bsgs(C, base, strong_gens) is True
def _subgroup_search(i, j, k): prop_true = lambda x: True prop_fix_points = lambda x: [x(point) for point in points] == points prop_comm_g = lambda x: rmul(x, g) == rmul(g, x) prop_even = lambda x: x.is_even for i in range(i, j, k): S = SymmetricGroup(i) A = AlternatingGroup(i) C = CyclicGroup(i) Sym = S.subgroup_search(prop_true) assert Sym.is_subgroup(S) Alt = S.subgroup_search(prop_even) assert Alt.is_subgroup(A) Sym = S.subgroup_search(prop_true, init_subgroup=C) assert Sym.is_subgroup(S) points = [7] assert S.stabilizer(7).is_subgroup(S.subgroup_search(prop_fix_points)) points = [3, 4] assert S.stabilizer(3).stabilizer(4).is_subgroup( S.subgroup_search(prop_fix_points)) points = [3, 5] fix35 = A.subgroup_search(prop_fix_points) points = [5] fix5 = A.subgroup_search(prop_fix_points) assert A.subgroup_search(prop_fix_points, init_subgroup=fix35 ).is_subgroup(fix5) base, strong_gens = A.schreier_sims_incremental() g = A.generators[0] comm_g = \ A.subgroup_search(prop_comm_g, base=base, strong_gens=strong_gens) assert _verify_bsgs(comm_g, base, comm_g.generators) is True assert [prop_comm_g(gen) is True for gen in comm_g.generators]
def test_subgroup_search(): _subgroup_search(10, 15, 2)
@XFAILdef test_subgroup_search2(): skip('takes too much time') _subgroup_search(16, 17, 1)
def test_normal_closure(): # the normal closure of the trivial group is trivial S = SymmetricGroup(3) identity = Permutation([0, 1, 2]) closure = S.normal_closure(identity) assert closure.is_trivial # the normal closure of the entire group is the entire group A = AlternatingGroup(4) assert A.normal_closure(A).is_subgroup(A) # brute-force verifications for subgroups for i in (3, 4, 5): S = SymmetricGroup(i) A = AlternatingGroup(i) D = DihedralGroup(i) C = CyclicGroup(i) for gp in (A, D, C): assert _verify_normal_closure(S, gp) # brute-force verifications for all elements of a group S = SymmetricGroup(5) elements = list(S.generate_dimino()) for element in elements: assert _verify_normal_closure(S, element) # small groups small = [] for i in (1, 2, 3): small.append(SymmetricGroup(i)) small.append(AlternatingGroup(i)) small.append(DihedralGroup(i)) small.append(CyclicGroup(i)) for gp in small: for gp2 in small: if gp2.is_subgroup(gp, 0) and gp2.degree == gp.degree: assert _verify_normal_closure(gp, gp2)
def test_derived_series(): # the derived series of the trivial group consists only of the trivial group triv = PermutationGroup([Permutation([0, 1, 2])]) assert triv.derived_series()[0].is_subgroup(triv) # the derived series for a simple group consists only of the group itself for i in (5, 6, 7): A = AlternatingGroup(i) assert A.derived_series()[0].is_subgroup(A) # the derived series for S_4 is S_4 > A_4 > K_4 > triv S = SymmetricGroup(4) series = S.derived_series() assert series[1].is_subgroup(AlternatingGroup(4)) assert series[2].is_subgroup(DihedralGroup(2)) assert series[3].is_trivial
def test_lower_central_series(): # the lower central series of the trivial group consists of the trivial # group triv = PermutationGroup([Permutation([0, 1, 2])]) assert triv.lower_central_series()[0].is_subgroup(triv) # the lower central series of a simple group consists of the group itself for i in (5, 6, 7): A = AlternatingGroup(i) assert A.lower_central_series()[0].is_subgroup(A) # GAP-verified example S = SymmetricGroup(6) series = S.lower_central_series() assert len(series) == 2 assert series[1].is_subgroup(AlternatingGroup(6))
def test_commutator(): # the commutator of the trivial group and the trivial group is trivial S = SymmetricGroup(3) triv = PermutationGroup([Permutation([0, 1, 2])]) assert S.commutator(triv, triv).is_subgroup(triv) # the commutator of the trivial group and any other group is again trivial A = AlternatingGroup(3) assert S.commutator(triv, A).is_subgroup(triv) # the commutator is commutative for i in (3, 4, 5): S = SymmetricGroup(i) A = AlternatingGroup(i) D = DihedralGroup(i) assert S.commutator(A, D).is_subgroup(S.commutator(D, A)) # the commutator of an abelian group is trivial S = SymmetricGroup(7) A1 = AbelianGroup(2, 5) A2 = AbelianGroup(3, 4) triv = PermutationGroup([Permutation([0, 1, 2, 3, 4, 5, 6])]) assert S.commutator(A1, A1).is_subgroup(triv) assert S.commutator(A2, A2).is_subgroup(triv) # examples calculated by hand S = SymmetricGroup(3) A = AlternatingGroup(3) assert S.commutator(A, S).is_subgroup(A)
def test_is_nilpotent(): # every abelian group is nilpotent for i in (1, 2, 3): C = CyclicGroup(i) Ab = AbelianGroup(i, i + 2) assert C.is_nilpotent assert Ab.is_nilpotent Ab = AbelianGroup(5, 7, 10) assert Ab.is_nilpotent # A_5 is not solvable and thus not nilpotent assert AlternatingGroup(5).is_nilpotent is False
def test_is_trivial(): for i in range(5): triv = PermutationGroup([Permutation(list(range(i)))]) assert triv.is_trivial
def test_pointwise_stabilizer(): S = SymmetricGroup(2) stab = S.pointwise_stabilizer([0]) assert stab.generators == [Permutation(1)] S = SymmetricGroup(5) points = [] stab = S for point in (2, 0, 3, 4, 1): stab = stab.stabilizer(point) points.append(point) assert S.pointwise_stabilizer(points).is_subgroup(stab)
def test_make_perm(): assert cube.pgroup.make_perm(5, seed=list(range(5))) == \ Permutation([4, 7, 6, 5, 0, 3, 2, 1]) assert cube.pgroup.make_perm(7, seed=list(range(7))) == \ Permutation([6, 7, 3, 2, 5, 4, 0, 1])
def test_elements(): from sympy.sets.sets import FiniteSet
p = Permutation(2, 3) assert set(PermutationGroup(p).elements) == {Permutation(3), Permutation(2, 3)} assert FiniteSet(*PermutationGroup(p).elements) \ == FiniteSet(Permutation(2, 3), Permutation(3))
def test_is_group(): assert PermutationGroup(Permutation(1,2), Permutation(2,4)).is_group is True assert SymmetricGroup(4).is_group is True
def test_PermutationGroup(): assert PermutationGroup() == PermutationGroup(Permutation()) assert (PermutationGroup() == 0) is False
def test_coset_transvesal(): G = AlternatingGroup(5) H = PermutationGroup(Permutation(0,1,2),Permutation(1,2)(3,4)) assert G.coset_transversal(H) == \ [Permutation(4), Permutation(2, 3, 4), Permutation(2, 4, 3), Permutation(1, 2, 4), Permutation(4)(1, 2, 3), Permutation(1, 3)(2, 4), Permutation(0, 1, 2, 3, 4), Permutation(0, 1, 2, 4, 3), Permutation(0, 1, 3, 2, 4), Permutation(0, 2, 4, 1, 3)]
def test_coset_table(): G = PermutationGroup(Permutation(0,1,2,3), Permutation(0,1,2), Permutation(0,4,2,7), Permutation(5,6), Permutation(0,7)); H = PermutationGroup(Permutation(0,1,2,3), Permutation(0,7)) assert G.coset_table(H) == \ [[0, 0, 0, 0, 1, 2, 3, 3, 0, 0], [4, 5, 2, 5, 6, 0, 7, 7, 1, 1], [5, 4, 5, 1, 0, 6, 8, 8, 6, 6], [3, 3, 3, 3, 7, 8, 0, 0, 3, 3], [2, 1, 4, 4, 4, 4, 9, 9, 4, 4], [1, 2, 1, 2, 5, 5, 10, 10, 5, 5], [6, 6, 6, 6, 2, 1, 11, 11, 2, 2], [9, 10, 8, 10, 11, 3, 1, 1, 7, 7], [10, 9, 10, 7, 3, 11, 2, 2, 11, 11], [8, 7, 9, 9, 9, 9, 4, 4, 9, 9], [7, 8, 7, 8, 10, 10, 5, 5, 10, 10], [11, 11, 11, 11, 8, 7, 6, 6, 8, 8]]
def test_subgroup(): G = PermutationGroup(Permutation(0,1,2), Permutation(0,2,3)) H = G.subgroup([Permutation(0,1,3)]) assert H.is_subgroup(G)
def test_generator_product(): G = SymmetricGroup(5) p = Permutation(0, 2, 3)(1, 4) gens = G.generator_product(p) assert all(g in G.strong_gens for g in gens) w = G.identity for g in gens: w = g*w assert w == p
def test_sylow_subgroup(): P = PermutationGroup(Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5)) S = P.sylow_subgroup(2) assert S.order() == 4
P = DihedralGroup(12) S = P.sylow_subgroup(3) assert S.order() == 3
P = PermutationGroup( Permutation(1, 5)(2, 4), Permutation(0, 1, 2, 3, 4, 5), Permutation(0, 2)) S = P.sylow_subgroup(3) assert S.order() == 9 S = P.sylow_subgroup(2) assert S.order() == 8
P = SymmetricGroup(10) S = P.sylow_subgroup(2) assert S.order() == 256 S = P.sylow_subgroup(3) assert S.order() == 81 S = P.sylow_subgroup(5) assert S.order() == 25
# the length of the lower central series # of a p-Sylow subgroup of Sym(n) grows with # the highest exponent exp of p such # that n >= p**exp exp = 1 length = 0 for i in range(2, 9): P = SymmetricGroup(i) S = P.sylow_subgroup(2) ls = S.lower_central_series() if i // 2**exp > 0: # length increases with exponent assert len(ls) > length length = len(ls) exp += 1 else: assert len(ls) == length
G = SymmetricGroup(100) S = G.sylow_subgroup(3) assert G.order() % S.order() == 0 assert G.order()/S.order() % 3 > 0
G = AlternatingGroup(100) S = G.sylow_subgroup(2) assert G.order() % S.order() == 0 assert G.order()/S.order() % 2 > 0
G = DihedralGroup(18) S = G.sylow_subgroup(p=2) assert S.order() == 4
G = DihedralGroup(50) S = G.sylow_subgroup(p=2) assert S.order() == 4
@slowdef test_presentation(): def _test(P): G = P.presentation() return G.order() == P.order()
def _strong_test(P): G = P.strong_presentation() chk = len(G.generators) == len(P.strong_gens) return chk and G.order() == P.order()
P = PermutationGroup(Permutation(0,1,5,2)(3,7,4,6), Permutation(0,3,5,4)(1,6,2,7)) assert _test(P)
P = AlternatingGroup(5) assert _test(P)
P = SymmetricGroup(5) assert _test(P)
P = PermutationGroup( [Permutation(0,3,1,2), Permutation(3)(0,1), Permutation(0,1)(2,3)]) assert _strong_test(P)
P = DihedralGroup(6) assert _strong_test(P)
a = Permutation(0,1)(2,3) b = Permutation(0,2)(3,1) c = Permutation(4,5) P = PermutationGroup(c, a, b) assert _strong_test(P)
def test_polycyclic(): a = Permutation([0, 1, 2]) b = Permutation([2, 1, 0]) G = PermutationGroup([a, b]) assert G.is_polycyclic is True
a = Permutation([1, 2, 3, 4, 0]) b = Permutation([1, 0, 2, 3, 4]) G = PermutationGroup([a, b]) assert G.is_polycyclic is False
def test_elementary(): a = Permutation([1, 5, 2, 0, 3, 6, 4]) G = PermutationGroup([a]) assert G.is_elementary(7) is False
a = Permutation(0, 1)(2, 3) b = Permutation(0, 2)(3, 1) G = PermutationGroup([a, b]) assert G.is_elementary(2) is True c = Permutation(4, 5, 6) G = PermutationGroup([a, b, c]) assert G.is_elementary(2) is False
G = SymmetricGroup(4).sylow_subgroup(2) assert G.is_elementary(2) is False H = AlternatingGroup(4).sylow_subgroup(2) assert H.is_elementary(2) is True
def test_perfect(): G = AlternatingGroup(3) assert G.is_perfect is False G = AlternatingGroup(5) assert G.is_perfect is True
def test_index(): G = PermutationGroup(Permutation(0,1,2), Permutation(0,2,3)) H = G.subgroup([Permutation(0,1,3)]) assert G.index(H) == 4
def test_cyclic(): G = SymmetricGroup(2) assert G.is_cyclic G = AbelianGroup(3, 7) assert G.is_cyclic G = AbelianGroup(7, 7) assert not G.is_cyclic G = AlternatingGroup(3) assert G.is_cyclic G = AlternatingGroup(4) assert not G.is_cyclic
# Order less than 6 G = PermutationGroup(Permutation(0, 1, 2), Permutation(0, 2, 1)) assert G.is_cyclic G = PermutationGroup( Permutation(0, 1, 2, 3), Permutation(0, 2)(1, 3) ) assert G.is_cyclic G = PermutationGroup( Permutation(3), Permutation(0, 1)(2, 3), Permutation(0, 2)(1, 3), Permutation(0, 3)(1, 2) ) assert G.is_cyclic is False
# Order 15 G = PermutationGroup( Permutation(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14), Permutation(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13) ) assert G.is_cyclic
# Distinct prime orders assert PermutationGroup._distinct_primes_lemma([3, 5]) is True assert PermutationGroup._distinct_primes_lemma([5, 7]) is True assert PermutationGroup._distinct_primes_lemma([2, 3]) is None assert PermutationGroup._distinct_primes_lemma([3, 5, 7]) is None assert PermutationGroup._distinct_primes_lemma([5, 7, 13]) is True
G = PermutationGroup( Permutation(0, 1, 2, 3), Permutation(0, 2)(1, 3)) assert G.is_cyclic assert G._is_abelian
# Non-abelian and therefore not cyclic G = PermutationGroup(*SymmetricGroup(3).generators) assert G.is_cyclic is False
# Abelian and cyclic G = PermutationGroup( Permutation(0, 1, 2, 3), Permutation(4, 5, 6) ) assert G.is_cyclic
# Abelian but not cyclic G = PermutationGroup( Permutation(0, 1), Permutation(2, 3), Permutation(4, 5, 6) ) assert G.is_cyclic is False
def test_dihedral(): G = SymmetricGroup(2) assert G.is_dihedral G = SymmetricGroup(3) assert G.is_dihedral
G = AbelianGroup(2, 2) assert G.is_dihedral G = CyclicGroup(4) assert not G.is_dihedral
G = AbelianGroup(3, 5) assert not G.is_dihedral G = AbelianGroup(2) assert G.is_dihedral G = AbelianGroup(6) assert not G.is_dihedral
# D6, generated by two adjacent flips G = PermutationGroup( Permutation(1, 5)(2, 4), Permutation(0, 1)(3, 4)(2, 5)) assert G.is_dihedral
# D7, generated by a flip and a rotation G = PermutationGroup( Permutation(1, 6)(2, 5)(3, 4), Permutation(0, 1, 2, 3, 4, 5, 6)) assert G.is_dihedral
# S4, presented by three generators, fails due to having exactly 9 # elements of order 2: G = PermutationGroup( Permutation(0, 1), Permutation(0, 2), Permutation(0, 3)) assert not G.is_dihedral
# D7, given by three generators G = PermutationGroup( Permutation(1, 6)(2, 5)(3, 4), Permutation(2, 0)(3, 6)(4, 5), Permutation(0, 1, 2, 3, 4, 5, 6)) assert G.is_dihedral
def test_abelian_invariants(): G = AbelianGroup(2, 3, 4) assert G.abelian_invariants() == [2, 3, 4] G=PermutationGroup([Permutation(1, 2, 3, 4), Permutation(1, 2), Permutation(5, 6)]) assert G.abelian_invariants() == [2, 2] G = AlternatingGroup(7) assert G.abelian_invariants() == [] G = AlternatingGroup(4) assert G.abelian_invariants() == [3] G = DihedralGroup(4) assert G.abelian_invariants() == [2, 2]
G = PermutationGroup([Permutation(1, 2, 3, 4, 5, 6, 7)]) assert G.abelian_invariants() == [7] G = DihedralGroup(12) S = G.sylow_subgroup(3) assert S.abelian_invariants() == [3] G = PermutationGroup(Permutation(0, 1, 2), Permutation(0, 2, 3)) assert G.abelian_invariants() == [3] G = PermutationGroup([Permutation(0, 1), Permutation(0, 2, 4, 6)(1, 3, 5, 7)]) assert G.abelian_invariants() == [2, 4] G = SymmetricGroup(30) S = G.sylow_subgroup(2) assert S.abelian_invariants() == [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] S = G.sylow_subgroup(3) assert S.abelian_invariants() == [3, 3, 3, 3] S = G.sylow_subgroup(5) assert S.abelian_invariants() == [5, 5, 5]
def test_composition_series(): a = Permutation(1, 2, 3) b = Permutation(1, 2) G = PermutationGroup([a, b]) comp_series = G.composition_series() assert comp_series == G.derived_series() # The first group in the composition series is always the group itself and # the last group in the series is the trivial group. S = SymmetricGroup(4) assert S.composition_series()[0] == S assert len(S.composition_series()) == 5 A = AlternatingGroup(4) assert A.composition_series()[0] == A assert len(A.composition_series()) == 4
# the composition series for C_8 is C_8 > C_4 > C_2 > triv G = CyclicGroup(8) series = G.composition_series() assert is_isomorphic(series[1], CyclicGroup(4)) assert is_isomorphic(series[2], CyclicGroup(2)) assert series[3].is_trivial
def test_is_symmetric(): a = Permutation(0, 1, 2) b = Permutation(0, 1, size=3) assert PermutationGroup(a, b).is_symmetric is True
a = Permutation(0, 2, 1) b = Permutation(1, 2, size=3) assert PermutationGroup(a, b).is_symmetric is True
a = Permutation(0, 1, 2, 3) b = Permutation(0, 3)(1, 2) assert PermutationGroup(a, b).is_symmetric is False
def test_conjugacy_class(): S = SymmetricGroup(4) x = Permutation(1, 2, 3) C = {Permutation(0, 1, 2, size = 4), Permutation(0, 1, 3), Permutation(0, 2, 1, size = 4), Permutation(0, 2, 3), Permutation(0, 3, 1), Permutation(0, 3, 2), Permutation(1, 2, 3), Permutation(1, 3, 2)} assert S.conjugacy_class(x) == C
def test_conjugacy_classes(): S = SymmetricGroup(3) expected = [{Permutation(size = 3)}, {Permutation(0, 1, size = 3), Permutation(0, 2), Permutation(1, 2)}, {Permutation(0, 1, 2), Permutation(0, 2, 1)}] computed = S.conjugacy_classes()
assert len(expected) == len(computed) assert all(e in computed for e in expected)
def test_coset_class(): a = Permutation(1, 2) b = Permutation(0, 1) G = PermutationGroup([a, b]) #Creating right coset rht_coset = G*a #Checking whether it is left coset or right coset assert rht_coset.is_right_coset assert not rht_coset.is_left_coset #Creating list representation of coset list_repr = rht_coset.as_list() expected = [Permutation(0, 2), Permutation(0, 2, 1), Permutation(1, 2), Permutation(2), Permutation(2)(0, 1), Permutation(0, 1, 2)] for ele in list_repr: assert ele in expected #Creating left coset left_coset = a*G #Checking whether it is left coset or right coset assert not left_coset.is_right_coset assert left_coset.is_left_coset #Creating list representation of Coset list_repr = left_coset.as_list() expected = [Permutation(2)(0, 1), Permutation(0, 1, 2), Permutation(1, 2), Permutation(2), Permutation(0, 2), Permutation(0, 2, 1)] for ele in list_repr: assert ele in expected
G = PermutationGroup(Permutation(1, 2, 3, 4), Permutation(2, 3, 4)) H = PermutationGroup(Permutation(1, 2, 3, 4)) g = Permutation(1, 3)(2, 4) rht_coset = Coset(g, H, G, dir='+') assert rht_coset.is_right_coset list_repr = rht_coset.as_list() expected = [Permutation(1, 2, 3, 4), Permutation(4), Permutation(1, 3)(2, 4), Permutation(1, 4, 3, 2)] for ele in list_repr: assert ele in expected
def test_symmetricpermutationgroup(): a = SymmetricPermutationGroup(5) assert a.degree == 5 assert a.order() == 120 assert a.identity() == Permutation(4)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105from sympy.core.symbol import symbolsfrom sympy.sets.sets import FiniteSetfrom sympy.combinatorics.polyhedron import (Polyhedron, tetrahedron, cube as square, octahedron, dodecahedron, icosahedron, cube_faces)from sympy.combinatorics.permutations import Permutationfrom sympy.combinatorics.perm_groups import PermutationGroupfrom sympy.testing.pytest import raises
rmul = Permutation.rmul
def test_polyhedron(): raises(ValueError, lambda: Polyhedron(list('ab'), pgroup=[Permutation([0])])) pgroup = [Permutation([[0, 7, 2, 5], [6, 1, 4, 3]]), Permutation([[0, 7, 1, 6], [5, 2, 4, 3]]), Permutation([[3, 6, 0, 5], [4, 1, 7, 2]]), Permutation([[7, 4, 5], [1, 3, 0], [2], [6]]), Permutation([[1, 3, 2], [7, 6, 5], [4], [0]]), Permutation([[4, 7, 6], [2, 0, 3], [1], [5]]), Permutation([[1, 2, 0], [4, 5, 6], [3], [7]]), Permutation([[4, 2], [0, 6], [3, 7], [1, 5]]), Permutation([[3, 5], [7, 1], [2, 6], [0, 4]]), Permutation([[2, 5], [1, 6], [0, 4], [3, 7]]), Permutation([[4, 3], [7, 0], [5, 1], [6, 2]]), Permutation([[4, 1], [0, 5], [6, 2], [7, 3]]), Permutation([[7, 2], [3, 6], [0, 4], [1, 5]]), Permutation([0, 1, 2, 3, 4, 5, 6, 7])] corners = tuple(symbols('A:H')) faces = cube_faces cube = Polyhedron(corners, faces, pgroup)
assert cube.edges == FiniteSet(*( (0, 1), (6, 7), (1, 2), (5, 6), (0, 3), (2, 3), (4, 7), (4, 5), (3, 7), (1, 5), (0, 4), (2, 6)))
for i in range(3): # add 180 degree face rotations cube.rotate(cube.pgroup[i]**2)
assert cube.corners == corners
for i in range(3, 7): # add 240 degree axial corner rotations cube.rotate(cube.pgroup[i]**2)
assert cube.corners == corners cube.rotate(1) raises(ValueError, lambda: cube.rotate(Permutation([0, 1]))) assert cube.corners != corners assert cube.array_form == [7, 6, 4, 5, 3, 2, 0, 1] assert cube.cyclic_form == [[0, 7, 1, 6], [2, 4, 3, 5]] cube.reset() assert cube.corners == corners
def check(h, size, rpt, target):
assert len(h.faces) + len(h.vertices) - len(h.edges) == 2 assert h.size == size
got = set() for p in h.pgroup: # make sure it restores original P = h.copy() hit = P.corners for i in range(rpt): P.rotate(p) if P.corners == hit: break else: print('error in permutation', p.array_form) for i in range(rpt): P.rotate(p) got.add(tuple(P.corners)) c = P.corners f = [[c[i] for i in f] for f in P.faces] assert h.faces == Polyhedron(c, f).faces assert len(got) == target assert PermutationGroup([Permutation(g) for g in got]).is_group
for h, size, rpt, target in zip( (tetrahedron, square, octahedron, dodecahedron, icosahedron), (4, 8, 6, 20, 12), (3, 4, 4, 5, 5), (12, 24, 24, 60, 60)): check(h, size, rpt, target)
def test_pgroups(): from sympy.combinatorics.polyhedron import (cube, tetrahedron_faces, octahedron_faces, dodecahedron_faces, icosahedron_faces) from sympy.combinatorics.polyhedron import _pgroup_calcs (tetrahedron2, cube2, octahedron2, dodecahedron2, icosahedron2, tetrahedron_faces2, cube_faces2, octahedron_faces2, dodecahedron_faces2, icosahedron_faces2) = _pgroup_calcs()
assert tetrahedron == tetrahedron2 assert cube == cube2 assert octahedron == octahedron2 assert dodecahedron == dodecahedron2 assert icosahedron == icosahedron2 assert sorted(map(sorted, tetrahedron_faces)) == sorted(map(sorted, tetrahedron_faces2)) assert sorted(cube_faces) == sorted(cube_faces2) assert sorted(octahedron_faces) == sorted(octahedron_faces2) assert sorted(dodecahedron_faces) == sorted(dodecahedron_faces2) assert sorted(icosahedron_faces) == sorted(icosahedron_faces2)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849from sympy.combinatorics.fp_groups import FpGroupfrom sympy.combinatorics.free_groups import free_groupfrom sympy.testing.pytest import raises
def test_rewriting(): F, a, b = free_group("a, b") G = FpGroup(F, [a*b*a**-1*b**-1]) a, b = G.generators R = G._rewriting_system assert R.is_confluent
assert G.reduce(b**-1*a) == a*b**-1 assert G.reduce(b**3*a**4*b**-2*a) == a**5*b assert G.equals(b**2*a**-1*b, b**4*a**-1*b**-1)
assert R.reduce_using_automaton(b*a*a**2*b**-1) == a**3 assert R.reduce_using_automaton(b**3*a**4*b**-2*a) == a**5*b assert R.reduce_using_automaton(b**-1*a) == a*b**-1
G = FpGroup(F, [a**3, b**3, (a*b)**2]) R = G._rewriting_system R.make_confluent() # R._is_confluent should be set to True after # a successful run of make_confluent assert R.is_confluent # but also the system should actually be confluent assert R._check_confluence() assert G.reduce(b*a**-1*b**-1*a**3*b**4*a**-1*b**-15) == a**-1*b**-1 # check for automaton reduction assert R.reduce_using_automaton(b*a**-1*b**-1*a**3*b**4*a**-1*b**-15) == a**-1*b**-1
G = FpGroup(F, [a**2, b**3, (a*b)**4]) R = G._rewriting_system assert G.reduce(a**2*b**-2*a**2*b) == b**-1 assert R.reduce_using_automaton(a**2*b**-2*a**2*b) == b**-1 assert G.reduce(a**3*b**-2*a**2*b) == a**-1*b**-1 assert R.reduce_using_automaton(a**3*b**-2*a**2*b) == a**-1*b**-1 # Check after adding a rule R.add_rule(a**2, b) assert R.reduce_using_automaton(a**2*b**-2*a**2*b) == b**-1 assert R.reduce_using_automaton(a**4*b**-2*a**2*b**3) == b
R.set_max(15) raises(RuntimeError, lambda: R.add_rule(a**-3, b)) R.set_max(20) R.add_rule(a**-3, b)
assert R.add_rule(a, a) == set()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263from sympy.combinatorics.subsets import Subset, ksubsetsfrom sympy.testing.pytest import raises
def test_subset(): a = Subset(['c', 'd'], ['a', 'b', 'c', 'd']) assert a.next_binary() == Subset(['b'], ['a', 'b', 'c', 'd']) assert a.prev_binary() == Subset(['c'], ['a', 'b', 'c', 'd']) assert a.next_lexicographic() == Subset(['d'], ['a', 'b', 'c', 'd']) assert a.prev_lexicographic() == Subset(['c'], ['a', 'b', 'c', 'd']) assert a.next_gray() == Subset(['c'], ['a', 'b', 'c', 'd']) assert a.prev_gray() == Subset(['d'], ['a', 'b', 'c', 'd']) assert a.rank_binary == 3 assert a.rank_lexicographic == 14 assert a.rank_gray == 2 assert a.cardinality == 16 assert a.size == 2 assert Subset.bitlist_from_subset(a, ['a', 'b', 'c', 'd']) == '0011'
a = Subset([2, 5, 7], [1, 2, 3, 4, 5, 6, 7]) assert a.next_binary() == Subset([2, 5, 6], [1, 2, 3, 4, 5, 6, 7]) assert a.prev_binary() == Subset([2, 5], [1, 2, 3, 4, 5, 6, 7]) assert a.next_lexicographic() == Subset([2, 6], [1, 2, 3, 4, 5, 6, 7]) assert a.prev_lexicographic() == Subset([2, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]) assert a.next_gray() == Subset([2, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]) assert a.prev_gray() == Subset([2, 5], [1, 2, 3, 4, 5, 6, 7]) assert a.rank_binary == 37 assert a.rank_lexicographic == 93 assert a.rank_gray == 57 assert a.cardinality == 128
superset = ['a', 'b', 'c', 'd'] assert Subset.unrank_binary(4, superset).rank_binary == 4 assert Subset.unrank_gray(10, superset).rank_gray == 10
superset = [1, 2, 3, 4, 5, 6, 7, 8, 9] assert Subset.unrank_binary(33, superset).rank_binary == 33 assert Subset.unrank_gray(25, superset).rank_gray == 25
a = Subset([], ['a', 'b', 'c', 'd']) i = 1 while a.subset != Subset(['d'], ['a', 'b', 'c', 'd']).subset: a = a.next_lexicographic() i = i + 1 assert i == 16
i = 1 while a.subset != Subset([], ['a', 'b', 'c', 'd']).subset: a = a.prev_lexicographic() i = i + 1 assert i == 16
raises(ValueError, lambda: Subset(['a', 'b'], ['a'])) raises(ValueError, lambda: Subset(['a'], ['b', 'c'])) raises(ValueError, lambda: Subset.subset_from_bitlist(['a', 'b'], '010'))
assert Subset(['a'], ['a', 'b']) != Subset(['b'], ['a', 'b']) assert Subset(['a'], ['a', 'b']) != Subset(['a'], ['a', 'c'])
def test_ksubsets(): assert list(ksubsets([1, 2, 3], 2)) == [(1, 2), (1, 3), (2, 3)] assert list(ksubsets([1, 2, 3, 4, 5], 2)) == [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)].gitattributes+2
janus/lib/python3.10/site-packages/sympy/combinatorics/__init__.pyAdded+43
janus/lib/python3.10/site-packages/sympy/combinatorics/coset_table.pyAdded+1255
janus/lib/python3.10/site-packages/sympy/combinatorics/fp_groups.pyAdded+1354
janus/lib/python3.10/site-packages/sympy/combinatorics/free_groups.pyAdded+1354
janus/lib/python3.10/site-packages/sympy/combinatorics/galois.pyAdded+611
janus/lib/python3.10/site-packages/sympy/combinatorics/generators.pyAdded+302
janus/lib/python3.10/site-packages/sympy/combinatorics/graycode.pyAdded+430
janus/lib/python3.10/site-packages/sympy/combinatorics/group_constructs.pyAdded+61
janus/lib/python3.10/site-packages/sympy/combinatorics/group_numbers.pyAdded+296
janus/lib/python3.10/site-packages/sympy/combinatorics/homomorphisms.pyAdded+549
janus/lib/python3.10/site-packages/sympy/combinatorics/named_groups.pyAdded+332
janus/lib/python3.10/site-packages/sympy/combinatorics/partitions.pyAdded+745
janus/lib/python3.10/site-packages/sympy/combinatorics/pc_groups.pyAdded+709
janus/lib/python3.10/site-packages/sympy/combinatorics/perm_groups.pyAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/permutations.pyAdded+3115
janus/lib/python3.10/site-packages/sympy/combinatorics/polyhedron.pyAdded+1019
janus/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem.pyAdded+453
janus/lib/python3.10/site-packages/sympy/combinatorics/rewritingsystem_fsm.pyAdded+60
janus/lib/python3.10/site-packages/sympy/combinatorics/schur_number.pyAdded+160
janus/lib/python3.10/site-packages/sympy/combinatorics/subsets.pyAdded+619
janus/lib/python3.10/site-packages/sympy/combinatorics/tensor_can.pyAdded+1190
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__init__.pyAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/__init__.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_fp_groups.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_free_groups.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_galois.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_generators.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_group_constructs.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_homomorphisms.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_named_groups.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_partitions.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_pc_groups.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_perm_groups.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_permutations.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_polyhedron.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_prufer.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_rewriting.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_schur_number.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_subsets.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/__pycache__/test_testutil.cpython-310.pycAdded
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_free_groups.pyAdded+221
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_generators.pyAdded+105
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_graycode.pyAdded+72
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_group_numbers.pyAdded+110
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_homomorphisms.pyAdded+114
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_perm_groups.pyAdded+1243
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_polyhedron.pyAdded+105
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_rewriting.pyAdded+49
janus/lib/python3.10/site-packages/sympy/combinatorics/tests/test_subsets.pyAdded+63