
    Opf                         d Z ddlmZ ddlZddlmZ g dZdZ ej	        g d          Z
d	  eee
          D             Zdd
Zd Zd Zd ZddZdS )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                     i | ]\  }}||	S  r   ).0css      R/var/www/html/nettyfy-visnx/env/lib/python3.11/site-packages/opt_einsum/helpers.py
<dictcomp>r      s    @@@daQ@@@    c                     t           g }|                     d          d                             d          }|D ]6}fd|D             }|                    t          j        j        |            7|S )a  
    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)

    Nz->r   ,c                      g | ]
}|         S r   r   )r   xdimension_dicts     r   
<listcomp>zbuild_views.<locals>.<listcomp>0   s    000aq!000r   )_default_dim_dictsplitappendnprandomrand)stringr   viewstermstermdimss    `    r   r   r      s    0 *ELLq!'',,E , ,00004000RY^T*++++Lr   c                 *    d}| D ]}|||         z  }|S )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   r   )indicesidx_dictretis       r   r   r   5   s-    . C  x{Jr   c                     t          |          fdt          | d          D             }t          j        | } |j         }||z  }||z
  }                    |           |||fS )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   B   K   | ]}                     |          V  d S N)pop)r   r.   	remainings     r   	<genexpr>z#find_contraction.<locals>.<genexpr>~   s/      HH1immAHHHHHHr   T)reverse)listsortedsetunionr!   )		positions
input_sets
output_setinputsidx_contract
idx_remain
new_resultidx_removedr3   s	           @r   r   r   R   s    V Z  IHHHHy$(G(G(GHHHF9f%L!!9-Jl*J*,KZ   y+|;;r   c                 `    t          | |          }t          d|dz
            }|r|dz  }||z  S )a  
    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	      sB    > (IILAy1}%%I Q	)##r   r   	   Fc                 (   |t           j                            |           | |z  dz  z   }d t          |           D             }	g t	          fdt          |          D                       fd}
t          t           j                            t           |
                                          D ]\  }}|| k     r|	|xx         |z  cc<   t           j                            d|           }||	|         v r*t           j                            d|           }||	|         v *|	|xx         |z  cc<   |r\t          |          }t           j                            dz             |<   t          |           D ]}|	|xx         |z  cc<   |z  d
                    t           j                                                d	                    d

                    |	                    }fd|	D             }||f}|r|fz  }|S )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)]
    Nr   c                     g | ]}d S ) r   )r   _s     r   r   z!rand_equation.<locals>.<listcomp>   s    ###Qb###r   c              3   |   K   | ]6}t          |          t          j                            d z             fV  7dS )r   N)r   r"   r#   randint)r   r.   d_maxd_mins     r   r4   z rand_equation.<locals>.<genexpr>   sE      jjUVZ]]BI,=,=eUQY,O,OPjjjjjjr   c               3      K   t                    D ]-\  } }| k     r                    |           |V  %|V  |V  .d S r1   )	enumerater!   )r.   ixn_outoutput	size_dicts     r   genzrand_equation.<locals>.gen   sh      y)) 	 	EAr5yyb!!! 	 	r   r   r   rM   z{}->{}r   c                 F    g | ]}t          fd |D                       S )c              3   (   K   | ]}|         V  d S r1   r   )r   rU   rX   s     r   r4   z+rand_equation.<locals>.<listcomp>.<genexpr>  s'      //bIbM//////r   )tuple)r   oprX   s     r   r   z!rand_equation.<locals>.<listcomp>  s6    AAABe////B/////AAAr   )r"   r#   seedranger   rT   permutationr6   rP   r   joinformat)nregrV   rR   rQ   r^   
global_dimreturn_size_dictnum_indsr=   rY   r.   rU   wheregdimeqshapesr-   rW   rX   s     ```             @@r   rand_equationrl      sW   h 
	t 3w!|e#H##%((###FFjjjjjZ_`hZiZijjjjjI	 	 	 	 	 	 	 2900ccee==>> 
  
 2q551IIIOIIII I%%a++Eu%%	))!Q// u%% 5MMMRMMMM  (##)++E519==	$q 	 	A1IIIIIII$ WWRY**62233F	&))6	2	2B BAAA&AAAFv,C 	}Jr   r1   )r   r   rJ   NFF)__doc__collectionsr   numpyr"   parserr   __all___valid_charsarray_sizeszipr   r   r   r   r	   rl   r   r   r   <module>rv      s     $ # # # # #          
S
S
S$	KKK	L	L@@cc,&?&?@@@        F  :4< 4< 4<n$$ $$ $$Nk k k k k kr   