U
    Ç-eHŸ  ã                   @   s  d dl mZmZmZmZ d dlmZmZmZ d dl	m
Z
mZ dd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd2dd„Zd3dd„Zd4d d!„Zd d"ged d#ƒd$d%ƒed"d&ƒd$d%ƒed%ƒd d"ƒd#d&ƒgfZd'd(„ Zd)d*„ Zd+d,„ Zd5d-d.„Zd/d0„ Zd1S )6é    )ÚPermutationÚ_af_rmulÚ
_af_invertÚ_af_new)ÚPermutationGroupÚ_orbitÚ_orbit_transversal©Ú_distribute_gens_by_baseÚ_orbits_transversals_from_bsgsc                 C   sö   t | ƒ|krtdƒ‚g }|dk	r| ddd… D ]`}tt|d ƒƒ}|dkrb|d ||< |||d < ||d  ||  ||< ||d < | |¡ q.| ddd… D ]R}tt|d ƒƒ}||d  ||d  || ||d  f|||d …< | |¡ qž|S )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Úa© r   ú_/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/sympy/combinatorics/tensor_can.pyÚ	dummy_sgs   s     "4r   c           	      C   sp   t |ƒ}dd„ | D ƒ}|dd… }t|ƒD ]@}t|ƒD ]2\}}t|ƒD ] }|| | krF|| ||<  q6qFq6q*|S )a“  
    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]
    c                 S   s   g | ]}|rt |ƒnd ‘qS ©N©Úmin)Ú.0Údxr   r   r   Ú
<listcomp>X   s     z _min_dummies.<locals>.<listcomp>N)r   r   Ú	enumerate)	r   r   ÚindicesÚ	num_typesÚmr   ÚiÚcr   r   r   r   Ú_min_dummiesJ   s    
r+   c                 C   s*   || D ]}| ||  |kr|  S qdS )zt
    Return the representative h satisfying s[h[b]] == j

    If there is not such a representative return None
    Nr   )Úsr   ÚbZS_cosetsÚhr   r   r   Ú_trace_Sc   s    
r/   c                 C   s"   |D ]}||  |kr|  S qdS )zt
    Return the representative h satisfying h[gj] == p_i

    If there is not such a representative return None
    Nr   )ZgjÚp_iÚDxtravr.   r   r   r   Ú_trace_Do   s    
r2   c                 C   sˆ   g }| D ]z}||kr |  |¡ q| |¡}|d dkrD||d  }n||d  }| |¡ | |¡ | |¡ | |¡ |  |¡ qdS )z
    remove p0 from dumx
    r   r   r   N)r   ÚindexÚremove)ÚdumxÚ	dumx_flatÚp0r   r#   ÚkZ	p0_pairedr   r   r   Ú_dumx_remove{   s    





r9   c                 C   sŽ   g }d}t | ƒD ]@}||kr<| t||  ¡ ƒ¡ |d7 }q| tt | ƒƒg¡ qt|ƒd }|| tt | ƒƒgkr~|d8 }q^|d |d … S ©Nr   r   )r   r   ÚsortedÚvaluesr   r   )ÚsizeÚbaseZtransversalr   r   r)   r   r   r   Útransversal2coset   s    

r?   c           "         sP  ˆj ‰ˆj‰ˆd }tt|ƒƒ}tdd„ |D ƒƒ }t|ƒ}	| dd… }
g }|
D ]}| |¡ qP|dd… }dd„ |D ƒ}|rŠtˆ||ƒ}g ‰t|	ƒD ]}ˆ t|
| || |ƒ¡ q–ttˆƒƒ}||ˆfg}tˆd ƒD ]f}|‰ ˆ |koî|}|rdd„ |D ƒ}t	ˆ|ˆ ƒ‰nˆ h‰|r,t
|
||ƒ‰n‡‡fdd„tˆd ƒD ƒ‰t‡‡fd	d„|D ƒƒ‰	d
d„ ˆD ƒ}ˆr†tˆ|ˆ	dddnd}|rždd„ |D ƒ}t|	ƒD ]V}ˆ	|
| kr¦|| dk	rÐ|
| }n$|
|  ˆ	¡d }|
| |dd… } qq¦ˆ	g}g }|rh| ¡ \‰
}‰t‡‡fdd„ˆD ƒƒˆ	kr>q‡‡‡	fdd„ˆD ƒ}t|ˆƒ}t|ƒ‰‡
fdd„|D ƒ}‡fdd„|D ƒ‰‡fdd„|D ƒ}|D ]Â}|rØtˆ
|ˆ |ƒ}|sÄq n‡
fdd„|D ƒ}nˆ
}|rþt|| ˆ	|ƒ‰ˆsq nˆ	|| krq |‰ˆ||  ˆ	ks*t‚‡fdd„|D ƒ‰‡‡fdd„|D ƒ} | |ˆ| f¡ q q|jdd„ d dgˆ }!|râ| ¡ \‰
}‰ˆdd… |!dd… krÊˆd |!d krÚ dS n| ˆ
|ˆf¡ ˆ}!q‚‡ fdd„|D ƒ}ˆ |kr| ˆ ¡ t|
|ˆ	ƒ g ‰t|	ƒD ] }ˆ t|
| || |ƒ¡ q qÚ|d d S )a%  
    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                 s   s   | ]}|d kV  qd S r   r   ©r"   Ú_r   r   r   Ú	<genexpr>‘  s     z'double_coset_can_rep.<locals>.<genexpr>Nc                 S   s   g | ]
}|j ‘qS r   ©Ú_array_form©r"   r.   r   r   r   r$   ˜  s     z(double_coset_can_rep.<locals>.<listcomp>c                 S   s   g | ]}t |ƒ‘qS r   ©r   r@   r   r   r   r$   §  s     c                    s&   g | ]}t tˆd d„ ˆ D ƒ|ƒƒ‘qS )c                 S   s   g | ]}t |ƒ‘qS r   rF   )r"   Zddxr   r   r   r$   ¯  s   ÿÿú3double_coset_can_rep.<locals>.<listcomp>.<listcomp>)r!   r   )r"   Úii)Údsgsxr=   r   r   r$   ¯  s   ÿÿÿc                    s*   g | ]"\}}‰ t ‡ ‡fd d„ˆD ƒƒ‘qS )c                    s   g | ]}ˆˆ |  ‘qS r   r   ©r"   Úx©r.   Úmdr   r   r$   ²  s     rG   r    )r"   r,   Úd)ÚdeltabrM   )r.   r   r$   ²  s     c                 S   s   g | ]}t |ƒ‘qS r   rF   r@   r   r   r   r$   ³  s     FT)Úafc                 S   s   g | ]}t |ƒ‘qS r   )r   rJ   r   r   r   r$   ·  s     c                    s   g | ]}ˆˆ |  ‘qS r   r   rJ   rL   r   r   r$   É  s     c                    s    g | ]}ˆˆ |  ˆkr|‘qS r   r   rJ   )r.   rM   r0   r   r   r$   Ë  s      c                    s   g | ]}ˆ | ‘qS r   r   rJ   ©r,   r   r   r$   Ï  s     c                    s   g | ]}ˆ | ‘qS r   r   rJ   )Údginvr   r   r$   Ð  s     c                    s   g | ]}|ˆ kr|‘qS r   r   rJ   )Úgdeltapr   r   r$   Ñ  s      c                    s   g | ]}ˆ | ‘qS r   r   ©r"   ZixrQ   r   r   r$   å  s     c                    s   g | ]}ˆ | ‘qS r   r   rT   )Úd1r   r   r$   ø  s     c                    s   g | ]}ˆ ˆ|  ‘qS r   r   rT   )rU   Úgr   r   r$   ù  s     c                 S   s   | d S )Néÿÿÿÿr   )rK   r   r   r   Ú<lambda>ÿ  ó    z&double_coset_can_rep.<locals>.<lambda>)Úkeyr   éþÿÿÿrW   c                    s   g | ]}|ˆ  ˆ kr|‘qS r   r   rE   )r-   r   r   r$     s      )r=   Ú
array_formr   r   Úanyr   Úextendr?   r   r   r+   r!   r   r3   Úpopr   r   r/   r2   ÚAssertionErrorr   Úsortr4   r9   )"r   r   Zb_SÚsgensZS_transversalsrV   Znum_dummiesr&   Zall_metrics_with_symr'   r5   r6   r#   Zsgensxr)   ZidnZTABZtestbZsgensx1Zdsgsx1r1   rH   ZdeltapZ	p_i_indexÚTAB1rN   Zdeltab1ÚdgZsdeltabZNEXTr   Ús1Úh1Úprevr   )r-   rU   rO   rR   rI   rV   rS   r.   rM   r0   r,   r=   r   Údouble_coset_can_repŸ   s¼     o
ÿÿÿ






 rh   c                    sÄ   |j }t|ƒ}| s|dd… S t| |ƒ}t|dd… ƒD ]}|| kr8|  |¡ q8|}t|ƒD ]b\}}	|g| }
d}|	 ¡ D ]4}t||ƒ‰ ‡ fdd„t|ƒD ƒ}||
k rz|}
|}qz|r\t||ƒ}q\|S )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[   c                    s   g | ]}ˆ   |¡‘qS r   ©r3   rT   ©rf   r   r   r$   V  s     z"canonical_free.<locals>.<listcomp>)	r\   r   Úget_transversalsr;   r   r%   r<   r   r   )r>   ÚgensrV   Únum_freer=   ÚtransversalsrK   r.   r)   ZtransvZh_ir,   ÚskÚhir   rj   r   Úcanonical_free  s*    0


rq   c                 C   s<   t t| ƒƒ}d}t| ƒD ]}||kr&q|||< |d7 }q|S r:   )r   r   )r=   Úfixed_slotsr   Úposr)   r   r   r   Ú_get_map_slots_  s    
rt   c           
      C   s€   g }d }}t t||ƒƒ}dd„ t|ƒD ƒ}t|ƒ}t| ƒD ]>}	|	|kr`| || ¡ |d7 }q<| || | ¡ |d7 }q<|S )Nr   c                 S   s   g | ]\}}|‘qS r   r   )r"   rK   Úyr   r   r   r$   n  s     z_lift_sgens.<locals>.<listcomp>r   )r   Úzipr;   r   r   r   )
