a
    yn„fÃ=  ã                	   @  s°   d dl mZ d dlmZ d dlZd dlmZ d dlm	Z	 d dl
mZmZmZ d dlmZ d dlmZ d d	lmZ d
Ze ¡ Ze ¡ Ze	ƒ ddddddddœdd„ƒZdd„ ZdS )é    )Úannotations)ÚMappingN)ÚNumpyBackend)Úhigh_level_function)ÚHighLevelContextÚensure_same_backendÚmaybe_posaxis)ÚNumpyMetadata)Úregularize_axis)Ú	AxisError)Ú	cartesiané   T)ÚnestedÚ
parametersÚ	with_nameÚ	highlevelÚbehaviorÚattrsc             	   c  s2   t | tƒr|  ¡ V  n| V  t| |||||||ƒS )a#  
    Args:
        arrays (mapping or sequence of arrays): Each value in this mapping or
            sequence can be any array-like data that #ak.to_layout recognizes.
        axis (int): The dimension at which this operation is applied. The
            outermost dimension is `0`, followed by `1`, etc., and negative
            values count backward from the innermost: `-1` is the innermost
            dimension, `-2` is the next level up, etc.
        nested (None, True, False, or iterable of str or int): If None or
            False, all combinations of elements from the `arrays` are
            produced at the same level of nesting; if True, they are grouped
            in nested lists by combinations that share a common item from
            each of the `arrays`; if an iterable of str or int, group common
            items for a chosen set of keys from the `array` dict or integer
            slots of the `array` iterable.
        parameters (None or dict): Parameters for the new
            #ak.contents.RecordArray node that is created by this operation.
        with_name (None or str): Assigns a `"__record__"` name to the new
            #ak.contents.RecordArray node that is created by this operation
            (overriding `parameters`, if necessary).
        highlevel (bool): If True, return an #ak.Array; otherwise, return
            a low-level #ak.contents.Content subclass.
        behavior (None or dict): Custom #ak.behavior for the output array, if
            high-level.
        attrs (None or dict): Custom attributes for the output array, if
            high-level.

    Computes a Cartesian product (i.e. cross product) of data from a set of
    `arrays`. This operation creates records (if `arrays` is a dict) or tuples
    (if `arrays` is another kind of iterable) that hold the combinations
    of elements, and it can introduce new levels of nesting.

    As a simple example with `axis=0`, the Cartesian product of

        >>> one = ak.Array([1, 2, 3])
        >>> two = ak.Array(["a", "b"])

    is

        >>> ak.cartesian([one, two], axis=0).show()
        [(1, 'a'),
         (1, 'b'),
         (2, 'a'),
         (2, 'b'),
         (3, 'a'),
         (3, 'b')]

    With nesting, a new level of nested lists is created to group combinations
    that share the same element from `one` into the same list.

        >>> ak.cartesian([one, two], axis=0, nested=True).show()
        [[(1, 'a'), (1, 'b')],
         [(2, 'a'), (2, 'b')],
         [(3, 'a'), (3, 'b')]]

    The primary purpose of this function, however, is to compute a different
    Cartesian product for each element of an array: in other words, `axis=1`.
    The following arrays each have four elements.

        >>> one = ak.Array([[1, 2, 3], [], [4, 5], [6]])
        >>> two = ak.Array([["a", "b"], ["c"], ["d"], ["e", "f"]])

    The default `axis=1` produces 6 pairs from the Cartesian product of
    `[1, 2, 3]` and `["a", "b"]`, 0 pairs from `[]` and `["c"]`, 1 pair from
    `[4, 5]` and `["d"]`, and 1 pair from `[6]` and `["e", "f"]`.

        >>> ak.cartesian([one, two]).show()
        [[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')],
         [],
         [(4, 'd'), (5, 'd')],
         [(6, 'e'), (6, 'f')]]

    The nesting depth is the same as the original arrays; with `nested=True`,
    the nesting depth is increased by 1 and tuples are grouped by their
    first element.

        >>> ak.cartesian([one, two], nested=True).show()
        [[[(1, 'a'), (1, 'b')], [(2, 'a'), (2, ...)], [(3, 'a'), (3, 'b')]],
         [],
         [[(4, 'd')], [(5, 'd')]],
         [[(6, 'e'), (6, 'f')]]]

    These tuples are #ak.contents.RecordArray nodes with unnamed fields. To
    name the fields, we can pass `one` and `two` in a dict, rather than a list.

        >>> ak.cartesian({"x": one, "y": two}).show()
        [[{x: 1, y: 'a'}, {x: 1, y: 'b'}, {...}, ..., {x: 3, y: 'a'}, {x: 3, y: 'b'}],
         [],
         [{x: 4, y: 'd'}, {x: 5, y: 'd'}],
         [{x: 6, y: 'e'}, {x: 6, y: 'f'}]]

    With more than two elements in the Cartesian product, `nested` can specify
    which are grouped and which are not. For example,

        >>> one = ak.Array([1, 2, 3, 4])
        >>> two = ak.Array([1.1, 2.2, 3.3])
        >>> three = ak.Array(["a", "b"])

    can be left entirely ungrouped:

        >>> ak.cartesian([one, two, three], axis=0).show()
        [(1, 1.1, 'a'),
         (1, 1.1, 'b'),
         (1, 2.2, 'a'),
         (1, 2.2, 'b'),
         (1, 3.3, 'a'),
         (1, 3.3, 'b'),
         (2, 1.1, 'a'),
         (2, 1.1, 'b'),
         (2, 2.2, 'a'),
         (2, 2.2, 'b'),
         ...,
         (3, 2.2, 'b'),
         (3, 3.3, 'a'),
         (3, 3.3, 'b'),
         (4, 1.1, 'a'),
         (4, 1.1, 'b'),
         (4, 2.2, 'a'),
         (4, 2.2, 'b'),
         (4, 3.3, 'a'),
         (4, 3.3, 'b')]

    can be grouped by `one` (adding 1 more dimension):

        >>> ak.cartesian([one, two, three], axis=0, nested=[0]).show()
        [[(1, 1.1, 'a'), (1, 1.1, 'b'), (1, 2.2, 'a')],
         [(1, 2.2, 'b'), (1, 3.3, 'a'), (1, 3.3, 'b')],
         [(2, 1.1, 'a'), (2, 1.1, 'b'), (2, 2.2, 'a')],
         [(2, 2.2, 'b'), (2, 3.3, 'a'), (2, 3.3, 'b')],
         [(3, 1.1, 'a'), (3, 1.1, 'b'), (3, 2.2, 'a')],
         [(3, 2.2, 'b'), (3, 3.3, 'a'), (3, 3.3, 'b')],
         [(4, 1.1, 'a'), (4, 1.1, 'b'), (4, 2.2, 'a')],
         [(4, 2.2, 'b'), (4, 3.3, 'a'), (4, 3.3, 'b')]]

    can be grouped by `one` and `two` (adding 2 more dimensions):

        >>> ak.cartesian([one, two, three], axis=0, nested=[0, 1]).show()
        [[[(1, 1.1, 'a'), (1, 1.1, 'b')], [...], [(1, 3.3, 'a'), (1, 3.3, ...)]],
         [[(2, 1.1, 'a'), (2, 1.1, 'b')], [...], [(2, 3.3, 'a'), (2, 3.3, ...)]],
         [[(3, 1.1, 'a'), (3, 1.1, 'b')], [...], [(3, 3.3, 'a'), (3, 3.3, ...)]],
         [[(4, 1.1, 'a'), (4, 1.1, 'b')], [...], [(4, 3.3, 'a'), (4, 3.3, ...)]]]

    or grouped by unique `one`-`two` pairs (adding 1 more dimension):

        >>> ak.cartesian([one, two, three], axis=0, nested=[1]).show()
        [[(1, 1.1, 'a'), (1, 1.1, 'b')],
         [(1, 2.2, 'a'), (1, 2.2, 'b')],
         [(1, 3.3, 'a'), (1, 3.3, 'b')],
         [(2, 1.1, 'a'), (2, 1.1, 'b')],
         [(2, 2.2, 'a'), (2, 2.2, 'b')],
         [(2, 3.3, 'a'), (2, 3.3, 'b')],
         [(3, 1.1, 'a'), (3, 1.1, 'b')],
         [(3, 2.2, 'a'), (3, 2.2, 'b')],
         [(3, 3.3, 'a'), (3, 3.3, 'b')],
         [(4, 1.1, 'a'), (4, 1.1, 'b')],
         [(4, 2.2, 'a'), (4, 2.2, 'b')],
         [(4, 3.3, 'a'), (4, 3.3, 'b')]]

    The order of the output is fixed: it is always lexicographical in the
    order that the `arrays` are written.

    To emulate an SQL or Pandas "group by" operation, put the keys that you
    wish to group by *first* and use `nested=[0]` or `nested=[n]` to group by
    unique n-tuples. If necessary, record keys can later be reordered with a
    list of strings in #ak.Array.__getitem__.

    To get list index positions in the tuples/records, rather than data from
    the original `arrays`, use #ak.argcartesian instead of #ak.cartesian. The
    #ak.argcartesian form can be particularly useful as nested indexing in
    #ak.Array.__getitem__.
    )Ú
