
    ,Vh                        d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
mZmZmZmZmZmZ ddlmZmZmZmZmZmZ ddlmZmZmZmZmZmZmZm Z  g dZ!ede"eed	   f   Z# G d
 d      Z$de#de
e"   dee"   fdZ%ed   Z&dee&ef   dee&ef   fdZ'edddddde(dede)dede#de)dedeee$f   fd       Z*eddddddedeeee"   f   de)dede#de)dedeee$f   fd       Z*ddddddedede)dede#de)dedeee$f   fdZ*ejV                  dededefd       Z,ded ee"d!f   defd"Z-ej\                  dAded ee"d!f   d#e(defd$       Z/ej`                  dAded%ed ee"d!f   d#e(def
d&       Z1ed!d!d!d!d!d'de(ded(ede)dede#d#ededefd)       Z2ed!d!d!d!d!d'dedeeee"   f   d(ede)dede#d#ededefd*       Z2ddddd+d'dee(ef   deeee"   f   d(ee   de)dede#d#ededefd,Z2 ed      d-e3de(fd.       Z4dede(fd/Z5d0ee   d#ee(   de(fd1Z6	 	 	 dBd2ee   d3ed#ee(   d4e)d(ee   dedefd5Z7d6e(d7e	e"   de(fd8Z8 G d9 d:      Z9d;e defd<Z:ed!d!d!d!d=de(deee f   d7eee"   df   de)dede#dede9fd>       Z;ed!d!d!d!d=deee f   deee ee"   f   d7eee"   df   de)dede#dede9fd?       Z;ddddd=dee(ee f   deee ee"   f   d7eee"   df   de)dede#dede9fd@Z;y)Cz;Contains the primary optimization and contraction routines.    )Decimal)	lru_cache)Any
CollectionDictIterableListLiteralOptionalSequenceTupleUnionoverload)backendsblashelpersparserpathssharing)ArrayIndexTypeArrayShaped	ArrayTypeBackendTypeContractionListTypeOptimizeKindPathTypeTensorShapeType)contract_pathcontractformat_const_einsum_strContractExpression
shape_onlyN	max_inputc                   b    e Zd ZdZdedededededee	   de	d	e	d
ee	   de
ee	f   fdZdefdZy)PathInfozCA printable object to contain information about a contraction path.contraction_listinput_subscriptsoutput_subscriptindicespath
scale_list
naive_costopt_cost	size_list	size_dictc                   
 || _         || _        || _        || _        || _        || _        t        |      | _        t        |      | _        | j                  t        | j                  t        d            z  | _
        |	| _        
| _        |j                  d      D cg c]  }t        
fd|D               c}| _        | d| | _        t        t        |	d            | _        y c c}w )N   ,c              3   (   K   | ]	  }|     y wN ).0kr/   s     C/home/dcms/DCMS/lib/python3.12/site-packages/opt_einsum/contract.py	<genexpr>z$PathInfo.__init__.<locals>.<genexpr><   s     6aYq\6s   ->default)r&   r'   r(   r*   r)   r+   r   r,   r-   maxspeedupr.   r/   splittupleshapeseqlargest_intermediate)selfr&   r'   r(   r)   r*   r+   r,   r-   r.   r/   kss             ` r8   __init__zPathInfo.__init__#   s     !1 0 0	$!*-)T]]GAJ)GG""AQAWAWX[A\]2u6266]%&b)9(:;$+C	1,E$F! ^s   C)returnc                    d}d| j                    ddt        | j                         ddt        | j                  d       dd| j
                  d	dd
| j                  d	dd| j                  d	dd| j                  d	dd dj                  | dg
}t        | j                        D ]  \  }}|\  }}}}}|"dj                  |      dz   | j                  z   }	nd}	t        ddt        dt        |            z
        }
| j                  |   |||	|
f}|j                   dj                  |         dj                  |      S )N)scalingBLAScurrent	remainingz  Complete contraction:  
z         Naive scaling:  z     Optimized scaling:  r   r;   z      Naive FLOP count:  z.3ez  Optimized FLOP count:  z   Theoretical speedup:  z  Largest intermediate:  z
 elements
zQ--------------------------------------------------------------------------------
z{:>6} {:>11} {:>22} {:>37}
zP--------------------------------------------------------------------------------r2   r:   z...8      z
{:>4} {:>14} {:>22}    {:>{}} )rB   lenr)   r=   r+   r,   r-   r>   rC   format	enumerater&   joinr(   append)rD   header
path_printncontraction_
einsum_strrL   do_blasremaining_strsize_remainingpath_runs               r8   __repr__zPathInfo.__repr__@   s{   < (y3'DLL(9':"='DOOQ(G'HK''<B?'c':"='S'9<'(A(A#'FkR1*116:

 ((=(=> 	SNA{3>0Aq*i$ # 3d :T=R=R R % BRZ)A$ABN "H F?FFQR!	S$ wwz""    N)__name__
__module____qualname____doc__r   strr   r   r   intr   rF   r`   r5   ra   r8   r%   r%       s    MG-G G 	G
  G G SMG G G C=G S>G:### ##ra   r%   memory_limitr.   rG   c                     | dk(  rt        |      S t        | t              rt        d      | y | dk  r| dk(  ry t        d      t	        |       S )Nr#   zCmemory_limit must be None, int, or the string Literal['max_input'].r1   z)Memory limit must be larger than 0, or -1)r=   
