§
    ’©ºj­5  ã                   ó  — d dl Z d dlmZmZmZ d dlZd dlmZmZ d dlm	Z	 d dl
mZ esdgZ G d„ dej        ¦  «        Zd'd
ededdfd„Z	 	 	 	 	 	 	 	 d(dedededed         dedee         dee         dee         ddfd„Z	 	 d)dedededed         def
d „Z	 	 	 	 	 	 	 	 	 	 d*d
ededededed         dedee         dee         dee         d#eej        ed$         f         d%eeej        f         deeeef         fd&„ZdS )+é    N)ÚLiteralÚOptionalÚUnion)ÚTensorÚnn)Ú_LPIPS)Ú_TORCHVISION_AVAILABLEÚperceptual_path_lengthc                   ó>   — e Zd ZdZedefd„¦   «         Zdedefd„ZdS )ÚGeneratorTypea  Basic interface for a generator model.

    Users can inherit from this class and implement their own generator model. The requirements are that the ``sample``
    method is implemented and that the ``num_classes`` attribute is present when ``conditional=True`` metric.

    Úreturnc                 ó   — t           ‚)z8Return the number of classes for conditional generation.©ÚNotImplementedError)Úselfs    ú„/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/functional/image/perceptual_path_length.pyÚnum_classeszGeneratorType.num_classes#   s
   € õ "Ð!ó    Únum_samplesc                 ó   — t           ‚)zkSample from the generator.

        Args:
            num_samples: Number of samples to generate.

        r   )r   r   s     r   ÚsamplezGeneratorType.sample(   s
   € õ "Ð!r   N)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚpropertyÚintr   r   r   © r   r   r   r      sg   € € € € € ðð ð ð"˜Sð "ð "ð "ñ „Xð"ð" #ð "¨&ð "ð "ð "ð "ð "ð "r   r   FÚ	generatorÚconditionalr   c                 ó&  — t          | d¦  «        st          d¦  «        ‚t          | j        ¦  «        st	          d¦  «        ‚|rt          | d¦  «        st          d¦  «        ‚|r)t          | j        t          ¦  «        st	          d¦  «        ‚dS dS )zíValidate that the user provided generator has the right methods and attributes.

    Args:
        generator: Generator model
        conditional: Whether the generator is conditional or not (i.e. whether it takes labels as input).

    r   zšThe generator must have a `sample` method with signature `sample(num_samples: int) -> Tensor` where the returned tensor has shape `(num_samples, z_size)`.z1The generator's `sample` method must be callable.r   zJThe generator must have a `num_classes` attribute when `conditional=True`.zSThe generator's `num_classes` attribute must be an integer when `conditional=True`.N)	Úhasattrr   Úcallabler   Ú
