a
    ~bG                     @   s  d dl mZ d dlZd dlZddlmZmZmZ ddl	m
Z
mZmZ ddlmZmZ ddlmZmZmZ ddlmZmZ dd	lmZ dd
lmZ G dd dee
eZG dd deZG dd deZG dd deZG dd deZe e!dd e" # D Z$dS )    )groupbyN   )DimensionedViewableElementasdim)
ComposableLayoutNdLayout)OrderedDict	NdMapping)Overlayable	NdOverlayCompositeOverlay)HoloMap	GridSpace)AttrTree)get_param_valuesc                   @   s   e Zd ZdZejd ddZdZdZdd Z	d&d	d
Z
dd Zdd Zdd Zdd ZeZed'ddZdd Zg ddfddZg ddfddZdd Zd(ddZd)d d!Zd*d"d#Zd+d$d%ZdS ),Elementat  
    Element is the atomic datastructure used to wrap some data with
    an associated visual representation, e.g. an element may
    represent a set of points, an image or a curve. Elements provide
    a common API for interacting with data of different types and
    define how the data map to a set of dimensions and how those
    map to the visual representation.
    T)defaultZconstant c                 K   s   dS )N)NNNr   )selfkwargsr   r   5lib/python3.9/site-packages/holoviews/core/element.py$_get_selection_expr_for_stream_value   s    z,Element._get_selection_expr_for_stream_valueN   c                 K   s   ddl m} t|ts|g}g }|ddd D ]&}|| f|||d|}	||	 q.|r~| }
tt|D ]}|
|| > }
qjnt|dkrt|}
n|d }
|
S )a  Computes and adjoins histogram along specified dimension(s).

        Defaults to first value dimension if present otherwise falls
        back to first key dimension.

        Args:
            dimension: Dimension(s) to compute histogram on
            num_bins (int, optional): Number of bins
            bin_range (tuple optional): Lower and upper bounds of bins
            adjoin (bool, optional): Whether to adjoin histogram

        Returns:
            AdjointLayout of element and histogram or just the
            histogram
           )	histogramN)num_bins	bin_range	dimensionr   r   )Z	operationr   
isinstancelistappendrangelenr   )r   r    r   r   Zadjoinr   r   ZhistsdhistlayoutZdidxr   r   r   r'   "   s$    

zElement.histc                 C   s"   |dkr| S t dt| j d S )Nr   z%%s currently does not support getitem)NotImplementedErrortype__name__)r   keyr   r   r   __getitem__I   s
    zElement.__getitem__c                 C   s   dS )zIndicates whether the element is empty.

        Subclasses may override this to signal that the Element
        contains no data and can safely be dropped during indexing.
        Tr   r   r   r   r   __nonzero__P   s    zElement.__nonzero__c                 C   s   ||   v S )z&Whether element contains the Dimension)
