
    wgܺ                     t   d Z ddlmZ ddlmZ ddlmZmZmZ ddl	m
Z
 ddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ed&d       Zed&d       Z ed        Z!d Z" G d de      Z# G d de      Z$d&dZ%d Z&d Z'd&dZ(dddZ)d Z*d Z+d'd Z,d! Z-d" Z.d# Z/d(d%Z0eZ1y$))z.Finitely Presented Groups and its algorithms.     )S)symbols)	FreeGroupFreeGroupElement
free_group)RewritingSystem)
CosetTablecoset_enumeration_rcoset_enumeration_c)PermutationGroup)invariant_factors)Matrix)gcd)DefaultPrinting)public)pollute)productc                 L    t        | |      }|ft        |j                        z   S N)FpGrouptuple_generatorsfr_grprelators	_fp_groups      b/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/combinatorics/fp_groups.pyfp_groupr      s&    )I<%	 5 5666    c                 6    t        | |      }||j                  fS r   )r   r   r   s      r   	xfp_groupr!      s    )Iy,,--r   c                     t        t        |      }t        |j                  D cg c]  }|j                   c}|j                         |S c c}w r   )r   r   r   name
generators)fr_grpmr   r   syms       r   	vfp_groupr'   !   s>    *I!2!23#SXX3Y5I5IJ 4s   Ac                     | S )zParse the passed relators. )relss    r   _parse_relatorsr+   (   s    Kr   c                   <   e Zd ZdZdZdZdZd Zd Zd Z	d Z
d Zed	        Zd
 Zd'dZ	 	 d(dZd Z	 	 d(dZd)dZd Zd*dZd Zd Zd)dZd ZeZd Zd Zd Zd Zd Zd Z d Z!d Z"d Z#ed         Z$ed!        Z%ed"        Z&ed#        Z'ed$        Z(d% Z)d& Z*y)+r   z
    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.

    TFc                     t        |      }|| _        || _        | j                         | _        t        dt        fd| i      | _        d | _        d| _	        d | _
        d | _        t        |       | _        d | _        y )NFpGroupElementgroupF)r+   r   r   r   r$   typer.   dtype_coset_table_is_standardized_order_centerr   _rewriting_system_perm_isomorphism)selfr   r   s      r   __init__zFpGroup.__init__=   s|    "8,  **,*^,=O
 ! !&!0!6!%r   c                 .    | j                   j                  S r   )r   r$   r8   s    r   r   zFpGroup._generatorsQ   s    )))r   c                 8    | j                   j                          y)zE
        Try to make the group's rewriting system confluent

        N)r6   make_confluentr;   s    r   r=   zFpGroup.make_confluentT   s    
 	--/r   c                 8    | j                   j                  |      S )z
        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.

        )r6   reduce)r8   words     r   r?   zFpGroup.reduce\   s     %%,,T22r   c                 |    | j                  ||dz  z        | j                  k(  ry| j                  j                  ryy)a+  
        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`)

        TFN)r?   identityr6   is_confluent)r8   word1word2s      r   equalszFpGroup.equalse   s9     ;;uUBY'4==8##00r   c                 .    | j                   j                  S r   )r   rC   r;   s    r   rC   zFpGroup.identityt   s    '''r   c                     || j                   v S r   )r   )r8   gs     r   __contains__zFpGroup.__contains__x   s    DOO##r   Nc                 x    t        d |D              st        d      t         fd|D              st        d      |rt         ||d      \  }}}nt         ||      \  }}|rt        |d   j                  |      }nt        t        d	      d   g       }|rdd
lm} | || |j                  d      fS |S )a  
        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]

        c              3   <   K   | ]  }t        |t                y wr   )
isinstancer   ).0rJ   s     r   	<genexpr>z#FpGroup.subgroup.<locals>.<genexpr>   s     Aq:a!12As   z&Generators must be `FreeGroupElement`sc              3   P   K   | ]  }|j                   j                  k(    y wr   )r/   r   )rO   rJ   r8   s     r   rP   z#FpGroup.subgroup.<locals>.<genexpr>   s     <!177doo-<s   #&z-Given generators are not members of the groupT)ChomomorphismrR   r    rS   Fcheck)	all
ValueErrorreidemeister_presentationr   r/   r   !sympy.combinatorics.homomorphismsrS   r$   )r8   gensrR   rS   rJ   r*   _genss   `      r   subgroupzFpGroup.subgroup{   s    * ADAAEFF<t<< !PQQ6tTQUYZNAtU/da@GAt!

D)A
2q)2.AFl1dALL%uMMMr   c                     |st         j                  }|dk(  rt        | ||||      }nt        | ||||      }|j	                         r|j                          |S )af  
        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.

        relator_based
