
    KhT                         S r SSKrSSKrSSKJr  SSKJrJr  SSKJ	r	  SS/r
Sr\" \5      rS	 rS
 rS rS rS rS rS rS rS rSSS.S jr\	" \SS9SSS.S j5       rSSS.S jr\	" \SS9SSS.S j5       rg)z&
Implementation of optimized einsum.

    N)c_einsum)
asanyarray	tensordot)array_function_dispatcheinsumeinsum_path4abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZc                 V    [        X5      n[        SUS-
  5      nU(       a  US-  nXE-  $ )aC  
Computes the number of FLOPS in the contraction.

Parameters
----------
idx_contraction : iterable
    The indices involved in the contraction
inner : bool
    Does this contraction require an inner product?
num_terms : int
    The number of terms in a contraction
size_dictionary : dict
    The size of each of the indices in idx_contraction

Returns
-------
flop_count : int
    The total number of FLOPS required for the contraction.

Examples
--------

>>> _flop_count('abc', False, 1, {'a': 2, 'b':3, 'c':5})
30

>>> _flop_count('abc', True, 2, {'a': 2, 'b':3, 'c':5})
60

   )_compute_size_by_dictmax)idx_contractioninner	num_termssize_dictionaryoverall_size	op_factors         H/var/www/html/env/lib/python3.13/site-packages/numpy/_core/einsumfunc.py_flop_countr      s3    > )JLAy1}%IQ	##    c                 *    SnU  H
  nX!U   -  nM     U$ )a\  
Computes the product of the elements in indices based on the dictionary
idx_dict.

Parameters
----------
indices : iterable
    Indices to base the product on.
idx_dict : dictionary
    Dictionary of index sizes

Returns
-------
ret : int
    The resulting product.

Examples
--------
>>> _compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
90

