
    g6X                        d dl mZ d dlmZ d dlmZ d dlmZ  ej                  d      Z
 ej                  d      Zd dlmZ dd	d
g dfdZddZd Zd Zd Zd ZddZd Zd dZd Zd Zd Z	 	 	 	 	 	 	 d!dZg dddddddddddfdZy)"    N)
graph_objs)
exceptions)optional_importsnumpyzscipy.interpolate)measurezTernary contour ploti&  i  )abcc                     t        | ||t        dt        t        |d         ddd      t        t        |d         ddd      t        t        |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   )text{Gz?   outside)titlemin	linewidthticks)sumaaxisbaxiscaxisF)r   widthheightternary
showlegend)dict)r   r   r   pole_labelss       c/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/plotly/figure_factory/_ternary_contour.py_ternary_layoutr       s|    $ A/TQi A/TQi A/TQi
 !     c                     | dk(  }t         j                  |d      }d||z  z
  }t         j                  |      dk  rt        d      t         j                  |||| z        } | 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)ternary_datadelta	zero_maskis_any_coord_zerounity_complements        r   _replace_zero_coordsr.   7   sv    * !Iyq15#444	vv!#1
 	
 88Iu.>.MNLr!   c                 F   t         j                  |       } t         j                  | d   | d   z        t         j                  d      z  }dt         j                  d      z  t         j                  | d   | d   z  | d   dz  z        z  }t         j	                  ||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         ?   )r%   asarraylogsqrtstack)barycentricx_0x_1	ilr_tdatas       r   _ilr_transformr:   Y   s      **[)K
&&Q+a.0
1BGGAJ
>Cbggaj266+a.;q>"AKPQNVWDW"WXX  #s$Ir!   c           
      B   t         j                  |       } t         j                  g dg dg dg      }t         j                  d      dz  }t         j                  d      }t         j                  dt         j                  ||g| |gg      |       }t         j	                  dt         j                  |      j                  d	      z          }t         j                  d|t         j                  d|z  | d   z  || d   z  |f            }t         j                  |      }|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.
    )      ?r   r0   )g      r   r0   )        r=   r0   r   g      ?ik, kj -> ijr   r   r#   )r%   arrayr4   einsumr3   expr   r5   )xmatrixstSkZlog_barycentric
iilr_tdatas           r   _ilr_inverserJ   r   s    " 	AXX}noFGF

QA
A	>288aVqb!W,=#>	BB	BFF2JNNN**	++Aii!a%!A$,AaD!)D EO (Jr!   c                     t         j                  dt         j                  d      dz  gddgddgg      } t         j                  | dddf   | dddf   t         j                  d      g      }|t         j                  j                  |      fS )zi
    Returns the transformation matrix from barycentric to Cartesian
    coordinates and conversely.
    r<      r   r   r   N)r%   r?   r4   oneslinalginv)	tri_vertsMs     r    _transform_barycentric_cartesianrR      sw     3
Q/!Q!Q@AI
)AqD/9QT?BGGAJ?@AbiimmAr!   c                    t        | t        t        j                  f      st	        d      t        j                  |       } | j                  d   dvrt	        d      t        |       dk(  r]t        j                  | j                  d      dd	      s5t        j                  | j                  d      d
d	      sd}t	        |      t        |       dk(  r| \  }}d||z   z
  }n| | j                  d      z  \  }}}t        j                  t        j                  |||f      dk        rt	        d      t        j                  |||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   rL   zCA point should have  2 (a, b) or 3 (a, b, c)barycentric coordinatesrL   r#   r   r   )rtold   z=The sum of coordinates should be 1 or 100 for all data pointsr   z+Barycentric coordinates should be positive.)
isinstancelistr%   ndarrayr'   r2   shapelenallcloser   r&   r5   )b_coordsmsgABCs        r   _prepare_barycentric_coordra      s/    hrzz 23/
 	
 zz(#H~~a&T
 	
 
X!	HLLaL0!$?HLLaL0#DAMo
8}1QKX\\q\111a	vvbhh1ay!A%&FGG88Q1Ir!   ilrc           
         |dk(  r%t               \  }}t        j                  d||       }n'|dk(  rt        |       } t	        |       }nt        d      |dd \  }}|j                         |j                         }	}|j                         |j                         }}