dimensions)r   r    r   r   r   __contains__Y   s    zElement.__contains__c                 C   s   t ddS )zDisable iterator interface.z'Iteration on Elements is not supported.Nr)   r.   r   r   r   __iter__^   s    zElement.__iter__c                 K   s   t d| j dS )z
        Deprecated method to perform collapse operations, which may
        now be performed through concatenation and aggregation.
        z"Collapsing not implemented for %s.N)r)   r+   )clsdatafunctionkdimsr   r   r   r   collapse_dataf   s    zElement.collapse_datac                 K   s   t dS )aY  Snap list or dict of coordinates to closest position.

        Args:
            coords: List of 1D or 2D coordinates
            **kwargs: Coordinates specified as keyword pairs

        Returns:
            List of tuples of the snapped coordinates

        Raises:
            NotImplementedError: Raised if snapping is not supported
        Nr2   )r   Zcoordsr   r   r   r   closesto   s    zElement.closestFc                 K   s   t dS )a  Samples values at supplied coordinates.

        Allows sampling of element with a list of coordinates matching
        the key dimensions, returning a new object containing just the
        selected samples. Supports multiple signatures:

        Sampling with a list of coordinates, e.g.:

            ds.sample([(0, 0), (0.1, 0.2), ...])

        Sampling a range or grid of coordinates, e.g.:

            1D: ds.sample(3)
            2D: ds.sample((3, 3))

        Sampling by keyword, e.g.:

            ds.sample(x=0)

        Args:
            samples: List of nd-coordinates to sample
            bounds: Bounds of the region to sample
                Defined as two-tuple for 1D sampling and four-tuple
                for 2D sampling.
            closest: Whether to snap to closest coordinates
            **kwargs: Coordinates specified as keyword pairs
                Keywords of dimensions and scalar coordinates

        Returns:
            Element containing the sampled coordinates
        Nr2   )r   ZsamplesZboundsr9   Zsample_valuesr   r   r   sample   s     zElement.samplec                 K   s   t dS )a  Applies reduction along the specified dimension(s).

        Allows reducing the values along one or more key dimension
        with the supplied function. Supports two signatures:

        Reducing with a list of dimensions, e.g.:

            ds.reduce(['x'], np.mean)

        Defining a reduction using keywords, e.g.:

            ds.reduce(x=np.mean)

        Args:
            dimensions: Dimension(s) to apply reduction on
                Defaults to all key dimensions
            function: Reduction operation to apply, e.g. numpy.mean
            spreadfn: Secondary reduction to compute value spread
                Useful for computing a confidence interval, spread, or
                standard deviation.
            **reductions: Keyword argument defining reduction
                Allows reduction to be defined as keyword pair of
                dimension and function

        Returns:
            The element after reductions have been applied.
        Nr2   )r   r0   r6   ZspreadfnZ	reductionr   r   r   reduce   s    zElement.reducec                    s   |r|rt dtt| dkr,t d|r8| }|rP fdd|D }n|sh fddjD }fdd|D }dd t|d	d
 D }|d S )NzPPass reduced dimensions either as an argument or as part of the kwargs not both.r   zFCannot define reduce operations with more than one function at a time.c                    s   g | ]}| fqS r   r   .0r&   r6   r   r   
<listcomp>       z'Element._reduce_map.<locals>.<listcomp>c                    s   g | ]}| fqS r   r   r<   r>   r   r   r?      r@   c                    s$   g | ]\}} j |d dj|fqS T)strictget_dimensionname)r=   r&   fnr.   r   r   r?      s   c                 S   s"   g | ]\}}|d d |D fqS )c                 S   s   g | ]\}}|qS r   r   )r=   dim_r   r   r   r?      r@   z2Element._reduce_map.<locals>.<listcomp>.<listcomp>r   )r=   rF   grpr   r   r   r?      r@   c                 S   s   | d S )Nr   r   )xr   r   r   <lambda>   r@   z%Element._reduce_map.<locals>.<lambda>r   )	Exceptionr%   setvaluesitemsr7   r   )r   r0   r6   Z
reduce_mapZreducedZgroupedr   )r6   r   r   _reduce_map   s    
zElement._reduce_mapc                    sz   ddl }|du r$dd   D }n fdd|D }|}t fdd|D }||}|rv| fdd|D }|S )a  Convert dimension values to DataFrame.

        Returns a pandas dataframe of columns along each dimension,
        either completely flat or indexed by key dimensions.

        Args:
            dimensions: Dimensions to return as columns
            multi_index: Convert key dimensions to (multi-)index

        Returns:
            DataFrame of columns corresponding to each dimension
        r   Nc                 S   s   g | ]
}|j qS r   )rE   r<   r   r   r   r?      r@   z"Element.dframe.<locals>.<listcomp>c                    s   g | ]} j |d djqS rA   rC   r<   r.   r   r   r?      r@   c                    s   g | ]}|  |fqS r   )dimension_valuesr=   rG   r.   r   r   r?      r@   c                    s   g | ]}| j v r|qS r   r7   r<   r.   r   r   r?      r@   )Zpandasr0   r
   Z	DataFrameZ	set_index)r   r0   Zmulti_indexpdZcolumn_namesdim_valsZdfr   r.   r   dframe   s    
zElement.dframec                    s   |du r dd  j  j D }n fdd|D }g g  }}|D ]&} |}|| ||jj q@tt|dkrdd |D }t	|S )zConvert dimension values to columnar array.

        Args:
            dimensions: List of dimensions to return

        Returns:
            Array of columns corresponding to each dimension
        Nc                 S   s   g | ]}|qS r   r   r<   r   r   r   r?      r@   z!Element.array.<locals>.<listcomp>c                    s   g | ]} j |d dqS rA   )rD   r<   r.   r   r   r?      r@   r   c                 S   s   g | ]}| d qS )object)Zastype)r=   cr   r   r   r?     r@   )