max_cosetsdraft
incomplete)r	   coset_table_max_limitr
   r   is_completecompressr8   Hstrategyrc   rd   re   rR   s          r   coset_enumerationzFpGroup.coset_enumeration   s_      #99J&#D!
:?JXA $D!
:?JXA==?JJLr   c                 F    | j                   j                          d| _        y)z
        Standardized the coset table ``self`` and makes the internal variable
        ``_is_standardized`` equal to ``True``.

        TN)r2   standardizer3   r;   s    r   standardize_coset_tablezFpGroup.standardize_coset_table   s     	%%' $r   c                 l   |s| j                   2| j                  s| j                          | j                   j                  S | j                  g ||||      }|| _         | j                          | j                   j                  S | j                  |||||      }|j                          |j                  S )zL
        Return the mathematical coset table of ``self`` in ``H``.

        rb   )r2   r3   ro   rl   tablern   ri   s          r   coset_tablezFpGroup.coset_table   s       ,,,002 $$***	 **2xJ27J + P$%!,,.$$***&&q(z27J ' PAMMO77Nr   c           	      h   | j                   | j                   S | j                  0t        | j                  j                        | _         | j                   S t        | j                        dk(  r+| j
                  j                         | _         | j                   S t        | j                        dk(  rMt        t        | j                  D cg c]  }|j                  d   d    c}            | _         | j                   S | j                         r!t        j                  | _         | j                   S | j                         \  }}|rJt        |j                        }|| j                  ||      j                         z  | _         | j                   S | j!                  g       | _         | j                   S c c}w )a  
        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

        r      rT   )r4   r2   lenrq   r   r   orderr$   absr   
array_form_is_infiniter   Infinity_finite_index_subgroupr_   index)r8   rk   rr]   rR   inds         r   rv   zFpGroup.order   s_     ;;";;(d//556DK {{ 1$////1DK {{ !Q&ct}}"M!1<<?1#5"MNODK {{  **DK {{ 113GD!!''l!$---":"@"@"BB {{ #jjn{{ #Ns   F/c           	         t               }| j                  D ]!  }|j                  |j                                # t        | j                        |k  syg }| j                  D ]:  }|j                  | j                  D cg c]  }|j                  |       c}       < t        t        |            }dt        |      v ryyc c}w )zq
        Test if the group is infinite. Return `True` if the test succeeds
        and `None` otherwise

        Tr   N)	setr   updatecontains_generatorsr$   appendexponent_sumr   r   )r8   	used_gensr}   abelian_relsrelrJ   ms          r   ry   zFpGroup._is_infinite   s     E	 	6AQ2245	64??#y0== 	PCdoo N!1!1!!4 NO	P6,'(!!$$ !Os   >C
c                    | j                         }t        | j                        }|j                  | j                         |st        | j                        dk(  r%|g| j                  D cg c]
  }||k7  s	| c}z   }n| j                  j                  }d}||v s|dz  |v s|j                  r7|dk  r2| j                         }|dz  }||v s|dz  |v s|j                  r|dk  r2||g| j                  D cg c]
  }||k7  s	| c}z   }t        |      dz   dz  }|d| }||d }	d}
