[docs]classPermutationGroup(Basic):"""The class defining a Permutation group. PermutationGroup([p1, p2, ..., pn]) returns the permutation group generated by the list of permutations. This group can be supplied to Polyhedron if one desires to decorate the elements to which the indices of the permutation refer. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.permutations import Cycle >>> from sympy.combinatorics.polyhedron import Polyhedron >>> from sympy.combinatorics.perm_groups import PermutationGroup The permutations corresponding to motion of the front, right and bottom face of a 2x2 Rubik's cube are defined: >>> F = Permutation(2, 19, 21, 8)(3, 17, 20, 10)(4, 6, 7, 5) >>> R = Permutation(1, 5, 21, 14)(3, 7, 23, 12)(8, 10, 11, 9) >>> D = Permutation(6, 18, 14, 10)(7, 19, 15, 11)(20, 22, 23, 21) These are passed as permutations to PermutationGroup: >>> G = PermutationGroup(F, R, D) >>> G.order() 3674160 The group can be supplied to a Polyhedron in order to track the objects being moved. An example involving the 2x2 Rubik's cube is given there, but here is a simple demonstration: >>> a = Permutation(2, 1) >>> b = Permutation(1, 0) >>> G = PermutationGroup(a, b) >>> P = Polyhedron(list('ABC'), pgroup=G) >>> P.corners (A, B, C) >>> P.rotate(0) # apply permutation 0 >>> P.corners (A, C, B) >>> P.reset() >>> P.corners (A, B, C) Or one can make a permutation as a product of selected permutations and apply them to an iterable directly: >>> P10 = G.make_perm([0, 1]) >>> P10('ABC') ['C', 'A', 'B'] See Also ======== sympy.combinatorics.polyhedron.Polyhedron, sympy.combinatorics.permutations.Permutation References ========== [1] Holt, D., Eick, B., O'Brien, E. "Handbook of Computational Group Theory" [2] Seress, A. "Permutation Group Algorithms" [3] http://en.wikipedia.org/wiki/Schreier_vector [4] http://en.wikipedia.org/wiki/Nielsen_transformation #Product_replacement_algorithm [5] Frank Celler, Charles R.Leedham-Green, Scott H.Murray, Alice C.Niemeyer, and E.A.O'Brien. "Generating Random Elements of a Finite Group" [6] http://en.wikipedia.org/wiki/Block_%28permutation_group_theory%29 [7] http://www.algorithmist.com/index.php/Union_Find [8] http://en.wikipedia.org/wiki/Multiply_transitive_group#Multiply_transitive_groups [9] http://en.wikipedia.org/wiki/Center_%28group_theory%29 [10] http://en.wikipedia.org/wiki/Centralizer_and_normalizer [11] http://groupprops.subwiki.org/wiki/Derived_subgroup [12] http://en.wikipedia.org/wiki/Nilpotent_group [13] http://www.math.colostate.edu/~hulpke/CGT/cgtnotes.pdf """is_group=Truedef__new__(cls,*args,**kwargs):"""The default constructor. Accepts Cycle and Permutation forms. Removes duplicates unless ``dups`` keyword is False. """ifnotargs:args=[Permutation()]else:args=list(args[0]ifis_sequence(args[0])elseargs)ifany(isinstance(a,Cycle)forainargs):args=[Permutation(a)forainargs]ifhas_variety(a.sizeforainargs):degree=kwargs.pop('degree',None)ifdegreeisNone:degree=max(a.sizeforainargs)foriinrange(len(args)):ifargs[i].size!=degree:args[i]=Permutation(args[i],size=degree)ifkwargs.pop('dups',True):args=list(uniq([_af_new(list(a))forainargs]))obj=Basic.__new__(cls,*args,**kwargs)obj._generators=argsobj._order=Noneobj._center=[]obj._is_abelian=Noneobj._is_transitive=Noneobj._is_sym=Noneobj._is_alt=Noneobj._is_primitive=Noneobj._is_nilpotent=Noneobj._is_solvable=Noneobj._is_trivial=Noneobj._transitivity_degree=Noneobj._max_div=Noneobj._r=len(obj._generators)obj._degree=obj._generators[0].size# these attributes are assigned after running schreier_simsobj._base=[]obj._strong_gens=[]obj._basic_orbits=[]obj._transversals=[]# these attributes are assigned after running _random_pr_initobj._random_gens=[]returnobjdef__getitem__(self,i):returnself._generators[i]def__contains__(self,i):"""Return True if `i` is contained in PermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> p = Permutation(1, 2, 3) >>> Permutation(3) in PermutationGroup(p) True """ifnotisinstance(i,Permutation):raiseTypeError("A PermutationGroup contains only Permutations as ""elements, not elements of type %s"%type(i))returnself.contains(i)def__len__(self):returnlen(self._generators)def__eq__(self,other):"""Return True if PermutationGroup generated by elements in the group are same i.e they represent the same PermutationGroup. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> p = Permutation(0, 1, 2, 3, 4, 5) >>> G = PermutationGroup([p, p**2]) >>> H = PermutationGroup([p**2, p]) >>> G.generators == H.generators False >>> G == H True """ifnotisinstance(other,PermutationGroup):returnFalseset_self_gens=set(self.generators)set_other_gens=set(other.generators)# before reaching the general case there are also certain# optimisation and obvious cases requiring less or no actual# computation.ifset_self_gens==set_other_gens:returnTrue# in the most general case it will check that each generator of# one group belongs to the other PermutationGroup and vice-versaforgen1inset_self_gens:ifnotother.contains(gen1):returnFalseforgen2inset_other_gens:ifnotself.contains(gen2):returnFalsereturnTruedef__hash__(self):returnsuper(PermutationGroup,self).__hash__()def__mul__(self,other):"""Return the direct product of two permutation groups as a permutation group. This implementation realizes the direct product by shifting the index set for the generators of the second group: so if we have G acting on n1 points and H acting on n2 points, G*H acts on n1 + n2 points. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import CyclicGroup >>> G = CyclicGroup(5) >>> H = G*G >>> H PermutationGroup([ (9)(0 1 2 3 4), (5 6 7 8 9)]) >>> H.order() 25 """gens1=[perm._array_formforperminself.generators]gens2=[perm._array_formforperminother.generators]n1=self._degreen2=other._degreestart=list(range(n1))end=list(range(n1,n1+n2))foriinrange(len(gens2)):gens2[i]=[x+n1forxingens2[i]]gens2=[start+genforgeningens2]gens1=[gen+endforgeningens1]together=gens1+gens2gens=[_af_new(x)forxintogether]returnPermutationGroup(gens)def_random_pr_init(self,r,n,_random_prec_n=None):r"""Initialize random generators for the product replacement algorithm. The implementation uses a modification of the original product replacement algorithm due to Leedham-Green, as described in [1], pp. 69-71; also, see [2], pp. 27-29 for a detailed theoretical analysis of the original product replacement algorithm, and [4]. The product replacement algorithm is used for producing random, uniformly distributed elements of a group ``G`` with a set of generators ``S``. For the initialization ``_random_pr_init``, a list ``R`` of ``\max\{r, |S|\}`` group generators is created as the attribute ``G._random_gens``, repeating elements of ``S`` if necessary, and the identity element of ``G`` is appended to ``R`` - we shall refer to this last element as the accumulator. Then the function ``random_pr()`` is called ``n`` times, randomizing the list ``R`` while preserving the generation of ``G`` by ``R``. The function ``random_pr()`` itself takes two random elements ``g, h`` among all elements of ``R`` but the accumulator and replaces ``g`` with a randomly chosen element from ``\{gh, g(~h), hg, (~h)g\}``. Then the accumulator is multiplied by whatever ``g`` was replaced by. The new value of the accumulator is then returned by ``random_pr()``. The elements returned will eventually (for ``n`` large enough) become uniformly distributed across ``G`` ([5]). For practical purposes however, the values ``n = 50, r = 11`` are suggested in [1]. Notes ===== THIS FUNCTION HAS SIDE EFFECTS: it changes the attribute self._random_gens See Also ======== random_pr """deg=self.degreerandom_gens=[x._array_formforxinself.generators]k=len(random_gens)ifk<r:foriinrange(k,r):random_gens.append(random_gens[i-k])acc=list(range(deg))random_gens.append(acc)self._random_gens=random_gens# handle randomized input for testing purposesif_random_prec_nisNone:foriinrange(n):self.random_pr()else:foriinrange(n):self.random_pr(_random_prec=_random_prec_n[i])def_union_find_merge(self,first,second,ranks,parents,not_rep):"""Merges two classes in a union-find data structure. Used in the implementation of Atkinson's algorithm as suggested in [1], pp. 83-87. The class merging process uses union by rank as an optimization. ([7]) Notes ===== THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, ``parents``, the list of class sizes, ``ranks``, and the list of elements that are not representatives, ``not_rep``, are changed due to class merging. See Also ======== minimal_block, _union_find_rep References ========== [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" [7] http://www.algorithmist.com/index.php/Union_Find """rep_first=self._union_find_rep(first,parents)rep_second=self._union_find_rep(second,parents)ifrep_first!=rep_second:# union by rankifranks[rep_first]>=ranks[rep_second]:new_1,new_2=rep_first,rep_secondelse:new_1,new_2=rep_second,rep_firsttotal_rank=ranks[new_1]+ranks[new_2]iftotal_rank>self.max_div:return-1parents[new_2]=new_1ranks[new_1]=total_ranknot_rep.append(new_2)return1return0def_union_find_rep(self,num,parents):"""Find representative of a class in a union-find data structure. Used in the implementation of Atkinson's algorithm as suggested in [1], pp. 83-87. After the representative of the class to which ``num`` belongs is found, path compression is performed as an optimization ([7]). Notes ===== THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives, ``parents``, is altered due to path compression. See Also ======== minimal_block, _union_find_merge References ========== [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory" [7] http://www.algorithmist.com/index.php/Union_Find """rep,parent=num,parents[num]whileparent!=rep:rep=parentparent=parents[rep]# path compressiontemp,parent=num,parents[num]whileparent!=rep:parents[temp]=reptemp=parentparent=parents[temp]returnrep@property