r=   rr   Úfreer,   r   r   r8   Úfdrm   r)   r   r   r   Ú_lift_sgensj  s    

ry   c           %         sX  ddl m} t|tƒs,|dkr&tdƒ‚d}n6t|ƒ}tdd„ |D ƒƒsNtdƒ‚t|ƒ|krbtd	ƒ‚| j}d}g }|D ]f\}	}
}}t|	|
ƒsºt	|	|
ƒ}|s²|| ||f|žŽ }|  S |\}	}
| 
|	|
g g| |f¡ ||7 }qt|dkrút|tƒsú|g}|g}g ‰ |D ]}ˆ  |¡ qˆ rBˆ ttˆ d ˆ d
 d ƒƒkrBtdƒ‚t|Ž \}}}||krjtd||f ƒ‚‡ fdd„t|d ƒD ƒ}t|ƒ‰t||| ˆƒ‰ˆ s¤ˆS ˆd
 |d krºdnd}d}t|ƒD ]\}\}	}
}}g }|
d jd }t|ƒD ]R}ˆ||| … }g }|D ] }||kr| 
| |¡¡ q| 
|¡ ||7 }qô|	|
||f||< qÊt|Ž \}}}‡fdd„tˆƒD ƒ‰|ˆ }‡ ‡fdd„ˆD ƒ}|rº| |d |d g¡ n| |d |d g¡ t|ˆƒ‰‡‡fdd„|D ƒ}‡‡fdd„|D ƒ} ‡fdd„|D ƒ}!t|| ƒ}"t|ƒ}t|!||| |"|ƒ}#|#dkrFdS t|ˆ||#ƒ}$|$S )av  
    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                 s   s   | ]}|d kV  qdS )r{   Nr   )r"   Zmsymxr   r   r   rB   þ  s     zcanonicalize.<locals>.<genexpr>z!msym entries must be 0, 1 or Nonez6dummies and msym must have the same number of elementsrW   zdummies is not validz&g has size %d, generators have size %dc                    s   g | ]}|ˆ kr|‘qS r   r   ©r"   r)   )Úflat_dummiesr   r   r$   "  s      z canonicalize.<locals>.<listcomp>r   c                    s   g | ]}ˆ   |¡‘qS r   ri   rJ   )Úg1r   r   r$   D  s     c                    s   g | ]}|ˆ kr|ˆ ‘qS r   r   rJ   )r}   rm   r   r   r$   F  s      c                    s   g | ]}|ˆkrˆ | ‘qS r   r   r|   ©Ú	map_slotsÚpos_freer   r   r$   L  s      c                    s&   g | ]}t ‡ ‡fd d„|jD ƒƒ‘qS )c                    s   g | ]}|ˆkrˆ | ‘qS r   r   r|   r   r   r   r$   M  s      ú+canonicalize.<locals>.<listcomp>.<listcomp>)r   rD   ©r"   ru   r   r   r   r$   M  s     c                    s   g | ]}‡ fd d„|D ƒ‘qS )c                    s   g | ]}|ˆ  ‘qS r   r   rJ   ©rm   r   r   r$   N  s     r‚   r   rƒ   r„   r   r   r$   N  s     )Zsympy.combinatorics.testutilrz   Ú