isinstancerf   
ValueErrorrg   )rh   r.   s     r8   _choose_memory_argrm   f   s]    {"9~,$^__a2HII|ra   )ordercastingdtypeoutkwargsc                     | j                         } i }| j                  dd      x}dk7  r||d<   | j                  dd      x}dk7  r||d<   | j                  dd      x}||d<   | j                  dd      x}||d<   |j                  |        |S )z@Filters out default contract kwargs to pass to various backends.rn   Kro   saferp   Nrq   )copypopupdate)rr   retrn   ro   rp   rq   s         r8   _filter_einsum_defaultsrz   |   s    [[]F)+CGS))c1G::i00V; IGT**7Gzz%&&3E
JJvJra   TF)use_blasoptimizerh   rA   
subscriptsoperandsr{   r|   rA   c                     y r4   r5   r}   r{   r|   rh   rA   r~   rr   s          r8   r   r           !$ra   c                     y r4   r5   r   s          r8   r   r      r   ra   c                	   |du s|d}|j                  dd      }t        |      rt        d|j                                | gt	        |      z   }t        j                  ||      \  }	}
}|	j                  d      }|D cg c]  }t        |       }}|r|}n"|D cg c]  }t        j                  |       }}t        |
      }t        |	j                  dd	            }i }t        |      D ]  \  }}||   }t        |      t        |      k7  rt        d