[docs]defbase(self):"""Return a base from the Schreier-Sims algorithm. For a permutation group ``G``, a base is a sequence of points ``B = (b_1, b_2, ..., b_k)`` such that no element of ``G`` apart from the identity fixes all the points in ``B``. The concepts of a base and strong generating set and their applications are discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. An alternative way to think of ``B`` is that it gives the indices of the stabilizer cosets that contain more than the identity permutation. Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> G = PermutationGroup([Permutation(0, 1, 3)(2, 4)]) >>> G.base [0, 2] See Also ======== strong_gens, basic_transversals, basic_orbits, basic_stabilizers """ifself._base==[]:self.schreier_sims()returnself._base

[docs]defbaseswap(self,base,strong_gens,pos,randomized=False,transversals=None,basic_orbits=None,strong_gens_distr=None):r"""Swap two consecutive base points in base and strong generating set. If a base for a group ``G`` is given by ``(b_1, b_2, ..., b_k)``, this function returns a base ``(b_1, b_2, ..., b_{i+1}, b_i, ..., b_k)``, where ``i`` is given by ``pos``, and a strong generating set relative to that base. The original base and strong generating set are not modified. The randomized version (default) is of Las Vegas type. Parameters ========== base, strong_gens The base and strong generating set. pos The position at which swapping is performed. randomized A switch between randomized and deterministic version. transversals The transversals for the basic orbits, if known. basic_orbits The basic orbits, if known. strong_gens_distr The strong generators distributed by basic stabilizers, if known. Returns ======= (base, strong_gens) ``base`` is the new base, and ``strong_gens`` is a generating set relative to it. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> S = SymmetricGroup(4) >>> S.schreier_sims() >>> S.base [0, 1, 2] >>> base, gens = S.baseswap(S.base, S.strong_gens, 1, randomized=False) >>> base, gens ([0, 2, 1], [(0 1 2 3), (3)(0 1), (1 3 2), (2 3), (1 3)]) check that base, gens is a BSGS >>> S1 = PermutationGroup(gens) >>> _verify_bsgs(S1, base, gens) True See Also ======== schreier_sims Notes ===== The deterministic version of the algorithm is discussed in [1], pp. 102-103; the randomized version is discussed in [1], p.103, and [2], p.98. It is of Las Vegas type. Notice that [1] contains a mistake in the pseudocode and discussion of BASESWAP: on line 3 of the pseudocode, ``|\beta_{i+1}^{\left\langle T\right\rangle}|`` should be replaced by ``|\beta_{i}^{\left\langle T\right\rangle}|``, and the same for the discussion of the algorithm. """# construct the basic orbits, generators for the stabilizer chain# and transversal elements from whatever was providedtransversals,basic_orbits,strong_gens_distr= \
_handle_precomputed_bsgs(base,strong_gens,transversals,basic_orbits,strong_gens_distr)base_len=len(base)degree=self.degree# size of orbit of base[pos] under the stabilizer we seek to insert# in the stabilizer chain at position pos + 1size=len(basic_orbits[pos])*len(basic_orbits[pos+1]) \
//len(_orbit(degree,strong_gens_distr[pos],base[pos+1]))# initialize the wanted stabilizer by a subgroupifpos+2>base_len-1:T=[]else:T=strong_gens_distr[pos+2][:]# randomized versionifrandomizedisTrue:stab_pos=PermutationGroup(strong_gens_distr[pos])schreier_vector=stab_pos.schreier_vector(base[pos+1])# add random elements of the stabilizer until they generate itwhilelen(_orbit(degree,T,base[pos]))!=size:new=stab_pos.random_stab(base[pos+1],schreier_vector=schreier_vector)T.append(new)# deterministic versionelse:Gamma=set(basic_orbits[pos])Gamma.remove(base[pos])ifbase[pos+1]inGamma:Gamma.remove(base[pos+1])# add elements of the stabilizer until they generate it by# ruling out member of the basic orbit of base[pos] along the waywhilelen(_orbit(degree,T,base[pos]))!=size:gamma=next(iter(Gamma))x=transversals[pos][gamma]temp=x._array_form.index(base[pos+1])# (~x)(base[pos + 1])iftempnotinbasic_orbits[pos+1]:Gamma=Gamma-_orbit(degree,T,gamma)else:y=transversals[pos+1][temp]el=rmul(x,y)ifel(base[pos])notin_orbit(degree,T,base[pos]):T.append(el)Gamma=Gamma-_orbit(degree,T,base[pos])# build the new base and strong generating setstrong_gens_new_distr=strong_gens_distr[:]strong_gens_new_distr[pos+1]=Tbase_new=base[:]base_new[pos],base_new[pos+1]=base_new[pos+1],base_new[pos]strong_gens_new=_strong_gens_from_distr(strong_gens_new_distr)forgeninT:ifgennotinstrong_gens_new:strong_gens_new.append(gen)returnbase_new,strong_gens_new

[docs]defcenter(self):r""" Return the center of a permutation group. The center for a group ``G`` is defined as ``Z(G) = \{z\in G | \forall g\in G, zg = gz \}``, the set of elements of ``G`` that commute with all elements of ``G``. It is equal to the centralizer of ``G`` inside ``G``, and is naturally a subgroup of ``G`` ([9]). Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> G = D.center() >>> G.order() 2 See Also ======== centralizer Notes ===== This is a naive implementation that is a straightforward application of ``.centralizer()`` """returnself.centralizer(self)

[docs]defcentralizer(self,other):r""" Return the centralizer of a group/set/element. The centralizer of a set of permutations ``S`` inside a group ``G`` is the set of elements of ``G`` that commute with all elements of ``S``:: ``C_G(S) = \{ g \in G | gs = sg \forall s \in S\}`` ([10]) Usually, ``S`` is a subset of ``G``, but if ``G`` is a proper subgroup of the full symmetric group, we allow for ``S`` to have elements outside ``G``. It is naturally a subgroup of ``G``; the centralizer of a permutation group is equal to the centralizer of any set of generators for that group, since any element commuting with the generators commutes with any product of the generators. Parameters ========== other a permutation group/list of permutations/single permutation Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) >>> S = SymmetricGroup(6) >>> C = CyclicGroup(6) >>> H = S.centralizer(C) >>> H.is_subgroup(C) True See Also ======== subgroup_search Notes ===== The implementation is an application of ``.subgroup_search()`` with tests using a specific base for the group ``G``. """ifhasattr(other,'generators'):ifother.is_trivialorself.is_trivial:returnselfdegree=self.degreeidentity=_af_new(list(range(degree)))orbits=other.orbits()num_orbits=len(orbits)orbits.sort(key=lambdax:-len(x))long_base=[]orbit_reps=[None]*num_orbitsorbit_reps_indices=[None]*num_orbitsorbit_descr=[None]*degreeforiinrange(num_orbits):orbit=list(orbits[i])orbit_reps[i]=orbit[0]orbit_reps_indices[i]=len(long_base)forpointinorbit:orbit_descr[point]=ilong_base=long_base+orbitbase,strong_gens=self.schreier_sims_incremental(base=long_base)strong_gens_distr=_distribute_gens_by_base(base,strong_gens)i=0foriinrange(len(base)):ifstrong_gens_distr[i]==[identity]:breakbase=base[:i]base_len=iforjinrange(num_orbits):ifbase[base_len-1]inorbits[j]:breakrel_orbits=orbits[:j+1]num_rel_orbits=len(rel_orbits)transversals=[None]*num_rel_orbitsforjinrange(num_rel_orbits):rep=orbit_reps[j]transversals[j]=dict(other.orbit_transversal(rep,pairs=True))trivial_test=lambdax:Truetests=[None]*base_lenforlinrange(base_len):ifbase[l]inorbit_reps:tests[l]=trivial_testelse:deftest(computed_words,l=l):g=computed_words[l]rep_orb_index=orbit_descr[base[l]]rep=orbit_reps[rep_orb_index]im=g._array_form[base[l]]im_rep=g._array_form[rep]tr_el=transversals[rep_orb_index][base[l]]# using the definition of transversal,# base[l]^g = rep^(tr_el*g);# if g belongs to the centralizer, then# base[l]^g = (rep^g)^tr_elreturnim==tr_el._array_form[im_rep]tests[l]=testdefprop(g):return[rmul(g,gen)forgeninother.generators]== \
[rmul(gen,g)forgeninother.generators]returnself.subgroup_search(prop,base=base,strong_gens=strong_gens,tests=tests)elifhasattr(other,'__getitem__'):gens=list(other)returnself.centralizer(PermutationGroup(gens))elifhasattr(other,'array_form'):returnself.centralizer(PermutationGroup([other]))