d}d}d}|s|dz  t        j                  k  rt        |t        j                        }| j                  |||
d	      }
|
j                         r|
}|}n)| j                  |	||d	      }|j                         r|}|	}|s|dz  }|s|dz  t        j                  k  r|sy
|j                          |fS c c}w c c}w )z
        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)`

           r   rB   
   rt   N   Trb   )NN)most_frequent_generatorlistr$   extendr   ru   r   rC   is_identityrandomr	   rf   minrl   rg   rh   )r8   sgenr*   rJ   randimidhalf1half2draft1draft2r   rR   halfs                  r   r{   zFpGroup._finite_index_subgroup  s
    **,DOO$DMM"4??#q(ED118QDD//bD(8D<L<LbD;;=DFA bD(8D<L<LbD $Kdoo"Jc1"JJ1vax!m$3#$1z???Az778A++Ea'-$ , @F!!#//!'-$ 0 @%%'A DQ 1z??? 	

QwE E #Ks   +
G*6G*7
G/G/c                     | j                   }| j                  }|D cg c]  t        fd|D               }}||j                  t	        |               S c c}w )Nc              3   @   K   | ]  }|j                          y wr   )generator_count)rO   r}   rJ   s     r   rP   z2FpGroup.most_frequent_generator.<locals>.<genexpr>H  s     8aQ&&q)8s   )r$   r   sumr|   max)r8   r]   r*   rJ   freqss      ` r   r   zFpGroup.most_frequent_generatorE  sQ    }}BFGQ8488GGEKKE
+,, Hs   Ac                     dd l }| j                  j                  }t        |j	                  dd            D ]4  }||j                  | j                        |j                  ddg      z  z  }6 |S )Nr   r      rt   rB   )r   r   rC   rangerandintchoicer$   )r8   r   r}   r   s       r   r   zFpGroup.randomK  sc    OO$$v~~a*+ 	HA&--0&--22GGGA	Hr   c                 z    |g k(  r| j                         S | j                  ||      }t        |j                        S )ae  
        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

        )rv   rl   ru   rq   )r8   rj   rk   rR   s       r   r|   zFpGroup.indexR  s7    $ 7::<&&q(3Aqww<r   c                     | j                   j                  dkD  rd| j                   j                  z  }|S dt        | j                        z  }|S )N   z<fp group with %s generators>z<fp group on the generators %s>)r   rankstrr$   r8   str_forms     r   __str__zFpGroup.__str__j  sI    ??"$69M9MMH  93t;OOHr   c                 $   ddl m} ddlm} | j	                         t
        j                  u rt        d      | j                  r | j                  }|j                         }||fS | j                  g       }| j                  }|D cg c]<  }t        t        |            D cg c]  }||   d|j                  |      z      c}> }	}}|	D cg c]
  } ||       }	}t        |	      } || |||	d      }|| _        ||fS c c}w c c}}w c c}w )z
        Return an isomorphic permutation group and the isomorphism.
        The implementation is dependent on coset enumeration so
        will only terminate for finite groups.

        r   )PermutationrV   z>Permutation presentation of infinite groups is not implementedr   FrW   )sympy.combinatoricsr   r\   rS   rv   r   rz   NotImplementedErrorr7   imagerr   r$   r   ru   r|   r   )