||    d| d      t        |      D ]O  \  }}t        ||         }||v r3||   dk(  r|||<   &|d||   fvs0t        d| d| d||    d| d	      |||<   Q  ||
gz   D cg c]  }t        j                  ||       }}t!        ||      }t        |      }t#        d |D              t        |      z
  dkD  }t        j$                  ||||      }|du rt'        t)        |            g}nt+        |t,        t.        j0                  f      s|}na|dk  rt'        t)        |            g}nFt+        |t.        j0                        r |||||      }n t/        j2                  |      } |||||      }g } g }!g }g }"t        |      D ]  \  }}#t'        t5        |#d            }#t        j6                  |#||      }$|$\  }%}}&}'t        j$                  |'t9        |&      t        |#      |      }(| j;                  |(       |!j;                  t        |'             |j;                  t        j                  |%|             |#D cg c]  }|j                  |       })}|#D cg c]  }|j                  |       }*}|r(t=        j>                  |)d	jA                  |%      |&|*      }+nd}+|t        |      z
  dk(  r|
},n7d	jA                  |)      }-d	jA                  t5        |%|-jB                              },t        jD                  |)|*|,      }.|j;                  |,       |j;                  |.       djA                  |)      dz   |,z   }/t        |      dk  rt'        |      }0nd}0|#|&|/|0|+f}1|"j;                  |1        t#        |       }2|r||"fS tG        |"|	|
|||!||2||
      }3||3fS c c}w c c}w c c}w c c}w c c}w )a  Find a contraction order `path`, without performing the contraction.

    Parameters:
          subscripts: Specifies the subscripts for summation.
          *operands: These are the arrays for the operation.
          use_blas: Do you use BLAS for valid operations, may use extra memory for more intermediates.
          optimize: Choose the type of path the contraction will be optimized with.
                - if a list is given uses this as the path.
                - `'optimal'` An algorithm that explores all possible ways of
                contracting the listed tensors. Scales factorially with the number of
                terms in the contraction.
                - `'dp'` A faster (but essentially optimal) algorithm that uses
                dynamic programming to exhaustively search all contraction paths
                without outer-products.
                - `'greedy'` An cheap algorithm that heuristically chooses the best
                pairwise contraction at each step. Scales linearly in the number of
                terms in the contraction.
                - `'random-greedy'` Run a randomized version of the greedy algorithm
                32 times and pick the best path.
                - `'random-greedy-128'` Run a randomized version of the greedy
                algorithm 128 times and pick the best path.
                - `'branch-all'` An algorithm like optimal but that restricts itself
                to searching 'likely' paths. Still scales factorially.
                - `'branch-2'` An even more restricted version of 'branch-all' that
                only searches the best two options at each step. Scales exponentially
                with the number of terms in the contraction.
                - `'auto'` Choose the best of the above algorithms whilst aiming to
                keep the path finding time below 1ms.
                - `'auto-hq'` Aim for a high quality contraction, choosing the best
                of the above algorithms whilst aiming to keep the path finding time
                below 1sec.

          memory_limit: Give the upper bound of the largest intermediate tensor contract will build.
                - None or -1 means there is no limit
                - `max_input` means the limit is set as largest input tensor
                - a positive integer is taken as an explicit limit on the number of elements

                The default is None. Note that imposing a limit can make contractions
                exponentially slower to perform.

          shapes: Whether ``contract_path`` should assume arrays (the default) or array shapes have been supplied.

    Returns:
          path: The optimized einsum contraciton path
          PathInfo: A printable object containing various information about the path found.

    Notes:
          The resulting path indicates which terms of the input contraction should be
          contracted first, the result of this contraction is then appended to the end of
          the contraction list.

    Examples:
          We can begin with a chain dot example. In this case, it is optimal to
          contract the b and c tensors represented by the first element of the path (1,
          2). The resulting tensor is added to the end of the contraction and the
          remaining contraction, `(0, 1)`, is then executed.

      ```python
      a = np.random.rand(2, 2)
      b = np.random.rand(2, 5)
      c = np.random.rand(5, 2)
      path_info = opt_einsum.contract_path('ij,jk,kl->il', a, b, c)
      print(path_info[0])
      #> [(1, 2), (0, 1)]
      print(path_info[1])
      #>   Complete contraction:  ij,jk,kl->il
      #>          Naive scaling:  4
      #>      Optimized scaling:  3
      #>       Naive FLOP count:  1.600e+02
      #>   Optimized FLOP count:  5.600e+01
      #>    Theoretical speedup:  2.857
      #>   Largest intermediate:  4.000e+00 elements
      #> -------------------------------------------------------------------------
      #> scaling                  current                                remaining
      #> -------------------------------------------------------------------------
      #>    3                   kl,jk->jl                                ij,jl->il
      #>    3                   jl,ij->il                                   il->il
      ```

      A more complex index transformation example.

      ```python
      I = np.random.rand(10, 10, 10, 10)
      C = np.random.rand(10, 10)
      path_info = oe.contract_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C)

      print(path_info[0])
      #> [(0, 2), (0, 3), (0, 2), (0, 1)]
      print(path_info[1])
      #>   Complete contraction:  ea,fb,abcd,gc,hd->efgh
      #>          Naive scaling:  8
      #>      Optimized scaling:  5
      #>       Naive FLOP count:  8.000e+08
      #>   Optimized FLOP count:  8.000e+05
      #>    Theoretical speedup:  1000.000
      #>   Largest intermediate:  1.000e+04 elements
      #> --------------------------------------------------------------------------
      #> scaling                  current                                remaining
      #> --------------------------------------------------------------------------
      #>    5               abcd,ea->bcde                      fb,gc,hd,bcde->efgh
      #>    5               bcde,fb->cdef                         gc,hd,cdef->efgh
      #>    5               cdef,gc->defg                            hd,defg->efgh
      #>    5               defg,hd->efgh                               efgh->efgh
      ```
    TNautoeinsum_callFz)Did not understand the following kwargs: )rA   r2   rP   zEinstein sum subscript 'z=' does not contain the correct number of indices for operand .r1   zSize of label 'z' for operand z (z!) does not match previous terms (z).c              3   2   K   | ]  }t        |        y wr4   )rQ   r6   xs     r8   r9   z contract_path.<locals>.<genexpr>T  s     4AQ4s   r      )reverserj   )keyr:      )$rw   rQ   	TypeErrorkeyslistr   parse_einsum_inputr?   	frozenset	get_shapereplacerS   rl   rg   r   compute_size_by_dictrm   sum