[docs]defcommutator(self,G,H):""" Return the commutator of two subgroups. For a permutation group ``K`` and subgroups ``G``, ``H``, the commutator of ``G`` and ``H`` is defined as the group generated by all the commutators ``[g, h] = hgh^{-1}g^{-1}`` for ``g`` in ``G`` and ``h`` in ``H``. It is naturally a subgroup of ``K`` ([1], p.27). Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> S = SymmetricGroup(5) >>> A = AlternatingGroup(5) >>> G = S.commutator(S, A) >>> G.is_subgroup(A) True See Also ======== derived_subgroup Notes ===== The commutator of two subgroups ``H, G`` is equal to the normal closure of the commutators of all the generators, i.e. ``hgh^{-1}g^{-1}`` for ``h`` a generator of ``H`` and ``g`` a generator of ``G`` ([1], p.28) """ggens=G.generatorshgens=H.generatorscommutators=[]forggeninggens:forhgeninhgens:commutator=rmul(hgen,ggen,~hgen,~ggen)ifcommutatornotincommutators:commutators.append(commutator)res=self.normal_closure(commutators)returnres

[docs]defcoset_factor(self,g,factor_index=False):"""Return ``G``'s (self's) coset factorization of ``g`` If ``g`` is an element of ``G`` then it can be written as the product of permutations drawn from the Schreier-Sims coset decomposition, The permutations returned in ``f`` are those for which the product gives ``g``: ``g = f[n]*...f[1]*f[0]`` where ``n = len(B)`` and ``B = G.base``. f[i] is one of the permutations in ``self._basic_orbits[i]``. If factor_index==True, returns a tuple ``[b[0],..,b[n]]``, where ``b[i]`` belongs to ``self._basic_orbits[i]`` Examples ======== >>> from sympy.combinatorics import Permutation, PermutationGroup >>> Permutation.print_cyclic = True >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) >>> G = PermutationGroup([a, b]) Define g: >>> g = Permutation(7)(1, 2, 4)(3, 6, 5) Confirm that it is an element of G: >>> G.contains(g) True Thus, it can be written as a product of factors (up to 3) drawn from u. See below that a factor from u1 and u2 and the Identity permutation have been used: >>> f = G.coset_factor(g) >>> f[2]*f[1]*f[0] == g True >>> f1 = G.coset_factor(g, True); f1 [0, 4, 4] >>> tr = G.basic_transversals >>> f[0] == tr[0][f1[0]] True If g is not an element of G then [] is returned: >>> c = Permutation(5, 6, 7) >>> G.coset_factor(c) [] see util._strip """ifisinstance(g,(Cycle,Permutation)):g=g.list()iflen(g)!=self._degree:# this could either adjust the size or return [] immediately# but we don't choose between the two and just signal a possible# errorraiseValueError('g should be the same size as permutations of G')I=list(range(self._degree))basic_orbits=self.basic_orbitstransversals=self._transversalsfactors=[]base=self.baseh=gforiinrange(len(base)):beta=h[base[i]]ifbeta==base[i]:factors.append(beta)continueifbetanotinbasic_orbits[i]:return[]u=transversals[i][beta]._array_formh=_af_rmul(_af_invert(u),h)factors.append(beta)ifh!=I:return[]iffactor_index:returnfactorstr=self.basic_transversalsfactors=[tr[i][factors[i]]foriinrange(len(base))]returnfactors

[docs]defcoset_rank(self,g):"""rank using Schreier-Sims representation The coset rank of ``g`` is the ordering number in which it appears in the lexicographic listing according to the coset decomposition The ordering is the same as in G.generate(method='coset'). If ``g`` does not belong to the group it returns None. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5) >>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6) >>> G = PermutationGroup([a, b]) >>> c = Permutation(7)(2, 4)(3, 5) >>> G.coset_rank(c) 16 >>> G.coset_unrank(16) (7)(2 4)(3 5) See Also ======== coset_factor """factors=self.coset_factor(g,True)ifnotfactors:returnNonerank=0b=1transversals=self._transversalsbase=self._basebasic_orbits=self._basic_orbitsforiinrange(len(base)):k=factors[i]j=basic_orbits[i].index(k)rank+=b*jb=b*len(transversals[i])returnrank

[docs]defdegree(self):"""Returns the size of the permutations in the group. The number of permutations comprising the group is given by len(group); the number of permutations that can be generated by the group is given by group.order(). Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 0, 2]) >>> G = PermutationGroup([a]) >>> G.degree 3 >>> len(G) 1 >>> G.order() 2 >>> list(G.generate()) [(2), (2)(0 1)] See Also ======== order """returnself._degree

@property

[docs]defelements(self):"""Returns all the elements of the permutatio group in a list Examples ======== >>> from sympy.combinatorics import Permutation """returnset(list(islice(self.generate(),None)))

[docs]defderived_series(self):r"""Return the derived series for the group. The derived series for a group ``G`` is defined as ``G = G_0 > G_1 > G_2 > \ldots`` where ``G_i = [G_{i-1}, G_{i-1}]``, i.e. ``G_i`` is the derived subgroup of ``G_{i-1}``, for ``i\in\mathbb{N}``. When we have ``G_k = G_{k-1}`` for some ``k\in\mathbb{N}``, the series terminates. Returns ======= A list of permutation groups containing the members of the derived series in the order ``G = G_0, G_1, G_2, \ldots``. Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup, DihedralGroup) >>> A = AlternatingGroup(5) >>> len(A.derived_series()) 1 >>> S = SymmetricGroup(4) >>> len(S.derived_series()) 4 >>> S.derived_series()[1].is_subgroup(AlternatingGroup(4)) True >>> S.derived_series()[2].is_subgroup(DihedralGroup(2)) True See Also ======== derived_subgroup """res=[self]current=selfnext=self.derived_subgroup()whilenotcurrent.is_subgroup(next):res.append(next)current=nextnext=next.derived_subgroup()returnres

[docs]defcontains(self,g,strict=True):"""Test if permutation ``g`` belong to self, ``G``. If ``g`` is an element of ``G`` it can be written as a product of factors drawn from the cosets of ``G``'s stabilizers. To see if ``g`` is one of the actual generators defining the group use ``G.has(g)``. If ``strict`` is not True, ``g`` will be resized, if necessary, to match the size of permutations in ``self``. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation(1, 2) >>> b = Permutation(2, 3, 1) >>> G = PermutationGroup(a, b, degree=5) >>> G.contains(G[0]) # trivial check True >>> elem = Permutation([[2, 3]], size=5) >>> G.contains(elem) True >>> G.contains(Permutation(4)(0, 1, 2, 3)) False If strict is False, a permutation will be resized, if necessary: >>> H = PermutationGroup(Permutation(5)) >>> H.contains(Permutation(3)) False >>> H.contains(Permutation(3), strict=False) True To test if a given permutation is present in the group: >>> elem in G.generators False >>> G.has(elem) False See Also ======== coset_factor, has, in """ifnotisinstance(g,Permutation):returnFalseifg.size!=self.degree:ifstrict:returnFalseg=Permutation(g,size=self.degree)ifginself.generators:returnTruereturnbool(self.coset_factor(g.array_form,True))

