
    wgB                     0    d dl mZ d dlmZ  G d d      Zy)    )deque)StateMachinec                   v    e Zd ZdZd Zd Zed        Zd Zd Z	ddZ
ddZdd	Zd
 ZddZd Zd Zd Zd Zy)RewritingSystema  
    A class implementing rewriting systems for `FpGroup`s.

    References
    ==========
    .. [1] Epstein, D., Holt, D. and Rees, S. (1991).
           The use of Knuth-Bendix methods to solve the word problem in automatic groups.
           Journal of Symbolic Computation, 12(4-5), pp.397-414.

    .. [2] GAP's Manual on its KBMAG package
           https://www.gap-system.org/Manuals/pkg/kbmag-1.5.3/doc/manual.pdf

    c                    || _         |j                  | _        d | _        d| _        d| _        d| _        d | _        i | _        i | _	        t        g d      | _        | j                          t        | j                        }||D cg c]  }|dz  	 c}z  }t        dt        | j                         z   |      | _        | j!                          y c c}w )Ni  d   F2   zReduction automaton for )group
generatorsalphabet_is_confluentmaxeqnstidyint_max_exceededreduction_automaton
_new_rulesrulesr   rules_cache_init_ruleslistr   reprconstruct_automaton)selfr   r   gens       h/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/combinatorics/rewritingsystem.py__init__zRewritingSystem.__init__   s    
((!  # $(  
 R= $--(
*53sBw55
#/0JDQUQ[Q[L\0\^h#i   " 6s   Cc                 >    || j                   kD  rd| _        || _         y)zF
        Set the maximum number of rules that can be defined

        FN)r   r   )r   ns     r   set_maxzRewritingSystem.set_max0   s"    
 t||!&D    c                 \    | j                   | j                         | _         | j                   S )z;
        Return `True` if the system is confluent

        )r   _check_confluencer   s    r   is_confluentzRewritingSystem.is_confluent:   s-     %!%!7!7!9D!!!r!   c                     | j                   j                  j                  }| j                   j                  D ]  }| j	                  ||        | j                          y N)r   
free_groupidentityrelatorsadd_rule_remove_redundancies)r   r)   rs      r   r   zRewritingSystem._init_rulesD   sM    ::((11$$ 	'AMM!X&	'!!#r!   c                     t        | j                        dz   | j                  kD  r'| j                         | _        d| _        t        d      || j                  |<   | j                  r|| j                  |<   yy)zW
        Add the rule r1 -> r2 with no checking or further
        deductions

           TzToo many rules were defined.N)	lenr   r   r#   r   r   RuntimeErrorr   r   )r   r1r2s      r   	_add_rulezRewritingSystem._add_ruleK   sk     tzz?Q-!%!7!7!9D!%D=>>

2##"$DOOB $r!   c                    t               }||k(  r|S ||k  r||}}||f| j                  v r|S | j                  j                  ||f       ||}}t        |      t        |      z
  dk  r}|| j                  vr%|j                  |       |s| j                  ||       |dz  |dz  kD  r?|dz  | j                  vr.|j                  |dz         |s| j                  |dz  |dz         t        |      t        |      z
  dkD  r|t        |      dz
     }|j                  dt        |      dz
        }||dz  z  }t        |      t        |      z
  dk  r4|| j                  vrd|s| j                  ||       |j                  |       n>t        |      t        |      z
  dk  r$| j                  |||      }|j                  |       t        |      t        |      z
  dkD  rt        |      t        |      z
  dkD  r|d   }|j                  dt        |            }|dz  |z  }t        |      t        |      z
  dk  r4|| j                  vrd|s| j                  ||       |j                  |       n>t        |      t        |      z
  dk  r$| j                  |||      }|j                  |       t        |      t        |      z
  dkD  r|S )N   r
   r/   r   )