flop_countr@   rangerk   rf   r   PathOptimizerget_path_fnsortedfind_contractionboolrU   r   can_blasrT   findfind_output_shaper%   )4r}   r{   r|   rh   rA   r~   rr   einsum_call_arg	operands_r'   r(   operands_prepped
input_listr   
input_setsinput_shapes
output_setr)   r/   tnumtermshcnumchardimr.   
memory_argnum_opsinner_productr,   
path_tuplepath_optimizer	cost_listr+   r&   contract_indscontract_tupleout_indsidx_removedidx_contractcost
tmp_inputs
tmp_shapesr\   
idx_resultall_input_inds
shp_resultr[   rL   rY   r-   rW   s4                                                       r8   r   r      sA   d 	Dh. jj6O
6{CFKKM?STT tH~-I;A;T;TU^gm;n8&(8 "'',J(231)A,3J3'5EF((+FF+,J(00b9:G !#I
+ &
d$r7c$i*:d+;*< =99=aA  $D/ 	&JD$bh-Cy T?a'&)IdOIdO 44$)$~dV2iPToEV W""%b* 
 #&	$	&&0 LVYiXjKjk4--dI>kIk#L)<J*oG
 444s7|CqHM##G]GYOJ 5 %eGn 56
3(;(;"<=
	AE'N+,
	He11	2j*iL
**84#J
IzR
IJI  )4 ,-mf]DAB 11-ZX:H7*k< !!,[0A3}CUW`a#l+,55h	JK1>?AjnnQ'?
?3@Aal&&q)A
AmmJ0A;PZ[GG 3z?"r))J  WWZ0Nn6I6I!JKJ--j*jQ
*%J'XXj)D0:=
 z?b 383DII$k:y'R,Y,-\ 9~H!111J z!!G 4 G< l\ @As   SS
S&SSc                  X   t        j                  d|j                  dd            }t        | d   t              s || i |S | d   | dd } }t        j                  |      s4d|vr|dt        j                  |      z   z  }t        j                  |      }t        |      } ||g| i |S )zJBase einsum, but with pre-parse for valid characters if a string is given.einsumbackendnumpyr   r1   Nr:   )
r   get_funcrw   rk   rf   r   has_valid_einsum_chars_onlyfind_output_strconvert_to_valid_einsum_charsrz   )r~   rr   fnr[   s       r8   _einsumr     s     
		8VZZ	7%C	DBhqk3'8&v&&#A;J --j9z!$!7!7
!CCCJ99*E
$V,Fj.8.v..ra   r   axes.c                 $    | j                  |      S r4   )	transpose)r   r   s     r8   _default_transposer     s    ;;tra   r   c                 J    t        j                  d|t              } || |      S )zBase transpose.r   )r   r   r   )r   r   r   r   s       r8   
_transposer     s%     
		;1C	DBa;ra   yc                 D    t        j                  d|      } || ||      S )zBase tensordot.	tensordot)r   )r   r   )r   r   r   r   r   s        r8   
_tensordotr     s%     
		;	0Bara   )rq   r{   r|   rh   r   rq   c                     y r4   r5   r}   rq   r{   r|   rh   r   r~   rr   s           r8   r   r          ra   c                     y r4   r5   r   s           r8   r   r     r   ra   r   c                
   |du s|d}| gt        |      z   }|du rt        |d|i|S |j                  dd      }	|j                  di       }
|	r|d   }t        |||d|d\  }}|	rt	        ||
fi |S t        ||f||d	|S )
a0  Evaluates the Einstein summation convention on the operands. A drop in
    replacement for NumPy's einsum function that optimizes the order of contraction
    to reduce overall scaling at the cost of several intermediate arrays.

    Parameters:
        subscripts: Specifies the subscripts for summation.
        *operands: These are the arrays for the operation.
        out: A output array in which set the resulting output.
        use_blas: Do you use BLAS for valid operations, may use extra memory for more intermediates.
        optimize:- Choose the type of path the contraction will be optimized with
            - if a list is given uses this as the path.
            - `'optimal'` An algorithm that explores all possible ways of
            contracting the listed tensors. Scales factorially with the number of
            terms in the contraction.
            - `'dp'` A faster (but essentially optimal) algorithm that uses
            dynamic programming to exhaustively search all contraction paths
            without outer-products.
            - `'greedy'` An cheap algorithm that heuristically chooses the best
            pairwise contraction at each step. Scales linearly in the number of
            terms in the contraction.
            - `'random-greedy'` Run a randomized version of the greedy algorithm
            32 times and pick the best path.
            - `'random-greedy-128'` Run a randomized version of the greedy
            algorithm 128 times and pick the best path.
            - `'branch-all'` An algorithm like optimal but that restricts itself
            to searching 'likely' paths. Still scales factorially.
            - `'branch-2'` An even more restricted version of 'branch-all' that
            only searches the best two options at each step. Scales exponentially
            with the number of terms in the contraction.
            - `'auto', None, True` Choose the best of the above algorithms whilst aiming to
            keep the path finding time below 1ms.
            - `'auto-hq'` Aim for a high quality contraction, choosing the best
            of the above algorithms whilst aiming to keep the path finding time
            below 1sec.
            - `False` will not optimize the contraction.

        memory_limit:- Give the upper bound of the largest intermediate tensor contract will build.
            - None or -1 means there is no limit.
            - `max_input` means the limit is set as largest input tensor.
            - A positive integer is taken as an explicit limit on the number of elements.

            The default is None. Note that imposing a limit can make contractions
            exponentially slower to perform.

        backend: Which library to use to perform the required ``tensordot``, ``transpose``
            and ``einsum`` calls. Should match the types of arrays supplied, See
            `contract_expression` for generating expressions which convert
            numpy arrays to and from the backend library automatically.

    Returns:
        The result of the einsum expression.

    Notes:
        This function should produce a result identical to that of NumPy's einsum
        function. The primary difference is ``contract`` will attempt to form
        intermediates which reduce the overall scaling of the given einsum contraction.
        By default the worst intermediate formed will be equal to that of the largest
        input array. For large einsum expressions with many input arrays this can
        provide arbitrarily large (1000 fold+) speed improvements.

        For contractions with just two tensors this function will attempt to use
        NumPy's built-in BLAS functionality to ensure that the given operation is
        performed optimally. When NumPy is linked to a threaded BLAS, potential
        speedups are on the order of 20-100 for a six core machine.
    Tr   Frq   _gen_expression_constants_dictr   )r|   rh   r   r{   r   rq   )r   r   rw   r   r!   _core_contract)r}   rq   r{   r|   rh   r   r~   rr   operands_listgen_expressionconstants_dictfull_strr&   s                r8   r   r     s    V 	Dh.L4>1M 5939&99 ZZ 159NZZ 126N # "/	RVai"H
 !(,<nWPVWW($4Yg3YRXYYra   clsc                 >    | j                   j                  d      d   S )Nr   r   )rc   r?   )r   s    r8   _infer_backend_class_cachedr   ^  s    >>$Q''ra   c                 ,    t        | j                        S r4   )r   	__class__)r   s    r8   infer_backendr   c  s    &q{{33ra   arraysc                 `    |dk7  r||S t        | d         }t        j                  |      sy|S )zuFind out what backend we should use, dipatching based on the first
    array if ``backend='auto'`` is specified.
    r   r   r   )r   r   has_tensordot)r   r   s     r8   parse_backendr   g  s<     	6 3F1I&G !!'*Nra   r   r&   evaluate_constantsc                    |du}t        |       t        |      }t        j                  |       }t	        |      D ]  \  }}	|	\  }
}}}|rt        fd|
D              r	||d fc S |
D cg c]  }j                  |       }}|xr |dz   t        |      k(  }|r
d|vs|r|j                  d      \  }}|j                  d      \  }}dj                  fd||z   D              }rpg g }}D ]B  }|j                  |j                  |             |j                  |j                  |             D t        t        t        t        ||                   }nd	}t        |||d
|}||k7  s|rMt        t!        |j"                  |            }t%        |||
      }|r||dd nd}|r|}t'        |g|||d|}j                  |       ~~ |r|S d   S c c}w )zInner loop used to perform an actual contraction given the output
    from a ``contract_path(..., einsum_call=True)`` call.
    Nc              3   ,   K   | ]  }|   d u   y wr4   r5   )r6   r   r~   s     r8   r9   z!_core_contract.<locals>.<genexpr>  s     %HahqkT&9%Hs   r1   EINSUMr:   r2   rP   c              3   ,   K   | ]  }|vs|  y wr4   r5   )r6   sidx_rms     r8   r9   z!_core_contract.<locals>.<genexpr>  s     #[!1TZ?A#[s   	)r5   r5   )r   r   r   r   )r   r   r   