ValueErrorÚAttributeErrorÚ
isinstancer   r   )r   r    s     r   Ú_validate_generator_modelr'   2   sÂ   € õ �9˜hÑ'Ô'ð 
Ý!ðBñ
ô 
ð 	
õ �IÔ$Ñ%Ô%ð NÝÐLÑMÔMÐMØð k�7 9¨mÑ<Ô<ð kÝÐiÑjÔjÐjØð p�: iÔ&;½SÑAÔAð pÝÐnÑoÔoÐoðpð pð pð pr   é'  é€   Úlerpç-Cëâ6?é@   ç{®Gáz„?ç®Gáz®ï?r   Ú
batch_sizeÚinterpolation_method©r*   Ú	slerp_anyÚ
slerp_unitÚepsilonÚresizeÚlower_discardÚupper_discardc                 óà  — t          | t          ¦  «        r| dk    st          d| › d�¦  «        ‚t          |t          ¦  «        st          d|› d�¦  «        ‚t          |t          ¦  «        r|dk    st          d|› d�¦  «        ‚|dvrt          d|› d�¦  «        ‚t          |t          ¦  «        r|dk    st          d|› d�¦  «        ‚|�.t          |t          ¦  «        r|dk    st          d
|› d�¦  «        ‚|�7t          |t          ¦  «        rd|cxk    rdk    sn t          d|› d�¦  «        ‚|�7t          |t          ¦  «        rd|cxk    rdk    sn t          d|› d�¦  «        ‚d	S d	S )z.Validate arguments for perceptual path length.r   z;Argument `num_samples` must be a positive integer, but got ú.z2Argument `conditional` must be a boolean, but got z:Argument `batch_size` must be a positive integer, but got r1   zUArgument `interpolation_method` must be one of 'lerp', 'slerp_any', 'slerp_unit',got z5Argument `epsilon` must be a positive float, but got Nz@Argument `resize` must be a positive integer or `None`, but got é   zLArgument `lower_discard` must be a float between 0 and 1 or `None`, but got zLArgument `upper_discard` must be a float between 0 and 1 or `None`, but got )r&   r   r$   ÚboolÚfloat)r   r    r/   r0   r4   r5   r6   r7   s           r   Ú*_perceptual_path_length_validate_argumentsr=   G   sþ  € õ �{¥CÑ(Ô(ð g¨[¸1ª_¨_ÝÐeÐWbÐeÐeÐeÑfÔfÐfÝ�k¥4Ñ(Ô(ð ^ÝÐ\ÈkÐ\Ð\Ð\Ñ]Ô]Ð]Ý�z¥3Ñ'Ô'ð e¨J¸ªN¨NÝÐcÐV`ÐcÐcÐcÑdÔdÐdØÐ#FÐFÐFÝð+Ø'ð+ð +ð +ñ
ô 
ð 	
õ �w¥Ñ&Ô&ð ]¨7°Qª;¨;ÝÐ[ÐQXÐ[Ð[Ð[Ñ\Ô\Ð\ØÐ¥:¨fµcÑ#:Ô#:Ð¸vÈºz¸zÝÐeÐ\bÐeÐeÐeÑfÔfÐfØÐ ­*°]ÅEÑ*JÔ*JÐ ÈqÐTaÐOfÐOfÒOfÐOfÐefÒOfÐOfÐOfÐOfÝØkÐ[hÐkÐkÐkñ
ô 
ð 	
ð Ð ­*°]ÅEÑ*JÔ*JÐ ÈqÐTaÐOfÐOfÒOfÐOfÐefÒOfÐOfÐOfÐOfÝØkÐ[hÐkÐkÐkñ
ô 
ð 	
ð !Ð ÐOfÐOfr   Úlatents1Úlatents2c                 ó  — d}| j         |j         k    rt          d¦  «        ‚|dk    r| || z
  |z  z   S |dk    �rÚ|                      ¦   «         dz
  }| j         d         }| | dz                       dd¬	¦  «                             ¦   «                              |¦  «        z  }||dz                       dd¬	¦  «                             ¦   «                              |¦  «        z  }||z                       dd¬	¦  «        }	|                     dd¬	¦  «        |k     |                     dd¬	¦  «        |k     z  }
|	d|z
  k    |	d|z   k     z  }|
|z                       d
„ t          |¦  «        D ¦   «         |gz   ¦  «        }|	 	                    ¦   «         }| 
                    ¦   «                              |¦  «        }d|z
  |z   
                    ¦   «         |z  }||z   
                    ¦   «         |z  }|| z  ||z  z   }t          | ||d¬¦  «        |         ||<   |S |dk    rUt          | ||d¬¦  «        }||dz                       dd¬	¦  «                             ¦   «                              |¦  «        z  S t          d|› d�¦  «        ‚)a¢  Interpolate between two sets of latents.

    Inspired by: https://github.com/toshas/torch-fidelity/blob/master/torch_fidelity/noise.py

    Args:
        latents1: First set of latents.
        latents2: Second set of latents.
        epsilon: Spacing between the points on the path between latent points.
        interpolation_method: Interpolation method to use. Choose from 'lerp', 'slerp_any', 'slerp_unit'.

    gH¯¼šò×z>z!Latents must have the same shape.r*   r2   r:   éÿÿÿÿé   T)ÚdimÚkeepdimc                 ó   — g | ]}d ‘ŒS )r:   r   )Ú.0Ú_s     r   ú
<listcomp>z _interpolate.<locals>.<listcomp>‰   s   € Ð8QÐ8QÐ8Q¸q¸Ð8QÐ8QÐ8Qr   ©r0   r3   )r>   r?   r4   r0   zInterpolation method z> not supported. Choose from 'lerp', 'slerp_any', 'slerp_unit'.)Úshaper$   rC   ÚsumÚsqrtÚ	clamp_minÚnormÚrepeatÚrangeÚacosÚsinÚ_interpolate)r>   r?   r4   r0   ÚepsÚndimsÚz_sizeÚlatents1_normÚlatents2_normÚdÚ	mask_zeroÚmask_collinearÚ	mask_lerpÚomegaÚdenomÚcoef_latents1Úcoef_latents2Úouts                     r   rS   rS   k   s©  € ð" €CØ„~˜œÒ'Ð'ÝÐ<Ñ=Ô=Ð=Ø˜vÒ%Ð%Ø˜8 hÑ.°'Ñ9Ñ9Ð9Ø˜{Ò*Ñ*Ø—’‘” Ñ"ˆØ” Ô#ˆØ  H¨a¡K×#4Ò#4¸ÀTÐ#4Ñ#JÔ#J×#OÒ#OÑ#QÔ#Q×#[Ò#[Ð\_Ñ#`Ô#`Ñ`ˆØ  H¨a¡K×#4Ò#4¸ÀTÐ#4Ñ#JÔ#J×#OÒ#OÑ#QÔ#Q×#[Ò#[Ð\_Ñ#`Ô#`Ñ`ˆØ˜]Ñ*×/Ò/°BÀÐ/ÑEÔEˆØ"×'Ò'¨B¸Ð'Ñ=Ô=ÀÒCÈ×HZÒHZÐ_aÐkoÐHZÑHpÔHpÐsvÒHvÑwˆ	Ø˜a #™gš+¨!¨b°3©hª,Ñ7ˆØ Ñ/×7Ò7Ð8QÐ8QÅEÈ%ÁLÄLÐ8QÑ8QÔ8QÐU[ÐT\Ñ8\Ñ]Ô]ˆ	Ø—’‘”ˆØ—	’	‘”×%Ò% cÑ*Ô*ˆØ˜g™+¨Ñ.×3Ò3Ñ5Ô5¸Ñ=ˆØ  5™×-Ò-Ñ/Ô/°%Ñ7ˆØ˜hÑ&¨¸Ñ)AÑAˆÝ% h°¸'ÐX^Ð_Ñ_Ô_Ð`iÔjˆˆI‰Øˆ
Ø˜|Ò+Ð+Ý H°xÈÐgrÐsÑsÔsˆØ�c˜1‘f—\’\ b°$�\Ñ7Ô7×<Ò<Ñ>Ô>×HÒHÈÑMÔMÑMÐMÝ
ØtÐ 4ÐtÐtÐtñô ð r   ÚvggÚcpuÚsim_net©Úalexrb   ÚsqueezeÚdevicec           
      óð  — t           st          d¦  «        ‚t          ||||||||¦  «         t          | |¦  «         |                      |
¦  «        } |                      |¦  «                             |
¦  «        }|                      |¦  «                             |
¦  «        }t          ||||¬¦  «        }|r/t          j        d| j	        |f¦  «                             |
¦  «        }t          |	t          j        ¦  «        r|	                     |
¦  «        }n<|	dv r&t          d|	|¬¦  «                             |
¦  «        }nt          d|	› �¦  «        ‚t          j        ¦   «         5  g }t!          j        ||z  ¦  «        }t%          |¦  «        D �]<}|||z  |dz   |z  …                              |
¦  «        }|||z  |dz   |z  …                              |
¦  «        }|r_|||z  |dz   |z  …                              |
¦  «        } | t          j        ||fd¬	¦  «        t          j        ||fd¬	¦  «        ¦  «        }n! | t          j        ||fd¬	¦  «        ¦  «        }|                     d
d¬	¦  «        \  }}d
|dz  z  dz
  }d
