o
    ³ôj}8  ã                   @   s  d dl mZmZ d dlmZ d dlmZmZmZ d dl	m
Z
mZmZmZmZ d dlZd dlZd dlmZ d dlmZmZmZ ermd dlZd dlZd dlmZ eejeejjej f f Z!ejjZ"eej#j$e%f Z&ej'j(Z)nee*e*f Z!e*Z"e*Z&d dl+m,Z, e,d	e
d
e
defdd„ƒZ)er”d dl-Z-ddgZ.er›er›dgndgZ.d2dd„Z/e)e.ƒ						d3deeee e0e%ef ee0e%ef  f dee" dee1 dee2 dee2 dee% dee% de!fdd„ƒZ3de4dee4e4f fdd„Z5dee2e2e2e2f de%fd d!„Z6d"ee"ej f d#e4deej e"f fd$d%„Z7e)e.ƒe		&		d4d'edee" d(e1d)ee8ee4e%f   d*ee& de!fd+d,„ƒƒZ9e)e.ƒ						d3d-eeeeef eee ee ee f f d.ee dee" d/eee%e%f  dee% dee% d)ee8ee4e%f   de!fd0d1„ƒZ:dS )5é    )Ú	GeneratorÚSequence)Úproduct)ÚceilÚfloorÚsqrt)ÚAnyÚListÚOptionalÚUnionÚno_type_checkN)ÚTensor)Ú_LATEX_AVAILABLEÚ_MATPLOTLIB_AVAILABLEÚ_SCIENCEPLOT_AVAILABLE)ÚcontextmanagerÚargsÚkwargsÚreturnc                  o   s   � dV  dS )z0No-ops decorator if matplotlib is not installed.N© )r   r   r   r   ún/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/utilities/plot.pyÚstyle_change*   s   €
r   Úsciencezno-latexÚdefaultc                   C   s   t stdƒ‚dS )z+Raise error if matplotlib is not installed.z`Plot function expects `matplotlib` to be installed. Please install with `pip install matplotlib`N)r   ÚModuleNotFoundErrorr   r   r   r   Ú_error_on_missing_matplotlib8   s
   ÿÿr   ÚvalÚaxÚhigher_is_betterÚlower_boundÚupper_boundÚlegend_nameÚnamec              	      s$  t ƒ  |du rt ¡ nd|f\}}| ¡  d¡ tˆtƒrVˆ ¡ dkr1|jˆ 	¡  
¡ gddd� nýtˆƒD ]\}}	|rB|› d|› �n|› }
|j||	 	¡  
¡ ddd|
d	� q5nØtˆtƒr¢tˆ ¡ ƒD ]?\}\}}	|	 ¡ dkr’|j|	 	¡  
¡ ddd
|d	� | ¡  d¡ | d¡ | t t|	ƒ¡¡ qa|j||	 	¡  
¡ dd|d� qanŒtˆtƒ�r*tˆƒ‰ tˆd tƒr×‡ ‡fdd„ˆd D ƒ‰ˆ ¡ D ]\}}	|j|	 	¡  
¡ ddd
|d	� qÃn>t ˆd¡‰ˆjdk}|rçˆjnˆ d¡‰tˆƒD ]$\}}	|�r|�r|› d|› �n|› nd}
|j|	 	¡  
¡ ddd
|
d	� qð| ¡  d¡ | d¡ | t ˆ ¡¡ ntdƒ‚| ¡ \}}|�rF|�rF|j||dddddd� | ¡ }|du�r[|du�r[d||  }n
d|d |d   }|j|du�rp|| n|d | |du�r~|| n|d | d� | d¡ | |du�r”|nd¡ | ¡ }d|d |d   }g }|du�r±|  |¡ |du�r»|  |¡ |j!||d |d ddd� |du�r|du�rî|�sî| "|d | |d ¡ |j#|d |dddd� |du�r|�r| "|d | |d ¡ |j#|d |dddd� ||fS )aÊ  Plot a single metric value or multiple, including bounds of value if existing.

    Args:
        val: A single tensor with one or multiple values (multiclass/label/output format) or a list of such tensors.
            If a list is provided the values are interpreted as a time series of evolving values.
        ax: Axis from a figure.
        higher_is_better: Indicates if a label indicating where the optimal value it should be added to the figure
        lower_bound: lower value that the metric can take
        upper_bound: upper value that the metric can take
        legend_name: for class based metrics specify the legend prefix e.g. Class or Label to use when multiple values
            are provided
        name: Name of the metric to use for the y-axis label

    Returns:
        A tuple consisting of the figure and respective ax objects of the generated figure

    Raises:
        ModuleNotFoundError:
            If `matplotlib` is not installed

    NFé   Úoé
   )ÚmarkerÚ
markersizeú ÚNone)r&   r'   Ú	linestyleÚlabelú-TZStep)r&   r'   r+   r   c                    s,   i | ]‰ ˆ t  ‡ ‡fd d„tˆƒD ƒ¡“qS )c                    s   g | ]}ˆ| ˆ  ‘qS r   r   )Ú.0Úi)Úkr   r   r   Ú
<listcomp>v   s    z7plot_single_or_multi_val.<locals>.<dictcomp>.<listcomp>)ÚtorchÚstackÚrange)r-   ©Ún_stepsr   )r/   r   Ú
<dictcomp>v   s   , z,plot_single_or_multi_val.<locals>.<dictcomp>Ú z&Got unknown format for argument `val`.zupper center)g      à?gffffffò?é   )ÚlocZbbox_to_anchorÚncolZfancyboxZshadowgš™™™™™¹?)ÚbottomÚtopÚdashedr/   )Z
linestylesÚcolorszOptimal 
 valueÚcenter)ÚsÚhorizontalalignmentÚverticalalignment)$r   ÚpltÚsubplotsZ	get_xaxisÚset_visibleÚ
isinstancer   ÚnumelÚplotÚdetachÚcpuÚ	enumerateÚdictÚitemsÚ
set_xlabelÚ
set_xticksr1   ÚarangeÚlenr   r2   ÚndimÚTÚ	unsqueezeÚ
ValueErrorÚget_legend_handles_labelsÚlegendÚget_ylimÚset_ylimÚgridÚ
set_ylabelÚget_xlimÚappendZhlinesÚset_xlimÚtext)r   r   r   r   r    r!   r"   Úfigr.   Úvr+   r/   Zmulti_seriesÚhandlesÚlabelsÚylimÚfactorÚxlimZy_linesr   r4   r   Úplot_single_or_multi_val@   sŠ   
 þ

ùÿ
$
þ





ÿÿrg   Únc                 C   sX   t | ƒ}t|ƒ|krt|ƒt|ƒfS t|ƒt|ƒ | kr$t|ƒt|ƒfS t|ƒt|ƒfS )z/Split `n` figures into `rows` x `cols` figures.)r   Úintr   r   )rh   Znsqr   r   r   Ú_get_col_row_split¯   s   rj   Úpatch_colorc                 C   sN   | \}}}}dd„ |||fD ƒ\}}}d| d|  d|  }|dkr%dS dS )	zÇGet the text color for a given value and colormap.

    Following Wikipedia's recommendations: https://en.wikipedia.org/wiki/Relative_luminance.

    Args:
        patch_color: RGBA color tuple

    c                 s   s0   � | ]}|d kr|d n|d d d V  qdS )g?ÆÜµ¤?g×£p=
×)@g)\�Âõ(¬?gáz®Gáð?g333333@Nr   )r-   Úcr   r   r   Ú	<genexpr>Ä   s   €. z"_get_text_color.<locals>.<genexpr>g¼–�z6Ë?g¥,Cëâæ?g]mÅþ²{²?gš™™™™™Ù?z.1Úwhiter   )rk   ÚrÚgÚbÚaÚyr   r   r   Ú_get_text_color¹   s   
rt   ÚaxsÚnbc                 C   s:   t | tƒr| S | j} | |d… D ]}| ¡  q| d|… S )zSReduce `axs` to `nb` Axes.

    All further Axes are removed from the figure.

    N)rF   Ú_AX_TYPEÚflatÚremove)ru   rv   r   r   r   r   Útrim_axsÌ   s   

rz   TÚconfmatÚadd_textrc   Úcmapc                 C   sz  t ƒ  | jdkr| jd d}}t|ƒ\}}nd| jd ddf\}}}}|dur?| jdkr?t|ƒ|kr?tdt|ƒ› d|› �ƒ‚| jdkrU|pJt |¡}	tt	t
t|ƒƒƒ}nd}	|p_t |¡ ¡ }|du rltj||dd	�n| ¡ |f\}
}t||ƒ}t|ƒD ]»}|dks‡|dkr‹|| n|}|	dur�|jd
|	| › �dd� |j| jdkr¬| |  ¡  ¡ n|  ¡  ¡ |d�}|| |d krÄ|jddd� || dkrÑ|jddd� | tt|ƒƒ¡ | tt|ƒƒ¡ |j|ddd� |j|ddd� |�r8tt|ƒt|ƒƒD ]8\}}| jdk�r| |||f n| ||f }| | | ¡ ¡¡}t|ƒ}|j ||t
t!| ¡ dƒƒddd|d� qÿq}|
|fS )aÏ  Plot an confusion matrix.

    Inspired by: https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/metrics/_plot/confusion_matrix.py.
    Works for both binary, multiclass and multilabel confusion matrices.

    Args:
        confmat: the confusion matrix. Either should be an [N,N] matrix in the binary and multiclass cases or an
            [N, 2, 2] matrix for multilabel classification
        ax: Axis from a figure. If not provided, a new figure and axis will be created
        add_text: if text should be added to each cell with the given value
        labels: labels to add the x- and y-axis
        cmap: matplotlib colormap to use for the confusion matrix
            https://matplotlib.org/stable/users/explain/colors/colormaps.html

    Returns:
        A tuple consisting of the figure and respective ax objects (or array of ax objects) of the generated figure

    Raises:
        ModuleNotFoundError:
            If `matplotlib` is not installed

    r8   r   é   r#   NzYExpected number of elements in arg `labels` to match number of labels in confmat but got ú and T)ÚnrowsÚncolsZconstrained_layoutzLabel é   )Úfontsize)r}   zPredicted classz
True classé-   r%   )Úrotationrƒ   é   r?   )ÚhaÚvarƒ   Úcolor)"r   rR   Úshaperj   rQ   rU   ÚnprP   ÚlistÚmapÚstrr3   ÚtolistrC   rD   Z
get_figurerz   Ú	set_titleÚimshowrJ   rI   rN   r[   rO   Ú
set_yticksÚset_xticklabelsÚset_yticklabelsr   r}   ÚnormÚitemrt   r_   Úround)r{   r   r|   rc   r}   rv   Ú	n_classesÚrowsÚcolsZ	fig_labelr`   ru   r.   ÚimÚiiÚjjr   rk   rl   r   r   r   Úplot_confusion_matrixÛ   sR   
ÿÿÿ
(
0&(€rž   ÚcurveÚscoreÚlabel_namesc                 C   s:  t | ƒdk rtdt | ƒ› �ƒ‚| dd… \}}tƒ  |du r"t ¡ nd|f\}	}t|tƒret|tƒre|jdkre|jdkre|durHd| ¡ d›�nd}
|j	| 
¡  ¡ | 
¡  ¡ dd|
d� |
durd| ¡  n—t|tƒrot|tƒsƒt|tƒrít|tƒrí|jdkrí|jdkrít |ƒ}|dur�t |ƒ|kr�td	t |ƒ› d
|› �ƒ‚tt||ƒƒD ]G\}\}}|durµ|› d|› �n|du r½t|ƒnt|| ƒ}
|
|durÒd||  ¡ d›�nd7 }
|j	| 
¡  ¡ | 
¡  ¡ dd|
d� | ¡  q¤ntdt|ƒ› d
t|ƒ› d�ƒ‚|du�r| |d ¡ | |d ¡ | d¡ | |¡ |	|fS )aÏ  Inspired by: https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/metrics/_plot/roc_curve.py.

    Plots a curve object

    Args:
        curve: a tuple of (x, y, t) where x and y are the coordinates of the curve and t are the thresholds used
            to compute the curve
        score: optional area under the curve added as label to the plot
        ax: Axis from a figure
        label_names: Tuple containing the names of the x and y axis
        legend_name: Name of the curve to be used in the legend
        name: Custom name to describe the metric
        labels: Optional labels for the different curves that will be added to the plot

    Returns:
        A tuple consisting of the figure and respective ax objects (or array of ax objects) of the generated figure

    Raises:
        ModuleNotFoundError:
            If `matplotlib` is not installed
        ValueError:
            If `curve` does not have 3 elements, being in the wrong format
    r~   z*Expected 2 or 3 elements in curve but got Nr#   zAUC=z0.3fr,   )r*   Ú	linewidthr+   z\Expected number of elements in arg `labels` to match number of labels in roc curves but got r   Ú_z AUC=r7   zQUnknown format for argument `x` and `y`. Expected either list or tensors but got Ú.r   T)rQ   rU   r   rC   rD   rF   r   rR   r–   rH   rI   rJ   rW   rŒ   rK   ÚziprŽ   ÚtyperN   r[   rZ   r�   )rŸ   r    r   r¡   r!   r"   rc   Úxrs   r`   r+   r˜   r.   Úx_Úy_r   r   r   Ú
plot_curve(  sR   !($€ÿÿÿÿÿ2$$
üÿ


rª   )r   N)NNNNNN)NTNN);Úcollections.abcr   r   Ú	itertoolsr   Úmathr   r   r   Útypingr   r	   r
   r   r   Únumpyr‹   r1   r   Útorchmetrics.utilities.importsr   r   r   Ú
matplotlibÚmatplotlib.axesÚmatplotlib.pyplotÚpyplotrC   ÚtupleÚFigureÚaxesÚAxesÚndarrayÚ_PLOT_OUT_TYPErw   r>   ZColormaprŽ   Z
_CMAP_TYPEÚstyleÚcontextr   ÚobjectÚ
contextlibr   ÚscienceplotsÚ_styler   rL   ÚboolÚfloatrg   ri   rj   rt   rz   rŒ   rž   rª   r   r   r   r   Ú<module>   sÂ   

ù&ÿþýüûúùøn
*ûÿþýüûúKù*ÿþýüûúùø