r8   r   rS   TPrR   r]   rJ   r   imagess
             r   _to_perm_groupzFpGroup._to_perm_groupw  s    	4B::<1::%% 'N O O!!&&A	A !t   $A??DNRSeCFmDqtAdjjmO,DSFS.45k!n5F5 (AT1dF%@A%&D"!t ES5s   D!!DDDDc                     | j                         \  }} t        ||      | }d}t        |t              r|gd}}g }|D ].  }|j                  }	|j                  |j                  |	             0 |r|d   S |S )a4  
        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`.

        FTr   )r   getattrrN   r   r$   r   invert)
r8   method_nameargsr   r   perm_resultsingleresultr/   r]   s
             r   _perm_group_listzFpGroup._perm_group_list  s     ""$1-ga-t4k#34#.-K  	*E##DMM!((4.)	* #vay..r   c                 $    | j                  d      S )z
        Return the list of lists containing the generators
        of the subgroups in the derived series of `self`.

        derived_seriesr   r;   s    r   r   zFpGroup.derived_series  s     $$%566r   c                 $    | j                  d      S )z
        Return the list of lists containing the generators
        of the subgroups in the lower central series of `self`.

        lower_central_seriesr   r;   s    r   r   zFpGroup.lower_central_series  s     $$%;<<r   c                 $    | j                  d      S )zI
        Return the list of generators of the center of `self`.

        centerr   r;   s    r   r   zFpGroup.center  s    
 $$X..r   c                 $    | j                  d      S )zS
        Return the list of generators of the derived subgroup of `self`.

        derived_subgroupr   r;   s    r   r   zFpGroup.derived_subgroup  s    
 $$%788r   c                 \    | j                         d   } ||      }| j                  d|      S )z
        Return the list of generators of the centralizer of `other`
        (a list of elements of `self`) in `self`.

        rt   centralizerr   r   r8   otherr   s      r   r   zFpGroup.centralizer  s3     !!$%$$]E::r   c                 \    | j                         d   } ||      }| j                  d|      S )z
        Return the list of generators of the normal closure of `other`
        (a list of elements of `self`) in `self`.

        rt   normal_closurer   r   s      r   r   zFpGroup.normal_closure  s4     !!$%$$%5u==r   c                 @    | j                         d   }t        ||      S )z
        Given an attribute of a `PermutationGroup`, return
        its value for a permutation group isomorphic to `self`.

        r   )r   r   )r8   attrr   s      r   _perm_propertyzFpGroup._perm_property  s$     !!$q$r   c                 $    | j                  d      S )z.
        Check if `self` is abelian.

        
is_abelianr   r;   s    r   r   zFpGroup.is_abelian  s     ""<00r   c                 $    | j                  d      S )z0
        Check if `self` is nilpotent.

        is_nilpotentr   r;   s    r   r   zFpGroup.is_nilpotent  s     "">22r   c                 $    | j                  d      S )z/
        Check if `self` is solvable.

        is_solvabler   r;   s    r   r   zFpGroup.is_solvable  s     ""=11r   c                 ^    | j                         \  }}|j                  |j                        S )z/
        List the elements of `self`.

        )r   r   elementsr8   r   r   s      r   r   zFpGroup.elements  s)     ""$1xx

##r   c                     t        | j                        dk  ry	 | j                         \  }}|j                  S # t        $ r t        d      w xY w)z6
        Return ``True`` if group is Cyclic.

        rt   Tz2Check for infinite Cyclic group is not implemented)ru   r$   r   r   	is_cyclicr   s      r   r   zFpGroup.is_cyclic  s^     t1$	<&&(DAq {{ # 	<% '; < <	<s	   : Ac                 z    	 | j                         \  }}|j                         S # t        $ r t        d      w xY w)z7
        Return Abelian Invariants of a group.
        z7abelian invariants is not implementedfor infinite group)r   r   abelian_invariantsr   s      r   r   zFpGroup.abelian_invariants  M    	<&&(DAq ##%% # 	<% '; < <	<   % :c                 z    	 | j                         \  }}|j                         S # t        $ r t        d      w xY w)zH
        Return subnormal series of maximum length for a group.
        z7composition series is not implementedfor infinite group)r   r   composition_seriesr   s      r   r   zFpGroup.composition_series  r   r   NF)ra   NNF)ra   r   )+__name__
__module____qualname____doc__is_group
is_FpGroupis_PermutationGroupr9   r   r=   r?   rG   propertyrC   rK   r_   rl   ro   rr   rv   ry   r{   r   r   r|   r   __repr__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r)   r   r   r   r   2   s;    HJ(*3 ( ($$L IMOT8% CGHM,!F,.`- 0 H2/&7=/9;>  1 1 3 3 2 2 $ $  	&	&r   r   c                   @     e Zd ZdZd fd	Zd Zd Zd Zd ZeZ	 xZ
S )
FpSubgroupz
    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

    c                     t         |           || _        t        |D ch c]  }||j                  k7  s| c}      | _        d | _        d | _        || _        y c c}w r   )	superr9   parentr   rC   r$   
_min_wordsrR   normal)r8   Gr]   r   rJ   	__class__s        r   r9   zFpSubgroup.__init__/  sQ    4Ca1

