
    Sh3                        d Z ddlZddlmZmZmZmZmZmZ ddl	m
Z
mZ g dZdZdedefd	Zd
edefdZdedefdZdededee         fdZd
edefdZdedefdZdedefdZdee         dee         dedefdZeeeeeefZdedefdZdedefdZdee         deeef         defdZdee         deeeed f         f         fd!Z d$dededeeeee
         f         fd#Z!dS )%zBA functionally equivalent parser of the numpy.einsum input parser.    N)AnyDictIteratorListSequenceTuple)	ArrayTypeTensorShapeType)is_valid_einsum_charhas_valid_einsum_chars_only
get_symbol	get_shapegen_unused_symbolsconvert_to_valid_einsum_charsalpha_canonicalizefind_output_strfind_output_shapepossibly_convert_to_numpyparse_einsum_input4abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZxreturnc                     | t           v p| dv S )u   Check if the character ``x`` is valid for numpy einsum.

    **Examples:**

    ```python
    is_valid_einsum_char("a")
    #> True

    is_valid_einsum_char("Ǵ")
    #> False
    ```
    z,->.)_einsum_symbols_base)r   s    W/var/www/html/movieo_spanner_bot/venv/lib/python3.11/site-packages/opt_einsum/parser.pyr   r      s     %%71;7    
einsum_strc                 F    t          t          t          |                     S )u   Check if ``einsum_str`` contains only valid characters for numpy einsum.

    **Examples:**

    ```python
    has_valid_einsum_chars_only("abAZ")
    #> True

    has_valid_einsum_chars_only("Över")
    #> False
    ```
    )allmapr   )r   s    r   r   r   )   s     s'44555r   ic                 |    | dk     rt           |          S | dk    rt          | dz             S t          | dz             S )u<  Get the symbol corresponding to int ``i`` - runs through the usual 52
    letters before resorting to unicode characters, starting at ``chr(192)`` and skipping surrogates.

    **Examples:**

    ```python
    get_symbol(2)
    #> 'c'

    get_symbol(200)
    #> 'Ŕ'

    get_symbol(20000)
    #> '京'
    ```
    4   i   i      )r   chr)r!   s    r   r   r   9   sA    " 	2vv#A&&	
e1t8}}1s7||r   usednc              #   r   K   dx}}||k     r*t          |          }|dz  }|| v r|V  |dz  }||k     (dS dS )zGenerate ``n`` symbols that are not already in ``used``.

    **Examples:**
    ```python
    list(oe.parser.gen_unused_symbols("abd", 2))
    #> ['c', 'e']
    ```
    r      Nr   )r&   r'   r!   cntss        r   r   r   S   s_       KA
''qMM	Q99q ''''''r   c                     t          t          |           t          d          z
            }d t          |          D             d                    fd| D                       S )u  Convert the str ``einsum_str`` to contain only the alphabetic characters
    valid for numpy einsum. If there are too many symbols, let the backend
    throw an error.

    Examples:
    --------
    >>> oe.parser.convert_to_valid_einsum_chars("Ĥěļļö")
    'cbdda'
    z,->c                 4    i | ]\  }}|t          |          S  r*   ).0r!   r   s      r   
<dictcomp>z1convert_to_valid_einsum_chars.<locals>.<dictcomp>q   s$    @@@TQ:a==@@@r    c              3   D   K   | ]}                     ||          V  d S Nget)r0   r   replacers     r   	<genexpr>z0convert_to_valid_einsum_chars.<locals>.<genexpr>r   s1      ::!8<<1%%::::::r   )sortedset	enumeratejoin)r   symbolsr7   s     @r   r   r   f   se     S__s5zz122G@@Yw-?-?@@@H77::::z::::::r   equationc                     i | D ]*}|dv r|vrt          t                              |<   +d                    fd| D                       S )u   Alpha convert an equation in an order-independent canonical way.

    Examples:
    --------
    >>> oe.parser.alpha_canonicalize("dcba")
    'abcd'

    >>> oe.parser.alpha_canonicalize("Ĥěļļö")
    'abccd'
    z.,->r2   c              3   D   K   | ]}                     ||          V  d S r4   r5   )r0   r   renames     r   r8   z%alpha_canonicalize.<locals>.<genexpr>   s1      666::a##666666r   )r   lenr<   )r>   namerA   s     @r   r   r   u   so      F 3 36>>v%c&kk22F4L776666X666666r   