isinstancer   ÚvaluesÚ_impl)ÚarraysÚaxisr   r   r   r   r   r   © r   úb/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/awkward/operations/ak_cartesian.pyr      s     9
ÿr   c                   sè  t |ƒ}t||d��n‰t| tƒrVt‡fdd„|  ¡ D ƒŽ }t|  ¡ ƒ‰tt	ˆ|ƒƒ‰nt‡fdd„| D ƒŽ  }‰d ‰W d   ƒ n1 sˆ0    Y  |d ur¸ˆ	d u r¨i ‰	ntˆ	ƒ‰	|ˆ	d< t
|d |dƒ‰
ˆ
d u sØˆ
dk ràtdƒ‚|dd … D ]}	t
|	|dƒˆ
krìtd	ƒ‚qìd
d„ |D ƒ}
ˆ
t|
ƒk�r@td|› dt|
ƒ› d�ƒ‚ˆd u �sTˆdu �rZg ‰n¨ˆdu �ršˆd u�r€tˆƒd d… ‰nttt|ƒƒd d… ƒ‰nhtˆtƒ�rât‡fdd„ˆD ƒƒ�rÆtdƒ‚tˆƒtˆƒk�rtdƒ‚n t‡fdd„ˆD ƒƒ�rtdƒ‚tdd„ |D ƒtƒ‰ˆ
dk�rÞˆd u�rB‡fdd„tˆƒD ƒ‰nˆ‰‡fdd„ˆjj‡fdd„|D ƒddiŽD ƒ}dd„ t	||ƒD ƒ}tjj|ˆˆ	d�}ttˆƒƒd d d… D ]*}|ˆv �r°tj |||d  jd¡}�q°nüˆd u�r ‡fdd„tˆƒD ƒ‰nˆ‰d d!d d"œ‡ fd#d$„‰ ‡ fd%d&„‰‡ ‡‡‡
fd'd(„‰‡‡‡
fd)d„tˆƒD ƒ}| ¡  ‡fd*d„t|ƒD ƒ}‡‡‡	‡
fd+d,„}tjj||dd-�}t|tƒ�r®t|ƒdk�s²J ‚|d }|D ]}tjj ||d|d.�}�q¾ˆj!||d/�S )0N)r   r   c                 3  s   | ]}ˆ j |d d d�V  qdS ©F)Zallow_recordZallow_unknownN©Úunwrap©Ú.0Úx©Úctxr   r   Ú	<genexpr>Ý   s   ÿz_impl.<locals>.<genexpr>c                 3  s   | ]}ˆ j |d d d�V  qdS r   r   r   r!   r   r   r#   ç   s   ÿZ
__record__r   r   z negative axis depth is ambiguouszHarrays to cartesian-product do not have the same depth for negative axisc                 S  s   g | ]
}|j ‘qS r   )Zpurelist_depth)r   Úobjr   r   r   Ú
<listcomp>ÿ   ó    z_impl.<locals>.<listcomp>zaxis=z5 exceeds the max depth of the given arrays (which is ú)FTéÿÿÿÿc                 3  s"   | ]}t |tƒo|ˆ v  V  qd S ©N)r   Ústrr   ©Úarray_layoutsr   r   r#     r&   zJthe 'nested' parameter of cartesian must be dict keys for a dict of arrayszRthe `nested` parameter of cartesian must contain fewer items than there are arraysc                 3  s:   | ]2}t |tƒo.d |  ko*tˆ ƒd k n   V  qdS )r   r   N)r   ÚintÚlenr   r+   r   r   r#     s   ÿzfthe 'nested' parameter of cartesian must be integers in [0, len(arrays) - 1) for an iterable of arraysc                 s  s   | ]}|j V  qd S r)   ©Úbackend)r   Úlayoutr   r   r   r#   #  r&   c                   s   g | ]\}}|ˆ v r|‘qS r   r   ©r   ÚiÚname©r   r   r   r%   '  r&   c                   s"   g | ]}t j ˆ j |d ¡¡‘qS ))r(   )ÚakÚindexZIndex64Úindex_nplikeZreshaper   r/   r   r   r%   +  s   ÿc                   s    g | ]}ˆ j j|jtjd �‘qS ))Zdtype)r8   ZarangeÚlengthÚnpZint64r   r/   r   r   r%   .  s   ÿZindexingZijc                 S  s    g | ]\}}t jj ||¡‘qS r   )r6   ÚcontentsZIndexedArrayZ
simplified)r   r    Úyr   r   r   r%   5  s   ©r   c                   s   g | ]\}}|ˆ v r|‘qS r   r   r2   r5   r   r   r%   A  r&   zak.contents.Contentr-   )r1   ÚnÚreturnc                   s*   |dkr| S t j ˆ | |d ƒdd¡S d S )Nr   r   )r6   r;   ÚRegularArray)r1   r>   ©Úadd_outer_dimensionsr   r   rB   E  s
    ÿz#_impl.<locals>.add_outer_dimensionsc                   s"   |d }|dkrˆ | |ƒS dS dS )za
            Add new dimensions (given by lateral_context["n"]) above innermost list
            r>   é   Nr   )r1   ÚdepthÚlateral_contextÚkwargsr>   rA   r   r   Úapply_pad_inner_listO  s    