r7   vdimsrQ   r#   Zdtypekindr%   rM   npZcolumn_stack)r   r0   dimscolumnstypesrG   columnr   r.   r   array   s    	


zElement.arrayc                 C   sT   | j dt| j  |r*t|ts*|g}ddlm} || fi |rLt|dni S )z4Deprecated method to convert any Element to a Table.zgThe table method is deprecated and should no longer be used. Instead cast the %s to a a Table directly.r   )Table)datatype)	paramwarningr*   r+   r!   r"   elementra   dict)r   rb   ra   r   r   r   table
  s    zElement.tablec                    s    j d t }|s j}|r<t fdd jD  }n
dg| }|sP j}|rlt fdd|D  }n
dg| }tt||S )z/Deprecated method to convert data to dictionaryzThe mapping method is deprecated and should no longer be used. Use another one of the common formats instead, e.g. .dframe, .array or .columns.c                    s   g | ]}  |jqS r   rQ   rE   rR   r.   r   r   r?   !  s   z#Element.mapping.<locals>.<listcomp>r   c                    s   g | ]}  |jqS r   rh   rR   r.   r   r   r?   (  s   )rc   rd   r%   r7   ziprY   r
   )r   r7   rY   r   lengthkeysrN   r   r.   r   mapping  s"    





zElement.mapping)Nr   NT)NN)NF)N)N)NN)r+   
__module____qualname____doc__rc   StringgroupZ_Element__abstract_selection_streamsr   r'   r-   r/   r1   r3   __bool__classmethodr8   r9   r:   r;   rP   rV   r`   rg   rl   r   r   r   r   r      s.   	  
'	#


r   c                   @   s<   e Zd ZdZdZedd Zedd Zdd Zd	d
 Z	dS )Tabularzp
    Baseclass to give an elements providing an API to generate a
    tabular representation of the object.
    Tc                 C   s   t | d S )z*Number of rows in table (including header)r   )r%   r.   r   r   r   rows8  s    zTabular.rowsc                 C   s   t |  S )zNumber of columns in table)r%   r0   r.   r   r   r   cols=  s    zTabular.colsc                 C   s   | j }|| jkr$td| j d nv|| jkrBtd| j d nX|dkrx||krl| jrh| j||  jS dS | j| jS | |}|| j	|d |f S dS )zFormatted contents of table cell.

        Args:
            row (int): Integer index of table row
            col (int): Integer index of table column

        Returns:
            Formatted table cell contents
        zMaximum column index is %dr   zMaximum row index is %dr    N)
ndimsrw   rL   rv   rY   Zpprint_labelr7   rD   Zpprint_valueZiloc)r   rowcolry   rG   r   r   r   pprint_cellC  s    



zTabular.pprint_cellc                 C   s   |dkrdS dS )a  Type of the table cell, either 'data' or 'heading'

        Args:
            row (int): Integer index of table row
            col (int): Integer index of table column

        Returns:
            Type of the table cell, either 'data' or 'heading'
        r   headingr5   r   )r   rz   r{   r   r   r   	cell_type^  s    
zTabular.cell_typeN)
r+   rm   rn   ro   Z_Tabular__abstractpropertyrv   rw   r|   r~   r   r   r   r   ru   0  s   

ru   c                   @   s   e Zd ZejdddZdZdS )	Element2D)NNNNz
        Allows overriding the extents of the Element in 2D space defined
        as four-tuple defining the (left, bottom, right and top) edges.r   docTN)r+   rm   rn   rc   TupleextentsZ_Element2D__abstractr   r   r   r   r   l  s   r   c                   @   s"   e Zd ZejdddZdZdZdS )	Element3D)NNNNNNzz
        Allows overriding the extents of the Element in 3D space
        defined as (xmin, ymin, zmin, xmax, ymax, zmax).r   Tr   N)r+   rm   rn   rc   r   r   Z_Element3D__abstractrr   r   r   r   r   r   u  s   r   c                       s   e Zd ZdZejg ddZejdddZejg ddZ	ej