setr   appendr0   r   addr4   subwordr+   update)	r   w1w2checknew_keyss1s2gnews	            r   r+   zRewritingSystem.add_ruleZ   s   58O7B8t'''OR)RB r7SWq #R NN2r*2vB2r6#;RV$NN2r62r62 "gB"$3r719AAs2wqy)BArEB2wR 1$TZZ' r2.LL$R3r7"Q&mmBE2$ "gB"$ "gB"$1AAs2w'BBrB2wR 1$TZZ' r2.LL$R3r7"Q&mmBE2$ "gB"$ r!   c                    t               }t               }| j                  j                         }|D ]  }| j                  ||      }| j                  ||         }||k7  rk| j                  |= |j	                  |       ||kD  r!|j	                  |       || j                  |<   s||k  sy|j	                  |       || j                  |<   || j                  |<    |r||fS y)a  
        Reduce left- and right-hand sides of reduction rules
        and remove redundant equations (i.e. those for which
        lhs == rhs). If `changes` is `True`, return a set
        containing the removed keys and a set containing the
        added keys

        )excludeN)r7   r   copyreducer9   )r   changesremovedaddedr   r-   vws           r   r,   z$RewritingSystem._remove_redundancies   s     %

! 	"AAq)AE!H%AAvJJqMAq5IIaL$%DJJqMUIIaL$%DJJqM !

1	" E>!r!   c                 8     j                   r j                  S t         j                  j	                               d } fd}d}d}|t              k  r$|   }|dz  }d}|t              k  r|   }|dz  }||k(  r |||      }	|	j                   ||dz  |             |	sE|	D ]F  }
 ||
|||      }|r$|r yj                  |       |t        |      z  }4|dk(  s: j                  c S  | j                  kD  rZ|sX j                  d      \  }}d}|rt        fd	|D              }D cg c]	  }||vs| c}j                  |       ||v rn|t              k  r|t              k  r$d _        |s j                          yc c}w )
zg
        Try to make the system confluent using the Knuth-Bendix
        completion algorithm

        c                    t        |       }t        |      }g }t        d||z         D ]  }| j                  ||z
  ||z   |z
  d      |j                  ||z
  |d      k(  s9| j                  d||z
  d      }||j                  d||z
  d      z  }|j                  ||z
  |d      }|j                  ||d      }|| j                  ||z   |z
  |d      z  }|j                  ||z  |z          |S )Nr/   F)strictr   )r0   ranger:   r8   )	r2   r3   len1len2resultjabcs	            r   	_overlapsz1RewritingSystem.make_confluent.<locals>._overlaps   s
   r7Dr7DF1dTk* )JJtaxqJG**QXq*?@

1d1fU
;A"**Q$u*==A

1T61U
;A

1d5
9A"**TD[1_d5*IIAMM!A#a%() Mr!   c                 $   | j                  |j                  |         }j                  |      }| j                  |j                  |         }j                  |      }||k7  r|rdgS 	 j                  |||      }|S y # t        $ r Y yw xY w)Nr   F)eliminate_wordr   rG   r+   r1   )rL   r2   r3   r>   str?   r   s          r   _process_overlapz8RewritingSystem.make_confluent.<locals>._process_overlap   s    $$RB8KKN$$RB8KKN6 !s
%#'==Au#='  ( %$%s   -B 	BBr   r/   r
   FT)rH   c              3   @   K   | ]  }j                  |        y wr'   )index).0r[   lhss     r   	<genexpr>z1RewritingSystem.make_confluent.<locals>.<genexpr>  s     8		!8s   )
r   r   r   r   keysr0   extendr   r,   min)r   r>   rX   r]   rJ   ir2   rT   r3   overlapsrL   r?   r-   rU   lra   s   `              @r   make_confluentzRewritingSystem.make_confluent   s    %%%4::??$%		  #c(lQBFA Ac#h,VQ8$R,	"b&" 56! 
2A/2r5AH #(

8,X.!U*  $111
2 4<<'44T4BDAqE8a88&)8QaZ18CJJqMQwA c#h, #c(lX "%%' 9s   7	FFc                 &    | j                  d      S )NT)r>   )ri   r$   s    r   r#   z!RewritingSystem._check_confluence  s    """..r!   Nc                    | j                   D ci c]  }||k7  s	|| j                   |    }}d}|}|rTd}|D ]J  }|}||   dz  |dz  kD  r|j                  |||   dd      }n|j                  |||   d      }||k7  sId}L |rT|S c c}w )zv
        Apply reduction rules to `word` excluding the reduction rule
        for the lhs equal to `exclude`

        TFr
   )_allinverse)rl   )r   rZ   )r   wordrE   r-   r   againrC   prevs           r   rG   zRewritingSystem.reduce  s     ,0::FagDJJqM!FF E !8R<!R%',,QatU,SC,,Qat,DC$; E!  
! Gs
   
B
B
c                 R    i }|D ]  }|dz  }||   dz  }||k  r|||<   |||<   ! |S )a0  
        Compute the inverse rules for a given set of rules.
        The inverse rules are used in the automaton for word reduction.

        Arguments:
            rules (dictionary): Rules for which the inverse rules are to computed.

        Returns:
            Dictionary of inverse_rules.

        r
    )r   r   inverse_rulesr-   rule_key_inverserule_value_inverses         r   _compute_inverse_rulesz&RewritingSystem._compute_inverse_rules-  sY      	EA "u"'(R"%552D./4D01	E r!   c                 :    | j                  | j                         y)a5  
        Construct the automaton based on the set of reduction rules of the system.

        Automata Design:
        The accept states of the automaton are the proper prefixes of the left hand side of the rules.
        The complete left hand side of the rules are the dead states of the automaton.

        N)_add_to_automatonr   r$   s    r   r   z#RewritingSystem.construct_automatonC  s     	tzz*r!   c                    g }i }|}| j                  |      }|j                  |       g }|D ]<  }||j                  z  }g ||<   t        |j                        }t	        |      }	t        d|	      D ]b  }
||
dz
     ||
   z  ||
<   ||
dz
     }|| j                  j                  vs5| j                  j                  |d       |j                  |       d |||<   ||v rPd| j                  j                  |   _
        ||   | j                  j                  |   _        |j                  |       || j                  j                  vs| j                  j                  |d||          ? t        |      }| j                  j                  D ]J  }|}| j                  j                  |   j                  }|dk(  rs|D ]m  }|| j                  j                  v r*| j                  j                  |   j                  ||       E| j                  j                  |   j                  ||       o |dk(  s|D ]  }||z  }t	        |      rW|| j                  j                  vr?|j                  dt	        |            }t	        |      r|| j                  j                  vr?t	        |      sd}| j                  j                  |   j                  ||        M t	        | j                  j                         t	        |      k7  r|D ]  }|}| j                  j                   D ]  }||z  }t	        |      rW|| j                  j                  vr?|j                  dt	        |            }t	        |      r|| j                  j                  vr?t	        |      sd}| j                  j                  |   j                  ||         yy)	an  
        Add new states and transitions to the automaton.

        Summary:
        States corresponding to the new rules added to the system are computed and added to the automaton.
        Transitions in the previously added states are also modified if necessary.

        Arguments:
            rules (dictionary) -- Dictionary of the newly added rules.

        r/   rU   )
state_typed)rz   rh_ruler[   startN)rv   r;   letter_form_elmr   r0   rP   r   states	add_stater8   rz   r|   remover7   add_transitionr:   automaton_alphabet)r   r   r   proper_prefixes	all_rulesrs   accept_statesruleletter_word_arraylen_letter_word_arrayrf   elemstatecurrent_state_namecurrent_state_typeletter_nexts                    r   rx   z!RewritingSystem._add_to_automatonN  s      	33I>'  	bD $"6"66$&OD! $T%9%9 :$'(9$:!A45 /'81'=>OPQ>R'R!!$(1-t77>>>,,66t6L!((./ %6OD!}$CF((//5@@I$((//5=$$T*433:::((224CQZ[_Q`2a/	b2 !!34 --44 	YE!&!%!9!9!@!@!G!R!R "S(0 jF!9!9!@!@@0077>MMfV\]0077>MMfVhi	j
 $s*0 YF.v5Ee*d6N6N6U6U)U %aU < e*d6N6N6U6U)Uu: ',,33E:II&RWXY	Y0 t''::;sCU?VV& Y%*""66II YF.v5Ee*d6N6N6U6U)U %aU < e*d6N6N6U6U)Uu: ',,33E:II&RWXYY Wr!   c                    | j                   r"| j                  | j                          i | _         d}|rd}| j                  j                  d   }t	        |j
                        D ]s  \  }}|j                  |   }| j                  j                  |   }|j                  dk(  r5|j                  }|j                  |t        |      z
  dz   |dz   |      }d} n|}u |r|S )af  
        Reduce a word using an automaton.

        Summary:
        All the symbols of the word are stored in an array and are given as the input to the automaton.
        If the automaton reaches a dead state that subword is replaced and the automaton is run from the beginning.
        The complete word has to be replaced when the word is read and the automaton reaches a dead state.
        So, this process is repeated until the word is read completely and the automaton reaches the accept state.

        Arguments:
            word (instance of FreeGroupElement) -- Word that needs to be reduced.

        r/   r   r}   r{   )r   rx   r   r   	enumerater~   transitionsrz   r|   substituted_wordr0   )	r   rn   flagcurrent_staterf   r[   next_state_name
next_statesubsts	            r   reduce_using_automatonz&RewritingSystem.reduce_using_automaton  s     ??""4??3 DOD 44;;GDM!$"6"67 +1"/";";A">!55<<_M
((C/&..E00S5I1IA1MqQRsTYZDD *+  r!   )Fr'   )__name__
__module____qualname____doc__r   r    propertyr%   r   r4   r+   r,   ri   r#   rG   rv   r   rx   r   rr   r!   r   r   r      sb    #< " "%<|<Zx/0,	+UYn r!   r   N)collectionsr   'sympy.combinatorics.rewritingsystem_fsmr   r   rr   r!   r   <module>r      s     @A Ar!   