|dz  z  dz
  } |||¦  «        }||d
z  z  }|                     |                     ¦   «         ¦  «         �Œ>t          j        |¦  «        }|�t          j        ||d¬¦  «        nd}|�t          j        ||d¬¦  «        nt1          |¦  «        }|||k    ||k    z           }|                     ¦   «         |                     ¦   «         |fcddd¦  «         S # 1 swxY w Y   dS )a  Computes the perceptual path length (`PPL`_) of a generator model.

    The perceptual path length can be used to measure the consistency of interpolation in latent-space models. It is
    defined as

    .. math::
        PPL = \mathbb{E}\left[\frac{1}{\epsilon^2} D(G(I(z_1, z_2, t)), G(I(z_1, z_2, t+\epsilon)))\right]

    where :math:`G` is the generator, :math:`I` is the interpolation function, :math:`D` is a similarity metric,
    :math:`z_1` and :math:`z_2` are two sets of latent points, and :math:`t` is a parameter between 0 and 1. The metric
    thus works by interpolating between two sets of latent points, and measuring the similarity between the generated
    images. The expectation is approximated by sampling :math:`z_1` and :math:`z_2` from the generator, and averaging
    the calculated distanced. The similarity metric :math:`D` is by default the `LPIPS`_ metric, but can be changed by
    setting the `sim_net` argument.

    The provided generator model must have a `sample` method with signature `sample(num_samples: int) -> Tensor` where
    the returned tensor has shape `(num_samples, z_size)`. If the generator is conditional, it must also have a
    `num_classes` attribute. The `forward` method of the generator must have signature `forward(z: Tensor) -> Tensor`
    if `conditional=False`, and `forward(z: Tensor, labels: Tensor) -> Tensor` if `conditional=True`. The returned
    tensor should have shape `(num_samples, C, H, W)` and be scaled to the range [0, 255].

    Args:
        generator: Generator model, with specific requirements. See above.
        num_samples: Number of samples to use for the PPL computation.
        conditional: Whether the generator is conditional or not (i.e. whether it takes labels as input).
        batch_size: Batch size to use for the PPL computation.
        interpolation_method: Interpolation method to use. Choose from 'lerp', 'slerp_any', 'slerp_unit'.
        epsilon: Spacing between the points on the path between latent points.
        resize: Resize images to this size before computing the similarity between generated images.
        lower_discard: Lower quantile to discard from the distances, before computing the mean and standard deviation.
        upper_discard: Upper quantile to discard from the distances, before computing the mean and standard deviation.
        sim_net: Similarity network to use. Can be a `nn.Module` or one of 'alex', 'vgg', 'squeeze', where the three
            latter options correspond to the pretrained networks from the `LPIPS`_ paper.
        device: Device to use for the computation.

    Returns:
        A tuple containing the mean, standard deviation and all distances.

    Example::
        >>> import torch
        >>> from torchmetrics.functional.image import perceptual_path_length
        >>> class DummyGenerator(torch.nn.Module):
        ...    def __init__(self, z_size) -> None:
        ...       super().__init__()
        ...       self.z_size = z_size
        ...       self.model = torch.nn.Sequential(torch.nn.Linear(z_size, 3*128*128), torch.nn.Sigmoid())
        ...    def forward(self, z):
        ...       return 255 * (self.model(z).reshape(-1, 3, 128, 128) + 1)
        ...    def sample(self, num_samples):
        ...      return torch.randn(num_samples, self.z_size)
        >>> generator = DummyGenerator(2)
        >>> perceptual_path_length(generator, num_samples=10)  # doctest: +SKIP
        (tensor(0.1945),
        tensor(0.1222),
        tensor([0.0990, 0.4173, 0.1628, 0.3573, 0.1875, 0.0335, 0.1095, 0.1887, 0.1953]))

    z—Metric `perceptual_path_length` requires torchvision which is not installed.Install with `pip install torchvision` or `pip install torchmetrics[image]`rI   r   re   T)Ú