d dZejdd	dZejeeddd
ZejdddZejg ddZdZdZeeeeeefeeeefeeiZd fdd	Zdd Ze dd Z!dd Z"  Z#S )Collatoral  
    Collator is an NdMapping type which can merge any number
    of HoloViews components with whatever level of nesting
    by inserting the Collators key dimensions on the HoloMaps.
    If the items in the Collator do not contain HoloMaps
    they will be created. Collator also supports filtering
    of Tree structures and dropping of constant dimensions.
    zV
        List of dimensions to drop when collating data, specified
        as strings.r   FzY
        Whether to demote any non-varying key dimensions to
        constant dimensions.z[
        List of paths to drop when collating data, specified
        as strings or tuples.)r   Nzk
         The progress bar instance used to report progress. Set to
         None to disable progress bars.)class_r   Zis_instanceZinstantiatea   
        If supplied the function will be applied on each Collator
        value during collation. This may be used to apply an operation
        to the data or load references from disk before they are collated
        into a displayable HoloViews object.z
         Collator operates on HoloViews objects, if vdims are specified
         a value_transform function must also be supplied.c                    sf   t |trJtt|fi |}d|vr0|j|d< d|vrB|j|d< | }tt| j	|fi | d S )Nr7   rY   )
r!   r   rf   r   r7   rY   rl   superr   __init__)r   r5   params	__class__r   r   r     s    


zCollator.__init__c                    s>  j  tjd}t}tj D ]\}\}}t|trJ|	j
}tjr|jr|ttjddd|}|}t|tstdtj|} fdd|D } fdd|D }	|s|	r܈||t|	}|||< jd	ur(t|d
 | d  q(| }
|j|
d j}|
D ]}|| q(|S )a"  
        Filter each Layout in the Collator with the supplied
        path_filters. If merge is set to True all Layouts are
        merged, otherwise an NdMapping containing all the
        Layouts is returned. Optionally a list of dimensions
        to be ignored can be supplied.
        rS   valueT)Zlabelz=Collator values must be Dimensioned objects before collation.c                    s0   g | ](\}}j r$| vr|jvr||fqS r   )drop_constantdropr=   r&   kZconstant_dimsr   r   r   r?     s   z%Collator.__call__.<locals>.<listcomp>c                    s0   g | ](\}}| v r|j vrjr||fqS r   )r   r   r   r   r   r   r?     s   Nr   d   r   )static_dimensionsr   r7   r%   	enumerater5   rO   r!   r   filterfiltersrY   value_transformrf   ri   r0   r   
ValueError_add_dimensionsprogress_barfloatrN   Zlastcloneupdate)r   	ndmappingZnum_elementsidxr,   r5   ZvargsZdim_keysZvarying_keysconstant_keys
componentsZaccumulatorZ	componentr   r   r   __call__  s4    



zCollator.__call__c                 C   s6   g }| j D ]&}tt| |jdkr
|| q
|S )z1
        Return all constant dimensions.
        r   )r7   r%   rM   rQ   rE   r#   )r   r0   rG   r   r   r   r     s
    
zCollator.static_dimensionsc                    s  t |trd|_ fdd|ddd D }t | jrt|j|d}|D ](\}}t|}||jvrH||d|}qHnt | j j rt	|rt
| \}}	 j|	|it||d}q|}n<|jd|d	}| D ]$\}
} ||ddd |||
< qt |trd
|_|S )z
        Recursively descend through an Layout and NdMapping objects
        in order to add the supplied dimension values to all contained
        HoloMaps.
        Fc                    s"   g | ]\}}| j vr||fqS r   )r   )r=   rG   valr.   r   r   r?     s   
z,Collator._add_dimensions.<locals>.<listcomp>Nr   )cdimsr   )r7   r   )Zshared_datar   T)r!   r   fixed
merge_typer   r   r7   Zadd_dimension_nest_orderr%   ri   r"   rO   r   )r   itemr\   r   rU   Znew_itemrG   r   r0   r,   r   vr   r.   r   r     s,    

zCollator._add_dimensions)N)$r+   rm   rn   ro   rc   Listr   ZBooleanr   r   rp   rq   Z	Parameterr   ZClassSelectorr   r   r   Callabler   rY   Z_deep_indexableZ_auxiliary_componentr   r   r   r	   r   r   r   r   r   r   r   r   __classcell__r   r   r   r   r     s.   	

)
r   c                 C   s(   g | ] \}}t |trt|tr|qS r   )r!   r*   
issubclassr   )r=   Z_kZ_vr   r   r   r?     s   r?   )%	itertoolsr   Znumpyr[   rc   r    r   r   r   r(   r   r   r	   r   r
   r   Zoverlayr   r   r   spacesr   r   Ztreer   utilr   r   ru   r   r   r   r"   rM   localsrO   __all__r   r   r   r   <module>   s$     #<	 