[docs]defis_alt_sym(self,eps=0.05,_random_prec=None):r"""Monte Carlo test for the symmetric/alternating group for degrees >= 8. More specifically, it is one-sided Monte Carlo with the answer True (i.e., G is symmetric/alternating) guaranteed to be correct, and the answer False being incorrect with probability eps. Notes ===== The algorithm itself uses some nontrivial results from group theory and number theory: 1) If a transitive group ``G`` of degree ``n`` contains an element with a cycle of length ``n/2 < p < n-2`` for ``p`` a prime, ``G`` is the symmetric or alternating group ([1], pp. 81-82) 2) The proportion of elements in the symmetric/alternating group having the property described in 1) is approximately ``\log(2)/\log(n)`` ([1], p.82; [2], pp. 226-227). The helper function ``_check_cycles_alt_sym`` is used to go over the cycles in a permutation and look for ones satisfying 1). Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.is_alt_sym() False See Also ======== _check_cycles_alt_sym """if_random_precisNone:n=self.degreeifn<8:returnFalseifnotself.is_transitive():returnFalseifn<17:c_n=0.34else:c_n=0.57d_n=(c_n*log(2))/log(n)N_eps=int(-log(eps)/d_n)foriinrange(N_eps):perm=self.random_pr()if_check_cycles_alt_sym(perm):returnTruereturnFalseelse:foriinrange(_random_prec['N_eps']):perm=_random_prec[i]if_check_cycles_alt_sym(perm):returnTruereturnFalse

@property

[docs]defis_nilpotent(self):"""Test if the group is nilpotent. A group ``G`` is nilpotent if it has a central series of finite length. Alternatively, ``G`` is nilpotent if its lower central series terminates with the trivial group. Every nilpotent group is also solvable ([1], p.29, [12]). Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup) >>> C = CyclicGroup(6) >>> C.is_nilpotent True >>> S = SymmetricGroup(5) >>> S.is_nilpotent False See Also ======== lower_central_series, is_solvable """ifself._is_nilpotentisNone:lcs=self.lower_central_series()terminator=lcs[len(lcs)-1]gens=terminator.generatorsdegree=self.degreeidentity=_af_new(list(range(degree)))ifall(g==identityforgingens):self._is_solvable=Trueself._is_nilpotent=TruereturnTrueelse:self._is_nilpotent=FalsereturnFalseelse:returnself._is_nilpotent

[docs]defis_primitive(self,randomized=True):"""Test if a group is primitive. A permutation group ``G`` acting on a set ``S`` is called primitive if ``S`` contains no nontrivial block under the action of ``G`` (a block is nontrivial if its cardinality is more than ``1``). Notes ===== The algorithm is described in [1], p.83, and uses the function minimal_block to search for blocks of the form ``\{0, k\}`` for ``k`` ranging over representatives for the orbits of ``G_0``, the stabilizer of ``0``. This algorithm has complexity ``O(n^2)`` where ``n`` is the degree of the group, and will perform badly if ``G_0`` is small. There are two implementations offered: one finds ``G_0`` deterministically using the function ``stabilizer``, and the other (default) produces random elements of ``G_0`` using ``random_stab``, hoping that they generate a subgroup of ``G_0`` with not too many more orbits than G_0 (this is suggested in [1], p.83). Behavior is changed by the ``randomized`` flag. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.is_primitive() False See Also ======== minimal_block, random_stab """ifself._is_primitiveisnotNone:returnself._is_primitiven=self.degreeifrandomized:random_stab_gens=[]v=self.schreier_vector(0)foriinrange(len(self)):random_stab_gens.append(self.random_stab(0,v))stab=PermutationGroup(random_stab_gens)else:stab=self.stabilizer(0)orbits=stab.orbits()fororbinorbits:x=orb.pop()ifx!=0andself.minimal_block([0,x])!=[0]*n:self._is_primitive=FalsereturnFalseself._is_primitive=TruereturnTrue

@property

[docs]defis_solvable(self):"""Test if the group is solvable. ``G`` is solvable if its derived series terminates with the trivial group ([1], p.29). Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(3) >>> S.is_solvable True See Also ======== is_nilpotent, derived_series """ifself._is_solvableisNone:ds=self.derived_series()terminator=ds[len(ds)-1]gens=terminator.generatorsdegree=self.degreeidentity=_af_new(list(range(degree)))ifall(g==identityforgingens):self._is_solvable=TruereturnTrueelse:self._is_solvable=FalsereturnFalseelse:returnself._is_solvable

[docs]defis_trivial(self):"""Test if the group is the trivial group. This is true if the group contains only the identity permutation. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup([Permutation([0, 1, 2])]) >>> G.is_trivial True """ifself._is_trivialisNone:self._is_trivial=len(self)==1andself[0].is_Identityreturnself._is_trivial

[docs]deflower_central_series(self):r"""Return the lower central series for the group. The lower central series for a group ``G`` is the series ``G = G_0 > G_1 > G_2 > \ldots`` where ``G_k = [G, G_{k-1}]``, i.e. every term after the first is equal to the commutator of ``G`` and the previous term in ``G1`` ([1], p.29). Returns ======= A list of permutation groups in the order ``G = G_0, G_1, G_2, \ldots`` Examples ======== >>> from sympy.combinatorics.named_groups import (AlternatingGroup, ... DihedralGroup) >>> A = AlternatingGroup(4) >>> len(A.lower_central_series()) 2 >>> A.lower_central_series()[1].is_subgroup(DihedralGroup(2)) True See Also ======== commutator, derived_series """res=[self]current=selfnext=self.commutator(self,current)whilenotcurrent.is_subgroup(next):res.append(next)current=nextnext=self.commutator(self,current)returnres

@property

[docs]defmax_div(self):"""Maximum proper divisor of the degree of a permutation group. Notes ===== Obviously, this is the degree divided by its minimal proper divisor (larger than ``1``, if one exists). As it is guaranteed to be prime, the ``sieve`` from ``sympy.ntheory`` is used. This function is also used as an optimization tool for the functions ``minimal_block`` and ``_union_find_merge``. Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> G = PermutationGroup([Permutation([0, 2, 1, 3])]) >>> G.max_div 2 See Also ======== minimal_block, _union_find_merge """ifself._max_divisnotNone:returnself._max_divn=self.degreeifn==1:return1forxinsieve:ifn%x==0:d=n//xself._max_div=dreturnd

[docs]defminimal_block(self,points):r"""For a transitive group, finds the block system generated by ``points``. If a group ``G`` acts on a set ``S``, a nonempty subset ``B`` of ``S`` is called a block under the action of ``G`` if for all ``g`` in ``G`` we have ``gB = B`` (``g`` fixes ``B``) or ``gB`` and ``B`` have no common points (``g`` moves ``B`` entirely). ([1], p.23; [6]). The distinct translates ``gB`` of a block ``B`` for ``g`` in ``G`` partition the set ``S`` and this set of translates is known as a block system. Moreover, we obviously have that all blocks in the partition have the same size, hence the block size divides ``|S|`` ([1], p.23). A ``G``-congruence is an equivalence relation ``~`` on the set ``S`` such that ``a ~ b`` implies ``g(a) ~ g(b)`` for all ``g`` in ``G``. For a transitive group, the equivalence classes of a ``G``-congruence and the blocks of a block system are the same thing ([1], p.23). The algorithm below checks the group for transitivity, and then finds the ``G``-congruence generated by the pairs ``(p_0, p_1), (p_0, p_2), ..., (p_0,p_{k-1})`` which is the same as finding the maximal block system (i.e., the one with minimum block size) such that ``p_0, ..., p_{k-1}`` are in the same block ([1], p.83). It is an implementation of Atkinson's algorithm, as suggested in [1], and manipulates an equivalence relation on the set ``S`` using a union-find data structure. The running time is just above ``O(|points||S|)``. ([1], pp. 83-87; [7]). Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(10) >>> D.minimal_block([0, 5]) [0, 6, 2, 8, 4, 0, 6, 2, 8, 4] >>> D.minimal_block([0, 1]) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] See Also ======== _union_find_rep, _union_find_merge, is_transitive, is_primitive """ifnotself.is_transitive():returnFalsen=self.degreegens=self.generators# initialize the list of equivalence class representativesparents=list(range(n))ranks=[1]*nnot_rep=[]k=len(points)# the block size must divide the degree of the groupifk>self.max_div:return[0]*nforiinrange(k-1):parents[points[i+1]]=points[0]not_rep.append(points[i+1])ranks[points[0]]=ki=0len_not_rep=k-1whilei<len_not_rep:temp=not_rep[i]i+=1forgeningens:# find has side effects: performs path compression on the list# of representativesdelta=self._union_find_rep(temp,parents)# union has side effects: performs union by rank on the list# of representativestemp=self._union_find_merge(gen(temp),gen(delta),ranks,parents,not_rep)iftemp==-1:return[0]*nlen_not_rep+=tempforiinrange(n):# force path compression to get the final state of the equivalence# relationself._union_find_rep(i,parents)returnparents