has_einsumrS   anyrw   rQ   r?   rT   rU   r   r@   zipr   r   mapindexr   r   )r   r&   r   r   rq   rr   specified_out	no_einsumnumrY   indsr[   rZ   	blas_flagr   tmp_operands
handle_out	input_strresults_index
input_leftinput_righttensor_resultleft_pos	right_posr   r   new_viewr   	out_kwargr   r~   s                                @@r8   r   r   w  s'    tOMIHHg.G ''00I &&67 6#[1<.fj!Y #%H4%H"H-cd333156AQ66 #KqS9I5J(J
 ()3y'1'7'7'=$I}&/ooc&:#JGG#[zK/G#[[M&(") :AOOJOOA$67$$[%5%5a%89:
 S&Xy)A"BCD   "<dGVvVH .:!#m&9&9="IJ	%hYP%CF 15I	zcLc'yc\bcH 	!(m6#p 
{g 7s   1G$r[   	constantsc                 0   |s| S d| v r| j                  d      \  }}d}n| dd}}}t        |j                  d            D cg c]  \  }}||v rd| dn| }}}dj                  dj                  |      ||      }|j	                  dd      }|S c c}}w )zAdd brackets to the constant terms in ``einsum_str``. For example:

        >>> format_const_einsum_str('ab,bc,cd->ad', [0, 2])
        'bc,[ab,cd]->ad'

    No-op if there are no constants.
    r:   rP   r2   []z{}{}{}z],[)r?   rS   rR   rT   r   )	r[   r  lhsrhsarrowitwrapped_termsformatted_einsum_strs	            r8   r    r      s     z##D)S$b"%SCLSYYWZ^C\]41aiq1XQ6]M]#??388M+BE3O 077sC ^s   Bc                   *   e Zd ZdZdededeeef   de	fdZ
ddee   d	d
fdZded	eee      fdZdee   ded	e	fdZ	 	 	 ddee   dee   dee   ded	ef
dZ	 ddee   dee   deded	ef
dZd
ddddeded
ef   deded	ef
dZd	efdZd	efdZy
)r!   zHelper class for storing an explicit ``contraction_list`` which can
    then be repeatedly called solely with the array arguments.
    rY   r&   r   rr   c                    t        ||j                               | _        || _        || _        |j                  d      dz   | _        | j                  t        |      z
  | _        || _	        || _
        i | _        i | _        y )Nr2   r1   )r    r   rY   r&   rr   count_full_num_argsrQ   num_args_full_contraction_listr   _evaluated_constants_backend_expressions)rD   rY   r&   r   rr   s        r8   rF   zContractExpression.__init__  s~     3;@S@S@UV 0 *//4q8++c..AA '7#-46!46!ra   r   r   rG   Nc                 6   t        | j                        D cg c]  }| j                  j                  |d        }}t	        ||      }	 t        j                  |||       \  }}|| j                  |<   || _	        yc c}w # t        $ r  | ||dd\  }}Y 3w xY w)aF  Convert any constant operands to the correct backend form, and
        perform as many contractions as possible to create a new list of
        operands, stored in ``self._evaluated_constants[backend]``. This also
        makes sure ``self.contraction_list`` only contains the remaining,
        non-const operations.
        NT)r   r   )