subscriptsc                     |                      dd          d                    fdt          t                              D                       S )aU  Find the output string for the inputs ``subscripts`` under canonical einstein summation rules.
    That is, repeated indices are summed over by default.

    Examples:
    --------
    >>> oe.parser.find_output_str("ab,bc")
    'ac'

    >>> oe.parser.find_output_str("a,b")
    'ab'

    >>> oe.parser.find_output_str("a,a,b,b")
    ''
    ,r2   c              3   N   K   | ]}                     |          d k    |V   dS )r)   N)count)r0   r,   tmp_subscriptss     r   r8   z"find_output_str.<locals>.<genexpr>   s=      ZZ^=Q=QRS=T=TXY=Y=Y1=Y=Y=Y=YZZr   )replacer<   r9   r:   )rD   rI   s    @r   r   r      sQ      ''R00N77ZZZZfS%8%899ZZZZZZr   inputsshapesoutputc                 >     t           fd|D                       S )aP  Find the output shape for given inputs, shapes and output string, taking
    into account broadcasting.

    Examples:
    --------
    >>> oe.parser.find_output_shape(["ab", "bc"], [(2, 3), (3, 4)], "ac")
    (2, 4)

    # Broadcasting is accounted for
    >>> oe.parser.find_output_shape(["a", "a"], [(4, ), (1, )], "a")
    (4,)
    c           	   3      K   | ]7t          d  t          fdD                       D                       V  8dS )c              3   8   K   | ]\  }}|d k    ||         V  dS )r   Nr/   )r0   shapelocs      r   r8   z.find_output_shape.<locals>.<genexpr>.<genexpr>   s6      ggJE3^aef^f^fU3Z^f^f^f^fggr   c                 :    g | ]}|                               S r/   )find)r0   r   cs     r   
<listcomp>z/find_output_shape.<locals>.<genexpr>.<listcomp>   s#    >Y>Y>YQqvvayy>Y>Y>Yr   N)maxzip)r0   rU   rK   rL   s    @r   r8   z$find_output_shape.<locals>.<genexpr>   s\      xxlmgg#f>Y>Y>Y>YRX>Y>Y>Y2Z2Zgggggxxxxxxr   )tuple)rK   rL   rM   s   `` r   r   r      s-     xxxxxqwxxxxxxr   c                    t          | d          r| j        S t          | t                    rdS t          | t                    rg }t          | t                    rit          | t                    sT|                    t          |                      | d         } t          | t                    rt          | t                    Tt          |          S t          d|  d          )a  Get the shape of the array-like object `x`. If `x` is not array-like, raise an error.

    Array-like objects are those that have a `shape` attribute, are sequences of BaseTypes, or are BaseTypes.
    BaseTypes are defined as `bool`, `int`, `float`, `complex`, `str`, and `bytes`.
    rQ   r/   r   zCannot determine the shape of z5, can only determine the shape of array-like objects.)	hasattrrQ   