[docs]defnormal_closure(self,other,k=10):r"""Return the normal closure of a subgroup/set of permutations. If ``S`` is a subset of a group ``G``, the normal closure of ``A`` in ``G`` is defined as the intersection of all normal subgroups of ``G`` that contain ``A`` ([1], p.14). Alternatively, it is the group generated by the conjugates ``x^{-1}yx`` for ``x`` a generator of ``G`` and ``y`` a generator of the subgroup ``\left\langle S\right\rangle`` generated by ``S`` (for some chosen generating set for ``\left\langle S\right\rangle``) ([1], p.73). Parameters ========== other a subgroup/list of permutations/single permutation k an implementation-specific parameter that determines the number of conjugates that are adjoined to ``other`` at once Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... CyclicGroup, AlternatingGroup) >>> S = SymmetricGroup(5) >>> C = CyclicGroup(5) >>> G = S.normal_closure(C) >>> G.order() 60 >>> G.is_subgroup(AlternatingGroup(5)) True See Also ======== commutator, derived_subgroup, random_pr Notes ===== The algorithm is described in [1], pp. 73-74; it makes use of the generation of random elements for permutation groups by the product replacement algorithm. """ifhasattr(other,'generators'):degree=self.degreeidentity=_af_new(list(range(degree)))ifall(g==identityforginother.generators):returnotherZ=PermutationGroup(other.generators[:])base,strong_gens=Z.schreier_sims_incremental()strong_gens_distr=_distribute_gens_by_base(base,strong_gens)basic_orbits,basic_transversals= \
_orbits_transversals_from_bsgs(base,strong_gens_distr)self._random_pr_init(r=10,n=20)_loop=Truewhile_loop:Z._random_pr_init(r=10,n=10)foriinrange(k):g=self.random_pr()h=Z.random_pr()conj=h^gres=_strip(conj,base,basic_orbits,basic_transversals)ifres[0]!=identityorres[1]!=len(base)+1:gens=Z.generatorsgens.append(conj)Z=PermutationGroup(gens)strong_gens.append(conj)temp_base,temp_strong_gens= \
Z.schreier_sims_incremental(base,strong_gens)base,strong_gens=temp_base,temp_strong_gensstrong_gens_distr= \
_distribute_gens_by_base(base,strong_gens)basic_orbits,basic_transversals= \
_orbits_transversals_from_bsgs(base,strong_gens_distr)_loop=Falseforginself.generators:forhinZ.generators:conj=h^gres=_strip(conj,base,basic_orbits,basic_transversals)ifres[0]!=identityorres[1]!=len(base)+1:_loop=Truebreakif_loop:breakreturnZelifhasattr(other,'__getitem__'):returnself.normal_closure(PermutationGroup(other))elifhasattr(other,'array_form'):returnself.normal_closure(PermutationGroup([other]))

[docs]deforbit(self,alpha,action='tuples'):r"""Compute the orbit of alpha ``\{g(\alpha) | g \in G\}`` as a set. The time complexity of the algorithm used here is ``O(|Orb|*r)`` where ``|Orb|`` is the size of the orbit and ``r`` is the number of generators of the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. Here alpha can be a single point, or a list of points. If alpha is a single point, the ordinary orbit is computed. if alpha is a list of points, there are three available options: 'union' - computes the union of the orbits of the points in the list 'tuples' - computes the orbit of the list interpreted as an ordered tuple under the group action ( i.e., g((1,2,3)) = (g(1), g(2), g(3)) ) 'sets' - computes the orbit of the list interpreted as a sets Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) >>> G = PermutationGroup([a]) >>> G.orbit(0) set([0, 1, 2]) >>> G.orbit([0, 4], 'union') set([0, 1, 2, 3, 4, 5, 6]) See Also ======== orbit_transversal """return_orbit(self.degree,self.generators,alpha,action)

[docs]deforbit_rep(self,alpha,beta,schreier_vector=None):"""Return a group element which sends ``alpha`` to ``beta``. If ``beta`` is not in the orbit of ``alpha``, the function returns ``False``. This implementation makes use of the schreier vector. For a proof of correctness, see [1], p.80 Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> G = AlternatingGroup(5) >>> G.orbit_rep(0, 4) (0 4 1 2 3) See Also ======== schreier_vector """ifschreier_vectorisNone:schreier_vector=self.schreier_vector(alpha)ifschreier_vector[beta]isNone:returnFalsek=schreier_vector[beta]gens=[x._array_formforxinself.generators]a=[]whilek!=-1:a.append(gens[k])beta=gens[k].index(beta)# beta = (~gens[k])(beta)k=schreier_vector[beta]ifa:return_af_new(_af_rmuln(*a))else:return_af_new(list(range(self._degree)))

[docs]deforbit_transversal(self,alpha,pairs=False):r"""Computes a transversal for the orbit of ``alpha`` as a set. For a permutation group ``G``, a transversal for the orbit ``Orb = \{g(\alpha) | g \in G\}`` is a set ``\{g_\beta | g_\beta(\alpha) = \beta\}`` for ``\beta \in Orb``. Note that there may be more than one possible transversal. If ``pairs`` is set to ``True``, it returns the list of pairs ``(\beta, g_\beta)``. For a proof of correctness, see [1], p.79 Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> G.orbit_transversal(0) [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] See Also ======== orbit """return_orbit_transversal(self._degree,self.generators,alpha,pairs)

[docs]deforder(self):"""Return the order of the group: the number of permutations that can be generated from elements of the group. The number of permutations comprising the group is given by len(group); the length of each permutation in the group is given by group.size. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a = Permutation([1, 0, 2]) >>> G = PermutationGroup([a]) >>> G.degree 3 >>> len(G) 1 >>> G.order() 2 >>> list(G.generate()) [(2), (2)(0 1)] >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.order() 6 See Also ======== degree """ifself._order!=None:returnself._orderifself._is_sym:n=self._degreeself._order=factorial(n)returnself._orderifself._is_alt:n=self._degreeself._order=factorial(n)/2returnself._orderbasic_transversals=self.basic_transversalsm=1forxinbasic_transversals:m*=len(x)self._order=mreturnm

[docs]defpointwise_stabilizer(self,points,incremental=True):r"""Return the pointwise stabilizer for a set of points. For a permutation group ``G`` and a set of points ``\{p_1, p_2,\ldots, p_k\}``, the pointwise stabilizer of ``p_1, p_2, \ldots, p_k`` is defined as ``G_{p_1,\ldots, p_k} = \{g\in G | g(p_i) = p_i \forall i\in\{1, 2,\ldots,k\}\} ([1],p20). It is a subgroup of ``G``. Examples ======== >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(7) >>> Stab = S.pointwise_stabilizer([2, 3, 5]) >>> Stab.is_subgroup(S.stabilizer(2).stabilizer(3).stabilizer(5)) True See Also ======== stabilizer, schreier_sims_incremental Notes ===== When incremental == True, rather than the obvious implementation using successive calls to .stabilizer(), this uses the incremental Schreier-Sims algorithm to obtain a base with starting segment - the given points. """ifincremental:base,strong_gens=self.schreier_sims_incremental(base=points)stab_gens=[]degree=self.degreeforgeninstrong_gens:if[gen(point)forpointinpoints]==points:stab_gens.append(gen)ifnotstab_gens:stab_gens=_af_new(list(range(degree)))returnPermutationGroup(stab_gens)else:gens=self._generatorsdegree=self.degreeforxinpoints:gens=_stabilizer(degree,gens,x)returnPermutationGroup(gens)

[docs]defmake_perm(self,n,seed=None):""" Multiply ``n`` randomly selected permutations from pgroup together, starting with the identity permutation. If ``n`` is a list of integers, those integers will be used to select the permutations and they will be applied in L to R order: make_perm((A, B, C)) will give CBA(I) where I is the identity permutation. ``seed`` is used to set the seed for the random selection of permutations from pgroup. If this is a list of integers, the corresponding permutations from pgroup will be selected in the order give. This is mainly used for testing purposes. Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> a, b = [Permutation([1, 0, 3, 2]), Permutation([1, 3, 0, 2])] >>> G = PermutationGroup([a, b]) >>> G.make_perm(1, [0]) (0 1)(2 3) >>> G.make_perm(3, [0, 1, 0]) (0 2 3 1) >>> G.make_perm([0, 1, 0]) (0 2 3 1) See Also ======== random """ifis_sequence(n):ifseedisnotNone:raiseValueError('If n is a sequence, seed should be None')n,seed=len(n),nelse:try:n=int(n)exceptTypeError:raiseValueError('n must be an integer or a sequence.')randrange=_randrange(seed)# start with the identity permutationresult=Permutation(list(range(self.degree)))m=len(self)foriinrange(n):p=self[randrange(m)]result=rmul(result,p)returnresult