t        dt        t        j                  t        |                        }t        j                  ||	|      }t        j                  |
||      }t        j                  ||      \  }}t        j                  |dd j                  |||fd	      }t        j                  |dd j                  |||f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.
    	cartesianr>   rb   z&interp_mode should be cartesian or ilrNr      cubic)methodnearest)rR   r%   r@   r.   r:   r'   r   maxintr4   rZ   linspacemeshgridscipy_interpgriddataT)coordinatesvaluesinterp_moderQ   invMcoord_pointsxxyyx_minx_maxy_miny_maxn_interpgr_xgr_ygrid_xgrid_ygrid_zgrid_z_others                      r   _compute_gridr      sU    k!244yyK@		*;7%k2ABB"1FB668RVVX5E668RVVX5E3BGGCK012H;;ueX.D;;ueX.D[[t,NFF ""RaFVV$4W # F  ((RaFVV$4Y ) L
 4r!   c                     dt         j                  t         j                  | t         j                  |d            t         j                  |t         j                  | d            z
        z  S )Nr<   r   )r%   absdotroll)rB   ys     r   _polygon_arear      sE    q"''!Q-0266!RWWQ]3KKLLLr!   c                 L   |t         j                  j                         v rt         j                  |   }n@t        j                  dj                  t         j                  j                                     t        j                  dd|       }t        j                  |D cg c]  }|d   	 c}      }t        j                  |D cg c]  }|d   	 c}      }t        j                  ||      }d|d   v r5|D cg c]*  }t        j                  t        j                  |            , }}|d   g}	t        |dd |dd       D ]P  \  }
}||
dz
     ||
   }}||z
  ||z
  z  }t        j                  ||
dz
     ||
   |d      }|	j                  |       R |	S c c}w c c}w c c}w )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   #Nrgb)	colortype)clrsPLOTLY_SCALESkeysr   PlotlyErrorformatr%   rk   r?   searchsorted	label_rgb
hex_to_rgbzipfind_intermediate_colorappend)	ncontourscolormapcmaprq   pair	vals_cmapcolsindscolcolorsindvalval1val2interms                  r   _colorsr      s    4%%**,,!!(+$$44:F4;M;M;R;R;T4U
 	
 [[Ay)Fd3d$q'34I88.T!W./D??9f-D
d1g~@DEts34EE1gYFQR&*- SsQw'3d*-**qM49f
 	c M 4. Fs   FF9/F!c                     t         j                  t         j                  | | d   z
        dk        xr1 t         j                  t         j                  ||d   z
        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%   allr   )rB   r   	too_smalls      r   _is_invalid_contourr   
  sR     rvva!A$h'!+,Mq1Q4x8H18L1MIr!   c                    t         j                  |       }| t         j                  |         j                         | t         j                  |         j	                         }}t         j                  |       }d|z  ||<   t         j                  |       }d|z  ||<   g g g g f\  }}	}
}g g g g f\  }}}}t        |      D ]X  \  }}t        j                  ||      }t        j                  ||      }|j                  |       |j                  |       |	j                  |gt        |      z         |j                  |gt        |      z         |
j                  |D cg c](  }t        |j                  d   |j                  d         * c}       |j                  |D cg c](  }t        |j                  d   |j                  d         * c}       |j                  ||   gt        |      z         |j                  ||   gt        |      z         [ t        |      t        |      k  r||	|
|fS ||||fS c c}w c c}w )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   r   r   )r%   isnanlogical_notr   ri   copy	enumerater   find_contoursextendrZ   r   ro   )imrq   r   mask_nanim_minim_maxzz_minzz_maxall_contours1all_values1
all_areas1all_colors1all_contours2all_values2
all_areas2all_colors2ir   contour_level1contour_level2contours                        r   _extract_contoursr     s    $ xx|H
2>>(#$((*
2>>(#$((* F WWR[F6zF8WWR[F6zF8:<b"b.7M;
K:<b"b.7M;
KF# >3 ..vs; ..vs;^,^,C53~#667C53~#667FTU7]799Q<16U	
 	FTU7]799Q<16U	
 	F1I;^)<<=F1I;^)<<=> =S//k:{BBk:{BB V Vs   -H<
 -I
c                    dt         j                  g dg dg      j                  z  }|g| z   } t         j                  |      d   }t         j	                  |d   |z
  g||d   |z   gf      }t         j	                  |	g||
gf      }t         j                  ||k(        d   d   }|t        |      dz  k  r|dz  }n|dz  }||   g|z   }||   g|z   }dg|z   }|D cg c]	  }||v s| }}t        |      }t         j                  dd|dz         }g }t        |      D ]:  \  }}|j                  ||   ||   g       |j                  ||dz      ||   g       < |j                  ||   ||dz
     g       | ||||fS c c}w )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   r   )r   r   r<   r   r   r   )