r   r  r   getr   r   r   KeyErrorr  r&   )rD   r   r  tmp_const_opsnew_opsnew_contraction_lists         r8   r   z%ContractExpression.evaluate_constants  s     EJ$J]J]D^_q--11!T:__w7	k,4,G,GQ^`d,e)G) .5!!'* 4 `  	k,0-ei,j)G)	ks   #A;
B   BBc                     	 | j                   |   S # t        $ r# | j                  |       | j                   |   cY S w xY w)zRetrieve or generate the cached list of constant operators (mixed
        in with None representing non-consts) and the remaining contraction
        list.
        )r  r  r   )rD   r   s     r8   _get_evaluated_constantsz+ContractExpression._get_evaluated_constants  sF    
	6,,W55 	6##G,,,W55	6s    )==r   c                     	 | j                   |   S # t        $ r+ t        j                  |||       }|| j                   |<   |cY S w xY wr4   )r  r  r   build_expression)rD   r   r   r   s       r8   _get_backend_expressionz*ContractExpression._get_backend_expression  sP    	,,W55 	**7FDAB13D%%g.I	s    1AAFrq   r   c                 ~    |r| j                   n| j                  }t        t        |      |f|||d| j                  S )zThe normal, core contraction.rq   r   r   )r  r&   r   r   rr   )rD   r   rq   r   r   r&   s         r8   	_contractzContractExpression._contract&  sQ     ;M466RVRgRgL
 1
 kk
 	