r    )indicesidx_dictretis       r   r   r   :   s$    . C{ Jr   c                     [        5       nUR                  5       n/ n[        U5       H%  u  pgX`;   a  X7-  nM  UR                  U5        XG-  nM'     XC-  nX8-
  n	UR                  U5        XX4$ )a~  
Finds the contraction for a given set of input and output sets.

Parameters
----------
positions : iterable
    Integer positions of terms used in the contraction.
input_sets : list
    List of sets that represent the lhs side of the einsum subscript
output_set : set
    Set that represents the rhs side of the overall einsum subscript

Returns
-------
new_result : set
    The indices of the resulting contraction
remaining : list
    List of sets that have not been contracted, the new set is appended to
    the end of this list
idx_removed : set
    Indices removed from the entire contraction
idx_contraction : set
    The indices used in the current contraction

Examples
--------

# A simple dot product test case
>>> pos = (0, 1)
>>> isets = [set('ab'), set('bc')]
>>> oset = set('ac')
>>> _find_contraction(pos, isets, oset)
({'a', 'c'}, [{'a', 'c'}], {'b'}, {'a', 'b', 'c'})

# A more complex case with additional terms in the contraction
>>> pos = (0, 2)
>>> isets = [set('abd'), set('ac'), set('bdc')]
>>> oset = set('ac')
>>> _find_contraction(pos, isets, oset)
({'a', 'c'}, [{'a', 'c'}, {'a', 'c'}], {'b', 'd'}, {'a', 'b', 'c', 'd'})
)setcopy	enumerateappend)
	positions
input_sets
output_setidx_contract
idx_remain	remainingindvalue
new_resultidx_removeds
             r   _find_contractionr,   W   s}    V 5L"JI
+
!LU#J , *J,KZ ;==r   c                 x   S/ U 4/n[        [        U 5      S-
  5       H  n/ nU H  nUu  pn
[        R                  " [        [        U 5      U-
  5      S5       H[  n[	        XU5      nUu  pnn[        X5      nUU:  a  M(  U[        UU[        U5      U5      -   nX/-   nUR                  UUU45        M]     M     U(       a  UnM  [        US S9S   nU[        [        [        U 5      U-
  5      5      /-  nUs  $    [        U5      S:X  a  [        [        [        U 5      5      5      /$ [        US S9S   nU$ )a;  
Computes all possible pair contractions, sieves the results based
on ``memory_limit`` and returns the lowest cost path. This algorithm
scales factorial with respect to the elements in the list ``input_sets``.

Parameters
----------
input_sets : list
    List of sets that represent the lhs side of the einsum subscript
output_set : set
    Set that represents the rhs side of the overall einsum subscript
idx_dict : dictionary
    Dictionary of index sizes
memory_limit : int
    The maximum number of elements in a temporary array

Returns
-------
path : list
    The optimal contraction order within the memory limit constraint.

Examples
--------
>>> isets = [set('abd'), set('ac'), set('bdc')]
>>> oset = set()
>>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
>>> _optimal_path(isets, oset, idx_sizes, 5000)
[(0, 2), (0, 1)]
r   r      c                     U S   $ Nr   r   xs    r   <lambda>_optimal_path.<locals>.<lambda>   s    1Q4r   keyc                     U S   $ r0   r   r1   s    r   r3   r4      s    1Q4r   )
rangelen	itertoolscombinationsr,   r   r   r!   mintuple)r#   r$   r   memory_limitfull_results	iterationiter_resultscurrcostr"   r'   concontr*   new_input_setsr+   r%   new_size
total_costnew_pospaths                        r   _optimal_pathrK      s^   > J'(L3z?Q./	 !D)-&DY --c*o	12A
 )DHLE
K 1Fl* "K +s3x% 
 $e+##Z.$IJ% !0 'L|8;DU5Z9!<=>??DKC 0H <AeC
O,-..|03DKr   c                    ^^ [        U TU5      nUu  pp[        UT5      nX:  a  gUU4S jU  5       n[        U5      U-
  n[        X[	        U 5      T5      nU* U4nX_-   U:  a  gUX	/$ )a}  Compute the cost (removed size + flops) and resultant indices for
performing the contraction specified by ``positions``.

Parameters
----------
positions : tuple of int
    The locations of the proposed tensors to contract.
input_sets : list of sets
    The indices found on each tensors.
output_set : set
    The output indices of the expression.
idx_dict : dict
    Mapping of each index to its size.
memory_limit : int
    The total allowed size for an intermediary tensor.
path_cost : int
    The contraction cost so far.
naive_cost : int
    The cost of the unoptimized expression.

Returns
-------
cost : (int, int)
    A tuple containing the size of any indices removed, and the flop cost.
positions : tuple of int
    The locations of the proposed tensors to contract.
new_input_sets : list of sets
    The resulting new list of indices if this proposed contraction
    is performed.

Nc              3   B   >#    U  H  n[        TU   T5      v   M     g 7fN)r   ).0pr   r#   s     r   	<genexpr>._parse_possible_contraction.<locals>.<genexpr>  s#      @I1jmX66	s   )r,   r   sumr   r9   )r"   r#   r$   r   r>   	path_cost
naive_costcontract
idx_resultrF   r+   r%   rG   	old_sizesremoved_sizerC   sorts    ` `             r   _parse_possible_contractionr[      s    J !J
CH<D9J %Z:H@II y>H,L |#i.(KDM4 D 	J& ),,r   c                    US   nUu  p4/ nU  H  u  nu  pxn	Xr;   d  X;   a  M  X[        XG:  5      -
  [        XH:  5      -
  	 X[        X7:  5      -
  [        X8:  5      -
  	 U	R                  SUS   S   5        U[        Xs:  5      -
  [        Xt:  5      -
  U[        X:  5      -
  [        X:  5      -
  4n
UR                  XjU	45        M     U$ )a  Update the positions and provisional input_sets of ``results``
based on performing the contraction result ``best``. Remove any
involving the tensors contracted.

Parameters
----------
results : list
    List of contraction results produced by
    ``_parse_possible_contraction``.
best : list
    The best contraction of ``results`` i.e. the one that
    will be performed.

Returns
-------
mod_results : list
    The list of modified results, updated with outcome of
    ``best`` contraction.
r   r.   )intinsertr!   )resultsbestbest_conbxbymod_resultsrC   r2   ycon_setsmod_cons              r   _update_other_resultsri     s    * AwHFBK")fqh =AM #bf+%BF34#bf+%BF34DGBK( c!&k/CK/S[3qv;1NND845 #* r   c                   ^ [        U 5      S:X  a  S/$ [        U 5      S:X  a  S/$ [        [        [        U 5      5      X5      nUu  pVpx[        X[        U 5      U5      n	[        R
                  " [        [        U 5      5      S5      n
/ nSn/ n[        [        U 5      S-
  5       GHR  nU
 HI  nXS      R                  XS      5      (       a  M%  [        XXX<U	5      nUc  M8  UR                  U5        MK     [        U5      S:X  a  [        R
                  " [        [        U 5      5      S5       H'  n[        XXX<U	5      nUc  M  UR                  U5        M)     [        U5      S:X  a/  UR                  [        [        [        U 5      5      5      5          U$ [        US S9n[        UU5      nUS   n [        U 5      S-
  mU4S j[        T5       5       n
UR                  US   5        UUS   S   -  nGMU     U$ )	a3  
Finds the path by contracting the best pair until the input list is
exhausted. The best pair is found by minimizing the tuple
``(-prod(indices_removed), cost)``.  What this amounts to is prioritizing
matrix multiplication or inner product operations, then Hadamard like
operations, and finally outer operations. Outer products are limited by
``memory_limit``. This algorithm scales cubically with respect to the
number of elements in the list ``input_sets``.

Parameters
----------
input_sets : list
    List of sets that represent the lhs side of the einsum subscript
output_set : set
    Set that represents the rhs side of the overall einsum subscript
idx_dict : dictionary
    Dictionary of index sizes
memory_limit : int
    The maximum number of elements in a temporary array

Returns
-------
path : list
    The greedy contraction order within the memory limit constraint.

Examples
--------
>>> isets = [set('abd'), set('ac'), set('bdc')]
>>> oset = set()
>>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
>>> _greedy_path(isets, oset, idx_sizes, 5000)
[(0, 2), (0, 1)]
r   )r   r.   )r   r   r   c                     U S   $ r0   r   r1   s    r   r3   _greedy_path.<locals>.<lambda>  s    QqTr   r5   c              3   *   >#    U  H  oT4v   M
     g 7frN   r   )rO   r   new_tensor_poss     r   rQ   _greedy_path.<locals>.<genexpr>  s     H2GQ(2Gs   )r9   r,   r8   r   r:   r;   
isdisjointr[   r!   r=   r<   ri   )r#   r$   r   r>   rV   rW   rF   r+   r%   rU   	comb_iterknown_contractionsrT   rJ   r@   r"   resultra   rn   s                     @r   _greedy_pathrt   G  s   H :!v	ZA	x !c*o
H =E9J3z?HJ
 &&uS_'=qAIID3z?Q./	 #I A,'22:l3KLL0zF !"))&1 # !"a' '33c*o&	 5: Z %&--f5 %&!+E%J"89:& K! %>: 33EtL !W
Z1,H%2GH	 	DGT!WQZ	k 0n Kr   c                    [        U5      S:X  a  g[        U 5      S:w  a  gU u  p4[        X4-   5       HR  nUR                  U5      UR                  U5      pvUS:  d  US:  d  Xg-   S:  a    gXg-   S-
  [        XQ;   5      :X  d  MR    g   [        U5      n[        U5      n	X-
  n
X-
  n[        U5      nX4:X  a  gX:X  a  gX<* S USU :X  a  gUSU XL* S :X  a  gX<* S XL* S :X  a  gUSU USU :X  a  gU
(       a  U(       d  gg)a@  
Checks if we can use BLAS (np.tensordot) call and its beneficial to do so.

Parameters
----------
inputs : list of str
    Specifies the subscripts for summation.
result : str
    Resulting summation.
idx_removed : set
    Indices that are removed in the summation


Returns
-------
type : bool
    Returns true if BLAS should and can be used, else False

Notes
-----
If the operations is BLAS level 1 or 2 and is not already aligned
we default back to einsum as the memory movement to copy is more
costly than the operation itself.


Examples
--------

# Standard GEMM operation
>>> _can_dot(['ij', 'jk'], 'ik', set('j'))
True

# Can use the standard BLAS, but requires odd data movement
>>> _can_dot(['ijj', 'jk'], 'ik', set('j'))
False

# DDOT where the memory is not aligned
>>> _can_dot(['ijk', 'ikj'], '', set('ijk'))
False

r   Fr.   r   TN)r9   r   countr^   )inputsrs   r+   
input_leftinput_rightcnlnrset_left	set_right	keep_left
keep_rightrss                r   _can_dotr     sM   X ;1 6{a$J)*!!!$k&7&7&:BFQBGaK
 7Q;#ak** + :HK I&I(J	[	B   
 #$;s++ #2+cd++ #$;st,, #2+cr** J r   c                    [        U 5      S:X  a  [        S5      e[        U S   [        5      (       a^  U S   R	                  SS5      nU SS  Vs/ s H  n[        U5      PM     n nU H#  nUS;   a  M  U[        ;  d  M  [        SU-  5      e   GOO[        U 5      n/ n/ n[        [        U 5      S	-  5       HC  nUR                  UR                  S5      5        UR                  UR                  S5      5        ME     [        U5      (       a  US
   OSnU Vs/ s H  n[        U5      PM     n nSn[        U5      S-
  n	[        U5       HM  u  pU H6  nU[        L a  US-  nM   [        R                  " U5      nU[        U   -  nM8     X:w  d  MH  US-  nMO     UbA  US-  nU H6  nU[        L a  US-  nM   [        R                  " U5      nU[        U   -  nM8     SU;   d  SU;   aV  UR!                  S5      S:  =(       d    UR!                  S5      S:  nU(       d  UR!                  S5      S:w  a  [        S5      eSU;   Ga^  UR	                  SS5      R	                  SS5      R	                  SS5      n[        ["        [%        U5      -
  5      nSR'                  U5      nSnSU;   a(  UR)                  S5      u  nnUR)                  S5      nSnOUR)                  S5      nSn[        U5       H  u  pSU;   d  M  UR!                  S5      S:w  d  UR!                  S5      S:w  a  [        S5      eX
   R*                  S:X  a  SnO)[-        X
   R.                  S5      nU[        U5      S-
  -  nUU:  a  UnUS:  a  [        S5      eUS:X  a  UR	                  SS5      UU
'   M  UU* S nUR	                  SU5      UU
'   M     SR'                  U5      nUS:X  a  SnOUU* S nU(       a  USWR	                  SU5      -   -  nOSnUR	                  SS5      n[1        [%        U5      5       H7  nU[        ;  a  [        SU-  5      eUR!                  U5      S:X  d  M2  UU-  nM9     SR'                  [1        [%        U5      [%        U5      -
  5      5      nUSU-   U-   -  nSU;   a  UR)                  S5      u  nnOeUnUR	                  SS5      nSn[1        [%        U5      5       H7  nU[        ;  a  [        SU-  5      eUR!                  U5      S:X  d  M2  UU-  nM9     U H:  nUR!                  U5      S:w  a  [        SU-  5      eUU;  d  M.  [        SU-  5      e   [        UR)                  S5      5      [        U 5      :w  a  [        S5      eUUU 4$ s  snf s  snf ! [         a  n[        S5      UeSnAff = f! [         a  n[        S5      UeSnAff = f)aJ  
A reproduction of einsum c side einsum parsing in python.

Returns
-------
input_strings : str
    Parsed input strings
output_string : str
    Parsed output string
operands : list of array_like
    The operands to use in the numpy contraction

Examples
--------
The operand list is simplified to reduce printing:

>>> np.random.seed(123)
>>> a = np.random.rand(4, 4)
>>> b = np.random.rand(4, 4, 4)
>>> _parse_einsum_input(('...a,...a->...', a, b))
('za,xza', 'xz', [a, b]) # may vary

>>> _parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
('za,xza', 'xz', [a, b]) # may vary
r   zNo input operands  r   Nz.,->z#Character %s is not a valid symbol.r.   r]   z...z=For this input type lists must contain either int or Ellipsis,->->z%Subscripts can only contain one '->'..TF   zInvalid Ellipses.r   zEllipses lengths do not match.z:Output character %s appeared more than once in the output.z/Output character %s did not appear in the inputzDNumber of einsum subscripts must be equal to the number of operands.)r9   
ValueError
isinstancestrreplacer   einsum_symbolslistr8   r!   popr    Ellipsisoperatorindex	TypeErrorrv   einsum_symbols_setr   joinsplitshaper   ndimsorted)operands
subscriptsvstmp_operandsoperand_listsubscript_listrP   output_listlastnumsubeinvalidusedunusedellipse_indslongest	input_tmp
output_subsplit_subscriptsout_subellipse_countrep_indsout_ellipseoutput_subscripttmp_subscriptsnormal_indsinput_subscriptschars                                 r   _parse_einsum_inputr   (  s;   6 8},--(1+s##a[((b1
+3AB<8<aJqM<8 AF{& !F!JKK	  H~s8})*A 0 0 34!!,"2"21"56 + +.l*;*;l2&+78<aJqM<8
>"Q&!.1HC=%'J!$NN1- ."33J  {c!
 2  "$J =%'J!$NN1- ."33J ! 	zsj0##C(1,L*2B2B32G!2Kz''-2DEE j!!#r*223;CCD"M(3t945wwv:$.$4$4T$:!Iz(s3G)//4G!"23HCczIIcNa'SYYu-=-B$%899 =&&",$%M$'(:(:A$>M!c#hl3M 7*+G 1$$%EFF"a',/KKr,B$S)+]NO<H,/KKx,H$S)+ 4. XX./
a<K&xy1K$!3!3E;!GGGJ  "'//R8NC/0^,$%JQ%NOO!''*a/$)$	 1
 ''&-=)>),[)9*: #; <K $,{::J z-7-=-=d-C**%#++C4N+,A& !F!JKK##A&!+ A% 	 - !!!$'1, +-12 3 3''N#$ % % ! !!#&'3x=8 / 0 	0 .99c 9$ 9 % !'5  !!!" % !'5  !!!s<   VV#&V(:W(
W2V>>W
W!WW!optimizeeinsum_callc                     U$ rN   r   )r   r   r   s      r   _einsum_path_dispatcherr     s	     Or   numpy)modulegreedyFc           	         U nUSL a  SnUc  SnSnSnUSL d  [        U[        5      (       a  O[        U5      (       a  US   S:X  a  SnOp[        U5      S:X  aJ  [        US   [        5      (       a2  [        US   [        [        45      (       a  [        US   5      nUS   nO[        S	[        U5      -  5      eUn[        U5      u  pxnUR                  S
5      n	U	 V
s/ s H  n
[        U
5      PM     nn
[        U5      n[        UR                  S
S5      5      n0 n[        [        U	5      5       V
s/ s H  n
/ PM     nn
[        U	5       H  u  nnUU   R                  n[        U5      [        U5      :w  a  [        SUU   U4-  5      e[        U5       Hp  u  nnUU   nUS:X  a  UU   R                  U5        UUR                  5       ;   a2  UU   S:X  a  UUU'   MI  USUU   4;  a  [        SUUUU   U4-  5      eMk  UUU'   Mr     M     U V
s/ s H  n
[        U
5      PM     nn
X/-    Vs/ s H  n[!        UU5      PM     nn[#        U5      nUc  UnOUn[%        S U 5       5      [        U5      -
  S:  n['        UU[        U	5      U5      nU(       a  USS nOlUSL d  [        U	5      S;   d  X:X  a  [)        [        [        U	5      5      5      /nO4US:X  a  [+        XUU5      nO US:X  a  [-        XUU5      nO[/        SU5      e/ / / / 4u  nnnn[        U5       GH  u  nn[)        [1        USS95      n[3        UX5      n U u  n!nn"n#['        U#U"[        U5      U5      n$UR                  U$5        UR                  [        U#5      5        UR                  [!        U!U5      5        [        5       n%/ n&U H7  n
U&R                  U	R5                  U
5      5        U%UR5                  U
5      -  n%M9     U%U"-
  n'[        U"U%-  5      (       d  [7        U&U!U"5      n(OSn(U[        U5      -
  S:X  a  Un)ODU! V*s/ s H
  n*UU*   U*4PM     n+n*SR9                  [1        U+5       V
s/ s H  oS   PM	     sn
5      n)U	R                  U)5        UR                  U'5        S
R9                  U&5      S-   U)-   n,UU"U,U	SS U(4n-UR                  U-5        GM     [%        U5      S-   n.[        U	5      S:w  a&  [;        SR=                  [        U	5      S-
  5      5      eU(       a  UU4$ US-   U-   n/Sn0UU.-  n1[#        U5      n2SU/-  n3U3S[        U5      -  -  n3U3S[#        U5      -  -  n3U3SU-  -  n3U3SU.-  -  n3U3SU1-  -  n3U3SU2-  -  n3U3S-  n3U3SU0-  -  n3U3S -  n3[        U5       H5  u  n4n-U-u  n5n6n,n7n8S
R9                  U75      S-   U-   n9UU4   U,U94n:U3S!U:-  -  n3M7     S/U-   nUU34$ s  sn
f s  sn
f s  sn
f s  snf s  sn*f s  sn
f )"aq  
einsum_path(subscripts, *operands, optimize='greedy')

Evaluates the lowest cost contraction order for an einsum expression by
considering the creation of intermediate arrays.

Parameters
----------
subscripts : str
    Specifies the subscripts for summation.
*operands : list of array_like
    These are the arrays for the operation.
optimize : {bool, list, tuple, 'greedy', 'optimal'}
    Choose the type of path. If a tuple is provided, the second argument is
    assumed to be the maximum intermediate size created. If only a single
    argument is provided the largest input or output array size is used
    as a maximum intermediate size.

    * if a list is given that starts with ``einsum_path``, uses this as the
      contraction path
    * if False no optimization is taken
    * if True defaults to the 'greedy' algorithm
    * 'optimal' An algorithm that combinatorially explores all possible
      ways of contracting the listed tensors and chooses the least costly
      path. Scales exponentially with the number of terms in the
      contraction.
    * 'greedy' An algorithm that chooses the best pair contraction
      at each step. Effectively, this algorithm searches the largest inner,
      Hadamard, and then outer products at each step. Scales cubically with
      the number of terms in the contraction. Equivalent to the 'optimal'
      path for most contractions.

    Default is 'greedy'.

Returns
-------
path : list of tuples
    A list representation of the einsum path.
string_repr : str
    A printable representation of the einsum path.

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. This list can then be iterated over until all
intermediate contractions are complete.

See Also
--------
einsum, linalg.multi_dot

Examples
--------

We can begin with a chain dot example. In this case, it is optimal to
contract the ``b`` and ``c`` tensors first as 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
completed.

>>> np.random.seed(123)
>>> a = np.random.rand(2, 2)
>>> b = np.random.rand(2, 5)
>>> c = np.random.rand(5, 2)
>>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')
>>> print(path_info[0])
['einsum_path', (1, 2), (0, 1)]
>>> print(path_info[1])
  Complete contraction:  ij,jk,kl->il # may vary
         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.

>>> I = np.random.rand(10, 10, 10, 10)
>>> C = np.random.rand(10, 10)
>>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C,
...                            optimize='greedy')

>>> print(path_info[0])
['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)]
>>> print(path_info[1])
  Complete contraction:  ea,fb,abcd,gc,hd->efgh # may vary
         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
Tr   NFr   r   r.   r   zDid not understand the path: %sr   r   zXEinstein sum subscript %s does not contain the correct number of indices for operand %d.zJSize of label '%s' for operand %d (%d) does not match previous terms (%d).c              3   8   #    U  H  n[        U5      v   M     g 7frN   )r9   )rO   r2   s     r   rQ   einsum_path.<locals>.<genexpr>  s     4AQs   )r   r.   optimalzPath name %s not found)reverser]   r   zHInvalid einsum_path is specified: {} more operands has to be contracted.)scalingcurrentr'   z  Complete contraction:  %s
z         Naive scaling:  %d
z     Optimized scaling:  %d
z      Naive FLOP count:  %.3e
z  Optimized FLOP count:  %.3e
z   Theoretical speedup:  %3.3f
z'  Largest intermediate:  %.3e elements
zK--------------------------------------------------------------------------
z%6s %24s %40s
zJ--------------------------------------------------------------------------z
%4d    %24s %40s)r   r   r9   r^   floatr   r   r   r   r   r8   r    r   r   r!   keysr   r   rS   r   r=   rt   rK   KeyErrorr   r,   r   r   r   RuntimeErrorformat);r   r   r   	path_typeexplicit_einsum_pathr>   einsum_call_argr   r   
input_listr2   r#   r$   r   dimension_dictbroadcast_indicestnumtermshcnumr   dim	size_listmax_size
memory_arginner_productrU   rJ   	cost_list
scale_listcontraction_listcontract_indsrV   out_indsr+   r%   rC   bcast
tmp_inputsnew_bcast_indsdo_blasrW   r(   sort_result
einsum_strcontractionopt_costoverall_contractionheaderspeedupmax_i
path_printnindsidx_rmr'   blasremaining_strpath_runs;                                                              r   r   r     s   ` ID		 L 	Uz)S99 
YYq\]:# y>QJy|S$A$Ay|c5\229Q<(aL	 9C	NJKK "O 	H% 1
 "'',J",-*Q#a&*J-%&J"**334G N%*3z?%;<%;%;<
+
dd^!!r7c$i I 0 6=> ? ? $D/JD$T(C ax!$'..t4~**,,!$'1,+.N4(N4$8 99$ &K(,dN44H#'N&O P P :
 (+t$! * ,2 *;;):AQ):; (*<<><T 't^<<  >9~H
!
 444s7|CqHMJJ
 }	e	
Ov%! eC
O,-.	h	NJ
 
i	NJ
 /;;9;RR6Iz9&6  )mf]DAB$]JK:B7*k<+s='9>
 	#l+,.xHI