?CD  Ds
   AAc                 N    t         j                  t              r  j                  d }g } j                  D ]5  } j
                  r|j                         }|j                   ||             7 |D ]^  }|D ]U  }||k(  st        |t              s	|dz  |k(  r"t        |t              r|d   d   |d   d   dz  }}n|d   |t        |      dz
     }}t        |t              r|d   d   |d   d   dz  }
}	n|d   |t        |      dz
     }
}	||}}t        |t              r|d   |d   z  |d   dz  z  }t        |t              r|d   |d   z  |d   dz  z  }|	dz  |k(  r/||z  j                  s  |||z        }||vr|j                  |       |
dz  |k(  s#||z  j                  r4 |||z        }||vsE|j                  |       X a | _         j                   fdi fd j
                  r|j                         } |      S  j                  , j                  j                   j                        }| _        d} j                  }t        t        |            D ]$  }|j                  |   |j                  ||         }& |dk(  S )Nc                 \    | j                  d      \  }}|j                  s||fgS | | dz  gS )NTremovedrB   )cyclic_reductionr   )wpr}   s      r   _processz)FpSubgroup.__contains__.<locals>._processA  s;     --d-;DAq==!"Ax !1b5z)r   rB   r   rt   c                    | j                  d      \  } }|j                  sj                  r| v S D cg c]   }t        |t              s|d   |k(  r|d   " }}|D cg c]  }| j                  |      s| c}g k7  S c c}w c c}w )NTr   r   rt   )r   r   r   rN   r   power_of)r   r}   r   t	min_wordsr8   s       r   _is_subwordz,FpSubgroup.__contains__.<locals>._is_subword  s     ))$)71==DKK	>)'0 O!Jq%4HDEaDAI 1 OA O'(:!AJJqMA:b@@O:s   BB"B9Bc                    t        |       dk(  ryd}|t        |       k  r_|dz  }| j                  d|      } |      s.| j                  |t        |             }|vr |      |<   |   ry|t        |       k  r_y)Nr   Trt   F)ru   subword)r   r   prefixrestr  _word_breakknowns       r   r  z,FpSubgroup.__contains__.<locals>._word_break  s     q6Q;#a&jFAYYq!_F&v. 99QA/D5(&1$&7dT{# #a&j r   )rN   r   r   r   r$   r   r   r   r   ru   r   rR   rl   r   rq   A_dict)r8   rJ   r  r]   r   w1w2s1s2r1r2p1p2newrR   r   jr  r  r  r  s   `                @@@@r   rK   zFpSubgroup.__contains__7  s   dkk9-&*  -A{{..0KK,-
  '1B" &18Jr5,A<>FbL$
 &b%0%'U1Xr!uQx|B%'UBs2wqyMB%b%0%'U1Xr!uQx|B%'UBs2wqyMB "$RB%b%0!#Ar!uRUBY!6B%b%0!#Ar!uRUBY!6B r6R<B0C0C"*2b5/C"$ $C 0r6R<B0C0C"*2b5/C"$ $C 0M&1'1R #'I	A E$ {{&&(q>!vv~KK11$//BAA3q6] /GGAJqxx!~./6Mr   c                 r   | j                   st        j                  S t        | j                  t
              rt        j                  S | j                  ,| j                  j                  | j                         }|| _        | j                  j                         t        | j                  j                        z  S r   )r$   r   OnerN   r   r   rz   rR   rl   rv   ru   rq   )r8   rR   s     r   rv   zFpSubgroup.order  sy    55Ldkk9-::66>--doo>ADF {{  "3tvv||#444r   c                 "   t        | j                  t              rKt        t	        | j
                              D cg c]  }d|z  	 }}t        dj                  |            d   S | j                  j                  | j                        S c c}w )Nzx_%d, r   rT   )
rN   r   r   r   ru   r$   r   joinr_   rR   )r8   r   gen_symss      r   
to_FpGroupzFpSubgroup.to_FpGroup  sp    dkk9-,1#doo2F,GHqHHHdii12155{{##dff#-- Is   Bc                     t        | j                        dkD  rdt        | j                        z  }|S dt        | j                        z  }|S )Nr   z <fp subgroup with %s generators>z"<fp subgroup on the generators %s>)ru   r$   r   r   s     r   r   zFpSubgroup.__str__  sG    t"$9C<PPH  <c$//>RRHr   F)r   r   r   r   r9   rK   rv   r  r   r   __classcell__)r   s   @r   r   r   '  s*    wr
5. Hr   r   c           	      >   t        | g       }| j                  }d}|D ch c]  }t        |      |kD  s| }}t        |      |z
  D ch c]  }|j	                          }}|j                  |      }	g }
t        |
||	|j                  d   |||       |
S c c}w c c}w )aL  
    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"

       r   )r	   r   ru   r   identity_cyclic_reduction
conjugatesdescendant_subgroupsA)r   NYrR   Rlen_short_relr   R2R1	R1_c_listr   s              r   low_index_subgroupsr/    s    R 	1bA	

AM 	7#c#h6#	7B	7 69Vb[	Ac#
'
'
)	AB	AR I
AAy!##a&"a;H 
8 
Bs   BB	Bc                 F   |j                   }|j                  }|j                         rEt        ||j                        D ]  \  }	}
|j                  |
|	      r y   | j                  |       y t        t        t        |j                              |j                        D ]   \  }
}|j                  |
   ||      |
