
    i                         S r SSKJr  SSKrSSKJr  / SQrSr\R                  " / SQ5      r
\" \\
5       V Vs0 s H  u  pX_M	     snn rSS	 jrS
 rS rS rSS jrgs  snn f )z:
Contains helper functions for opt_einsum testing scripts
    )OrderedDictN   )
get_symbol)build_viewscompute_size_by_dictfind_contraction
flop_countabcdefghijklmopqABC)            r   r   r      r   r   r   r   r      r   r   r   r   r   c                     Uc  [         n/ nU R                  S5      S   R                  S5      nU HC  nU Vs/ s H  oQU   PM	     nnUR                  [        R                  R
                  " U6 5        ME     U$ s  snf )ad  
Builds random numpy arrays for testing.

Parameters
----------
string : list of str
    List of tensor strings to build
dimension_dict : dictionary
    Dictionary of index _sizes

Returns
-------
ret : list of np.ndarry's
    The resulting views.

Examples
--------
>>> view = build_views(['abbc'], {'a': 2, 'b':3, 'c':5})
>>> view[0].shape
(2, 3, 3, 5)

z->r   ,)_default_dim_dictsplitappendnprandomrand)stringdimension_dictviewstermstermxdimss          R/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/opt_einsum/helpers.pyr   r      sx    0 *ELLq!'',E+/04aq!40RYY^^T*+  L 1s   A: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   5   s$    . C{ J    c                    ^ [        U5      mU4S j[        U SS9 5       n[        R                  " U6 nUR                  " T6 nXT-  nXF-
  nTR	                  U5        UTXt4$ )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'})
c              3   F   >#    U  H  nTR                  U5      v   M     g 7fN)pop).0r&   	remainings     r    	<genexpr>#find_contraction.<locals>.<genexpr>~   s     H(G1immA(Gs   !T)reverse)listsortedsetunionr   )		positions
input_sets
output_setinputsidx_contract
idx_remain
new_resultidx_removedr-   s	           @r    r   r   R   sj    V Z IHy$(GHF99f%L!!9-J*J,KZ y+;;r'   c                 V    [        X5      n[        SUS-
  5      nU(       a  US-  nXE-  $ )aB  
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})
90

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

r   )r   max)idx_contractioninner	num_termssize_dictionaryoverall_size	op_factors         r    r	   r	      s3    > (ILAy1}%IQ	##r'   c                 $  ^^^^^ Ub  [         R                  R                  U5        X-  S-  T-   n[        U 5       V	s/ s H  n	SPM     n
n	/ m[	        UU4S j[        U5       5       5      mUUU4S jn[        [         R                  R                  [        U" 5       5      5      5       Hv  u  pX:  a  X==   U-  ss'   M  [         R                  R                  SU 5      nXU   ;   a*  [         R                  R                  SU 5      nXU   ;   a  M*  X==   U-  ss'   Mx     U(       aT  [        U5      n[         R                  R                  TTS-   5      TU'   [        U 5       H  nX==   U-  ss'   M     TU-  mSR                  [         R                  R                  T5      5      mSR                  SR                  U
5      T5      nU
 Vs/ s H  n[        U4S	 jU 5       5      PM     nnUU4nU(       a  UT4-  nU$ s  sn	f s  snf )
a  Generate a random contraction and shapes.

Parameters
----------
n : int
    Number of array arguments.
reg : int
    'Regularity' of the contraction graph. This essentially determines how
    many indices each tensor shares with others on average.
n_out : int, optional
    Number of output indices (i.e. the number of non-contracted indices).
    Defaults to 0, i.e., a contraction resulting in a scalar.
d_min : int, optional
    Minimum dimension size.
d_max : int, optional
    Maximum dimension size.
seed: int, optional
    If not None, seed numpy's random generator with this.
global_dim : bool, optional
    Add a global, 'broadcast', dimension to every operand.
return_size_dict : bool, optional
    Return the mapping of indices to sizes.

Returns
-------
eq : str
    The equation string.
shapes : list[tuple[int]]
    The array shapes.
size_dict : dict[str, int]
    The dict of index sizes, only returned if ``return_size_dict=True``.

Examples
--------
>>> eq, shapes = rand_equation(n=10, reg=4, n_out=5, seed=42)
>>> eq
'oyeqn,tmaq,skpo,vg,hxui,n,fwxmr,hitplcj,kudlgfv,rywjsb->cebda'

>>> shapes
[(9, 5, 4, 5, 4),
 (4, 4, 8, 5),
 (9, 4, 6, 9),
 (6, 6),
 (6, 9, 7, 8),
 (4,),
 (9, 3, 9, 4, 9),
 (6, 8, 4, 6, 8, 6, 3),
 (4, 7, 8, 8, 6, 9, 6),
 (9, 5, 3, 3, 9, 5)]
r    c              3      >#    U  H3  n[        U5      [        R                  R                  TTS -   5      4v   M5     g7f)r   N)r   r   r   randint)r,   r&   d_maxd_mins     r    r.    rand_equation.<locals>.<genexpr>   s2     jZiUVZ]BII,=,=eUQY,OPZi   ;>c               3      >#    [        T5       H*  u  pU T:  a  TR                  U5        Uv   M"  Uv   Uv   M,     g 7fr*   )	enumerater   )r&   ixn_outoutput	size_dicts     r    genrand_equation.<locals>.gen   s;     y)EA5yb!  *rL   r   r   z{}->{}r   c              3   .   >#    U  H
  nTU   v   M     g 7fr*   r"   )r,   rO   rR   s     r    r.   rK     s     /BbIbMBs   )r   r   seedranger   rN   permutationr1   rH   r   joinformattuple)nregrP   rJ   rI   rV   
global_dimreturn_size_dictnum_inds_r8   rS   r&   rO   wheregdimeqopshapesr%   rQ   rR   s     ```               @@r    rand_equationrg      s   h 
		t w!|e#H(#(Qb(F#FjZ_`hZijjI	 29900ce=>5IOI II%%a+Eu%		))!Q/ u% MRM ? (#))++E519=	$qAII $ WWRYY**623F	&)6	2B ;AA&Be/B//&FAv,C	}Je $V Bs   HHr*   )r   r   	   NFF)__doc__collectionsr   numpyr   parserr   __all___valid_charsarray_sizeszipr   r   r   r   r	   rg   )css   00r    <module>rt      st    $  
S$	K	L&),&?@&?daQT&?@  F:4<n$$NkC As   A