isinstance
_BaseTypesr   appendrB   rY   
ValueError)r   rQ   s     r   r   r      s     q' tw	Az	"	" 	tr	Ax	 	  tH%% 	jJ.G.G 	LLQ   !A H%% 	jJ.G.G 	 U||r!rrrsssr   c                     t          | d          s8	 ddl}n# t          $ r t          d          w xY w|                    |           S | S )aU  Convert things without a 'shape' to ndarrays, but leave everything else.

    Examples:
    --------
    >>> oe.parser.possibly_convert_to_numpy(5)
    array(5)

    >>> oe.parser.possibly_convert_to_numpy([5, 3])
    array([5, 3])

    >>> oe.parser.possibly_convert_to_numpy(np.array([5, 3]))
    array([5, 3])

    # Any class with a shape is passed through
    >>> class Shape:
    ...     def __init__(self, shape):
    ...         self.shape = shape
    ...

    >>> myshape = Shape((5, 5))
    >>> oe.parser.possibly_convert_to_numpy(myshape)
    <__main__.Shape object at 0x10f850710>
    rQ   r   Nzinumpy is required to convert non-array objects to arrays. This function will be deprecated in the future.)r[   numpyModuleNotFoundError
asanyarray)r   nps     r   r   r      ss    0 1g 
	" 	 	 	%{  	
 }}Qs    1old_sub
symbol_mapc                 H    d}| D ]}|t           u r|dz  }|||         z  }|S )a  Convert user custom subscripts list to subscript string according to `symbol_map`.

    Examples:
    --------
    >>>  oe.parser.convert_subscripts(['abc', 'def'], {'abc':'a', 'def':'b'})
    'ab'
    >>> oe.parser.convert_subscripts([Ellipsis, object], {object:'a'})
    '...a'
    r2   ...)Ellipsis)re   rf   new_subr,   s       r   convert_subscriptsrk      sD     G % %==uGG z!}$GGNr   operands.c                    t          |           }g }g }t          t          |           dz            D ]R}|                    |                    d                     |                    |                    d                     St          |          r|d         nd}	 t          t          j                            |                    }|	                    t                     d t          t          |                    D             n# t          $ r t          d          w xY wd                    fd|D                       }||d	z  }|t          |          z  }|t!          |          fS )
