
    \h"                     6   S SK JrJrJrJr  S SKJrJrJr  S SK	J
r
Jr   S rS rS rS rS rS	 rS
 rS rS rS rS rSS jrSS jrSS jrS S/\" S S5      " SS5      \" SS5      " SS5      \" S5      " S S5      " SS5      /4rS rS rS rSS jrS rg)     )Permutation_af_rmul
_af_invert_af_new)PermutationGroup_orbit_orbit_transversal)_distribute_gens_by_base_orbits_transversals_from_bsgsc                    [        U 5      U:  a  [        S5      e/ nUb^  U SSS2    HR  n[        [        US-   5      5      nUS:X  a  US-   XR'   X%US-   '   XTS-      XT   sXT'   XTS-   '   UR	                  U5        MT     U SSS2    HG  n[        [        US-   5      5      nXTS-      XTS-      XT   XTS-      4XTUS-   & UR	                  U5        MI     U$ )a  
Return the strong generators for dummy indices.

Parameters
==========

dummies : List of dummy indices.
    `dummies[2k], dummies[2k+1]` are paired indices.
    In base form, the dummy indices are always in
    consecutive positions.
sym : symmetry under interchange of contracted dummies::
    * None  no symmetry
    * 0     commuting
    * 1     anticommuting

n : number of indices

Examples
========

>>> from sympy.combinatorics.tensor_can import dummy_sgs
>>> dummy_sgs(list(range(2, 8)), 0, 8)
[[0, 1, 3, 2, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 5, 4, 6, 7, 8, 9],
 [0, 1, 2, 3, 4, 5, 7, 6, 8, 9], [0, 1, 4, 5, 2, 3, 6, 7, 8, 9],
 [0, 1, 2, 3, 6, 7, 4, 5, 8, 9]]
zList too largeN            )len
ValueErrorlistrangeappend)dummiessymnresjas         V/var/www/auris/envauris/lib/python3.13/site-packages/sympy/combinatorics/tensor_can.py	dummy_sgsr      s    6 7|a)**
C
1AU1q5\"Aax1u!a%1uXqtNAD!E(JJqM  UbU^q1u1uXqQxqQx7AE


1  J    c                    [        U5      nU  Vs/ s H  oD(       a  [        U5      OSPM     nnUSS n[        U5       H:  n[        U5       H(  u  p[        U5       H  n	XpU	   ;   d  M  XY   Xh'     M&     M*     M<     U$ s  snf )ao  
Return list of minima of the orbits of indices in group of dummies.
See ``double_coset_can_rep`` for the description of ``dummies`` and ``sym``.
``indices`` is the initial list of dummy indices.

Examples
========

>>> from sympy.combinatorics.tensor_can import _min_dummies
>>> _min_dummies([list(range(2, 8))], [0], list(range(10)))
[0, 1, 2, 2, 2, 2, 2, 2, 8, 9]
N)r   minr   	enumerate)
r   r   indices	num_typesdxmr   icr   s
             r   _min_dummiesr)   J   s     CI+237RBRD	 7A3
!*C9g&DA9%
?TCF & '  J 	4s   A?c                 8    X2    H  nXU      U:X  d  M  Us  $    g)zh
Return the representative h satisfying s[h[b]] == j

If there is not such a representative return None
N )sr   bS_cosetshs        r   _trace_Sr0   c   s'     [qT7a<H  r   c                 .    U H  nX0   U:X  d  M  Us  $    g)zh
Return the representative h satisfying h[gj] == p_i

If there is not such a representative return None
Nr+   )gjp_iDxtravr/   s       r   _trace_Dr5   o   s!     5C<H  r   c                 F   / nU  H  nX$;  a  UR                  U5        M  UR                  U5      nUS-  S:X  a  XES-      nOXES-
     nUR                  U5        UR                  U5        UR                  U5        UR                  U5        UR                  U5        M     g)z
remove p0 from dumx
r   r   r   N)r   indexremove)dumx	dumx_flatp0r   r%   k	p0_paireds          r   _dumx_remover>   {   s     C<JJrNHHRLq5A:q5	Iq5	I
		"
		)#

2 r   c                    / nSn[        U 5       H]  nXQ;   a1  UR                  [        X$   R                  5       5      5        US-  nM9  UR                  [	        [        U 5      5      /5        M_     [        U5      S-
  nX4   [	        [        U 5      5      /:X  a"  US-  nX4   [	        [        U 5      5      /:X  a  M"  US US-    $ Nr   r   )r   r   sortedvaluesr   r   )sizebasetransversalr   r   r'   s         r   transversal2cosetrF      s    
A	A4[9HHVKN11345FAHHd5;'()  	A
A
$4d$%
%	Q $4d$%
%Va!e9r   c                 2
  ^^/^0 UR                   nUR                  nUS-
  n[        [        U5      5      n[	        S U 5       5      (       + n	[        U5      n
U SS n/ nU H  nUR                  U5        M     USS nU Vs/ s H  oR                  PM     nnU(       a  [        XbU5      n/ n[        U
5       H%  nUR                  [        UU   UU   U5      5        M'     [        [        U5      5      nUUU4/n[        US-
  5       GH  nUnUU;   =(       a    UnU(       a)  U Vs/ s H  n[        U5      PM     nn[        UUU5      m/OU1m/U	(       a  [        XU5      m0OO[        US-
  5       VVs/ s H3  n[        [        UU Vs/ s H  n[        U5      PM     snU5      5      PM5     snnm0[        U/U04S jU 5       5      nU Vs/ s H  n[        U5      PM     nnU(       a  [        UUUSSS9OSnU(       a  U Vs/ s H  n[        U5      PM     nn[        U
5       H<  nUUU   ;   d  M  UU   b  UU   nO"UU   R!                  U5      S-  nUU   USS2   n  O   U/n/ n U(       Gaq  UR#                  5       u  n!n"m[        UU04S jT/ 5       5      U:w  a  M8  T/ Vs/ s H  nT0TU      U:X  d  M  UPM     n#n[%        U"U5      n$[        U$5      n%U# Vs/ s H  nU!U   PM
     n&nU Vs/ s H  nU%U   PM
     n'nU& Vs/ s H  nUU';   d  M  UPM     n(nU( H  n)U(       a-  ['        U!U)UU5      n*U*(       d  M!  U* V+s/ s H  n+U!U+   PM
     n*n+OU!n*U(       a  [)        U$U)   UU5      n,U,(       d  MY  OUU$U)   :w  a  Me  Un,U,U$U)      U:X  d   eU" V+s/ s H  n+U,U+   PM
     n,n+U* V+s/ s H  n+U,UU+      PM     n-n+U R+                  U*U,U-45        M     U(       a  GMq  U R-                  S	 S
9  S/U-  n.U (       aN  U R#                  5       u  n!n"mTSS U.SS :X  a  TS   U.S   :w  a    gOUR+                  U!U"T45        Tn.U (       a  MN  U Vs/ s H  oU   U:X  d  M  UPM     nnUU;   a  UR/                  U5        [1        XU5        / n[        U
5       H%  nUR                  [        UU   UU   U5      5        M'     GM     US   S   $ s  snf s  snf s  snf s  snnf s  snf s  snf s  snf s  snf s  snf s  snf s  sn+f s  sn+f s  sn+f s  snf )aR"  
Butler-Portugal algorithm for tensor canonicalization with dummy indices.

Parameters
==========

  dummies
    list of lists of dummy indices,
    one list for each type of index;
    the dummy indices are put in order contravariant, covariant
    [d0, -d0, d1, -d1, ...].

  sym
    list of the symmetries of the index metric for each type.

  possible symmetries of the metrics
          * 0     symmetric
          * 1     antisymmetric
          * None  no symmetry

  b_S
    base of a minimal slot symmetry BSGS.

  sgens
    generators of the slot symmetry BSGS.

  S_transversals
    transversals for the slot BSGS.

  g
    permutation representing the tensor.

Returns
=======

Return 0 if the tensor is zero, else return the array form of
the permutation representing the canonical form of the tensor.

Notes
=====

A tensor with dummy indices can be represented in a number
of equivalent ways which typically grows exponentially with
the number of indices. To be able to establish if two tensors
with many indices are equal becomes computationally very slow
in absence of an efficient algorithm.

The Butler-Portugal algorithm [3] is an efficient algorithm to
put tensors in canonical form, solving the above problem.

Portugal observed that a tensor can be represented by a permutation,
and that the class of tensors equivalent to it under slot and dummy
symmetries is equivalent to the double coset `D*g*S`
(Note: in this documentation we use the conventions for multiplication
of permutations p, q with (p*q)(i) = p[q[i]] which is opposite
to the one used in the Permutation class)

Using the algorithm by Butler to find a representative of the
double coset one can find a canonical form for the tensor.

To see this correspondence,
let `g` be a permutation in array form; a tensor with indices `ind`
(the indices including both the contravariant and the covariant ones)
can be written as

`t = T(ind[g[0]], \dots, ind[g[n-1]])`,

where `n = len(ind)`;
`g` has size `n + 2`, the last two indices for the sign of the tensor
(trick introduced in [4]).

A slot symmetry transformation `s` is a permutation acting on the slots
`t \rightarrow T(ind[(g*s)[0]], \dots, ind[(g*s)[n-1]])`

A dummy symmetry transformation acts on `ind`
`t \rightarrow T(ind[(d*g)[0]], \dots, ind[(d*g)[n-1]])`

Being interested only in the transformations of the tensor under
these symmetries, one can represent the tensor by `g`, which transforms
as

`g -> d*g*s`, so it belongs to the coset `D*g*S`, or in other words
to the set of all permutations allowed by the slot and dummy symmetries.

Let us explain the conventions by an example.

Given a tensor `T^{d3 d2 d1}{}_{d1 d2 d3}` with the slot symmetries
      `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`

      `T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}`

and symmetric metric, find the tensor equivalent to it which
is the lowest under the ordering of indices:
lexicographic ordering `d1, d2, d3` and then contravariant
before covariant index; that is the canonical form of the tensor.

The canonical form is `-T^{d1 d2 d3}{}_{d1 d2 d3}`
obtained using `T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`.

To convert this problem in the input for this function,
use the following ordering of the index names
(- for covariant for short) `d1, -d1, d2, -d2, d3, -d3`

`T^{d3 d2 d1}{}_{d1 d2 d3}` corresponds to `g = [4, 2, 0, 1, 3, 5, 6, 7]`
where the last two indices are for the sign

`sgens = [Permutation(0, 2)(6, 7), Permutation(0, 4)(6, 7)]`

sgens[0] is the slot symmetry `-(0, 2)`
`T^{a0 a1 a2 a3 a4 a5} = -T^{a2 a1 a0 a3 a4 a5}`

sgens[1] is the slot symmetry `-(0, 4)`
`T^{a0 a1 a2 a3 a4 a5} = -T^{a4 a1 a2 a3 a0 a5}`

The dummy symmetry group D is generated by the strong base generators
`[(0, 1), (2, 3), (4, 5), (0, 2)(1, 3), (0, 4)(1, 5)]`
where the first three interchange covariant and contravariant
positions of the same index (d1 <-> -d1) and the last two interchange
the dummy indices themselves (d1 <-> d2).

The dummy symmetry acts from the left
`d = [1, 0, 2, 3, 4, 5, 6, 7]`  exchange `d1 \leftrightarrow -d1`
`T^{d3 d2 d1}{}_{d1 d2 d3} == T^{d3 d2}{}_{d1}{}^{d1}{}_{d2 d3}`

`g=[4, 2, 0, 1, 3, 5, 6, 7]  -> [4, 2, 1, 0, 3, 5, 6, 7] = _af_rmul(d, g)`
which differs from `_af_rmul(g, d)`.

The slot symmetry acts from the right
`s = [2, 1, 0, 3, 4, 5, 7, 6]`  exchanges slots 0 and 2 and changes sign
`T^{d3 d2 d1}{}_{d1 d2 d3} == -T^{d1 d2 d3}{}_{d1 d2 d3}`

`g=[4,2,0,1,3,5,6,7]  -> [0, 2, 4, 1, 3, 5, 7, 6] = _af_rmul(g, s)`

Example in which the tensor is zero, same slot symmetries as above:
`T^{d2}{}_{d1 d3}{}^{d1 d3}{}_{d2}`

`= -T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}`   under slot symmetry `-(0,4)`;

`= T_{d3 d1}{}^{d3}{}^{d1 d2}{}_{d2}`    under slot symmetry `-(0,2)`;

`= T^{d3}{}_{d1 d3}{}^{d1 d2}{}_{d2}`    symmetric metric;

`= 0`  since two of these lines have tensors differ only for the sign.

The double coset D*g*S consists of permutations `h = d*g*s` corresponding
to equivalent tensors; if there are two `h` which are the same apart
from the sign, return zero; otherwise
choose as representative the tensor with indices
ordered lexicographically according to `[d1, -d1, d2, -d2, d3, -d3]`
that is ``rep = min(D*g*S) = min([d*g*s for d in D for s in S])``

The indices are fixed one by one; first choose the lowest index
for slot 0, then the lowest remaining index for slot 1, etc.
Doing this one obtains a chain of stabilizers

`S \rightarrow S_{b0} \rightarrow S_{b0,b1} \rightarrow \dots` and
`D \rightarrow D_{p0} \rightarrow D_{p0,p1} \rightarrow \dots`

where ``[b0, b1, ...] = range(b)`` is a base of the symmetric group;
the strong base `b_S` of S is an ordered sublist of it;
therefore it is sufficient to compute once the
strong base generators of S using the Schreier-Sims algorithm;
the stabilizers of the strong base generators are the
strong base generators of the stabilizer subgroup.

``dbase = [p0, p1, ...]`` is not in general in lexicographic order,
so that one must recompute the strong base generators each time;
however this is trivial, there is no need to use the Schreier-Sims
algorithm for D.

The algorithm keeps a TAB of elements `(s_i, d_i, h_i)`
where `h_i = d_i \times g \times s_i` satisfying `h_i[j] = p_j` for `0 \le j < i`
starting from `s_0 = id, d_0 = id, h_0 = g`.

The equations `h_0[0] = p_0, h_1[1] = p_1, \dots` are solved in this order,
choosing each time the lowest possible value of p_i

For `j < i`
`d_i*g*s_i*S_{b_0, \dots, b_{i-1}}*b_j = D_{p_0, \dots, p_{i-1}}*p_j`
so that for dx in `D_{p_0,\dots,p_{i-1}}` and sx in
`S_{base[0], \dots, base[i-1]}` one has `dx*d_i*g*s_i*sx*b_j = p_j`

Search for dx, sx such that this equation holds for `j = i`;
it can be written as `s_i*sx*b_j = J, dx*d_i*g*J = p_j`
`sx*b_j = s_i**-1*J; sx = trace(s_i**-1, S_{b_0,...,b_{i-1}})`
`dx**-1*p_j = d_i*g*J; dx = trace(d_i*g*J, D_{p_0,...,p_{i-1}})`

`s_{i+1} = s_i*trace(s_i**-1*J, S_{b_0,...,b_{i-1}})`
`d_{i+1} = trace(d_i*g*J, D_{p_0,...,p_{i-1}})**-1*d_i`
`h_{i+1}*b_i = d_{i+1}*g*s_{i+1}*b_i = p_i`

`h_n*b_j = p_j` for all j, so that `h_n` is the solution.

Add the found `(s, d, h)` to TAB1.

At the end of the iteration sort TAB1 with respect to the `h`;
if there are two consecutive `h` in TAB1 which differ only for the
sign, the tensor is zero, so return 0;
if there are two consecutive `h` which are equal, keep only one.

Then stabilize the slot generators under `i` and the dummy generators
under `p_i`.

Assign `TAB = TAB1` at the end of the iteration step.

At the end `TAB` contains a unique `(s, d, h)`, since all the slots
of the tensor `h` have been fixed to have the minimum value according
to the symmetries. The algorithm returns `h`.

It is important that the slot BSGS has lexicographic minimal base,
otherwise there is an `i` which does not belong to the slot base
for which `p_i` is fixed by the dummy symmetry only, while `i`
is not invariant from the slot stabilizer, so `p_i` is not in
general the minimal value.

This algorithm differs slightly from the original algorithm [3]:
  the canonical form is minimal lexicographically, and
  the BSGS has minimal base under lexicographic order.
  Equal tensors `h` are eliminated from TAB.


Examples
========

>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.tensor_can import double_coset_can_rep, get_transversals
>>> gens = [Permutation(x) for x in [[2, 1, 0, 3, 4, 5, 7, 6], [4, 1, 2, 3, 0, 5, 7, 6]]]
>>> base = [0, 2]
>>> g = Permutation([4, 2, 0, 1, 3, 5, 6, 7])
>>> transversals = get_transversals(base, gens)
>>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g)
[0, 1, 2, 3, 4, 5, 7, 6]

>>> g = Permutation([4, 1, 3, 0, 5, 2, 6, 7])
>>> double_coset_can_rep([list(range(6))], [0], base, gens, transversals, g)
0
r   c              3   (   #    U  H  oS L v   M
     g 7fNr+   ).0_s     r   	<genexpr>'double_coset_can_rep.<locals>.<genexpr>  s     ":c9cs   Nc              3   X   >^#    U  H  u  pm[        UU4S  jT 5       5      v   M      g7f)c              3   4   >#    U  H  nTTU      v   M     g 7frI   r+   rJ   xr/   mds     r   rL   1double_coset_can_rep.<locals>.<genexpr>.<genexpr>  s     /1b1h   N)r!   )rJ   r,   dr/   deltabrR   s      @r   rL   rM     s#     CsGA!#////ss   &*FT)afc              3   4   >#    U  H  nTTU      v   M     g 7frI   r+   rP   s     r   rL   rM     s     ,V2ad8VrT   c                     U S   $ )Nr+   )rQ   s    r   <lambda>&double_coset_can_rep.<locals>.<lambda>  s    "r   )keyr   rZ   )rC   
array_formr   r   anyr   extend_array_formrF   r   r   r   r)   r!   r	   r   r7   popr   r0   r5   r   sortr8   r>   )1r   r   b_SsgensS_transversalsgrC   num_dummiesr#   all_metrics_with_symr$   r9   r:   r%   r/   sgensxdsgsxr'   idnTABr-   testbrK   sgensx1iiddxr3   dsgsx1r4   rQ   deltap	p_i_indexTAB1r,   rU   deltab1dgdginvsdeltabgdeltapNEXTr   s1ixd1h1prevrV   rR   s1                 `                                @@r   double_coset_can_repr      sC   \ 66D	A(K5%&G"":c":::CI1:DI 
a&C%*+UmmUF+
*4nEE9YtAwA<= 
uT{
C a=/C4!8_S#V+126awqz6G2D'1-FSFd1B 8=TAXH7F fT %$' % %,% %$'(*, -7FHB CsCC&+,e'!*e, $D&#uF 	-34VjmVF4	"Bd2hr7&!"XF !%Rs 3a 7I!"Xill3F # UFggiGAq!,V,,3"(<&QBqtHOq&G<!QBrNE%,-WqtWG-)/0AuQxG0&7w!!w,AwD7 
 "!Q>:B .01baeb1B !"Q%f5B   be| B"Q%yC''''()qbfq)*,-"Bb2i"-RRL)A ) cp 			o	&sTzhhjGAq!"vcr"R5DH$ % 

Aq!9%D d $1Vtqy!V18JJqMTc*y!ALL47CFK@A "[ ^ q6":u , 3$' H - 5( = .07( 2& *-$ 2sr   S(S5S!
SS!S'S,(S1<S1S64S;	
T T TT
/TT$TS!c                    UR                   n[        U5      nU (       d  USS $ [        X5      n[        USS 5       H  nX`;  d  M
  U R	                  U5        M     UnU Hu  nU/U-  n	Sn
UR                  5        HB  n[        X{5      n[        U5       Vs/ s H  oR                  U5      PM     nnX:  d  M>  Un	Un
MD     U
(       d  Mj  [        Xz5      nMw     U$ s  snf )a  
Canonicalization of a tensor with respect to free indices
choosing the minimum with respect to lexicographical ordering
in the free indices.

Explanation
===========

``base``, ``gens``  BSGS for slot permutation group
``g``               permutation representing the tensor
``num_free``        number of free indices
The indices must be ordered with first the free indices

See explanation in double_coset_can_rep
The algorithm is a variation of the one given in [2].

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import canonical_free
>>> gens = [[1, 0, 2, 3, 5, 4], [2, 3, 0, 1, 4, 5],[0, 1, 3, 2, 5, 4]]
>>> gens = [Permutation(h) for h in gens]
>>> base = [0, 2]
>>> g = Permutation([2, 1, 0, 3, 4, 5])
>>> canonical_free(base, gens, g, 4)
[0, 3, 1, 2, 5, 4]

Consider the product of Riemann tensors
``T = R^{a}_{d0}^{d1,d2}*R_{d2,d1}^{d0,b}``
The order of the indices is ``[a, b, d0, -d0, d1, -d1, d2, -d2]``
The permutation corresponding to the tensor is
``g = [0, 3, 4, 6, 7, 5, 2, 1, 8, 9]``

In particular ``a`` is position ``0``, ``b`` is in position ``9``.
Use the slot symmetries to get `T` is a form which is the minimal
in lexicographic order in the free indices ``a`` and ``b``, e.g.
``-R^{a}_{d0}^{d1,d2}*R^{b,d0}_{d2,d1}`` corresponding to
``[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]``

>>> from sympy.combinatorics.tensor_can import riemann_bsgs, tensor_gens
>>> base, gens = riemann_bsgs
>>> size, sbase, sgens = tensor_gens(base, gens, [[], []], 0)
>>> g = Permutation([0, 3, 4, 6, 7, 5, 2, 1, 8, 9])
>>> canonical_free(sbase, [Permutation(h) for h in sgens], g, 2)
[0, 3, 4, 6, 1, 2, 7, 5, 9, 8]
Nr^   )	r_   r   get_transversalsrA   r   rB   r   r   r7   )rD   gensrh   num_freerC   transversalsrQ   r/   transvh_ir,   skr   r~   his                  r   canonical_freer     s    ` 	
Aq6Dt#D/LAcrF^=KKN  	
AfXo --/B!B).x92((2,B9x " 1A  H :s   Cc                 v    [        [        U 5      5      nSn[        U 5       H  nXA;   a  M
  X2U'   US-  nM     U$ r@   )r   r   )rC   fixed_slotsr   posr'   s        r   _get_map_slotsr   _  sC    
uT{
C
C4[Aq	 
 Jr   c                    / nS=pV[        [        X5      5       VVs/ s H  u  pxUPM	     n	nn[        U5      n
[        U 5       H=  nX;   a  UR	                  X   5        US-  nM"  UR	                  X5   U
-   5        US-  nM?     U$ s  snnf r@   )rA   zipr   r   r   )rC   r   freer,   r   r   r<   rK   yfdr   r'   s               r   _lift_sgensr   j  s    
AIAs;56	76!6B	74yH4[HHRUOFAHHQTH_%FA  H 
8s   Bc                    SSK Jn  [        U[        5      (       d  US;  a  [	        S5      eSnOG[        U5      n[        S U 5       5      (       d  [	        S5      e[        U5      U:w  a  [	        S5      eU R                  nSn/ nU HV  u  pp[        X5      (       d$  [        X5      nU(       d  U" XU/UQ76 nUs  $ Uu  pUR                  X/ /U-  U45        X{-  nMX     US:X  a  [        U[        5      (       d  U/nU/n/ nU H  nUR                  U5        M     U(       a-  U[        [        US   US	   S-   5      5      :w  a  [	        S
5      e[        U6 u  nnnUU:w  a  [	        SUU4-  5      e[        US-
  5       Vs/ s H  nUU;  d  M  UPM     nn[        U5      n[        UUU U5      nU(       d  U$ US	   US-
  :X  a  SOSnSn[        U5       H  u  nu  pp/ nU
S   R                  S-
  n[        U5       HT  nUUUU-    n/ nU H+  nUU;   d  M  UR                  UR!                  U5      5        M-     UR                  U5        UU-  nMV     XUU4UU'   M     [        U6 u  nnn[        U5       V s/ s H  n UR!                  U 5      PM     n!n UU-
  n"U V s/ s H  n U U;   d  M  U U-
  PM     n#n U(       a  U#R                  U"S-
  U"S-
  /5        OU#R                  U"S-
  U"S-
  /5        [#        UU!5      n$U Vs/ s H  nUU!;  d  M  U$U   PM     n%nU V&Vs/ s H4  n&[%        U&R&                   Vs/ s H  nUU!;  d  M  U$U   PM     sn5      PM6     n'n&nU V&V s/ s H  n&U& V s/ s H  n U U-
  PM
     sn PM     n(n&n [)        U%U'5      n)[%        U#5      n#[+        U(UU%U'U)U#5      n*U*S:X  a  g[-        UU!UU*5      n+U+$ s  snf s  sn f s  sn f s  snf s  snf s  snn&f s  sn f s  sn n&f )a  
canonicalize tensor formed by tensors

Parameters
==========

g : permutation representing the tensor

dummies : list representing the dummy indices
  it can be a list of dummy indices of the same type
  or a list of lists of dummy indices, one list for each
  type of index;
  the dummy indices must come after the free indices,
  and put in order contravariant, covariant
  [d0, -d0, d1,-d1,...]

msym :  symmetry of the metric(s)
    it can be an integer or a list;
    in the first case it is the symmetry of the dummy index metric;
    in the second case it is the list of the symmetries of the
    index metric for each type

v : list, (base_i, gens_i, n_i, sym_i) for tensors of type `i`

base_i, gens_i : BSGS for tensors of this type.
    The BSGS should have minimal base under lexicographic ordering;
    if not, an attempt is made do get the minimal BSGS;
    in case of failure,
    canonicalize_naive is used, which is much slower.

n_i :    number of tensors of type `i`.

sym_i :  symmetry under exchange of component tensors of type `i`.

    Both for msym and sym_i the cases are
        * None  no symmetry
        * 0     commuting
        * 1     anticommuting

Returns
=======

0 if the tensor is zero, else return the array form of
the permutation representing the canonical form of the tensor.

Algorithm
=========

First one uses canonical_free to get the minimum tensor under
lexicographic order, using only the slot symmetries.
If the component tensors have not minimal BSGS, it is attempted
to find it; if the attempt fails canonicalize_naive
is used instead.

Compute the residual slot symmetry keeping fixed the free indices
using tensor_gens(base, gens, list_free_indices, sym).

Reduce the problem eliminating the free indices.

Then use double_coset_can_rep and lift back the result reintroducing
the free indices.

Examples
========

one type of index with commuting metric;

`A_{a b}` and `B_{a b}` antisymmetric and commuting

`T = A_{d0 d1} * B^{d0}{}_{d2} * B^{d2 d1}`

`ord = [d0,-d0,d1,-d1,d2,-d2]` order of the indices

g = [1, 3, 0, 5, 4, 2, 6, 7]

`T_c = 0`

>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize, bsgs_direct_product
>>> from sympy.combinatorics import Permutation
>>> base2a, gens2a = get_symmetric_group_sgs(2, 1)
>>> t0 = (base2a, gens2a, 1, 0)
>>> t1 = (base2a, gens2a, 2, 0)
>>> g = Permutation([1, 3, 0, 5, 4, 2, 6, 7])
>>> canonicalize(g, range(6), 0, t0, t1)
0

same as above, but with `B_{a b}` anticommuting

`T_c = -A^{d0 d1} * B_{d0}{}^{d2} * B_{d1 d2}`

can = [0,2,1,4,3,5,7,6]

>>> t1 = (base2a, gens2a, 2, 1)
>>> canonicalize(g, range(6), 0, t0, t1)
[0, 2, 1, 4, 3, 5, 7, 6]

two types of indices `[a,b,c,d,e,f]` and `[m,n]`, in this order,
both with commuting metric

`f^{a b c}` antisymmetric, commuting

`A_{m a}` no symmetry, commuting

`T = f^c{}_{d a} * f^f{}_{e b} * A_m{}^d * A^{m b} * A_n{}^a * A^{n e}`

ord = [c,f,a,-a,b,-b,d,-d,e,-e,m,-m,n,-n]

g = [0,7,3, 1,9,5, 11,6, 10,4, 13,2, 12,8, 14,15]

The canonical tensor is
`T_c = -f^{c a b} * f^{f d e} * A^m{}_a * A_{m d} * A^n{}_b * A_{n e}`

can = [0,2,4, 1,6,8, 10,3, 11,7, 12,5, 13,9, 15,14]

>>> base_f, gens_f = get_symmetric_group_sgs(3, 1)
>>> base1, gens1 = get_symmetric_group_sgs(1)
>>> base_A, gens_A = bsgs_direct_product(base1, gens1, base1, gens1)
>>> t0 = (base_f, gens_f, 2, 0)
>>> t1 = (base_A, gens_A, 4, 0)
>>> dummies = [range(2, 10), range(10, 14)]
>>> g = Permutation([0, 7, 3, 1, 9, 5, 11, 6, 10, 4, 13, 2, 12, 8, 14, 15])
>>> canonicalize(g, dummies, [0, 0], t0, t1)
[0, 2, 4, 1, 6, 8, 10, 3, 11, 7, 12, 5, 13, 9, 15, 14]
r   )canonicalize_naiver   r   Nzmsym must be 0, 1 or Noner   c              3   *   #    U  H	  oS ;   v   M     g7f)r   Nr+   )rJ   msymxs     r   rL   canonicalize.<locals>.<genexpr>  s     ;dUL(ds   z!msym entries must be 0, 1 or Nonez6dummies and msym must have the same number of elementsrZ   zdummies is not validz&g has size %d, generators have size %dr   )sympy.combinatorics.testutilr   
isinstancer   r   r   allrC   _is_minimal_bsgsget_minimal_bsgsr   ra   r   gens_productsr   r"   r7   r   r   rb   r   r   r   ),rh   r   msymvr   r$   rC   num_tensorsv1base_igens_in_isym_imbsgscanflat_dummiesr9   size1sbaserf   r'   r   r   g1signstartfree_ilen_tensr   r/   frr<   rQ   pos_freesize_redg1_red	map_slots	sbase_redr   	sgens_reddummies_red
transv_redg2g3s,                                               r   canonicalizer   y  s-   z @dD!!|#899	I	;d;;;@AAw<9$HJ J66DK	B&'"  //$V4E(T>A>
"NF
		6B4#:u56 '( A~jt44)vLD!  U<?LQSDTWXDX-Y(ZZ/00 (,E5%u}4e}DF 	FTAX@!!<*?AD@4yH 
ua	2B	2$("1D
 E+4Q<''FC!9>>A%sA5%(*,AB6IIaggaj)  MM"XE  /1 ,8" '+D% &+8_5__H5hH$&<Bq!|*;la(lBF<x!|X\23x!|X\23tX.I',Bu!0A1uIB^cd^cYZS1(AR,)A,ST^cId6=>g!,!QAL!,gK>!)Y7JV_F	T9iV
EB	Qw	T8T2	.BIk AD 6< CSd,>s`   
OO O&
O4	O	
O	O'O$ 
O	OO$*
O/4O*O/O$*O/c           
         U  Vs/ s H  n[        U5      PM     n nU Vs/ s H  n[        U5      PM     nnU(       a  SOSn[        U S   5      U-
  n[        US   5      U-
  n[        [        U5      5      n[        [        XUU-   5      5      nU(       aS  U  V	s/ s H  n	U	SS U-   U	S   U-   U	S   U-   /-   PM     n n	U V	Vs/ s H  oU	 Vs/ s H  o3U-   PM	     sn-   PM     nn	nO=U  V	s/ s H  oU-   PM	     n n	U V	Vs/ s H  oU	 Vs/ s H  o3U-   PM	     sn-   PM     nn	nX-   n
U
$ s  snf s  snf s  sn	f s  snf s  snn	f s  sn	f s  snf s  snn	f )a  
Direct products of the generators gens1 and gens2.

Examples
========

>>> from sympy.combinatorics.tensor_can import perm_af_direct_product
>>> gens1 = [[1, 0, 2, 3], [0, 1, 3, 2]]
>>> gens2 = [[1, 0]]
>>> perm_af_direct_product(gens1, gens2, False)
[[1, 0, 2, 3, 4, 5], [0, 1, 3, 2, 4, 5], [0, 1, 2, 3, 5, 4]]
>>> gens1 = [[1, 0, 2, 3, 5, 4], [0, 1, 3, 2, 4, 5]]
>>> gens2 = [[1, 0, 2, 3]]
>>> perm_af_direct_product(gens1, gens2, True)
[[1, 0, 2, 3, 4, 5, 7, 6], [0, 1, 3, 2, 4, 5, 6, 7], [0, 1, 2, 3, 5, 4, 6, 7]]
r   r   Nr^   rZ   )r   r   r   )gens1gens2signedrQ   r,   n1n2r   endgenr   s              r   perm_af_direct_productr   Y  sX   " $$eT!WeE$#$eT!WeE$A	U1X	B	U1X	BrOE
uRb!
"C!#!S SbC3r7R<R2">>! 	 #:?@%3#.#Qb&#..%@&+,esse,:?@%3#.#Qb&#..%@
-CJ# %$#.@,.@sF   D,D1#D6
E D;	E -E
EE	E;E Ec                    U(       a  SOSnUS   R                   U-
  n[        U 5      nXr Vs/ s H  oU-   PM	     sn-  nU V	s/ s H  oR                  PM     nn	U V	s/ s H  oR                  PM     nn	[        XU5      n
[	        U
S   5      n[        [        U5      5      nU
 V	s/ s H  oU:w  d  M
  U	PM     n
n	U
(       d  U/n
Xz V	s/ s H  n	[        U	5      PM     sn	4$ s  snf s  sn	f s  sn	f s  sn	f s  sn	f )a  
Direct product of two BSGS.

Parameters
==========

base1 : base of the first BSGS.

gens1 : strong generating sequence of the first BSGS.

base2, gens2 : similarly for the second BSGS.

signed : flag for signed permutations.

Examples
========

>>> from sympy.combinatorics.tensor_can import (get_symmetric_group_sgs, bsgs_direct_product)
>>> base1, gens1 = get_symmetric_group_sgs(1)
>>> base2, gens2 = get_symmetric_group_sgs(2)
>>> bsgs_direct_product(base1, gens1, base2, gens2)
([1], [(4)(1 2)])
r   r   )rC   r   rb   r   r   r   r   )base1r   base2r   r   r,   r   rD   rQ   r/   r   rC   id_afs                r   bsgs_direct_productr   ~  s    0 A	q	B;DU#UVU##D$)*Eq]]EE*$)*Eq]]EE*!%7DtAw<DtE*t!EzAtD*wd+d'!*d+++ $** + ,s#   C$C)C.(	C35C3C8c                    U S:X  a   / [        [        [        S5      5      5      /4$ [        U S-
  5       Vs/ s H$  n[        U S-
  5      " X"S-   5      R                  PM&     nnUS:X  a  U Vs/ s H  oDX S-   /-   PM     nnOU Vs/ s H  oDU S-   U /-   PM     nn[        [        U S-
  5      5      nXS Vs/ s H  n[        U5      PM     sn4$ s  snf s  snf s  snf s  snf )ao  
Return base, gens of the minimal BSGS for (anti)symmetric tensor

Parameters
==========

n : rank of the tensor
antisym : bool
    ``antisym = False`` symmetric tensor
    ``antisym = True``  antisymmetric tensor

Examples
========

>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs
>>> get_symmetric_group_sgs(3)
([0, 1], [(4)(0 1), (4)(1 2)])
r   r   r   )r   r   r   r   rb   )r   antisymr'   r   rQ   rD   r/   s          r   get_symmetric_group_sgsr     s    & 	AvGDqN+,,,>CAElKlKAqa%(44lDK!|(,-1QAJ-(,-1QUAJ-a!eDd+d'!*d+++ L--+s   +C.CC7Cr   r   r      r   c                     U (       d  / $ [        X5      n[        X5      u  p4U VVVs/ s H1  oUR                  5        VVs0 s H  u  pgXgR                  _M     snnPM3     nnnnU$ s  snnf s  snnnf )z8
Return transversals for the group with BSGS base, gens
)r
   r   itemsrb   )rD   r   stabsorbitsr   r   rQ   r/   s           r   r   r     sq     	$T0E9$FF "  BC'')<)$!Q%)<   " = "s   A, A&A,&A,c                   ^ / nUSS nUS   R                   n[        U5       HV  m[        U4S jU 5       5      (       a  M  UR                  T5        U Vs/ s H  oUR                  T   T:X  d  M  UPM     nnMX     X :H  $ s  snf )a  
Check if the BSGS has minimal base under lexigographic order.

base, gens BSGS

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import riemann_bsgs, _is_minimal_bsgs
>>> _is_minimal_bsgs(*riemann_bsgs)
True
>>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)]))
>>> _is_minimal_bsgs(*riemann_bsgs1)
False
Nr   c              3   F   >#    U  H  oR                   T   T:H  v   M     g 7frI   )rb   )rJ   r/   r'   s     r   rL   #_is_minimal_bsgs.<locals>.<genexpr>  s     7$Q==#q($s   !)rC   r   r   r   rb   )rD   r   r   sgs1rC   r/   r'   s         @r   r   r     s}    " E7D7<<D4[7$777LLO#=t!}}Q'71'<AtD=D  = >s   B1Bc                 d    [        U5      nUR                  5       u  p[        X5      (       d  gX4$ )a  
Compute a minimal GSGS

base, gens BSGS

If base, gens is a minimal BSGS return it; else return a minimal BSGS
if it fails in finding one, it returns None

TODO: use baseswap in the case in which if it fails in finding a
minimal BSGS

Examples
========

>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.tensor_can import get_minimal_bsgs
>>> riemann_bsgs1 = ([2, 0], ([Permutation(5)(0, 1)(4, 5), Permutation(5)(0, 2)(1, 3)]))
>>> get_minimal_bsgs(*riemann_bsgs1)
([0, 2], [(0 1)(4 5), (5)(0 2)(1 3), (2 3)(4 5)])
N)r   schreier_sims_incrementalr   )rD   r   Gs      r   r   r     s4    * 	A,,.JDD'':r   c           
         S nU (       dZ  UR                  / 5      S:  aE  [        U5      nUS   R                  nXVS-
  -  S-   nU/ [        [	        [        U5      5      5      /4$ [        U5      (       a  [        U5      nOSn/ nUS   R                  n[	        [        U5      5      n	US-
  n
US   (       d#  UR                  [	        [        U
5      5      5        U" XpXS   5      u  p[        S[        U5      5       HZ  nU" XpXU   5      u  p[        XXS5      u  pX-   (       d-  UR                  [	        [        US-
  US-
  U
-   5      5      5        Xj-  nM\     US-
  nU Vs/ s H  nUR                  U	:w  d  M  UPM     nnUb  U(       d  U(       d  [        U	5      /nXkU4$ / n[        [        U5      S-
  5       H  nX   nXS-      n[	        [        US   5      5      nUR                  U5        UR                  U5        UR                  US   5        UR                  [	        [        US   S-   U5      5      5        US:X  a  UR                  UUS-   /5        OUR                  US-   U/5        UR                  [        U5      5        M     [	        U5      nU H  nX;  d  M
  UR                  U5        M     UR                  5         U(       d  [        U	5      /nXkU4$ s  snf )a  
Returns size, res_base, res_gens BSGS for n tensors of the
same type.

Explanation
===========

base, gens BSGS for tensors of this type
list_free_indices  list of the slots occupied by fixed indices
                   for each of the tensors

sym symmetry under commutation of two tensors
sym   None  no symmetry
sym   0     commuting
sym   1     anticommuting

Examples
========

>>> from sympy.combinatorics.tensor_can import tensor_gens, get_symmetric_group_sgs

two symmetric tensors with 3 indices without free indices

>>> base, gens = get_symmetric_group_sgs(3)
>>> tensor_gens(base, gens, [[], []])
(8, [0, 1, 3, 4], [(7)(0 1), (7)(1 2), (7)(3 4), (7)(4 5), (7)(0 3)(1 4)(2 5)])

two symmetric tensors with 3 indices with free indices in slot 1 and 0

>>> tensor_gens(base, gens, [[1], [0]])
(8, [0, 4], [(7)(0 2), (7)(4 5)])

four symmetric tensors with 3 indices, two of which with free indices

c                 p    U(       d
  USS USS 4$ U R                  U5      nUR                  5       u  pX4$ )z:
return the BSGS for G.pointwise_stabilizer(free_indices)
N)pointwise_stabilizerr   )r   rD   r   free_indicesHsgss         r   	_get_bsgstensor_gens.<locals>._get_bsgs.  sB     7DG##&&|4A335ID9r   r   r   Nr   rZ   )countr   rC   r   r   r   r`   r   r   r   rb   ra   rd   )rD   r   list_free_indicesr   r   r   rC   r   no_freer   num_indicesres_baseres_gensr'   r   r   nrr/   	base_commind1ind2r   s                         r   tensor_gensr   
  s   H	 %++B/!3!"Aw||1H~!R'$uT{"34555 T" G7<<DtE(KQtE+./0"1DA2FGH1c+,- $!0DE016qB #NN4dQhq;0F GHI . 
B#>8aq}}'=8H>
{''Hx'' I3w<!#$z1u~tAw 		a!	eDHqL"-./!8HHb"q&\"HHb1fb\"
# % H~HOOA  MMOEN#8##K ?s   $K'<K'c                  .   [        U S   6 u  pn[        S[        U 5      5       H   n[        X   6 u  pVn[        X#UUS5      u  p#M"     US   R                  n[        [        U5      5      nU V	s/ s H  oU:w  d  M
  U	PM     nn	U(       d  U/nXU4$ s  sn	f )a  
Returns size, res_base, res_gens BSGS for n tensors of different types.

Explanation
===========

v is a sequence of (base_i, gens_i, free_i, sym_i)
where
base_i, gens_i  BSGS of tensor of type `i`
free_i          list of the fixed slots for each of the tensors
                of type `i`; if there are `n_i` tensors of type `i`
                and none of them have fixed slots, `free = [[]]*n_i`
sym   0 (1) if the tensors of type `i` (anti)commute among themselves

Examples
========

>>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, gens_products
>>> base, gens = get_symmetric_group_sgs(2)
>>> gens_products((base, gens, [[], []], 0))
(6, [0, 2], [(5)(0 1), (5)(2 3), (5)(0 2)(1 3)])
>>> gens_products((base, gens, [[1], []], 0))
(6, [2], [(5)(2 3)])
r   r   )r   r   r   r   rC   r   )
r   res_sizer   r   r'   rC   rD   r   r   r/   s
             r   r   r     s    2 $/!#5 H1c!f&-D0T15q:(  {Hx!E#28aEz8H27x'' 3s   /	B<BN)T)F)r   )  sympy.combinatorics.permutationsr   r   r   r   sympy.combinatorics.perm_groupsr   r   r	   sympy.combinatorics.utilr
   r   r   r)   r0   r5   r>   rF   r   r   r   r   r   r   r   r   riemann_bsgsr   r   r   r   r   r+   r   r   <module>r      s     #&,^2		*slGT]@"J$,N,: 1vAq)!Q/Q1B1a1H#Aq!,Q24 4
68u$p#(r   