ra   c                 t    |rt        j                  |||       S  | j                  ||      | }|||d<   |S |S )a  Special contraction, i.e., contraction with a different backend
        but converting to and from that backend. Retrieves or generates a
        cached expression using ``arrays`` as templates, then calls it
        with ``arrays``.

        If ``evaluate_constants=True``, perform a partial contraction that
        prepares the constant tensors and operations with the right backend.
        r5   )r   r   r#  )rD   r   rq   r   r   results         r8   _contract_with_conversionz,ContractExpression._contract_with_conversion9  sM      ..wEE>--fg>G?CGJra   r%  c                z   t        ||      }|r| j                  n| j                  }t        |      |k7  r%t	        d| j                   dt        |       d      | j
                  r;|s9t        |      | j                  |      }}|D cg c]  }|t        |      n| }	}n|}		 t        j                  |      r't        d |D              r| j                  |	|||      S | j                  |	|||      S c c}w # t        $ r7}
|
j                  rt        |
j                        nd}d	| d
f}||
_         d}
~
ww xY w)a(  Evaluate this expression with a set of arrays.

        Parameters:
            arrays: The arrays to supply as input to the expression.
            out: If specified, output the result into this array.
            backend: Perform the contraction with this backend library. If numpy arrays
                are supplied then try to convert them to and from the correct
                backend array type.
            evaluate_constants: Pre-evaluates constants with the appropriate backend.

        Returns:
            The contracted result.
        z(This `ContractExpression` takes exactly z array arguments but received r   Nc              3   8   K   | ]  }t        |      d k(    yw)r   N)r   r   s     r8   r9   z.ContractExpression.__call__.<locals>.<genexpr>|  s     4aUV]15E5P4as   )r   r%  rP   zInternal error while evaluating `ContractExpression`. Note that few checks are performed - the number and rank of the array arguments must match the original expression. The internal error was: '')r   r  r  rQ   rl   r   iterr   nextr   has_backendallr)  r&  argsrf   )rD   rq   r   r   r   correct_num_argsops_var	ops_constopopserroriginal_msgmsgs                r8   __call__zContractExpression.__call__T  sR   (  02D4..$--v;**:4==/ J  #F}A/ 
 (:!%ft/L/LW/UYGV_'`PRW(K'`C'`C	 ##G,4aZ`4a1a55c3\n5oo>>#3Tf>gg (a  	,/HH3sxx="L,,8><C
 CH	s$   C5$;C:  C: :	D:2D55D:c                 v    | j                   rdt        | j                          }nd}d| j                   d| dS )Nz, constants=rP   z<ContractExpression('r,  z)>)r   r   rY   )rD   constants_reprs     r8   r`   zContractExpression.__repr__  sE    +F43G3G,H+IJNN&t'7'7&8.9ILLra   c                 >   | j                         g}t        | j                        D ]d  \  }}|j                  d|dz    d       |j                  d|d    d|d   r	d|d    dnd	z          |j                  d
| j                          f d	j                  |      S )Nz
  r1   z.  r,  r   rj   z [r	  rP   z
einsum_kwargs=)r`   rS   r&   rU   rr   rT   )rD   r   r  cs       r8   __str__zContractExpression.__str__  s    ]]_d334 	7DAqHHtAE7#&'HHq1a[QrUb2qMCDHH'}56	7 wwqzra   )r   )Nr   F)F)rb   rc   rd   re   rf   r   r   rg   r   r   rF   r   r   r	   r   r   r#  r   r&  r)  r   r:  r`   r?  r5   ra   r8   r!   r!     s   77 .7 S)^,	7
 7,5(3- 5T 5(	6 	6Xi=P8Q 	6hy.A C TW  $(!'#(
#
 i 
 #	

 !
 

0 $)# i  	
 ! 
< '+#(55 4?#5 	5
 !5 
5nM# M ra   r!   shapec                     t        |       S )z^Dummy ``numpy.ndarray`` which has a shape only - for generating
    contract expressions.
    )r   )r@  s    r8   r"   r"     s     ura   )r  r{   r|   rh   c                     y r4   r5   r}   r  r{   r|   rh   r~   rr   s          r8   contract_expressionrD         ra   c                     y r4   r5   rC  s          r8   rD  rD    rE  ra   c                   |st        d      dD ]#  }|j                  |d      t        d| d       t        | t              st	        j
                  | f|z         \  } }d|d<   |xs d}|D ci c]  }|||   
 }	}|	|d	<   t        |      D 