z5Convert 'interleaved' input to standard einsum input.   r   Nc                 4    i | ]\  }}|t          |          S r/   r*   )r0   idxsymbols      r   r1   z-convert_interleaved_input.<locals>.<dictcomp>  s$    ___+#vfjoo___r   ziFor this input type lists must contain either Ellipsis or hashable and comparable object (e.g. int, str).rF   c              3   8   K   | ]}t          |          V  d S r4   )rk   )r0   subrf   s     r   r8   z,convert_interleaved_input.<locals>.<genexpr>  s.      XX#,S*==XXXXXXr   ->)listrangerB   r^   popr:   	itertoolschainfrom_iterablediscardri   r;   r9   	TypeErrorr<   rk   rY   )	rl   tmp_operandsoperand_listsubscript_list_output_list
symbol_setrD   rf   s	           @r   convert_interleaved_inputr      s   >>LLN3x==A%&& 3 3L,,Q//000l..q112222&),&7&7A,r""TK
66~FFGG
 	8$$$ `_6R\K]K]A^A^___

 
 
 
A
 
 	

 XXXXXXXXXJd
(jAAA
u\****s   !A,D D(Fc           	         t          |           dk    rt          d          t          | d         t                    rY| d                             dd          }|r0t          d | dd         D                       rt          d          | dd         } nt          |           \  }} |r| }nd	 | D             }d
|v sd|v r\|                    d
          dk    p|                    d          dk    }|s|                    d          dk    rt          d          d|v rd|                    dd                              dd                              dd          }d                    t          |t          d |D                                           }d}d|v r0|                    d          \  }}	|                    d          }
d}n|                    d          }
d}t          |
          D ]\  }}d|v r|                    d          dk    s|                    d          dk    rt          d          ||         dk    rd}n6t          t          ||                   d          t          |          dz
  z
  }||k    r|}|dk     rt          d          |dk    r|                    dd          |
|<   |                    d|| d                   |
|<   d                    |
          }|dk    rd}n|| d         }|r|d|	                    d|          z   z  }nYt          |          }d                    t          t          |          t          |          z
                      }|d|z   |z   z  }d|v r|                    d          \  }}n|t          |          }}|D ]E}|                    |          dk    rt          d| d          ||vrt          d| d          Ft          |                    d                    t          |           k    rCt          dt          |                    d                     dt          |            d          ||| fS )ay  A reproduction of einsum c side einsum parsing in python.

    Parameters:
        operands: Intakes the same inputs as `contract_path`, but NOT the keyword args. The only
            supported keyword argument is:
        shapes: Whether ``parse_einsum_input`` should assume arrays (the default) or
            array shapes have been supplied.

    Returns:
        input_strings: Parsed input strings
        output_string: Parsed output string
        operands: The operands to use in the numpy contraction

    Examples:
        The operand list is simplified to reduce printing:

        ```python
        >>> 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])

        >>> parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
        ('za,xza', 'xz', [a, b])
        ```
    r   zNo input operands r2   c              3   6   K   | ]}t          |d           V  dS )rQ   N)r[   r0   os     r   r8   z%parse_einsum_input.<locals>.<genexpr>B  s,      ==171g&&======r   r)   Nzwshapes is set to True but given at least one operand looks like an array (at least one operand has a shape attribute). c                 ,    g | ]}t          |          S r/   )r   r   s     r   rV   z&parse_einsum_input.<locals>.<listcomp>N  s    9991)A,,999r   ->ru   z%Subscripts can only contain one '->'..rF   c              3   4   K   | ]}t          |          V  d S r4   )rB   )r0   r   s     r   r8   z%parse_einsum_input.<locals>.<genexpr>Y  s(      ;[;[qCFF;[;[;[;[;[;[r   TF   rh   zInvalid Ellipses.r/   zEllipses lengths do not match.zOutput character 'z(' appeared more than once in the output.z' did not appear in the inputzNumber of einsum subscripts, z+, must be equal to the number of operands, )rB   r_   r\   strrJ   anyr   rH   r<   r   rW   splitr;   r   r9   r:   )rl   rL   rD   operand_shapesinvalidr&   ellipse_indslongest	input_tmp
output_subsplit_subscriptsout_subnumrt   ellipse_countout_ellipseoutput_subscriptnormal_indsinput_subscriptschars                       r   r   r   !  s.   6 8}},---(1+s## 
Ca[((b11
 	=======  F   ABB<8BB
H :!99999 	zsj00##C((1,L*2B2B32G2G!2K 	Fz''--22DEEE j!!#r**223;;CCD"MMww1$;[;[N;[;[;[8[8[\\]] :$.$4$4T$:$:!Iz(s33GG)//44G!"233 	^ 	^HCczzIIcNNa''SYYu-=-=-B-B$%8999 "#&",,$%MM$'N3,?(@(@!$D$DCST$UM 7**+G 1$$$%EFFF"a'',/KKr,B,B$S)),/KK|]NOO?\,],]$S)XX.//
 a<<KK&xyy1K 	;$!3!3E;!G!GGGJJ  /z::''&-=)>)>[AQAQ)Q"R"RSSK$,{::J z-7-=-=d-C-C***-79T9T* ! W W!!$''1,,`$```aaa'''U$UUUVVV ( !!#&&''3x==884C0@0F0Fs0K0K,L,L 4 4#&x==4 4 4
 
 	

 -x77r   )F)"__doc__ry   typingr   r   r   r   r   r   opt_einsum.typingr	   r
   __all__r   r   boolr   r   intr   r   r   r   r   r   floatcomplexbytesr]   r   r   rk   r   r   r/   r   r   <module>r      s   H H     = = = = = = = = = = = = = = = = 8 8 8 8 8 8 8 8   N 8C 8D 8 8 8 8 6C 6D 6 6 6 6 # #    4S S Xc]    &;c ;c ; ; ; ;7 7 7 7 7 7([ [ [ [ [ [&yd3i yo1F yPS yXg y y y y  Ce4
t t t t t t(" " " " " "JS	 tCH~ #    ("+ "+%U3PS8_@T:U "+ "+ "+ "+J~8 ~8 ~8d ~8uS#tT]E^?_ ~8 ~8 ~8 ~8 ~8 ~8r   