AjnnQ/0&**1--E  , ;&''z8[AGG 3t9#)JAIJ#N3/5KJ{0C!D0C1A$0C!DEJ*%  0XXj)D0:=
 ;
JqM7
 	,U  /X 9~!H
:!  &Z1!457 	7 *++ +T14DD0F8#G	NE03FFJ1CL@@J1C
OCCJ3j@@J3h>>J4w>>J<uDDJ/!J#f,,J(J#$45;4?1fj)T+d25EEqM:}=*X55
	 6 ?T!D*y . =4 <>P K!Ds$   W 4W%W*2W/8W4#W9
)outr   c              /   ,   #    U S h  vN   U v   g  N	7frN   r   )r   r   r   kwargss       r   _einsum_dispatcherr     s      
I s   
c           	         U SLnUSL a  U(       a  XS'   [        U0 UD6$ / SQnUR                  5        VVs/ s H  u  pgXe;  d  M  UPM     nnn[        U5      (       a  [        SU-  5      e[	        X!SS.6u  p)UR                  SS	5      n
U
R                  5       S
:X  a  [        S U 5       5      (       a  Sn
OSn
[        U	5       GHe  u  pUu  pnnnU Vs/ s H  nUR                  U5      PM     nnU=(       a    US-   [        U	5      :H  nU(       a  UR                  S5      u  nnUR                  S5      u  nnUU-   nU H  nUR                  US5      nM     / / nn[        U5       HC  nUR                  UR                  U5      5        UR                  UR                  U5      5        ME     [        US[        U5      [        U5      406nUU:w  d  U(       a  U(       a  XS'   [        US-   U-   U40 UD6nOU(       a  XS'   [        U/UQ70 UD6nUR                  U5        AAGMh     U(       a  U $ [!        US   U
S9$ s  snnf s  snf )a;1  
einsum(subscripts, *operands, out=None, dtype=None, order='K',
       casting='safe', optimize=False)

Evaluates the Einstein summation convention on the operands.

Using the Einstein summation convention, many common multi-dimensional,
linear algebraic array operations can be represented in a simple fashion.
In *implicit* mode `einsum` computes these values.

In *explicit* mode, `einsum` provides further flexibility to compute
other array operations that might not be considered classical Einstein
summation operations, by disabling, or forcing summation over specified
subscript labels.

See the notes and examples for clarification.

Parameters
----------
subscripts : str
    Specifies the subscripts for summation as comma separated list of
    subscript labels. An implicit (classical Einstein summation)
    calculation is performed unless the explicit indicator '->' is
    included as well as subscript labels of the precise output form.
operands : list of array_like
    These are the arrays for the operation.
out : ndarray, optional
    If provided, the calculation is done into this array.
dtype : {data-type, None}, optional
    If provided, forces the calculation to use the data type specified.
    Note that you may have to also give a more liberal `casting`
    parameter to allow the conversions. Default is None.
order : {'C', 'F', 'A', 'K'}, optional
    Controls the memory layout of the output. 'C' means it should
    be C contiguous. 'F' means it should be Fortran contiguous,
    'A' means it should be 'F' if the inputs are all 'F', 'C' otherwise.
    'K' means it should be as close to the layout as the inputs as
    is possible, including arbitrarily permuted axes.
    Default is 'K'.
casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
    Controls what kind of data casting may occur.  Setting this to
    'unsafe' is not recommended, as it can adversely affect accumulations.

    * 'no' means the data types should not be cast at all.
    * 'equiv' means only byte-order changes are allowed.
    * 'safe' means only casts which can preserve values are allowed.
    * 'same_kind' means only safe casts or casts within a kind,
      like float64 to float32, are allowed.
    * 'unsafe' means any data conversions may be done.

    Default is 'safe'.
optimize : {False, True, 'greedy', 'optimal'}, optional
    Controls if intermediate optimization should occur. No optimization
    will occur if False and True will default to the 'greedy' algorithm.
    Also accepts an explicit contraction list from the ``np.einsum_path``
    function. See ``np.einsum_path`` for more details. Defaults to False.

Returns
-------
output : ndarray
    The calculation based on the Einstein summation convention.

See Also
--------
einsum_path, dot, inner, outer, tensordot, linalg.multi_dot
einsum:
    Similar verbose interface is provided by the
    `einops <https://github.com/arogozhnikov/einops>`_ package to cover
    additional operations: transpose, reshape/flatten, repeat/tile,
    squeeze/unsqueeze and reductions.
    The `opt_einsum <https://optimized-einsum.readthedocs.io/en/stable/>`_
    optimizes contraction order for einsum-like expressions
    in backend-agnostic manner.

Notes
-----
The Einstein summation convention can be used to compute
many multi-dimensional, linear algebraic array operations. `einsum`
provides a succinct way of representing these.

A non-exhaustive list of these operations,
which can be computed by `einsum`, is shown below along with examples:

* Trace of an array, :py:func:`numpy.trace`.
* Return a diagonal, :py:func:`numpy.diag`.
* Array axis summations, :py:func:`numpy.sum`.
* Transpositions and permutations, :py:func:`numpy.transpose`.
* Matrix multiplication and dot product, :py:func:`numpy.matmul`
    :py:func:`numpy.dot`.
* Vector inner and outer products, :py:func:`numpy.inner`
    :py:func:`numpy.outer`.
* Broadcasting, element-wise and scalar multiplication,
    :py:func:`numpy.multiply`.
* Tensor contractions, :py:func:`numpy.tensordot`.
* Chained array operations, in efficient calculation order,
    :py:func:`numpy.einsum_path`.

The subscripts string is a comma-separated list of subscript labels,
where each label refers to a dimension of the corresponding operand.
Whenever a label is repeated it is summed, so ``np.einsum('i,i', a, b)``
is equivalent to :py:func:`np.inner(a,b) <numpy.inner>`. If a label
appears only once, it is not summed, so ``np.einsum('i', a)``
produces a view of ``a`` with no changes. A further example
``np.einsum('ij,jk', a, b)`` describes traditional matrix multiplication
and is equivalent to :py:func:`np.matmul(a,b) <numpy.matmul>`.
Repeated subscript labels in one operand take the diagonal.
For example, ``np.einsum('ii', a)`` is equivalent to
:py:func:`np.trace(a) <numpy.trace>`.

In *implicit mode*, the chosen subscripts are important
since the axes of the output are reordered alphabetically.  This
means that ``np.einsum('ij', a)`` doesn't affect a 2D array, while
``np.einsum('ji', a)`` takes its transpose. Additionally,
``np.einsum('ij,jk', a, b)`` returns a matrix multiplication, while,
``np.einsum('ij,jh', a, b)`` returns the transpose of the
multiplication since subscript 'h' precedes subscript 'i'.

In *explicit mode* the output can be directly controlled by
specifying output subscript labels.  This requires the
identifier '->' as well as the list of output subscript labels.
This feature increases the flexibility of the function since
summing can be disabled or forced when required. The call
``np.einsum('i->', a)`` is like :py:func:`np.sum(a) <numpy.sum>`
if ``a`` is a 1-D array, and ``np.einsum('ii->i', a)``
is like :py:func:`np.diag(a) <numpy.diag>` if ``a`` is a square 2-D array.
The difference is that `einsum` does not allow broadcasting by default.
Additionally ``np.einsum('ij,jh->ih', a, b)`` directly specifies the
order of the output subscript labels and therefore returns matrix
multiplication, unlike the example above in implicit mode.

To enable and control broadcasting, use an ellipsis.  Default
NumPy-style broadcasting is done by adding an ellipsis
to the left of each term, like ``np.einsum('...ii->...i', a)``.
``np.einsum('...i->...', a)`` is like
:py:func:`np.sum(a, axis=-1) <numpy.sum>` for array ``a`` of any shape.
To take the trace along the first and last axes,
you can do ``np.einsum('i...i', a)``, or to do a matrix-matrix
product with the left-most indices instead of rightmost, one can do
``np.einsum('ij...,jk...->ik...', a, b)``.

When there is only one operand, no axes are summed, and no output
parameter is provided, a view into the operand is returned instead
of a new array.  Thus, taking the diagonal as ``np.einsum('ii->i', a)``
produces a view (changed in version 1.10.0).

`einsum` also provides an alternative way to provide the subscripts and
operands as ``einsum(op0, sublist0, op1, sublist1, ..., [sublistout])``.
If the output shape is not provided in this format `einsum` will be
calculated in implicit mode, otherwise it will be performed explicitly.
The examples below have corresponding `einsum` calls with the two
parameter methods.

Views returned from einsum are now writeable whenever the input array
is writeable. For example, ``np.einsum('ijk...->kji...', a)`` will now
have the same effect as :py:func:`np.swapaxes(a, 0, 2) <numpy.swapaxes>`
and ``np.einsum('ii->i', a)`` will return a writeable view of the diagonal
of a 2D array.

Added the ``optimize`` argument which will optimize the contraction order
of an einsum expression. For a contraction with three or more operands
this can greatly increase the computational efficiency at the cost of
a larger memory footprint during computation.

Typically a 'greedy' algorithm is applied which empirical tests have shown
returns the optimal path in the majority of cases. In some cases 'optimal'
will return the superlative path through a more expensive, exhaustive
search. For iterative calculations it may be advisable to calculate
the optimal path once and reuse that path by supplying it as an argument.
An example is given below.

See :py:func:`numpy.einsum_path` for more details.

Examples
--------
>>> a = np.arange(25).reshape(5,5)
>>> b = np.arange(5)
>>> c = np.arange(6).reshape(2,3)

Trace of a matrix:

>>> np.einsum('ii', a)
60
>>> np.einsum(a, [0,0])
60
>>> np.trace(a)
60

Extract the diagonal (requires explicit form):

>>> np.einsum('ii->i', a)
array([ 0,  6, 12, 18, 24])
>>> np.einsum(a, [0,0], [0])
array([ 0,  6, 12, 18, 24])
>>> np.diag(a)
array([ 0,  6, 12, 18, 24])

Sum over an axis (requires explicit form):

>>> np.einsum('ij->i', a)
array([ 10,  35,  60,  85, 110])
>>> np.einsum(a, [0,1], [0])
array([ 10,  35,  60,  85, 110])
>>> np.sum(a, axis=1)
array([ 10,  35,  60,  85, 110])

For higher dimensional arrays summing a single axis can be done
with ellipsis:

>>> np.einsum('...j->...', a)
array([ 10,  35,  60,  85, 110])
>>> np.einsum(a, [Ellipsis,1], [Ellipsis])
array([ 10,  35,  60,  85, 110])

Compute a matrix transpose, or reorder any number of axes:

>>> np.einsum('ji', c)
array([[0, 3],
       [1, 4],
       [2, 5]])
>>> np.einsum('ij->ji', c)
array([[0, 3],
       [1, 4],
       [2, 5]])
>>> np.einsum(c, [1,0])
array([[0, 3],
       [1, 4],
       [2, 5]])
>>> np.transpose(c)
array([[0, 3],
       [1, 4],
       [2, 5]])

Vector inner products:

>>> np.einsum('i,i', b, b)
30
>>> np.einsum(b, [0], b, [0])
30
>>> np.inner(b,b)
30

Matrix vector multiplication:

>>> np.einsum('ij,j', a, b)
array([ 30,  80, 130, 180, 230])
>>> np.einsum(a, [0,1], b, [1])
array([ 30,  80, 130, 180, 230])
>>> np.dot(a, b)
array([ 30,  80, 130, 180, 230])
>>> np.einsum('...j,j', a, b)
array([ 30,  80, 130, 180, 230])

Broadcasting and scalar multiplication:

>>> np.einsum('..., ...', 3, c)
array([[ 0,  3,  6],
       [ 9, 12, 15]])
>>> np.einsum(',ij', 3, c)
array([[ 0,  3,  6],
       [ 9, 12, 15]])
>>> np.einsum(3, [Ellipsis], c, [Ellipsis])
array([[ 0,  3,  6],
       [ 9, 12, 15]])
>>> np.multiply(3, c)
array([[ 0,  3,  6],
       [ 9, 12, 15]])

Vector outer product:

>>> np.einsum('i,j', np.arange(2)+1, b)
array([[0, 1, 2, 3, 4],
       [0, 2, 4, 6, 8]])
>>> np.einsum(np.arange(2)+1, [0], b, [1])
array([[0, 1, 2, 3, 4],
       [0, 2, 4, 6, 8]])
>>> np.outer(np.arange(2)+1, b)
array([[0, 1, 2, 3, 4],
       [0, 2, 4, 6, 8]])

Tensor contraction:

>>> a = np.arange(60.).reshape(3,4,5)
>>> b = np.arange(24.).reshape(4,3,2)
>>> np.einsum('ijk,jil->kl', a, b)
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])
>>> np.einsum(a, [0,1,2], b, [1,0,3], [2,3])
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])
>>> np.tensordot(a,b, axes=([1,0],[0,1]))
array([[4400., 4730.],
       [4532., 4874.],
       [4664., 5018.],
       [4796., 5162.],
       [4928., 5306.]])

Writeable returned arrays (since version 1.10.0):

>>> a = np.zeros((3, 3))
>>> np.einsum('ii->i', a)[:] = 1
>>> a
array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])

Example of ellipsis use:

>>> a = np.arange(6).reshape((3,2))
>>> b = np.arange(12).reshape((4,3))
>>> np.einsum('ki,jk->ij', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
>>> np.einsum('ki,...k->i...', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])
>>> np.einsum('k...,jk', a, b)
array([[10, 28, 46, 64],
       [13, 40, 67, 94]])

Chained array operations. For more complicated contractions, speed ups
might be achieved by repeatedly computing a 'greedy' path or pre-computing
the 'optimal' path and repeatedly applying it, using an `einsum_path`
insertion (since version 1.12.0). Performance improvements can be
particularly significant with larger arrays:

>>> a = np.ones(64).reshape(2,4,8)

Basic `einsum`: ~1520ms  (benchmarked on 3.1GHz Intel i5.)

>>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a)

Sub-optimal `einsum` (due to repeated path calculation time): ~330ms

>>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
...         optimize='optimal')

Greedy `einsum` (faster optimal path approximation): ~160ms

>>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize='greedy')

Optimal `einsum` (best usage pattern in some use cases): ~110ms

>>> path = np.einsum_path('ijk,ilm,njm,nlk,abc->',a,a,a,a,a,
...     optimize='optimal')[0]
>>> for iteration in range(500):
...     _ = np.einsum('ijk,ilm,njm,nlk,abc->',a,a,a,a,a, optimize=path)

NFr   )dtypeordercastingz+Did not understand the following kwargs: %sTr   r   KAc              3   L   #    U  H  oR                   R                  v   M     g 7frN   )flagsf_contiguous)rO   arrs     r   rQ   einsum.<locals>.<genexpr>  s     :#yy%%s   "$FCr   r   r   r   axesr   )r   )r   itemsr9   r   r   r   upperallr    r   r   r   r!   findr   r=   r   )r   r   r   r   specified_outvalid_einsum_kwargskr   unknown_kwargsr   output_orderr   r   r   r   r   r'   r   r2   r   
handle_out	input_strresults_indexrx   ry   tensor_resultr   left_pos	right_posnew_views                                 r   r   r   !  s   P tOM 55M,V,, 8&,lln 4nFQ2 nN 4
>E() * 	* "-h9="?H ::gs+Ls"::::LL &&674?1j)T156AQ6 #KqS9I5J(J
 '1'7'7'=$I}&/ooc&:#J&4M - 5 5a <  #%biHF^
 23  !1!1!!45 $
 !%*8_eI6F$GH
 .:$'5M#!D(=8(FL  #u  
D\DVDH 	!(_ 8b 
(1+\::O4* 7s   III)__doc__r:   r   numpy._core.multiarrayr   numpy._core.numericr   r   numpy._core.overridesr   __all__r   r   r   r   r   r,   rK   r[   ri   rt   r   r   r   r   r   r   r   r   r   <module>r     s      + 5 9]
# H( $$L:9>xHT=-@(Tpfk\q:h 15$  0A$,% o Bod	 '+T  +G< y; =y;r   