|}} n |j                  |j                  gz   }|D ]@  }||k  s	||j                  k(  s|j                  |   |      .t        | ||||||	       B y r   )r  
A_dict_invrg   r   omega
scan_checkr   r   ru   rq   r'  ntry_descendant)r   rR   r.  xr,  r(  r)  r  r1  r   alphaundefined_cosetundefined_genreachbetas                  r   r&  r&  	  s   XXFJ}}  AGG, 	HAu<<q)	 	  c!''l 3QSS9 	HE1wwu~fQi(016		 133% 	4Dax133;!''$-
=0I"J"R"1aB?)44	4r   c	           	      t   |j                         }	||	j                  k(  rR||k  rM|	j                  j                  dgt	        |	j
                        z         |	j                  j                  |       ||	j                  |   |	j                  |   <   ||	j                  |   |	j                  |   <   |	j                  j                  ||f       |	j                  ||	j                  |      ||	j                  |            sy|D ]  }
|	j                  d|
      r y t        |	|      rt        | |	|||||       yy)zZ
    Solves the problem of trying out each individual possibility
    for `\alpha^x.

    Nr   )copyr4  rq   r   ru   r'  r   r  r1  deduction_stackprocess_deductions_checkr3  first_in_classr&  )r   rR   r.  r,  r(  r7  r6  r;  r)  Dr   s              r   r5  r5  %  s    	
Aqss{tax	vc!##h'	

4"&AGGEN188A;%*AGGDM!,,q/"eQZ(%%i&<all1o&( ||Aq! aQ9aQ: r   c                 H   | j                   }d}dg|z  }dg|z  }d}t        d|      D ]  }t        |dz         D ]
  }d|||   <    |D ](  }	| j                  |   | j                  |	      |k7  s&d} n |rd}P||d<   d||<   d}t        |      D ]  }| j                  D ]w  }
| j                  |   | j                  |
      }| j                  ||      | j                  |
      }||d} n.||   |dz  }|||<   |||<   ||   |k  r   y||   |kD  sud} n |sd}   y)a  
    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]

    rB   NFrt   Tr   )r4  r   rq   r  r'  )rR   r)  r4  lamdanumu
next_alphar7  r;  r   r6  gammadeltas                r   r@  r@  <  s   l 	
AE
B
B J q! .%'N 	 DBr$xL	   	A wwu~ahhqk*e3!
	 J15	!H 	DSS ahhqk24)!((1+6 =EM!%Je9$QJE %BuI %BuIe9u$ e9u$!%J'( "
/	/.^ r   Fchange_gensc                 $   t        |      dk(  rxt        |d   t              st        d      |d   }t	        |j
                  |j                  |       \  }}|rt        |d   j                  |      S t        t        g       g       S t        |      dk(  r0|d   dd |d   dd }}|s||fS |d   j                  j                  }n(t        |      dk(  rd}t        |      d}t        |      g }g }t        |      t        |      k(  sj|}| rCt        |      t        |      k(  s,|}t        |||      \  }}| rt        |      t        |      k(  s,t        |      }t        |      t        |      k(  sj| r|D 	cg c]  }	|	j                  d   d    }
}	t        |
      d   }|j                  }|j
                  }t!        t#        |
|            }t%        |      D ]-  \  }}|j                  }|}|D ]  \  }}|||   |z  z  } |||<   / ||fS c c}	w )	a  
    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`.

    rt   r   z+The argument must be an instance of FpGrouprI  r   NzNot enough argumentszToo many arguments)ru   rN   r   	TypeErrorsimplify_presentationr$   r   r/   r   rC   RuntimeErrorr   elimination_technique_1_simplify_relatorsrx   r   dictzip	enumerate)rJ  r   r   r]   r*   rC   r   	prev_gens	prev_relsrJ   symsFsubsr  r}   ar   r&   r   s                      r   rM  rM    s    4yA~$q'7+IJJG*1<<:EG