[docs]defrandom(self,af=False):"""Return a random group element """rank=randrange(self.order())returnself.coset_unrank(rank,af)

[docs]defrandom_pr(self,gen_count=11,iterations=50,_random_prec=None):"""Return a random group element using product replacement. For the details of the product replacement algorithm, see ``_random_pr_init`` In ``random_pr`` the actual 'product replacement' is performed. Notice that if the attribute ``_random_gens`` is empty, it needs to be initialized by ``_random_pr_init``. See Also ======== _random_pr_init """ifself._random_gens==[]:self._random_pr_init(gen_count,iterations)random_gens=self._random_gensr=len(random_gens)-1# handle randomized input for testing purposesif_random_precisNone:s=randrange(r)t=randrange(r-1)ift==s:t=r-1x=choice([1,2])e=choice([-1,1])else:s=_random_prec['s']t=_random_prec['t']ift==s:t=r-1x=_random_prec['x']e=_random_prec['e']ifx==1:random_gens[s]=_af_rmul(random_gens[s],_af_pow(random_gens[t],e))random_gens[r]=_af_rmul(random_gens[r],random_gens[s])else:random_gens[s]=_af_rmul(_af_pow(random_gens[t],e),random_gens[s])random_gens[r]=_af_rmul(random_gens[s],random_gens[r])return_af_new(random_gens[r])

[docs]defrandom_stab(self,alpha,schreier_vector=None,_random_prec=None):"""Random element from the stabilizer of ``alpha``. The schreier vector for ``alpha`` is an optional argument used for speeding up repeated calls. The algorithm is described in [1], p.81 See Also ======== random_pr, orbit_rep """ifschreier_vectorisNone:schreier_vector=self.schreier_vector(alpha)if_random_precisNone:rand=self.random_pr()else:rand=_random_prec['rand']beta=rand(alpha)h=self.orbit_rep(alpha,beta,schreier_vector)returnrmul(~h,rand)

[docs]defschreier_sims_incremental(self,base=None,gens=None):"""Extend a sequence of points and generating set to a base and strong generating set. Parameters ========== base The sequence of points to be extended to a base. Optional parameter with default value ``[]``. gens The generating set to be extended to a strong generating set relative to the base obtained. Optional parameter with default value ``self.generators``. Returns ======= (base, strong_gens) ``base`` is the base obtained, and ``strong_gens`` is the strong generating set relative to it. The original parameters ``base``, ``gens`` remain unchanged. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> A = AlternatingGroup(7) >>> base = [2, 3] >>> seq = [2, 3] >>> base, strong_gens = A.schreier_sims_incremental(base=seq) >>> _verify_bsgs(A, base, strong_gens) True >>> base[:2] [2, 3] Notes ===== This version of the Schreier-Sims algorithm runs in polynomial time. There are certain assumptions in the implementation - if the trivial group is provided, ``base`` and ``gens`` are returned immediately, as any sequence of points is a base for the trivial group. If the identity is present in the generators ``gens``, it is removed as it is a redundant generator. The implementation is described in [1], pp. 90-93. See Also ======== schreier_sims, schreier_sims_random """ifbaseisNone:base=[]ifgensisNone:gens=self.generators[:]degree=self.degreeid_af=list(range(degree))# handle the trivial groupiflen(gens)==1andgens[0].is_Identity:returnbase,gens# prevent side effects_base,_gens=base[:],gens[:]# remove the identity as a generator_gens=[xforxin_gensifnotx.is_Identity]# make sure no generator fixes all base pointsforgenin_gens:ifall(x==gen._array_form[x]forxin_base):fornewinid_af:ifgen._array_form[new]!=new:breakelse:assertNone# can this ever happen?_base.append(new)# distribute generators according to basic stabilizersstrong_gens_distr=_distribute_gens_by_base(_base,_gens)# initialize the basic stabilizers, basic orbits and basic transversalsorbs={}transversals={}base_len=len(_base)foriinrange(base_len):transversals[i]=dict(_orbit_transversal(degree,strong_gens_distr[i],_base[i],pairs=True,af=True))orbs[i]=list(transversals[i].keys())# main loop: amend the stabilizer chain until we have generators# for all stabilizersi=base_len-1whilei>=0:# this flag is used to continue with the main loop from inside# a nested loopcontinue_i=False# test the generators for being a strong generating setdb={}forbeta,u_betainlist(transversals[i].items()):forgeninstrong_gens_distr[i]:gb=gen._array_form[beta]u1=transversals[i][gb]g1=_af_rmul(gen._array_form,u_beta)ifg1!=u1:# test if the schreier generator is in the i+1-th# would-be basic stabilizery=Truetry:u1_inv=db[gb]exceptKeyError:u1_inv=db[gb]=_af_invert(u1)schreier_gen=_af_rmul(u1_inv,g1)h,j=_strip_af(schreier_gen,_base,orbs,transversals,i)ifj<=base_len:# new strong generator h at level jy=Falseelifh:# h fixes all base pointsy=Falsemoved=0whileh[moved]==moved:moved+=1_base.append(moved)base_len+=1strong_gens_distr.append([])ifyisFalse:# if a new strong generator is found, update the# data structures and start overh=_af_new(h)forlinrange(i+1,j):strong_gens_distr[l].append(h)transversals[l]=\
dict(_orbit_transversal(degree,strong_gens_distr[l],_base[l],pairs=True,af=True))orbs[l]=list(transversals[l].keys())i=j-1# continue main loop using the flagcontinue_i=Trueifcontinue_iisTrue:breakifcontinue_iisTrue:breakifcontinue_iisTrue:continuei-=1# build the strong generating setstrong_gens=list(uniq(iforgensinstrong_gens_distrforiingens))return_base,strong_gens

[docs]defschreier_sims_random(self,base=None,gens=None,consec_succ=10,_random_prec=None):r"""Randomized Schreier-Sims algorithm. The randomized Schreier-Sims algorithm takes the sequence ``base`` and the generating set ``gens``, and extends ``base`` to a base, and ``gens`` to a strong generating set relative to that base with probability of a wrong answer at most ``2^{-consec\_succ}``, provided the random generators are sufficiently random. Parameters ========== base The sequence to be extended to a base. gens The generating set to be extended to a strong generating set. consec_succ The parameter defining the probability of a wrong answer. _random_prec An internal parameter used for testing purposes. Returns ======= (base, strong_gens) ``base`` is the base and ``strong_gens`` is the strong generating set relative to it. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> from sympy.combinatorics.named_groups import SymmetricGroup >>> S = SymmetricGroup(5) >>> base, strong_gens = S.schreier_sims_random(consec_succ=5) >>> _verify_bsgs(S, base, strong_gens) #doctest: +SKIP True Notes ===== The algorithm is described in detail in [1], pp. 97-98. It extends the orbits ``orbs`` and the permutation groups ``stabs`` to basic orbits and basic stabilizers for the base and strong generating set produced in the end. The idea of the extension process is to "sift" random group elements through the stabilizer chain and amend the stabilizers/orbits along the way when a sift is not successful. The helper function ``_strip`` is used to attempt to decompose a random group element according to the current state of the stabilizer chain and report whether the element was fully decomposed (successful sift) or not (unsuccessful sift). In the latter case, the level at which the sift failed is reported and used to amend ``stabs``, ``base``, ``gens`` and ``orbs`` accordingly. The halting condition is for ``consec_succ`` consecutive successful sifts to pass. This makes sure that the current ``base`` and ``gens`` form a BSGS with probability at least ``1 - 1/\text{consec\_succ}``. See Also ======== schreier_sims """ifbaseisNone:base=[]ifgensisNone:gens=self.generatorsbase_len=len(base)n=self.degree# make sure no generator fixes all base pointsforgeningens:ifall(gen(x)==xforxinbase):new=0whilegen._array_form[new]==new:new+=1base.append(new)base_len+=1# distribute generators according to basic stabilizersstrong_gens_distr=_distribute_gens_by_base(base,gens)# initialize the basic stabilizers, basic transversals and basic orbitstransversals={}orbs={}foriinrange(base_len):transversals[i]=dict(_orbit_transversal(n,strong_gens_distr[i],base[i],pairs=True))orbs[i]=list(transversals[i].keys())# initialize the number of consecutive elements siftedc=0# start sifting random elements while the number of consecutive sifts# is less than consec_succwhilec<consec_succ:if_random_precisNone:g=self.random_pr()else:g=_random_prec['g'].pop()h,j=_strip(g,base,orbs,transversals)y=True# determine whether a new base point is neededifj<=base_len:y=Falseelifnoth.is_Identity:y=Falsemoved=0whileh(moved)==moved:moved+=1base.append(moved)base_len+=1strong_gens_distr.append([])# if the element doesn't sift, amend the strong generators and# associated stabilizers and orbitsifyisFalse:forlinrange(1,j):strong_gens_distr[l].append(h)transversals[l]=dict(_orbit_transversal(n,strong_gens_distr[l],base[l],pairs=True))orbs[l]=list(transversals[l].keys())c=0else:c+=1# build the strong generating setstrong_gens=strong_gens_distr[0][:]forgeninstrong_gens_distr[1]:ifgennotinstrong_gens:strong_gens.append(gen)returnbase,strong_gens