cg c]  \  }}
||v r|
n
t        |
       }}}
t        | g||||d
|S c c}w c c}
}w )a>  Generate a reusable expression for a given contraction with
    specific shapes, which can, for example, be cached.

    Parameters:

        subscripts: Specifies the subscripts for summation.
        shapes: Shapes of the arrays to optimize the contraction for.
        constants: The indices of any constant arguments in `shapes`, in which case the
            actual array should be supplied at that position rather than just a
            shape. If these are specified, then constant parts of the contraction
            between calls will be reused. Additionally, if a GPU-enabled backend is
            used for example, then the constant tensors will be kept on the GPU,
            minimizing transfers.
        kwargs: Passed on to `contract_path` or `einsum`. See `contract`.

    Returns:
        Callable with signature `expr(*arrays, out=None, backend='numpy')` where the array's shapes should match `shapes`.

    Notes:
        The `out` keyword argument should be supplied to the generated expression
        rather than this function.
        The `backend` keyword argument should also be supplied to the generated
        expression. If numpy arrays are supplied, if possible they will be
        converted to and back from the correct backend array type.
        The generated expression will work with any arrays which have
        the same rank (number of dimensions) as the original shapes, however, if
        the actual sizes are different, the expression may no longer be optimal.
        Constant operations will be computed upon the first call with a particular
        backend, then subsequently reused.

    Examples:
    Basic usage:

    ```python
    expr = contract_expression("ab,bc->ac", (3, 4), (4, 5))
    a, b = np.random.rand(3, 4), np.random.rand(4, 5)
    c = expr(a, b)
    np.allclose(c, a @ b)
    #> True
    ```

    Supply `a` as a constant:

    ```python
    expr = contract_expression("ab,bc->ac", a, (4, 5), constants=[0])
    expr
    #> <ContractExpression('[ab],bc->ac', constants=[0])>

    c = expr(b)
    np.allclose(c, a @ b)
    #> True
    ```

    z9Can only generate expressions for optimized contractions.)rq   r   Nr,  zU' should only be specified when calling a `ContractExpression`, not when building it.Tr   r5   r   )r{   r|   rh   )	rl   r  rk   rf   r   convert_interleaved_inputrS   r"   r   )r}   r  r{   r|   rh   rA   rr   argr  r   r   dummy_arrayss               r8   rD  rD    s   ~ TUU! ::c4 ,C5qq  j#&#==zmf>TU
F $F RI,56qal6N6 .F HQQWGXYtq!iAZ]:YLY!,4xVbfl  7 Zs   1CC	)r   )r   FN)<re   decimalr   	functoolsr   typingr   r   r   r   r	   r
   r   r   r   r   r   
opt_einsumr   r   r   r   r   r   opt_einsum.typingr   r   r   r   r   r   r   r   __all__rg   _MemoryLimitr%   rm   _EinsumDefaultKeysrz   rf   r   r   einsum_cache_wrapr   r   transpose_cache_wrapr   tensordot_cache_wrapr   r   typer   r   r   r   r    r!   r"   rD  r5   ra   r8   <module>rW     sP   A   m m m m F F	 	 	 T3)==>C# C#L\ d3i HUXM & ?@ D);S)@$A dK]_bKbFc * 
 !!%$$$ $ 	$
 $ $ $ 8X$ 
$ 
 !!%$$Y
3/0$ $ 	$
 $ $ $ 8X$ 
$ !!%C"C"C" C" 	C"
 C" C" C" 8XC"L 	/s /c /i / /*) 5c? y 
 	) 5c? S y   	) 	 sCx 3 ]f   
  !$			 
	 		
 	 	 	 	 	 
	 
  !$		Y
3/0	 
	 		
 	 	 	 	 	 
	  $!!%!eZc9n%eZY
3/0eZ 
)	eZ 	eZ
 eZ eZ eZ eZ eZP 4(T (c ( (4S 4S 4(9-  # & $$#P	"P)P c]P 	P
 
)	P P Pf     #  4t tno +  
 /2 !$Y/0 Z_d*+ 	
     
 
 /2 !$i01YC@A Z_d*+ 	
     
 /3!!%Wc9o56W9oz#>?W Z_d*+W 	W
 W W W Wra   