B
    &[¨_žX  ã               @   s  d dl mZ d dlmZ d dlmZ d dlm	Z	m
Z
 d dlm
Z
 d dlmZ e
 d¡Ze
 d¡Zd dlmZ d	d
ddddgfdd„Zd4dd„Zdd„ Zdd„ Zdd„ Zdd„ Zd5dd„Zdd „ Zd6d!d"„Zd#d$„ Zd%d&„ Zd'd(„ Zd7d-d.„Zdddgd/d/dd0dd1dddd0fd2d3„ZdS )8é    )Úabsolute_importN)Ú
graph_objs)Ú
exceptionsÚoptional_imports)r   Znumpyzscipy.interpolate)ÚmeasurezTernary contour ploti&  i  ÚaÚbÚcc             C   s`   t | ||t dt t |d dddddt t |d dddddt t |d ddddddd	d
S )a]  
    Layout of ternary contour plot, to be passed to ``go.FigureWidget``
    object.

    Parameters
    ==========
    title : str or None
        Title of ternary plot
    width : int
        Figure width.
    height : int
        Figure height.
    pole_labels : str, default ['a', 'b', 'c']
        Names of the three poles of the triangle.
    é   r   )Útextg{®Gáz„?é   Zoutside)ÚtitleÚminZ	linewidthZticks)ÚsumZaaxisZbaxisZcaxisF)r   ÚwidthÚheightZternaryÚ
showlegend)Údict)r   r   r   Úpole_labels© r   úJ/tmp/pip-install-l29rncou/plotly/plotly/figure_factory/_ternary_contour.pyÚ_ternary_layout   s    r   çü©ñÒMb@?c             C   sN   | dk}t j|dd}d||  }t  |¡dk r8tdƒ‚t  ||||  ¡} | S )aû  
    Replaces zero ternary coordinates with delta and normalize the new
    triplets (a, b, c).

    Parameters
    ----------

    ternary_data : ndarray of shape (N, 3)

    delta : float
        Small float to regularize logarithm.

    Notes
    -----
    Implements a method
    by J. A. Martin-Fernandez,  C. Barcelo-Vidal, V. Pawlowsky-Glahn,
    Dealing with zeros and missing values in compositional data sets
    using nonparametric imputation, Mathematical Geology 35 (2003),
    pp 253-278.
    r   )Úaxisr
   zMThe provided value of delta led to negativeternary coords.Set a smaller delta)ÚnpÚanyÚ
ValueErrorÚwhere)Zternary_dataÚdeltaZ	zero_maskZis_any_coord_zeroZunity_complementr   r   r   Ú_replace_zero_coords9   s    r   c             C   sl   t  | ¡} t  | d | d  ¡t  d¡ }dt  d¡ t  | d | d  | d d  ¡ }t  ||f¡}|S )aÝ  
    Perform Isometric Log-Ratio on barycentric (compositional) data.

    Parameters
    ----------
    barycentric: ndarray of shape (3, N)
        Barycentric coordinates.

    References
    ----------
    "An algebraic method to compute isometric logratio transformation and
    back transformation of compositional data", Jarauta-Bragulat, E.,
    Buenestado, P.; Hervada-Sala, C., in Proc. of the Annual Conf. of the
    Intl Assoc for Math Geology, 2003, pp 31-30.
    r   r
   r   g      ð?é   )r   ÚasarrayÚlogÚsqrtÚstack)ZbarycentricZx_0Zx_1Z	ilr_tdatar   r   r   Ú_ilr_transform[   s
    
 0r%   c          
   C   sÀ   t  | ¡} t  dddgdddgdddgg¡}t  d¡d }t  d¡}t  dt  ||g| |gg¡| ¡}t  dt  |¡jd	d
 ¡ }t  d|t  d| | d	  || d  |f¡¡}t  |¡}|S )aø  
    Perform inverse Isometric Log-Ratio (ILR) transform to retrieve
    barycentric (compositional) data.

    Parameters
    ----------
    x : array of shape (2, N)
        Coordinates in ILR space.

    References
    ----------
    "An algebraic method to compute isometric logratio transformation and
    back transformation of compositional data", Jarauta-Bragulat, E.,
    Buenestado, P.; Hervada-Sala, C., in Proc. of the Annual Conf. of the
    Intl Assoc for Math Geology, 2003, pp 31-30.
    g      à?r
   g      ð?g      à¿g        r   g      ø?zik, kj -> ijr   )r   )r   Úarrayr#   Úeinsumr"   Úexpr   r$   )ÚxZmatrixÚsÚtZSkÚZZlog_barycentricZ
iilr_tdatar   r   r   Ú_ilr_inverset   s    
"
"*
r-   c              C   sd   t  dt  d¡d gddgddgg¡} t  | dd…df | dd…df t  d¡g¡}|t j |¡fS )zi
    Returns the transformation matrix from barycentric to Cartesian
    coordinates and conversely.
    g      à?é   r   r   r
   N)r   r&   r#   ÚonesZlinalgÚinv)Z	tri_vertsÚMr   r   r   Ú _transform_barycentric_cartesian’   s    &.r2   c             C   sê   t | ttjfƒstdƒ‚t | ¡} | jd dkr8tdƒ‚t| ƒdkr€tj| j	ddddd	s€tj| j	ddd
dd	s€d}t|ƒ‚t| ƒdkr¢| \}}d||  }n| | j	dd \}}}t 
t |||f¡dk ¡rÚtdƒ‚t |||f¡S )zQ
    Check ternary coordinates and return the right barycentric coordinates.
    zOData  should be either an array of shape (n,m),or a list of n m-lists, m=2 or 3r   )r   r.   zCA point should have  2 (a, b) or 3 (a, b, c)barycentric coordinatesr.   )r   r
   g{®Gáz„?)Zrtoléd   z=The sum of coordinates should be 1 or 100 for all data pointsr   z+Barycentric coordinates should be positive.)Ú
isinstanceÚlistr   Zndarrayr   r!   ÚshapeÚlenZallcloser   r   r$   )Zb_coordsÚmsgÚAÚBÚCr   r   r   Ú_prepare_barycentric_coord   s&    
r<   Úilrc             C   s  |dkr"t ƒ \}}t d|| ¡}n"|dkr<t| ƒ} t| ƒ}ntdƒ‚|dd… \}}| ¡ | ¡  }}	| ¡ | ¡  }
}tdtt 	t
|ƒ¡ƒƒ}t ||	|¡}t |
||¡}t ||¡\}}tj|dd… j|||fdd	}tj|dd… j|||fd
d	}|||fS )a£  
    Transform data points with Cartesian or ILR mapping, then Compute
    interpolation on a regular grid.

    Parameters
    ==========

    coordinates : array-like
        Barycentric coordinates of data points.
    values : 1-d array-like
        Data points, field to be represented as contours.
    interp_mode : 'ilr' (default) or 'cartesian'
        Defines how data are interpolated to compute contours.
    Ú	cartesianzik, kj -> ijr=   z&interp_mode should be cartesian or ilrNr   éÈ   Zcubic)ÚmethodZnearest)r2   r   r'   r   r%   r   r   ÚmaxÚintr#   r7   ÚlinspaceZmeshgridÚscipy_interpZgriddataÚT)ÚcoordinatesÚvaluesÚinterp_moder1   ÚinvMZcoord_pointsZxxÚyyZx_minZx_maxZy_minZy_maxZn_interpÚgr_xÚgr_yZgrid_xZgrid_yÚgrid_zZgrid_z_otherr   r   r   Ú_compute_grid½   s&    

rN   c             C   s2   dt  t  | t  |d¡¡t  |t  | d¡¡ ¡ S )Ng      à?r
   )r   ÚabsÚdotZroll)r)   Úyr   r   r   Ú_polygon_areaë   s    rR   c             C   s  |t j ¡ krt j| }nt d t j ¡ ¡¡‚t dd| ¡}t dd„ |D ƒ¡}t dd„ |D ƒ¡}t 	||¡}d|d krŒdd„ |D ƒ}|d g}xtt
|dd	… |dd	… ƒD ]V\}}	||d  ||  }
}|	|
 ||
  }t j||d  || |d
d}| |¡ q²W |S )zQ
    Return a list of ``ncontours`` colors from the ``colormap`` colorscale.
    zRColorscale must be a valid Plotly Colorscale.The available colorscale names are {}r   r
   c             S   s   g | ]}|d  ‘qS )r   r   )Ú.0Úpairr   r   r   ú
<listcomp>û   s    z_colors.<locals>.<listcomp>c             S   s   g | ]}|d  ‘qS )r
   r   )rS   rT   r   r   r   rU   ü   s    ú#c             S   s   g | ]}t  t  |¡¡‘qS r   )ÚclrsZ	label_rgbZ
hex_to_rgb)rS   Úcolr   r   r   rU   ÿ   s    NZrgb)Z	colortype)rW   ZPLOTLY_SCALESÚkeysr   ZPlotlyErrorÚformatr   rC   r&   ZsearchsortedÚzipZfind_intermediate_colorÚappend)Ú	ncontoursZcolormapZcmaprG   Z	vals_cmapÚcolsZindsÚcolorsÚindÚvalZval1Zval2ZintermrX   r   r   r   Ú_colorsï   s&    
$rb   c             C   s<   t  t  | | d  ¡dk ¡o6t  t  ||d  ¡dk ¡}|S )zy
    Utility function for _contour_trace

    Contours with an area of the order as 1 pixel are considered spurious.
    r   r   )r   ÚallrO   )r)   rQ   Z	too_smallr   r   r   Ú_is_invalid_contour  s    8rd   c             C   st  t  | ¡}| t  |¡  ¡ | t  |¡  ¡  }}t  | ¡}d| ||< t  | ¡}d| ||< g g g g f\}}	}
}g g g g f\}}}}xÀt|ƒD ]´\}}t ||¡}t ||¡}| 	|¡ | 	|¡ |	 	|gt
|ƒ ¡ | 	|gt
|ƒ ¡ |
 	dd„ |D ƒ¡ | 	dd„ |D ƒ¡ | 	|| gt
|ƒ ¡ | 	|| gt
|ƒ ¡ qŽW t
|ƒt
|ƒkrd||	|
|fS ||||fS dS )a{  
    Utility function for _contour_trace.

    In ``im`` only one part of the domain has valid values (corresponding
    to a subdomain where barycentric coordinates are well defined). When
    computing contours, we need to assign values outside of this domain.
    We can choose a value either smaller than all the values inside the
    valid domain, or larger. This value must be chose with caution so that
    no spurious contours are added. For example, if the boundary of the valid
    domain has large values and the outer value is set to a small one, all
    intermediate contours will be added at the boundary.

    Therefore, we compute the two sets of contours (with an outer value
    smaller of larger than all values in the valid domain), and choose
    the value resulting in a smaller total number of contours. There might
    be a faster way to do this, but it works...
    r   c             S   s"   g | ]}t |jd  |jd ƒ‘qS )r
   r   )rR   rE   )rS   Úcontourr   r   r   rU   ;  s    z%_extract_contours.<locals>.<listcomp>c             S   s"   g | ]}t |jd  |jd ƒ‘qS )r
   r   )rR   rE   )rS   re   r   r   r   rU   >  s    N)r   ÚisnanZlogical_notr   rA   ÚcopyÚ	enumerater   Zfind_contoursÚextendr7   )ZimrG   r_   Zmask_nanZim_minZim_maxZzz_minZzz_maxZall_contours1Zall_values1Z
all_areas1Zall_colors1Zall_contours2Zall_values2Z
all_areas2Zall_colors2Úira   Zcontour_level1Zcontour_level2r   r   r   Ú_extract_contours  s2    




rk   c                sn  dt  dddgdddgg¡j }|g|  } t  |¡d }t  |d | g||d | gf¡}t  |	g||
gf¡}t  ||k¡d d }|t|ƒd k r |d8 }n|d7 }|| gˆ  ‰ || g| }dg| }‡ fdd„|D ƒ}t|ƒ}t  dd|d ¡}g }xFt|ƒD ]:\}}| 	|| || g¡ | 	||d  || g¡ qW | 	|| ||d  g¡ | ||ˆ |fS )	a  
    Utility function for _contour_trace

    Adds the background color to fill gaps outside of computed contours.

    To compute the background color, the color of the contour with largest
    area (``val_outer``) is used. As background color, we choose the next
    color value in the direction of the extrema of the colormap.

    Then we add information for the outer contour for the different lists
    provided as arguments.

    A discrete colormap with all used colors is also returned (to be used
    by colorscale trace).
    é   r   r
   g      à?éÿÿÿÿr   c                s   g | ]}|ˆ kr|‘qS r   r   )rS   Úcolor)Ú
all_colorsr   r   rU   t  s    z&_add_outer_contour.<locals>.<listcomp>)
r   r&   rE   ZdiffÚconcatenateZnonzeror7   rC   rh   r\   )Úall_contoursÚ
all_valuesÚ	all_areasro   rG   Z	val_outerÚv_minÚv_maxr_   Ú	color_minÚ	color_maxZouter_contourZdelta_valuesÚindexZused_colorsZcolor_numberZscaleÚdiscrete_cmrj   rn   r   )ro   r   Ú_add_outer_contourH  s,     
 

 rz   ÚElectricúrgb(150,150,150)Úllrr
   c
       #      C   sX  t |d |ƒ}
t ||	|d ¡}|
d |
d  }}|
dd… }
|dd… }|dkrXd}n
|g| }
t|||
ƒ\}}}}t |¡ddd… }t|||||||d  ||	|
||ƒ\}}}}}t dg|d f¡}g }tƒ \}}|  ¡ |  	¡  | j
 }| ¡ | 	¡  |j
 }xF|D ]<}|| j\}}|| }|dkr^t |t || || t |j¡f¡¡}n4|dkr’tt || |  	¡  || | 	¡  f¡ƒ}|dkrÎt dddg¡}t dddg¡}t dddg¡} n
|\}}} t||ƒrèq|d	krú|| n|}!td
||| d	t|!dddd|| ddd| d}"|d	kr@d|"d< | |"¡ qW ||fS )aî  
    Contour trace in Cartesian coordinates.

    Parameters
    ==========

    x, y : array-like
        Cartesian coordinates
    z : array-like
        Field to be represented as contours.
    ncontours : int or None
        Number of contours to display (determined automatically if None).
    colorscale : None or str (Plotly colormap)
        colorscale of the contours.
    linecolor : rgb color
        Color used for lines. If ``colorscale`` is not None, line colors are
        determined from ``colorscale`` instead.
    interp_mode : 'ilr' (default) or 'cartesian'
        Defines how data are interpolated to compute contours. If 'irl',
        ILR (Isometric Log-Ratio) of compositional data is performed. If
        'cartesian', contours are determined in Cartesian space.
    coloring : None or 'lines'
        How to display contour. Filled contours if None, lines if ``lines``.
    vmin, vmax : float
        Bounds of interval of values used for the colorspace

    Notes
    =====
    r   r   rm   r
   Nzrgb(150, 150, 150)r>   r=   ÚlinesÚscatterternaryZspline)rn   r6   r   ZtoselfTÚskipz%.3f)Útyper   r   r	   ÚmodeÚlineÚfillZ	fillcolorr   Z	hoverinfoÚnamer„   )rb   r   rC   rk   Zargsortrz   rp   r2   rA   r   ÚsizerE   rP   r$   r/   r6   r-   r&   rd   r   r\   )#r)   rQ   Úzr]   Ú
colorscaleÚ	linecolorrH   Úcoloringrt   ru   r_   rG   rv   rw   rq   rr   rs   ro   Úorderry   Ztracesr1   rI   ZdxZdyrx   Z	y_contourZ	x_contourra   Z
bar_coordsr   r   r	   Ú_colÚtracer   r   r   Ú_contour_trace  s|    ,



$
(


rŽ   iô  FZBlueredc             C   sb  t dkrtdƒ‚t d¡}|dkr*tdƒ‚|dkr6d}|dkrBd}t| ƒ} | ¡ | ¡  }}t| ||d\}}}t||||
d}t	||||||	||||d	
\}}t
j||d
}|r¶dnd}| \}}}|d d |d  d |d  d }|j|||d||dt|dkƒdœdœ||d |r^|s&|}tddgdgdg| ¡ | ¡ |ddœddœƒ}| |¡ |S )a´  
    Ternary contour plot.

    Parameters
    ----------

    coordinates : list or ndarray
        Barycentric coordinates of shape (2, N) or (3, N) where N is the
        number of data points. The sum of the 3 coordinates is expected
        to be 1 for all data points.
    values : array-like
        Data points of field to be represented as contours.
    pole_labels : str, default ['a', 'b', 'c']
        Names of the three poles of the triangle.
    width : int
        Figure width.
    height : int
        Figure height.
    ncontours : int or None
        Number of contours to display (determined automatically if None).
    showscale : bool, default False
        If True, a colorbar showing the color scale is displayed.
    coloring : None or 'lines'
        How to display contour. Filled contours if None, lines if ``lines``.
    colorscale : None or str (Plotly colormap)
        colorscale of the contours.
    linecolor : None or rgb color
        Color used for lines. ``colorscale`` has to be set to None, otherwise
        line colors are determined from ``colorscale``.
    title : str or None
        Title of ternary plot
    interp_mode : 'ilr' (default) or 'cartesian'
        Defines how data are interpolated to compute contours. If 'irl',
        ILR (Isometric Log-Ratio) of compositional data is performed. If
        'cartesian', contours are determined in Cartesian space.
    showmarkers : bool, default False
        If True, markers corresponding to input compositional points are
        superimposed on contours, using the same colorscale.

    Examples
    ========

    Example 1: ternary contour plot with filled contours

    >>> import plotly.figure_factory as ff
    >>> import numpy as np
    >>> # Define coordinates
    >>> a, b = np.mgrid[0:1:20j, 0:1:20j]
    >>> mask = a + b <= 1
    >>> a = a[mask].ravel()
    >>> b = b[mask].ravel()
    >>> c = 1 - a - b
    >>> # Values to be displayed as contours
    >>> z = a * b * c
    >>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z)
    >>> fig.show()

    It is also possible to give only two barycentric coordinates for each
    point, since the sum of the three coordinates is one:

    >>> fig = ff.create_ternary_contour(np.stack((a, b)), z)


    Example 2: ternary contour plot with line contours

    >>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z, coloring='lines')

    Example 3: customize number of contours

    >>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z, ncontours=8)

    Example 4: superimpose contour plot and original data as markers

    >>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z, coloring='lines',
    ...                                 showmarkers=True)

    Example 5: customize title and pole labels

    >>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z,
    ...                                 title='Ternary plot',
    ...                                 pole_labels=['clay', 'quartz', 'fledspar'])
    NzH    The create_ternary_contour figure factory requires the scipy packageÚskimagezS    The create_ternary_contour figure factory requires the scikit-image
    packageFé   )rH   )r   r   r   r   )r]   rˆ   r‰   rH   rŠ   rt   ru   )ÚdataÚlayoutr
   r   z: %{a:.3f}<br>z: %{b:.3f}<br>r   z3: %{c:.3f}<br>z: %{marker.color:.3f}<extra></extra>Úmarkerszrgb(120, 120, 120)r~   )rn   r   )rn   rˆ   rƒ   )r   r   r	   r‚   ÚmarkerÚopacityÚhovertemplater   T)ZcminZcmaxrˆ   Ú	showscale)r   r   r   r	   r”   r‚   )rD   ÚImportErrorr   Ú
get_moduler<   r   rA   rN   r   rŽ   ÚgoZFigureZadd_scatterternaryrB   r   Z	add_trace)rF   rG   r   r   r   r]   r—   rŠ   rˆ   r‰   r   rH   ZshowmarkersZ
sk_measurert   ru   rM   rK   rL   r’   Zcontour_tracery   Zfigr•   r   r   r	   r–   Zcolorbarr   r   r   Úcreate_ternary_contour  sp    a

$

r›   )r   )r=   )N)Nr{   r|   r}   Nr   r
   )Ú
__future__r   Zplotly.colorsr_   rW   Zplotly.graph_objsr   rš   Zplotlyr   r   r™   r   rD   r   r   r   r   r%   r-   r2   r<   rN   rR   rb   rd   rk   rz   rŽ   r›   r   r   r   r   Ú<module>   sL   

(
" 
.

2=      
~