d47==$//y}b))	Ta!WQZad:7==))t9>&A 1o %A1oII)nD	)	#i.CI"=I0tXFJD$ #i.CI"= "$' )nD	) ,01qQ"11tQ::||CdO$dO 	DAqAC 'Q$s)Q,&'DG	 : 2s   8Hc                    | dd } | sg S | d   j                   j                  }i }t        t        |             D ]  }| |   }|j	                         dk(  s|d   }t        |j                  d   d         }|j                  d   d   dk  r| |   dz  | |<   |dz  }||v rt        |||   j                  d   d         }||z  ||<    t        |j                               }t        |       D ]  \  }}||v r|j                  |d      }|j                         D ]`  }||v s||   j                  d   d   }|dz   dz  }|j                  ||z  |||z
  z  d      }|j                  || z  |||z
   z  d      }b || |<    | D 	cg c]  }	|	j                          } }	| |z  } t        t        |             } | j!                          	 | j#                  |       | S c c}	w # t$        $ r Y | S w xY w)a  
    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]

    Nr   rt   rB   T_allr   )r/   rC   r   ru   number_syllablesrw   rx   r   r   valuesrS  eliminate_wordsr   eliminate_wordr$  r   sortremoverZ   )
r*   rC   expsr   r   rJ   expone_syllables_wordsmax_expr}   s
             r   rP  rP    sK   : 7D	Aw}}%%H D3t9 