[docs]defschreier_vector(self,alpha):"""Computes the schreier vector for ``alpha``. The Schreier vector efficiently stores information about the orbit of ``alpha``. It can later be used to quickly obtain elements of the group that send ``alpha`` to a particular element in the orbit. Notice that the Schreier vector depends on the order in which the group generators are listed. For a definition, see [3]. Since list indices start from zero, we adopt the convention to use "None" instead of 0 to signify that an element doesn't belong to the orbit. For the algorithm and its correctness, see [2], pp.78-80. Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([2, 4, 6, 3, 1, 5, 0]) >>> b = Permutation([0, 1, 3, 5, 4, 6, 2]) >>> G = PermutationGroup([a, b]) >>> G.schreier_vector(0) [-1, None, 0, 1, None, 1, 0] See Also ======== orbit """n=self.degreev=[None]*nv[alpha]=-1orb=[alpha]used=[False]*nused[alpha]=Truegens=self.generatorsr=len(gens)forbinorb:foriinrange(r):temp=gens[i]._array_form[b]ifused[temp]isFalse:orb.append(temp)used[temp]=Truev[temp]=ireturnv

[docs]defstrong_gens(self):"""Return a strong generating set from the Schreier-Sims algorithm. A generating set ``S = \{g_1, g_2, ..., g_t\}`` for a permutation group ``G`` is a strong generating set relative to the sequence of points (referred to as a "base") ``(b_1, b_2, ..., b_k)`` if, for ``1 \leq i \leq k`` we have that the intersection of the pointwise stabilizer ``G^{(i+1)} := G_{b_1, b_2, ..., b_i}`` with ``S`` generates the pointwise stabilizer ``G^{(i+1)}``. The concepts of a base and strong generating set and their applications are discussed in depth in [1], pp. 87-89 and [2], pp. 55-57. Examples ======== >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> D.strong_gens [(0 1 2 3), (0 3)(1 2), (1 3)] >>> D.base [0, 1] See Also ======== base, basic_transversals, basic_orbits, basic_stabilizers """ifself._strong_gens==[]:self.schreier_sims()returnself._strong_gens

[docs]defsubgroup_search(self,prop,base=None,strong_gens=None,tests=None,init_subgroup=None):"""Find the subgroup of all elements satisfying the property ``prop``. This is done by a depth-first search with respect to base images that uses several tests to prune the search tree. Parameters ========== prop The property to be used. Has to be callable on group elements and always return ``True`` or ``False``. It is assumed that all group elements satisfying ``prop`` indeed form a subgroup. base A base for the supergroup. strong_gens A strong generating set for the supergroup. tests A list of callables of length equal to the length of ``base``. These are used to rule out group elements by partial base images, so that ``tests[l](g)`` returns False if the element ``g`` is known not to satisfy prop base on where g sends the first ``l + 1`` base points. init_subgroup if a subgroup of the sought group is known in advance, it can be passed to the function as this parameter. Returns ======= res The subgroup of all elements satisfying ``prop``. The generating set for this group is guaranteed to be a strong generating set relative to the base ``base``. Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(7) >>> prop_even = lambda x: x.is_even >>> base, strong_gens = S.schreier_sims_incremental() >>> G = S.subgroup_search(prop_even, base=base, strong_gens=strong_gens) >>> G.is_subgroup(AlternatingGroup(7)) True >>> _verify_bsgs(G, base, G.generators) True Notes ===== This function is extremely lenghty and complicated and will require some careful attention. The implementation is described in [1], pp. 114-117, and the comments for the code here follow the lines of the pseudocode in the book for clarity. The complexity is exponential in general, since the search process by itself visits all members of the supergroup. However, there are a lot of tests which are used to prune the search tree, and users can define their own tests via the ``tests`` parameter, so in practice, and for some computations, it's not terrible. A crucial part in the procedure is the frequent base change performed (this is line 11 in the pseudocode) in order to obtain a new basic stabilizer. The book mentiones that this can be done by using ``.baseswap(...)``, however the current imlementation uses a more straightforward way to find the next basic stabilizer - calling the function ``.stabilizer(...)`` on the previous basic stabilizer. """# initialize BSGS and basic group propertiesdefget_reps(orbits):# get the minimal element in the base orderingreturn[min(orbit,key=lambdax:base_ordering[x]) \
fororbitinorbits]defupdate_nu(l):temp_index=len(basic_orbits[l])+1-\
len(res_basic_orbits_init_base[l])# this corresponds to the element larger than all pointsiftemp_index>=len(sorted_orbits[l]):nu[l]=base_ordering[degree]else:nu[l]=sorted_orbits[l][temp_index]ifbaseisNone:base,strong_gens=self.schreier_sims_incremental()base_len=len(base)degree=self.degreeidentity=_af_new(list(range(degree)))base_ordering=_base_ordering(base,degree)# add an element larger than all pointsbase_ordering.append(degree)# add an element smaller than all pointsbase_ordering.append(-1)# compute BSGS-related structuresstrong_gens_distr=_distribute_gens_by_base(base,strong_gens)basic_orbits,transversals=_orbits_transversals_from_bsgs(base,strong_gens_distr)# handle subgroup initialization and testsifinit_subgroupisNone:init_subgroup=PermutationGroup([identity])iftestsisNone:trivial_test=lambdax:Truetests=[]foriinrange(base_len):tests.append(trivial_test)# line 1: more initializations.res=init_subgroupf=base_len-1l=base_len-1# line 2: set the base for K to the base for Gres_base=base[:]# line 3: compute BSGS and related structures for Kres_base,res_strong_gens=res.schreier_sims_incremental(base=res_base)res_strong_gens_distr=_distribute_gens_by_base(res_base,res_strong_gens)res_generators=res.generatorsres_basic_orbits_init_base= \
[_orbit(degree,res_strong_gens_distr[i],res_base[i])\
foriinrange(base_len)]# initialize orbit representativesorbit_reps=[None]*base_len# line 4: orbit representatives for f-th basic stabilizer of Korbits=_orbits(degree,res_strong_gens_distr[f])orbit_reps[f]=get_reps(orbits)# line 5: remove the base point from the representatives to avoid# getting the identity element as a generator for Korbit_reps[f].remove(base[f])# line 6: more initializationsc=[0]*base_lenu=[identity]*base_lensorted_orbits=[None]*base_lenforiinrange(base_len):sorted_orbits[i]=basic_orbits[i][:]sorted_orbits[i].sort(key=lambdapoint:base_ordering[point])# line 7: initializationsmu=[None]*base_lennu=[None]*base_len# this corresponds to the element smaller than all pointsmu[l]=degree+1update_nu(l)# initialize computed wordscomputed_words=[identity]*base_len# line 8: main loopwhileTrue:# apply all the testswhilel<base_len-1and \
computed_words[l](base[l])inorbit_reps[l]and \
base_ordering[mu[l]]< \
base_ordering[computed_words[l](base[l])]< \
base_ordering[nu[l]]and \
tests[l](computed_words):# line 11: change the (partial) base of Knew_point=computed_words[l](base[l])res_base[l]=new_pointnew_stab_gens=_stabilizer(degree,res_strong_gens_distr[l],new_point)res_strong_gens_distr[l+1]=new_stab_gens# line 12: calculate minimal orbit representatives for the# l+1-th basic stabilizerorbits=_orbits(degree,new_stab_gens)orbit_reps[l+1]=get_reps(orbits)# line 13: amend sorted orbitsl+=1temp_orbit=[computed_words[l-1](point)forpointinbasic_orbits[l]]temp_orbit.sort(key=lambdapoint:base_ordering[point])sorted_orbits[l]=temp_orbit# lines 14 and 15: update variables used minimality testsnew_mu=degree+1foriinrange(l):ifbase[l]inres_basic_orbits_init_base[i]:candidate=computed_words[i](base[i])ifbase_ordering[candidate]>base_ordering[new_mu]:new_mu=candidatemu[l]=new_muupdate_nu(l)# line 16: determine the new transversal elementc[l]=0temp_point=sorted_orbits[l][c[l]]gamma=computed_words[l-1]._array_form.index(temp_point)u[l]=transversals[l][gamma]# update computed wordscomputed_words[l]=rmul(computed_words[l-1],u[l])# lines 17 & 18: apply the tests to the group element foundg=computed_words[l]temp_point=g(base[l])ifl==base_len-1and \
base_ordering[mu[l]]< \
base_ordering[temp_point]<base_ordering[nu[l]]and \
temp_pointinorbit_reps[l]and \
tests[l](computed_words)and \
prop(g):# line 19: reset the base of Kres_generators.append(g)res_base=base[:]# line 20: recalculate basic orbits (and transversals)res_strong_gens.append(g)res_strong_gens_distr=_distribute_gens_by_base(res_base,res_strong_gens)res_basic_orbits_init_base= \
[_orbit(degree,res_strong_gens_distr[i],res_base[i]) \
foriinrange(base_len)]# line 21: recalculate orbit representatives# line 22: reset the search depthorbit_reps[f]=get_reps(orbits)l=f# line 23: go up the tree until in the first branch not fully# searchedwhilel>=0andc[l]==len(basic_orbits[l])-1:l=l-1# line 24: if the entire tree is traversed, return Kifl==-1:returnPermutationGroup(res_generators)# lines 25-27: update orbit representativesifl<f:# line 26f=lc[l]=0# line 27temp_orbits=_orbits(degree,res_strong_gens_distr[f])orbit_reps[f]=get_reps(temp_orbits)# line 28: update variables used for minimality testingmu[l]=degree+1temp_index=len(basic_orbits[l])+1- \
len(res_basic_orbits_init_base[l])iftemp_index>=len(sorted_orbits[l]):nu[l]=base_ordering[degree]else:nu[l]=sorted_orbits[l][temp_index]# line 29: set the next element from the current branch and update# accorndinglyc[l]+=1ifl==0:gamma=sorted_orbits[l][c[l]]else:gamma=computed_words[l-1]._array_form.index(sorted_orbits[l][c[l]])u[l]=transversals[l][gamma]ifl==0:computed_words[l]=u[l]else:computed_words[l]=rmul(computed_words[l-1],u[l])

