o
    .wi                     @   s   d dl mZ d dlmZmZmZmZ d dlZd dlmZ d dl	m
Z
mZ d dlmZ d dlmZ d dlmZmZ es=d	gZG d
d deZdS )    )Sequence)AnyLiteralOptionalUnionN)Tensor)!_hausdorff_distance_validate_argshausdorff_distance)Metric)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEHausdorffDistance.plotc                       s   e Zd ZU dZdZeed< dZeed< dZeed< dZ	e
ed< eed	< eed
< 					d$dededed deeeee
 f  deded deddf fddZdededdfddZdefddZ	d%d eeeee f  d!ee defd"d#Z  ZS )&HausdorffDistancea
  Compute the `Hausdorff Distance`_ between two subsets of a metric space for semantic segmentation.

    .. math::
        d_{\Pi}(X,Y) = \max{/sup_{x\in X} {d(x,Y)}, /sup_{y\in Y} {d(X,y)}}

    where :math:`\X, \Y` are two subsets of a metric space with distance metric :math:`d`. The Hausdorff distance is
    the maximum distance from a point in one set to the closest point in the other set. The Hausdorff distance is a
    measure of the degree of mismatch between two sets.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
        the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
        can be provided, where the integer values correspond to the class index. The input type can be controlled
        with the ``input_format`` argument.
    - ``target`` (:class:`~torch.Tensor`): An one-hot boolean tensor of shape ``(N, C, ...)`` with ``N`` being
        the number of samples and ``C`` the number of classes. Alternatively, an integer tensor of shape ``(N, ...)``
        can be provided, where the integer values correspond to the class index. The input type can be controlled
        with the ``input_format`` argument.

    As output of ``forward`` and ``compute`` the metric returns the following output:

    - ``hausdorff_distance`` (:class:`~torch.Tensor`): A scalar float tensor with the Hausdorff distance averaged over
        classes and samples

    Args:
        num_classes: number of classes
        include_background: whether to include background class in calculation
        distance_metric: distance metric to calculate surface distance. Choose one of `"euclidean"`,
          `"chessboard"` or `"taxicab"`
        spacing: spacing between pixels along each spatial dimension. If not provided the spacing is assumed to be 1
        directed: whether to calculate directed or undirected Hausdorff distance
        input_format: What kind of input the function receives. Choose between ``"one-hot"`` for one-hot encoded tensors
          or ``"index"`` for index tensors
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torch import randint
        >>> from torchmetrics.segmentation import HausdorffDistance
        >>> preds = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
        >>> target = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
        >>> hausdorff_distance = HausdorffDistance(distance_metric="euclidean", num_classes=5)
        >>> hausdorff_distance(preds, target)
        tensor(1.9567)

    Tis_differentiableFhigher_is_betterfull_state_update        plot_lower_boundscoretotal	euclideanNone-hotnum_classesinclude_backgrounddistance_metric)r   
chessboardtaxicabspacingdirectedinput_format)r   indexkwargsreturnc                    sx   t  jdi | t|||||| || _|| _|| _|| _|| _|| _| j	dt
ddd | j	dt
ddd d S )Nr   r   sum)defaultdist_reduce_fxr   r    )super__init__r   r   r   r   r   r   r    	add_statetorchtensor)selfr   r   r   r   r   r    r"   	__class__r'   i/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/segmentation/hausdorff_distance.pyr)   W   s   
zHausdorffDistance.__init__predstargetc              
   C   sL   t ||| j| j| j| j| j| jd}|  j| 7  _|  j	|
 7  _	dS )z*Update state with predictions and targets.)r   r   r   r   r    N)r	   r   r   r   r   r   r    r   r$   r   numel)r-   r1   r2   r   r'   r'   r0   updaten   s   
zHausdorffDistance.updatec                 C   s   | j | j S )z-Compute final Hausdorff distance over states.)r   r   )r-   r'   r'   r0   compute}   s   zHausdorffDistance.computevalaxc                 C   s   |  ||S )a  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> from torch import randint
            >>> from torchmetrics.segmentation import HausdorffDistance
            >>> preds = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
            >>> target = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
            >>> metric = HausdorffDistance(num_classes=5)
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        )_plot)r-   r6   r7   r'   r'   r0   plot   s   r   )Fr   NFr   )NN)__name__
__module____qualname____doc__r   bool__annotations__r   r   r   floatr   intr   r   r   listr   r)   r4   r5   r   r   r   r9   __classcell__r'   r'   r.   r0   r      sP   
 /	r   )collections.abcr   typingr   r   r   r   r+   r   7torchmetrics.functional.segmentation.hausdorff_distancer   r	   torchmetrics.metricr
   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__r   r'   r'   r'   r0   <module>   s   