isinstancer   r   r   Úallr=   Ú_is_minimal_bsgsÚget_minimal_bsgsr   r^   r   Úgens_productsrq   r%   r3   rt   rk   r   rh   ry   )%rV   r   ZmsymÚvrz   r'   r=   Znum_tensorsZv1Zbase_iZgens_iZn_iZsym_iZmbsgsZcanr5   Zsize1Zsbaserb   rw   ÚsignÚstartr)   Zfree_iZlen_tensr   r.   Úfrr8   Zsize_redZg1_redZ	sbase_redZ	sgens_redZdummies_redZ
transv_redÚg2Zg3r   )r}   r~   r€   rm   r   r   Úcanonicalizez  s¢    }
ÿ


&

ÿ



     ÿ
r   Tc                    sÆ   dd„ | D ƒ} dd„ |D ƒ}|r$dnd}t | d ƒ| ‰t |d ƒ| ‰ttˆƒƒ‰ttˆˆˆ ƒƒ‰ |r”‡ ‡fdd„| D ƒ} ‡‡fdd„|D ƒ}n&‡ fdd„| D ƒ} ‡‡fd	d„|D ƒ}| | }|S )
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]]
    c                 S   s   g | ]}t |ƒ‘qS r   ©r   rJ   r   r   r   r$   k  s     z*perm_af_direct_product.<locals>.<listcomp>c                 S   s   g | ]}t |ƒ‘qS r   r   rJ   r   r   r   r$   l  s     r   r   c                    s4   g | ],}|d d… ˆ  |d ˆ |d ˆ g ‘qS )Nr[   rW   r   ©r"   Úgen)ÚendÚn2r   r   r$   s  s   ÿc                    s"   g | ]}ˆ‡ fd d„|D ƒ ‘qS )c                    s   g | ]}|ˆ  ‘qS r   r   rJ   ©Ún1r   r   r$   u  s     ú5perm_af_direct_product.<locals>.<listcomp>.<listcomp>r   r‘   ©r–   rŒ   r   r   r$   u  s     c                    s   g | ]}|ˆ  ‘qS r   r   r‘   )r“   r   r   r$   w  s     c                    s"   g | ]}ˆ‡ fd d„|D ƒ ‘qS )c                    s   g | ]}|ˆ  ‘qS r   r   rJ   r•   r   r   r$   x  s     r—   r   r‘   r˜   r   r   r$   x  s     )r   r   r   )Úgens1Úgens2Úsignedr,   r   r   )r“   r–   r”   rŒ   r   Úperm_af_direct_productZ  s     ÿrœ   c           	         s¦   |rdnd}|d j | ‰t| ƒ}|‡fdd„|D ƒ7 }dd„ |D ƒ}dd„ |D ƒ}t|||ƒ}t|d ƒ}tt|ƒƒ‰ ‡ fdd„|D ƒ}|s”ˆ g}|dd„ |D ƒfS )	a3  
    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   c                    s   g | ]}|ˆ  ‘qS r   r   rJ   r•   r   r   r$   š  s     z'bsgs_direct_product.<locals>.<listcomp>c                 S   s   g | ]
}|j ‘qS r   rC   rE   r   r   r   r$   ›  s     c                 S   s   g | ]
}|j ‘qS r   rC   rE   r   r   r   r$   œ  s     c                    s   g | ]}|ˆ kr|‘qS r   r   rE   ©Úid_afr   r   r$      s      c                 S   s   g | ]}t |ƒ‘qS r   rF   rE   r   r   r   r$   £  s     )r=   r   rœ   r   r   )	Úbase1r™   Zbase2rš   r›   r,   r>   rl   r=   r   )rž   r–   r   Úbsgs_direct_product  s    r    Fc                    sˆ   ˆ dkrg t ttdƒƒƒgfS ‡ fdd„tˆ d ƒD ƒ}|dkrT‡ fdd„|D ƒ}n‡ fdd„|D ƒ}ttˆ d ƒƒ}|dd„ |D ƒfS )	a£  
    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   c                    s$   g | ]}t ˆ d  ƒ||d  ƒj‘qS ©r   )r   rD   r|   ©r   r   r   r$   »  s     z+get_symmetric_group_sgs.<locals>.<listcomp>r   c                    s   g | ]}|ˆ ˆ d  g ‘qS r¡   r   rJ   r¢   r   r   r$   ½  s     c                    s   g | ]}|ˆ d  ˆ g ‘qS r¡   r   rJ   r¢   r   r   r$   ¿  s     c                 S   s   g | ]}t |ƒ‘qS r   rF   rE   r   r   r   r$   Á  s     )r   r   r   )r   Zantisymrl   r>   r   r¢   r   Úget_symmetric_group_sgs¦  s    r£   r   r   r   é   r   c                 C   s2   | sg S t | |ƒ}t| |ƒ\}}dd„ |D ƒ}|S )z@
    Return transversals for the group with BSGS base, gens
    c                 S   s   g | ]}d d„ |  ¡ D ƒ‘qS )c                 S   s   i | ]\}}||j “qS r   rC   )r"   rK   r.   r   r   r   Ú