z#_impl.<locals>.apply_pad_inner_listc                   sp   |d }|ˆkrht ˆƒ| d }|}|  d¡dks@|  d¡dkrHtdƒ‚tjj| ˆd|id�}ˆ ||ƒS d	S d	S )
a�  
            Each array in arrays contributes to one of these new dimensions.
            To make the cartesian product of the given arrays broadcastable,
            each array is padded by (n, m) new length-1 regular dimensions
            (above, below) the target depth. The values of (n, m) are given by
            the position of the array; the first array is the outermost axis.
            r3   r   Z	__array__ÚstringÚ
bytestringzdak.cartesian does not compute combinations of the characters of a string; please split it into listsr>   ©rE   N)r.   Z	parameterÚ
ValueErrorr6   Ú_doÚrecursively_apply)r1   rD   rE   rF   r3   Zn_insideZ	n_outsideZ
nextlayout)rB   rG   r,   Úposaxisr   r   Úapply_pad_inner_list_at_axisZ  s$    ÿþÿý
z+_impl.<locals>.apply_pad_inner_list_at_axisc                   s4   g | ],\}}|t ˆ ƒd  k r|ˆvrˆ| d  ‘qS )r   )r.   )r   r3   Ú_)r,   Únested_as_indexrN   r   r   r%   y  s   þc                   s&   g | ]\}}t jj|ˆ d |id�‘qS )r3   rJ   )r6   rL   rM   )r   r3   r1   )rO   r   r   r%   �  s   ûýc                   s,   |ˆt ˆ ƒ kr$tjj| ˆˆd�fS d S d S )Nr=   )r.   r6   r;   ÚRecordArray)ÚinputsrD   rF   )r,   Úfieldsr   rN   r   r   Úapply_build_recordŠ  s    z!_impl.<locals>.apply_build_record)Zright_broadcast)r   r   r   )r   )"r
   r   r   r   r   r   ÚlistÚkeysÚdictÚzipr   r   ÚmaxÚranger.   ÚanyrK   ÚnextÚcpuÚ	enumerater8   Zmeshgridr6   r;   rR   r@   r9   ÚreverseZ_broadcastingZbroadcast_and_applyÚtupleÚ
operationsÚflattenÚwrap)r   r   r   r   r   r   r   r   Zlayoutsr1   ZdepthsZindexesZoutsÚresultr3   Zaxes_to_flattenZnew_layoutsrU   ÚoutZaxis_to_flattenr   )rB   rG   rO   r,   r0   r"   rT   r   rQ   r   rN   r   r   Ø   sÈ    

þÿ
þÿ"ÿÿ

ÿÿþ
ÿ



þÿûþ
ÿ
 

þ
ú	ÿÿ
r   )r   )Ú
__future__r   Úcollections.abcr   Zawkwardr6   Zawkward._backends.numpyr   Zawkward._dispatchr   Zawkward._layoutr   r   r   Zawkward._nplikes.numpy_liker	   Zawkward._regularizer
   Zawkward.errorsr   Ú__all__Úinstancer:   r^   r   r   r   r   r   r   Ú<module>   s.    þ÷ C