pretrainedÚnetr5   zDsim_net must be a nn.Module or one of 'alex', 'vgg', 'squeeze', got r:   )rC   rB   éÿ   NÚlower)Úinterpolationg        )r	   ÚModuleNotFoundErrorr=   r'   Útor   rS   ÚtorchÚrandintr   r&   r   ÚModuler   r$   Úinference_modeÚmathÚceilrP   ÚcatÚchunkÚappendÚdetachÚquantileÚmaxÚmeanÚstd)r   r   r    r/   r0   r4   r5   r6   r7   rd   rh   Úlatent1Úlatent2Úlabelsrk   Ú	distancesÚnum_batchesÚ	batch_idxÚbatch_latent1Úbatch_latent2Úbatch_labelsÚoutputsÚout1Úout2Úout1_rescaleÚout2_rescaleÚ
similarityÚdistrm   Úuppers                                 r   r
   r
   ™   s  € õL "ð 
Ý!ðZñ
ô 
ð 	
õ /Ø�[ *Ð.BÀGÈVÐUbÐdqñô ð õ ˜i¨Ñ5Ô5Ð5Ø—’˜VÑ$Ô$€Ià×Ò˜{Ñ+Ô+×.Ò.¨vÑ6Ô6€GØ×Ò˜{Ñ+Ô+×.Ò.¨vÑ6Ô6€GÝ˜7 G¨WÐK_Ð`Ñ`Ô`€Gàð TÝ”˜q )Ô"7¸+¸ÑHÔH×KÒKÈFÑSÔSˆå�'�2œ9Ñ%Ô%ð kØ�jŠj˜Ñ Ô ˆˆØ	Ð.Ð	.Ð	.Ý ¨'¸&ÐAÑAÔA×DÒDÀVÑLÔLˆˆåÐiÐ`gÐiÐiÑjÔjÐjå	Ô	Ñ	Ô	ð #<ð #<Øˆ	Ý”i ¨jÑ 8Ñ9Ô9ˆÝ˜{Ñ+Ô+ð 	,ñ 	,ˆIØ# I°
Ñ$:¸iÈ!¹mÈzÑ=YÐ$YÔZ×]Ò]Ð^dÑeÔeˆMØ# I°
Ñ$:¸iÈ!¹mÈzÑ=YÐ$YÔZ×]Ò]Ð^dÑeÔeˆMàð VØ% i°*Ñ&<À	ÈAÁÐQ[Ñ?[Ð&[Ô\×_Ò_Ð`fÑgÔg�Ø#˜)Ý”I˜}¨mÐ<À!ÐDÑDÔDÅeÄiÐQ]Ð_kÐPlÐrsÐFtÑFtÔFtñô ��ð $˜)¥E¤I¨}¸mÐ.LÐRSÐ$TÑ$TÔ$TÑUÔU�à Ÿš q¨a˜Ñ0Ô0‰JˆD�$ð   s¡
Ñ+¨aÑ/ˆLØ  s¡
Ñ+¨aÑ/ˆLà˜˜\¨<Ñ8Ô8ˆJØ ¨¡
Ñ*ˆDØ×Ò˜TŸ[š[™]œ]Ñ+Ô+Ð+Ñ+å”I˜iÑ(Ô(ˆ	àS`ÐSl•”˜y¨-ÀwÐOÑOÔOÐOÐruˆð Ð(õ ŒN˜9 mÀ7ÐKÑKÔKÐKå�Y‘”ð 	ð
 ˜y¨EÒ1°iÀ5Ò6HÑIÔJˆ	à�~Š~ÑÔ §¢¡¤°)Ð;ðG#<ð #<ð #<ð #<ñ #<ô #<ð #<ð #<ð #<ð #<ð #<ð #<øøøð #<ð #<ð #<ð #<ð #<ð #<s   Å%G9M+Í+M/Í2M/)F)r(   Fr)   r*   r+   r,   r-   r.   )r+   r*   )
r(   Fr,   r*   r+   r,   r-   r.   rb   rc   )ru   Útypingr   r   r   rq   r   r   Ú#torchmetrics.functional.image.lpipsr   Útorchmetrics.utilities.importsr	   Ú__doctest_skip__rs   r   r;   r'   r   r<   r=   rS   Ústrrh   Útupler
   r   r   r   ú<module>r–      sß  ðð €€€Ø +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +Ð +à €€€Ø Ð Ð Ð Ð Ð Ð Ð à 6Ð 6Ð 6Ð 6Ð 6Ð 6Ø AÐ AÐ AÐ AÐ AÐ Aàð 2Ø0Ð1Ðð"ð "ð "ð "ð "�B”Iñ "ô "ð "ð.pð p¨ð pÀTð pÐVZð pð pð pð pð, ØØØGMØØØ%)Ø%)ð!
ð !
Øð!
àð!
ð ð!
ð "Ð"CÔDð	!
ð
 ð!
ð �SŒMð!
ð ˜E”?ð!
ð ˜E”?ð!
ð 
ð!
ð !
ð !
ð !
ðN ØGMð	+ð +Øð+àð+ð ð+ð "Ð"CÔDð	+ð
 ð+ð +ð +ð +ð` ØØØGMØØØ%)Ø%)ØCHØ',ðB<ð B<ØðB<àðB<ð ðB<ð ð	B<ð
 "Ð"CÔDðB<ð ðB<ð �SŒMðB<ð ˜E”?ðB<ð ˜E”?ðB<ð �2”9˜gÐ&>Ô?Ð?Ô@ðB<ð �#�u”|Ð#Ô$ðB<ð ˆ6�6˜6Ð!Ô"ðB<ð B<ð B<ð B<ð B<ð B<r   