1g!Q&AAcnnQ'*+C~~a #a'q'2+QrEDy#tAw11!4Q78fDG
 t{{}- D/ 3%%!!"5d!C ((* 	ZADy1g((+A.7Q,((Wq73;7GPT(U((gXgckN8KTX(Y	Z Q 488aA'')8D8DD	?DIIKH K 9  Ks   G
G" "	G/.G/c                    |d d  }|j                          | d d  } i }g }t               }|D ]  }|j                         t        fd|D              r(t	              j                  d       D ]  }|j                  |      dk(  s||vs|j                  |      }|j                  ||z        }	|j                  |	dz   t        |            }
|j                  d|	      }|
|z  }|d|z  z  ||<   |j                  |j                                |j                  |          |D cg c]	  }||vs| }}|D cg c]#  }|j                  |d      j                         % }}t	        t        |            }	 |j                  |       | D cg c]	  }||vs| } }| |fS c c}w c c}w # t        $ r Y -w xY wc c}w )Nc              3   &   K   | ]  }|v  
 y wr   r)   )rO   rJ   contained_genss     r   rP   z*elimination_technique_1.<locals>.<genexpr>K  s     ;qqN";s   Treversert   r   rB   r[  )ra  r   r   anyr   r   r   r|   r  ru   r   r   r_  r$  rb  rZ   )r]   r*   rC   redundant_gensredundant_relsr   r   r   k	gen_indexbkfwchir}   rJ   ri  s                  @r   rO  rO  <  s   7D 	IIK7DNNI   002;N;;n-d+! 
	C""3'1,I1E$$S)IIc1f-	[[QC9[[I.e&)BqDks#  !8!8!:;%%c*
	& 7!q6A7D7`de[\AnT:TTVeDeD	?DH 7!q6A7D7: 8e  7s0   .	F*8F*(F/F4 	G G4	G ?G c                    g }d}| j                   }|j                  }|ri }i }|j                  |d<   t        | j                        D cg c]  }dgt        | j                        z   c}| _        t        | j                  | j                        D ]  \  }	}
| j                  |	   | j                  |
      }||k(  rRd| j                  |	   | j                  |
   <   d| j                  |   | j                  |
   <   |dz  }|sp|	   |
z  ||<   ||
|v s| j                  |	   | j                  |
      |
d|	}|j                  |       || j                  |	   | j                  |
   <   |s|	   |
z  ||   dz  z  |<    t        t        dj!                  |                  }|j#                  d      | _        || _        |r| _        t        t        t        | j                              t        t        | j                                    D ]  \  }}| j                  |   |   dk(  r'| j$                  j                  | j                  |   |<   Bt+        | j                  |   |   t,              sc| j&                  |j/                  | j                  |   |            }|| j                  |   |<   | j                  |   |   }|dz  | j                  |   |dz   <    yc c}w )z
    Parameters
    ==========

    C -- Coset table.
    homomorphism -- When set to True, return a dictionary containing the images
                     of the presentation generators in the original group.
    rt   r   Nz
<identity>_rB   r  )r   r$   rC   r   r4  ru   r'  r   r   r2  rq   r  r1  r   r   r   r  pop_schreier_free_group_schreier_generators_schreier_gen_elemrN   r   r|   )rR   rS   yrG  fXr^   taur   r7  r6  r;  	y_alpha_xgrp_gensr  r}   s                   r   define_schreier_generatorsr  j  s    	AE	

A	A A$)!##J
/qD6#acc(?
/ACAGGQSS) >qwwu~ahhqk*5=&2ACCJqxx{#)5ACCIall1o&QJEJqLD	!VE
188A;/7#$e,IHHY&/ACCJqxx{##&u:a<D	2#=i > Jtyy|,-H%\\!_A%A$c!##hs133x9 %133q6!9$..77ACCF1IAq	3'&&qwwqss1vay'9:AACCF1I771:a=D "uACCIa!e%+ 0s   	 Kc           
         | j                   j                  }|D cg c])  }t        | j                        D ]  }t	        | ||       + }}}|D ch c]  }t        |      dk(  s| c}t        t        fd|            }t        t        |            D ]  }||   }|j                  d      }|||<   ! | j                  D cg c]  }|v s	|dz  v s| c}| _	        d}|t        |      k  rX||   }|dz   }|t        |      k  r,|j                  ||         r||= n|dz  }|t        |      k  r,|dz  }|t        |      k  rX|| _        y c c}}w c c}w c c}w )Nrt   c                     | vS r   r)   )r   order_1_genss    r   <lambda>z'reidemeister_relators.<locals>.<lambda>  s    3l#: r   Tr[  rB   r   )r   r   r   r4  rewriteru   r   filterr_  rx  is_cyclic_conjugate_reidemeister_relators)	rR   r*  r@   cosetr*   r   r   r  r  s	           @r   reidemeister_relatorsr    sx   	

A01JuQSSzJeGAud#J#JDJ#3!s1v{A3L :DABD 3t9 Gl6Q
 *+)?)? IA-B,1F   IA
 	
A
c$i-GE#d)m$$T!W-GQ	 #d)m
 	
Q c$i-  $A9 K3Is   .EE&E	E c                     | j                   j                  }t        t        |            D ]H  }||   }|| j                  |   | j
                  |      z  }| j                  |   | j
                  |      }J |S )a  
    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

    )rw  rC   r   ru   r   r  rq   )rR   r7  r   vr   x_is         r   r  r    su    : 	
''A3q6] .dacc%j#''qxx}-. Hr   c                    | j                   }|j                  d       | j                  }t        t	        |      dz
  dd      D ]  }||   }t        t	        |      dz
  dd      D ]  }||   }|j                  |      dk(  s|j                  |      }|j                  ||z        }|j                  |dz   t	        |            }	|j                  d|      }
|	|
z  d|z  z  }||= ||= t        t	        |            D ]  }||   j                  ||      ||<       || _         || _        | j                  | j                   fS )a
  
    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])

    Trj  rt   rB   r   )
r  ra  rx  r   ru   r   r   r|   r  r`  )rR   r*   r]   r   r   r  r   ro  rp  rq  rr  rep_byls                r   elimination_technique_2r    sU   & ##DIIdI!!D3t9q="b) 1gs4y1}b"- 	Aq'C""3'1,$$S)IIc1f-	[[QC9[[I.R%2a4Gas4y) BA"1g44S&ADGB	  $A!A!!1#;#;;;r   Nc                    |st        | |      }|j                          |j                          t        ||       t	        |       |j
                  |j                  }}t        ||d      \  }}t        |      |_	        t        |      |_        |rIg }|D ])  }|j                  |j                  t        |                + |j                  |j                  |fS |j                  |j                  fS )a  
    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,))

    rV   TrI  )r
   rh   rn   r  r  rx  r  rM  r   schreier_generatorsr   ry  r   )fp_grprj   rR   rS   r]   r*   r^   r   s           r   r[   r[     s    V *JJL!--/q|<!'')A)A$D&tTtDJD$!$KA#DkA 	9CLL--c#h78	9$$a&=&=uDD  !"9"999r   )r)   r   r   )2r   sympy.core.singletonr   sympy.core.symbolr   sympy.combinatorics.free_groupsr   r   r   #sympy.combinatorics.rewritingsystemr   sympy.combinatorics.coset_tabler	   r
   r   r   r   sympy.matrices.normalformsr   sympy.matricesr   sympy.polys.polytoolsr   sympy.printing.defaultsr   sympy.utilitiesr   sympy.utilities.magicr   	itertoolsr   r   r!   r'   r+   r   r   r/  r&  r5  r@  rM  rP  rO  r  r  r  r  r[   r.   r)   r   r   <module>r     s    4 " %< < ?B B 1 8 ! % 3 " )  7 7 . .
  r&o r&jb bR6r48;.qn .3 6pNb'\1%f$B"J&<P<:~ "r   