@property

[docs]deftransitivity_degree(self):"""Compute the degree of transitivity of the group. A permutation group ``G`` acting on ``\Omega = \{0, 1, ..., n-1\}`` is ``k``-fold transitive, if, for any k points ``(a_1, a_2, ..., a_k)\in\Omega`` and any k points ``(b_1, b_2, ..., b_k)\in\Omega`` there exists ``g\in G`` such that ``g(a_1)=b_1, g(a_2)=b_2, ..., g(a_k)=b_k`` The degree of transitivity of ``G`` is the maximum ``k`` such that ``G`` is ``k``-fold transitive. ([8]) Examples ======== >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> a = Permutation([1, 2, 0]) >>> b = Permutation([1, 0, 2]) >>> G = PermutationGroup([a, b]) >>> G.transitivity_degree 3 See Also ======== is_transitive, orbit """ifself._transitivity_degreeisNone:n=self.degreeG=self# if G is k-transitive, a tuple (a_0,..,a_k)# can be brought to (b_0,...,b_(k-1), b_k)# where b_0,...,b_(k-1) are fixed points;# consider the group G_k which stabilizes b_0,...,b_(k-1)# if G_k is transitive on the subset excluding b_0,...,b_(k-1)# then G is (k+1)-transitiveforiinrange(n):orb=G.orbit((i))iflen(orb)!=n-i:self._transitivity_degree=ireturniG=G.stabilizer(i)self._transitivity_degree=nreturnnelse:returnself._transitivity_degree

def_orbit(degree,generators,alpha,action='tuples'):r"""Compute the orbit of alpha ``\{g(\alpha) | g \in G\}`` as a set. The time complexity of the algorithm used here is ``O(|Orb|*r)`` where ``|Orb|`` is the size of the orbit and ``r`` is the number of generators of the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21. Here alpha can be a single point, or a list of points. If alpha is a single point, the ordinary orbit is computed. if alpha is a list of points, there are three available options: 'union' - computes the union of the orbits of the points in the list 'tuples' - computes the orbit of the list interpreted as an ordered tuple under the group action ( i.e., g((1, 2, 3)) = (g(1), g(2), g(3)) ) 'sets' - computes the orbit of the list interpreted as a sets Examples ======== >>> from sympy.combinatorics import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup, _orbit >>> a = Permutation([1, 2, 0, 4, 5, 6, 3]) >>> G = PermutationGroup([a]) >>> _orbit(G.degree, G.generators, 0) set([0, 1, 2]) >>> _orbit(G.degree, G.generators, [0, 4], 'union') set([0, 1, 2, 3, 4, 5, 6]) See Also ======== orbit, orbit_transversal """ifnothasattr(alpha,'__getitem__'):alpha=[alpha]gens=[x._array_formforxingenerators]iflen(alpha)==1oraction=='union':orb=alphaused=[False]*degreeforelinalpha:used[el]=Trueforbinorb:forgeningens:temp=gen[b]ifused[temp]==False:orb.append(temp)used[temp]=Truereturnset(orb)elifaction=='tuples':alpha=tuple(alpha)orb=[alpha]used=set([alpha])forbinorb:forgeningens:temp=tuple([gen[x]forxinb])iftempnotinused:orb.append(temp)used.add(temp)returnset(orb)elifaction=='sets':alpha=frozenset(alpha)orb=[alpha]used=set([alpha])forbinorb:forgeningens:temp=frozenset([gen[x]forxinb])iftempnotinused:orb.append(temp)used.add(temp)returnset([tuple(x)forxinorb])def_orbits(degree,generators):"""Compute the orbits of G. If rep=False it returns a list of sets else it returns a list of representatives of the orbits Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.perm_groups import PermutationGroup, _orbits >>> a = Permutation([0, 2, 1]) >>> b = Permutation([1, 0, 2]) >>> _orbits(a.size, [a, b]) [set([0, 1, 2])] """seen=set()# elements that have already appeared in orbitsorbs=[]sorted_I=list(range(degree))I=set(sorted_I)whileI:i=sorted_I[0]orb=_orbit(degree,generators,i)orbs.append(orb)# remove all indices that are in this orbitI-=orbsorted_I=[iforiinsorted_Iifinotinorb]returnorbsdef_orbit_transversal(degree,generators,alpha,pairs,af=False):r"""Computes a transversal for the orbit of ``alpha`` as a set. generators generators of the group ``G`` For a permutation group ``G``, a transversal for the orbit ``Orb = \{g(\alpha) | g \in G\}`` is a set ``\{g_\beta | g_\beta(\alpha) = \beta\}`` for ``\beta \in Orb``. Note that there may be more than one possible transversal. If ``pairs`` is set to ``True``, it returns the list of pairs ``(\beta, g_\beta)``. For a proof of correctness, see [1], p.79 if af is True, the transversal elements are given in array form Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.named_groups import DihedralGroup >>> from sympy.combinatorics.perm_groups import _orbit_transversal >>> G = DihedralGroup(6) >>> _orbit_transversal(G.degree, G.generators, 0, False) [(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)] """tr=[(alpha,list(range(degree)))]used=[False]*degreeused[alpha]=Truegens=[x._array_formforxingenerators]forx,pxintr:forgeningens:temp=gen[x]ifused[temp]==False:tr.append((temp,_af_rmul(gen,px)))used[temp]=Trueifpairs:ifnotaf:tr=[(x,_af_new(y))forx,yintr]returntrifaf:return[yfor_,yintr]return[_af_new(y)for_,yintr]def_stabilizer(degree,generators,alpha):r"""Return the stabilizer subgroup of ``alpha``. The stabilizer of ``\alpha`` is the group ``G_\alpha = \{g \in G | g(\alpha) = \alpha\}``. For a proof of correctness, see [1], p.79. degree degree of G generators generators of G Examples ======== >>> from sympy.combinatorics import Permutation >>> Permutation.print_cyclic = True >>> from sympy.combinatorics.perm_groups import _stabilizer >>> from sympy.combinatorics.named_groups import DihedralGroup >>> G = DihedralGroup(6) >>> _stabilizer(G.degree, G.generators, 5) [(5)(0 4)(1 3), (5)] See Also ======== orbit """orb=[alpha]table={alpha:list(range(degree))}table_inv={alpha:list(range(degree))}used=[False]*degreeused[alpha]=Truegens=[x._array_formforxingenerators]stab_gens=[]forbinorb:forgeningens:temp=gen[b]ifused[temp]isFalse:gen_temp=_af_rmul(gen,table[b])orb.append(temp)table[temp]=gen_temptable_inv[temp]=_af_invert(gen_temp)used[temp]=Trueelse:schreier_gen=_af_rmuln(table_inv[temp],gen,table[b])ifschreier_gennotinstab_gens:stab_gens.append(schreier_gen)return[_af_new(x)forxinstab_gens]PermGroup=PermutationGroup