<dictcomp>Ï  s      z/get_transversals.<locals>.<listcomp>.<dictcomp>)Úitemsrƒ   r   r   r   r$   Ï  s     z$get_transversals.<locals>.<listcomp>r	   )r>   rl   ZstabsZorbitsrn   r   r   r   rk   Ç  s    
ÿrk   c                    sb   g }|dd… }|d j }t|ƒD ]6‰ t‡ fdd„|D ƒƒs"| ˆ ¡ ‡ fdd„|D ƒ}q"|| kS )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   s   | ]}|j ˆ  ˆ kV  qd S r   rC   rE   ©r)   r   r   rB   é  s     z#_is_minimal_bsgs.<locals>.<genexpr>c                    s   g | ]}|j ˆ  ˆ kr|‘qS r   rC   rE   r§   r   r   r$   ë  s      z$_is_minimal_bsgs.<locals>.<listcomp>)r=   r   r†   r   )r>   rl   rŸ   Zsgs1r=   r   r§   r   r‡   Ô  s    

r‡   c                 C   s*   t |ƒ}| ¡ \} }t| |ƒs"dS | |fS )aW  
    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‡   )r>   rl   ÚGr   r   r   rˆ   ï  s
    
rˆ   c                    sv  dd„ }| sT|  g ¡dk rTt|ƒ}|d j}||d  d }|g ttt|ƒƒƒgfS t|ƒrft|ƒ}nd}g }|d j}tt|ƒƒ‰ |d }	|d s¦| tt|	ƒƒ¡ ||| ||d ƒ\}
}tdt|ƒƒD ]`}||| ||| ƒ\}}t	|
|||dƒ\}
}|| s"| tt|d |d |	 ƒƒ¡ ||	7 }qÊ|d }‡ fdd„|D ƒ}|dksV|sp|sftˆ ƒg}||
|fS g }tt|ƒd ƒD ]¦}|| }||d  }tt|d ƒƒ}| 
|¡ | 
|¡ | |d ¡ | 
tt|d	 d |ƒƒ¡ |dkr| 
||d g¡ n| 
|d |g¡ | t|ƒ¡ q„t|
ƒ}
|D ]}||
kr8|
 |¡ q8|
 ¡  |sltˆ ƒg}||
|fS )
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                 S   s>   |s|dd… |dd… fS |   |¡}| ¡ \}}||fS dS )zJ
        return the BSGS for G.pointwise_stabilizer(free_indices)
        N)Zpointwise_stabilizerr¨   )r©   r>   rl   Zfree_indicesÚHZsgsr   r   r   Ú	_get_bsgs/  s
    
ztensor_gens.<locals>._get_bsgsr   r   Nr   c                    s   g | ]}|j ˆ kr|‘qS r   rC   rE   r   r   r   r$   [  s     
 ztensor_gens.<locals>.<listcomp>rW   )Úcountr   r=   r   r   r   r]   r   r   r    r^   ra   )r>   rl   Zlist_free_indicesr   r«   r   r=   r©   Zno_freeZnum_indicesÚres_baseÚres_gensr)   rŸ   r™   ÚnrZ	base_commZind1Zind2r   r   r   r   Útensor_gens  sj    $


  ÿ
 


	




r°   c                     sˆ   t | d Ž \}}}tdt| ƒƒD ]*}t | | Ž \}}}t||||dƒ\}}q |d j}tt|ƒƒ‰ ‡ fdd„|D ƒ}|s~ˆ g}|||fS )aY  
    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   c                    s   g | ]}|ˆ kr|‘qS r   r   rE   r   r   r   r$   £  s      z!gens_products.<locals>.<listcomp>)r°   r   r   r    r=   r   )rŠ   Zres_sizer­   r®   r)   r=   r>   rl   r   r   r   r‰   ƒ  s     ÿ

r‰   N)T)T)F)r   ) Z sympy.combinatorics.permutationsr   r   r   r   Zsympy.combinatorics.perm_groupsr   r   r   Zsympy.combinatorics.utilr
   r   r   r+   r/   r2   r9   r?   rh   rq   rt   ry   r   rœ   r    r£   Zriemann_bsgsrk   r‡   rˆ   r°   r‰   r   r   r   r   Ú<module>   s6   /  xJ a
%
'
"ÿ
x