r%   r?   ro   diffconcatenatenonzerorZ   rk   r   r   )all_contours
all_values	all_areas
all_colorsrq   	val_outerv_minv_maxr   	color_min	color_maxouter_contourdelta_valuesindexcolorused_colorscolor_numberscalediscrete_cmr   s                       r   _add_outer_contourr   F  s   : 9k":;===M!?\1L776?1%L^^
)l
"	#VfRj<.G-HIF ^^i[&9+>?FJJv*+A.q1Es6{Q

-:-J-:-JiI&,DU0C5DKD{#LKK1lQ./EKk* ;5E!Hk!n56E!a%L+a.9:; l+[9I-JKLY
KGG Es   	E?'E?c
                 "   t        |dz   |      }
t        j                  ||	|dz         }|
d   |
d   }}|
dd }
|dd }|d}n|g|z  }
t        |||
      \  }}}}t        j	                  |      ddd   }t        |||||||d      ||	|
||      \  }}}}}t        j                  dg|dz   f      }g }t               \  }}| j                         | j                         z
  | j                  z  }|j                         |j                         z
  |j                  z  }|D ]j  }||   j                  \  }}||   }|dk(  rPt        j                  |t        j                  ||z  ||z  t        j                  |j                        f            }nM|dk(  rHt!        t        j                  ||z  | j                         z   ||z  |j                         z   f            }|dk(  rFt        j#                  g d	      }t        j#                  g d
      }t        j#                  g d      } n\  }}} t%        ||      r|dk(  r||   n|}!t'        d||| dt'        |!dd      d||   ddd|z        }"|dk(  rd|"d<   |j)                  |"       m ||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   r   r   Nzrgb(150, 150, 150)rd   rb   )r   r   r   )r   r   r   r   linesscatterternaryspline)r   rY   r   toselfTskipz%.3f)typer   r	   r
   modelinefill	fillcolorr   	hoverinfonamer   )r   r%   rk   r   argsortr   r   rR   ri   r   sizero   r   r5   rM   rY   rJ   r?   r   r   r   )#rB   r   zr   
colorscale	linecolorrr   coloringr   r   r   rq   r   r   r   r   r   r   orderr   tracesrQ   rs   dxdyr   	y_contour	x_contourr   
bar_coordsr   r	   r
   _coltraces#                                      r   _contour_tracer     s   X Y]J/F [[y1}5F!!9fRjyIAb\FAb\F (	y( 7H	6673L*i
 JJy!$B$'E DV58D@L*i[ NNQC+,E F.0GAt
%%'AEEG
qvv	%B
%%'AEEG
qvv	%B %+E244	9+%"y."y."'')//:RSTJ E!%"y.15572BNQUUW4LMNJ A:#A#A#A GAq!y)4$,$7z% Y!D: '#
 w E&MeK%N ;r!   i  FBlueredc                    t         t        d      t        j                  d      }|t        d      |d}|d}t	        |       } |j                         |j                         }}t        | ||      \  }}}t        ||||
      }t        ||||||	||||	
      \  }}t        j                  ||
      }|rdnd}| \  }}}|d   dz   |d   z   dz   |d   z   dz   }|j                  |||d||dt        |dk7        dd||       |rK|s|}t        ddgdgdg|j                         |j                         |dddd      }|j                  |       |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   )rr   )r   r   r   r   )r   r   r   rr   r   r   r   )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   )r   r   )r   r   r   )r   r	   r
   r   markeropacityhovertemplater   T)cmincmaxr   	showscale)r   r   r	   r
   r  r   )rm   ImportErrorr   
get_modulera   r   ri   r   r    r   goFigureadd_scatterternaryrj   r   	add_trace)rp   rq   r   r   r   r   r  r   r   r   r   rr   showmarkers
sk_measurer   r   r   r|   r}   r   contour_tracer   figr  r   r	   r
   r  colorbars                                r   create_ternary_contourr    s   B L
 	
 ",,Y7J
 	

 		,[9K::<5E&{FTFD$uV5F "0"M; ))v
6CaAGGAq!A
	
a.	 	 a.		
0	0  


$2SWAT=UV

 #   $J(VVV"JJL"JJL",!%	 "
 	hJr!   )gMb@?)rb   )N)NElectriczrgb(150,150,150)llrNr   r   )plotly.colorsr   r   plotly.graph_objsr   r
  plotlyr   r   r	  r%   rm   r   r   r    r.   r:   rJ   rR   ra   r   r   r   r   r   r   r   r   r!   r   <module>r     s     .  #   )***+>?  !C_#RD2<@(\M:/Cd6Hz  

P  

ur!   