+
    åûjví  ã                  óÆ  € ^ RI Ht ^ RIHtHt ^ RIHt ^ RIt^ RIH	t	H
t
Ht ^ RIHt RtR7R	 R
 lltR7R R lltR7R R llt ! R R]4      tR R ltR R ltR R ltR8R R lltR R ltR8R R llt ! R R]P2                  P4                  4      t ! R R ]4      t ! R! R"]4      t ! R# R$]4      t ! R% R&]4      t ! R' R(]4      t  ! R) R*]4      t!RR]PD                  ^@R3R+ R, llt#RR]PD                  ^@R3R- R. llt$RR]PD                  ^@R3R/ R0 llt%RR]PD                  ^@R3R1 R2 llt&RR]PD                  ^@R3R3 R4 llt'RR]PD                  ^@R3R5 R6 llt(R# )9é    )Úannotations)ÚEnumÚmember)ÚpartialN)ÚKORNIA_CHECKÚKORNIA_CHECK_IS_TENSORÚKORNIA_CHECK_SAME_SHAPE)Úis_exportingi @  ç      ð?c               ó$   € V ^8„  d   QhRRRRRR/# ©é   Úxútorch.TensorÚwindow_radiusÚfloatÚreturn© )Úformats   "Ú\C:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\losses\mutual_information.pyÚ__annotate__r   %   s!   € ÷ ñ �ð ¨eð ¸lñ ó    c                ó„  € V P                  4       P                  RV,          4      pVR	V,          R,
          ,          R,           pVRV,          R,
          ,          R,           p\        P                  ! VR8  V\        P                  ! VR8*  V\        P                  ! RV P
                  V P                  R7      4      4      # )
a¢  Implementation of a 2nd-order polynomial kernel for Kernel density estimate (Xu et al., 2008).

Support: [-window_radius, window_radius]. Returns 0 outside this range.
Ref: "Parzen-Window Based Normalized Mutual Information for Medical Image Registration", Eq. 22.

Args:
    x (torch.Tensor): signal, any shape
    window_radius (float): radius of window for the kernel

Returns:
    torch.Tensor: transformed signal
r   gÍÌÌÌÌÌü?gš™™™™™¹?gš™™™™™@gffffffþ?ç      à?ç        )ÚdeviceÚdtypegÍÌÌÌÌÌü¿)ÚabsÚmulÚtorchÚwhereÚtensorr   r   )r   r   Úx_absÚpoly1Úpoly2s   &&   r   Ú	xu_kernelr&   %   s•   € ð �E‰E‹G�K‰K˜˜mÕ+Ó,€Eà�T˜E•\ CÕ'Õ(¨3Õ.€EØ�S˜5•[ 3Õ&Õ'¨#Õ-€Eä�;Š;Ø�‰�UœEŸKšK¨°©°e¼U¿\º\È#ÐVW×V^ÑV^Ðfg×fmÑfmÔ=nÓoóð r   c               ó$   € V ^8„  d   QhRRRRRR/# r   r   )r   s   "r   r   r   <   s!   € ÷ ,ñ ,˜,ð ,°uð ,À|ñ ,r   c                óh   € \         P                  ! V 4      p W8*  P                  V P                  4      # )a  Implementation of a rectangular kernel.

Support: [-window_radius, window_radius]. Returns 1.0 inside this range, 0.0 otherwise.

Args:
    x (torch.Tensor): signal, any shape
    window_radius (float): radius of window for the kernel

Returns:
    torch.Tensor: transformed signal
)r    r   Útor   )r   r   s   &&r   Úrectangular_kernelr*   <   s)   € ô 	�	Š	�!‹€AØÑ×"Ñ" 1§7¡7Ó+Ð+r   c               ó$   € V ^8„  d   QhRRRRRR/# r   r   )r   s   "r   r   r   L   s!   € ÷ 0ñ 0 ð 0¸eð 0Èlñ 0r   c                ó  € Tp\         P                  ! V 4      V8*  p\         P                  ! RW,          ^,          ,          4      V^\         P                  ,          R,          ,          ,          p\         P                  ! W4R4      # )a[  Implementation of a truncated Gaussian kernel.

Support: [-window_radius, window_radius]. Returns Gaussian value inside this range, 0.0 otherwise.
Sigma is set to window_radius.

Args:
    x (torch.Tensor): signal, any shape
    window_radius (float): radius of window for the kernel (used as sigma)

Returns:
    torch.Tensor: transformed signal
r   r   g      à¿)r    r   ÚexpÚpir!   )r   r   ÚsigmaÚmaskÚgaussian_vals   &&   r   Útruncated_gaussian_kernelr2   L   s^   € ð €EÜ�9Š9�Q‹<˜=Ñ(€Dä—9’9˜T Q¥Y°1Õ$4Õ4Ó5¸À!ÄeÇhÁhÅ,ÐSVÕAVÕ9VÕW€Lä�;Š;�t¨3Ó/Ð/r   c                  óJ   € ] tR t^atRt]! ]4      t]! ]4      t	]! ]
4      tRtR# )ÚMIKernelaï  Choose the kernel that spreads a sample over the histogram bins of the mutual-information losses.

Pass a member as the ``kernel_function`` of a mutual-information loss. The members are not callable: a member's
``value`` is the kernel ``f(d, window_radius=1.0)``, the weight that a sample at distance ``d`` from a bin centre,
in bin widths, gives that bin.

Convention:
    - Every kernel is 0 outside ``|d| <= window_radius``. With ``u = |d| / window_radius``:

      - ``xu`` (Xu et al., 2008), the default: :math:`1 - 0.1 u - 1.8 u^2` for :math:`u < 0.5` and
        :math:`1.9 - 3.7 u + 1.8 u^2` up to :math:`u = 1`. At ``window_radius=1`` the weights of a sample
        between the first and the last bin centre sum to 1.
      - ``rectangular``: 1 on the closed support, so a sample counts fully in every bin within
        ``window_radius``. Its loss has no gradient (evaluation only, see
        :func:`~kornia.losses.mutual_information_loss`).
      - ``truncated_gaussian``: the normal density with standard deviation ``window_radius``, cut at one
        standard deviation.

See Also:
    - :func:`~kornia.losses.mutual_information_loss`: takes a member as ``kernel_function``, as do the other
      mutual-information losses and their module forms.
r   N)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r   r&   Úxur*   Úrectangularr2   Útruncated_gaussianÚ__static_attributes__r   r   r   r4   r4   a   s*   † ññ. 
�	Ó	€BÙÐ+Ó,€KÙÐ 9Ó:Ôr   r4   c               ó$   € V ^8„  d   QhRRRRRR/# )r   r0   útorch.Tensor | NoneÚshapeú
torch.Sizer   ÚNoner   )r   s   "r   r   r   ~   s"   € ÷ 
ñ 
Ð,ð 
°Zð 
ÀDñ 
r   c                óì   € V ep   \        V R4       \        V P                  \        P                  \        P
                  39   R4       \        V P                  V8H  RV RV P                   R24       R # R # )Nz&mask must be a boolean tensor or None.z3mask must have boolean dtype (torch.bool or uint8).z mask must have one-sample shape z, common to the batch. Got Ú.)r   r   r   r    ÚboolÚuint8r@   ©r0   r@   s   &&r   Ú_validate_maskrH   ~   si   € ØÒÜ˜tÐ%MÔNÜ�T—Z‘Z¤E§J¡J´·±Ð#<Ñ<Ð>sÔtÜØ�J‰J˜%ÑØ.¨u¨gÐ5PÐQU×Q[ÑQ[ÐP\Ð\]Ð^ö	
ñ r   c               ó$   € V ^8„  d   QhRRRRRR/# )r   r0   r?   r@   rA   r   r   )r   s   "r   r   r   ˆ   s#   € ÷ 6ñ 6Ð+ð 6°Jð 6ÐCVñ 6r   c                óF   € \        W4       V f   R # V P                  R4      # )Néÿÿÿÿ)rH   ÚreshaperG   s   &&r   Ú_flatten_maskrM   ˆ   s"   € Ü�4ÔØ’<ˆ4Ð5 T§\¡\°"Ó%5Ð5r   c               ó    € V ^8„  d   QhRRRR/# )r   r0   r?   r   rE   r   )r   s   "r   r   r   �   s   € ÷ 
>ñ 
>Ð+ð 
>°ñ 
>r   c                ó”   € V f   R# V P                  4       ^8w  d   R# \        4       '       d   R# \        V P                  R4      4      # )a  Whether ``mask`` selects everything: ``None`` or ``True`` for a one-element signal.

A one-element mask is decided structurally under graph capture (a single ``False`` would mask
the whole signal, which is never meaningful), so exported graphs carry no data-dependent gather.
TFr   )Únumelr
   rE   rL   )r0   s   &r   Ú_mask_is_fullrQ   �   s<   € ð ‚|ÙØ‡z�zƒ|�qÔÙÜ—>’>ˆ4Ð=¤t¨D¯L©L¸Ó,<Ó'=Ð=r   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   Údatar   Únum_binsÚintÚepsr   r   r   )r   s   "r   r   r   š   s.   € ÷ 	cñ 	c˜Lð 	c°Cð 	c¸eð 	cÈ|ñ 	cr   c                ób  € V P                  RR7      w  r4V P                  RR7      w  rTWS,
          P                  R4      pWb8„  p\        P                  ! Wv\        P
                  ! V4      4      p\        P                  ! WpVP                  R4      ,
          V,          V^,
          ,          ^ 4      # )é   ©ÚdimrK   )ÚminÚmaxÚ	unsqueezer    r!   Ú	ones_like)	rS   rT   rV   Úmin_valÚ_Úmax_valÚdiffÚ
nontrivialÚ	safe_diffs	   &&&      r   Ú_normalize_signalre   š   sŽ   € Ø—‘˜b�Ó!�J€GØ—‘˜b�Ó!�J€GØÕ×(Ñ(¨Ó,€Dð ‘€JÜ—’˜J¬e¯oªo¸dÓ.CÓD€IÜ�;Š;�z¨7×+<Ñ+<¸RÓ+@Õ$@ÀIÕ#MÐQYÐ\]ÕQ]Õ#^Ð`aÓbÐbr   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   Úvals_1r   Úvals_2Ú
chunk_sizerU   r   r   )r   s   "r   r   r   ¦   s*   € ÷ ñ ¨ð ¸lð ÐX[ð Ð`lñ r   c                óö   € \        V P                  VRR7      VP                  VRR7      4      p\        P                  ! R.\	        V4      O5!  pV F#  w  rVV\        P                  ! RWV4      ,           pK%  	  V# )znReturn ``einsum("...in,...jn->...ij", vals_1, vals_2)``, contracting at most ``chunk_size`` samples at a time.rY   ú...in,...jn->...ijrK   )ÚzipÚsplitr    ÚeinsumÚnext)rg   rh   ri   ÚchunksÚjoint_histogramÚchunk_1Úchunk_2s   &&&    r   Ú_contract_kernels_in_chunksrt   ¦   sl   € ô �—‘˜j¨b�Ó1°6·<±<À
ÐPR°<Ó3SÓT€FÜ—l’lÐ#7ÐG¼$¸v»,ÓG€OÛ"ÑˆØ)¬E¯LªLÐ9MÈwÓ,`Õ`Šñ #àÐr   c               ó$   € V ^8„  d   QhRRRRRR/# )r   rq   r   rV   r   r   r   )r   s   "r   r   r   °   s"   € ÷ ñ °<ð Àeð ÐWcñ r   c                óâ  € T pVP                  V4      pW"P                  RRR7      ,          pVP                  RR7      pVP                  RR7      p\        P                  ! V) \        P                  ! V4      ,          RR7      p\        P                  ! V) \        P                  ! V4      ,          RR7      p\        P                  ! V) \        P                  ! V4      ,          RR7      pWgV3# )rX   T)rZ   ÚkeepdimrY   rK   éþÿÿÿ)rK   rx   )ÚclampÚsumr    Úlog)rq   rV   ÚP_xyÚP_xÚP_yÚH_xyÚH_xÚH_ys   &&      r   Ú_joint_histogram_to_entropiesr‚   °   s°   € Ø€Dà�:‰:�c‹?€Dà�H‰H˜¨4ˆHÓ0Õ0€Dà
�(‰(�rˆ(Ó
€CØ
�(‰(�rˆ(Ó
€CÜ�9Š9�d�UœUŸYšY t›_Õ,°(Ô;€DÜ
�)Š)�S�Dœ5Ÿ9š9 S›>Õ)¨rÔ
2€CÜ
�)Š)�S�Dœ5Ÿ9š9 S›>Õ)¨rÔ
2€Cà�Tˆ>Ðr   c                  ó¤   a € ] tR t^ÀtRtR]P                  ^@R3R V 3R lllt]R R l4       t	]
R R	 l4       tR
 tRR R lltRR R lltRtV ;t# )ÚEntropyBasedLossBaseac  A base class for entropy-based loss functions using kernel density estimation.

This class provides the foundation for computing entropy-based losses between signals
by estimating probability distributions using kernel density estimation (KDE). It
computes joint histograms and derives entropy measures that can be used to quantify
the similarity or dissimilarity between signals.

The class pre-processes a reference signal and provides methods to compute joint
histograms with other signals, from which various entropy measures (joint, marginal,
conditional, mutual information) can be derived in subclasses.
Nr   c               ó0   € V ^8„  d   QhRRRRRRRRR	R
RR/# ©r   Úreference_signalr   r0   r?   Úkernel_functionr4   rT   rU   r   r   r   rB   r   )r   s   "r   r   Ú!EntropyBasedLossBase.__annotate__Í   sN   € ÷ 8vñ 8và&ð8vð "ð8vð "ð	8vð
 ð8vð ð8vð 
ñ8vr   c                ó  <€ \         SV `  4        \        \        V\        4      ;'       d#    \        V\
        4      '       * ;'       d    V^8¬  R4       \        V^ 8„  R4       \        VP                  R,          ^ 8„  R4       \        V\        4      '       g   \        R\        \        4       R24      h\        W!P                  RR 4       \        V4      V n        V P                  W!4      p\        P                  ! VP                   4      P"                  pV P%                  RVP'                  ^ 4      RR	7       VP                  V n        V P                  '       d   TM
VR
V3,          p\        V P                  ;'       g    VP                  R,          ^ 8„  R4       VP                   \        P*                  \        P,                  39   d   VP/                  4       pV P%                  R\1        WtV4      4       V P%                  RVP3                  4       4       W@n        \7        VP8                  VR7      V n        WPn        V P%                  R\        P>                  ! V P4                  V P@                  PB                  R7      RR	7       R# )a  Initialize the entropy-based loss base module.

Args:
    reference_signal (torch.Tensor): reference signal to which
        other signals will be compared by the forward method
    mask (torch.Tensor | None): mask of roi in reference_signal, by default None
        boolean with shape (N,), equal to reference_signal.shape[-1:]. It is common to all the samples
        in reference_signal.
    kernel_function (MIKernel): Used kernel function for kernel
        density estimate, by default MIKernel.xu
    num_bins (int): number of signal value bins in kernel
        density estimate, by default 64
    window_radius (float): radius of the kernel's support
        interval, by default 1.0

Raises:
    ValueError: If kernel_function is not a valid MIKernel member.
z!num_bins must be an integer >= 2.zwindow_radius must be > 0.z&signals must have at least one sample.zEkernel_function must be a MIKernel member, the available options are rD   NÚ_reference_dtypeF)Ú
persistent.z%mask must select at least one sample.Úsignalr0   )r   Úbin_centers)r   rK   )"ÚsuperÚ__init__r   Ú
isinstancerU   rE   r@   r4   Ú
ValueErrorÚlistrH   rQ   Ú_ref_mask_is_fullÚfix_maskr    Úfinfor   rV   Úregister_bufferÚ	new_emptyÚinitial_shapeÚfloat16Úbfloat16r   re   ÚclonerT   r   Úvaluerˆ   r   Úaranger�   r   )	Úselfr‡   r0   rˆ   rT   r   rV   r�   Ú	__class__s	   &&&&&&  €r   r�   ÚEntropyBasedLossBase.__init__Í   s  ø€ ô4 	‰ÑÔÜÜ�x¤Ó%×ZÐZ¬j¸Ä4Ó.HÔ*H×ZÐZÈXÐYZÉ]Ø/ô	
ô 	�] QÑ&Ð(DÔEÜÐ%×+Ñ+¨BÕ/°!Ñ3Ð5]Ô^Ü˜/¬8×4Ò4ÜÐdÔeiÔjrÓesÐdtÐtuÐvÓwÐwÜ�t×3Ñ3°B°CÐ8Ô9Ü!.¨tÓ!4ˆÔØ�}‰}˜TÓ4ˆÜ�kŠkÐ*×0Ñ0Ó1×5Ñ5ˆð 	×ÑÐ/Ð1A×1KÑ1KÈAÓ1NÐ[`ÐÔaØ-×3Ñ3ˆÔð &*×%;×%;Ð%;Ñ!ÐAQÐRUÐW[ÐR[ÕA\ˆÜ�T×+Ñ+×CÐC¨v¯|©|¸BÕ/?À!Ñ/CÐElÔmØ�<‰<œEŸM™M¬5¯>©>Ð:Ô:Ø—\‘\“^ˆFØ×Ñ˜XÔ'8¸È3Ó'OÔPà×Ñ˜V T§Z¡Z£\Ô2Ø ŒÜ& ×'<Ñ'<ÈMÔZˆÔØ*Ôà×Ñ˜]¬E¯LªL¸¿¹ÈtÏ{É{×OaÑOaÔ,bÐotÐÖur   c               ó   € V ^8„  d   QhRR/# )r   r   r   r   )r   s   "r   r   r‰     s   € ÷ <ñ <�Uñ <r   c                ój   € \         P                  ! V P                  P                  4      P                  # )zPMachine epsilon of the reference dtype, so that it follows ``Module.to(dtype)``.)r    r–   r‹   r   rV   )rŸ   s   &r   rV   ÚEntropyBasedLossBase.eps  s%   € ô �{Š{˜4×0Ñ0×6Ñ6Ó7×;Ñ;Ð;r   c               ó$   € V ^8„  d   QhRRRRRR/# )r   r0   r   Ú
masked_guyr   r   )r   s   "r   r   r‰     s!   € ÷ 6ñ 6�|ð 6°ð 6À,ñ 6r   c                ó  € \        WP                  RR 4       V fC   \        P                  ! VP                  R,          \        P                  VP
                  R7      # V P                  VP
                  \        P                  4      # )zÎConvert mask to correct full mask if it is None.

Args:
    mask (torch.Tensor | None): input mask
    masked_guy (torch.Tensor): the tensor to be masked by mask

Returns:
    torch.Tensor: normalized mask
N)r   r   rK   )rH   r@   r    ÚonesrE   r   r)   )r0   r¦   s   &&r   r•   ÚEntropyBasedLossBase.fix_mask  sa   € ô 	�t×-Ñ-¨b¨cÐ2Ô3ØŠ<Ü—:’:˜j×.Ñ.¨rÕ2¼%¿*¹*ÈZ×M^ÑM^Ô_Ð_Ø�w‰w�z×(Ñ(¬%¯*©*Ó5Ð5r   c                óì   € VP                  4       '       d   VRV P                  3,          # \        P                  ! V P                  4      P                  V4      pWRV3&   VRV P                  3,          # )a|  Align another masked signal with the reference mask positions.

The reference signal can be stored with a mask, while the compared
signal may use a different mask over the same flattened coordinate
space. This helper restores the compared signal to the original flat
shape when needed, then selects the elements that correspond to the
stored reference mask.

Args:
    other_signal: Flattened signal values after applying ``other_mask``.
    other_mask: Boolean mask describing which flattened positions are
        present in ``other_signal``.

Returns:
    Signal values traced onto the reference mask used by this loss
    instance.
.)Úallr0   r    Úzerosr™   r)   )rŸ   Úother_signalÚ
other_maskÚintermediates   &&& r   Útrace_in_ref_maskÚ&EntropyBasedLossBase.trace_in_ref_mask  sb   € ð$ �>‰>×ÒØ  T§Y¡Y Õ/Ð/ä—{’{ 4×#5Ñ#5Ó6×9Ñ9¸,ÓGˆØ(4�S˜*�_Ñ%Ø˜C §¡˜NÕ+Ð+r   c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   r­   r   rV   r   r®   r?   r   r   )r   s   "r   r   r‰   6  s2   € ÷ =Fñ =FØ(ð=FØ/4ð=FØBUð=Fà	ñ=Fr   c                ó  € VP                   V P                  8w  d'   \        RVP                    RV P                   R24      h\        W1P                   RR 4       VP                  \
        P                  \
        P                  39   d   VP                  4       pV P                  '       d6   \        V4      '       d%   V P                  p\        WP                  VR7      pM–V P                  W14      pW0P                  ,          pV P                  RV3,          p\!        VP                   R,          ^ 8„  R4       VRV3,          p\        WP                  VR7      pV P#                  W4      pVRV3,          pVP                  \
        P                  \
        P                  39   d!   VP                  4       pVP                  4       pV P$                  P'                  R4      VP'                  R4      ,
          pV P$                  P'                  R4      VP'                  R4      ,
          pV P)                  V4      pV P)                  V4      p	\
        P*                  ! VP,                  P.                  RR	7      ;_uu_ 4        VP,                  P.                  R
8X  d7   VP                   R,          \0        8”  d   \3        W‰\0        4      uuRRR4       # \
        P4                  ! RW‰4      uuRRR4       #   + '       g   i     R# ; i)aš  Compute the joint histogram between the reference signal and another signal.

Uses kernel density estimation to estimate the joint probability distribution
between the reference signal and the provided other signal. The histogram is
computed by evaluating kernel functions at discretized signal values.

Args:
    other_signal (torch.Tensor): Signal to compare with the reference signal.
        Must have the same shape as the reference signal.
    eps (float): Epsilon value for numerical stability in computations.
    other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to None

Returns:
    torch.Tensor: Joint histogram tensor with shape [..., num_bins, num_bins]
        representing the estimated joint probability distribution of the passed signals in the intersection
        of rois.

Raises:
    ValueError: If other_signal has incompatible shape with reference signal.
z*The two signals have incompatible shapes: ú and rD   N)rT   rV   .z2mask intersection must select at least one sample.F)Údevice_typeÚenabledÚmpsrk   rK   rx   )r@   r™   r’   rH   r   r    rš   r›   r   r”   rQ   r�   re   rT   r•   r0   r   r°   rŽ   r]   rˆ   Úautocastr   ÚtypeÚ_MPS_MAX_CONTRACTED_SAMPLESrt   rn   )
rŸ   r­   rV   r®   Ú
ref_signalÚcommon_maskÚdiff_1Údiff_2rg   rh   s
   &&&&      r   Ú_compute_joint_histogramÚ-EntropyBasedLossBase._compute_joint_histogram6  sb  € ð. ×Ñ ×!3Ñ!3Ô3ÜØ<¸\×=OÑ=OÐ<PÐPUÐVZ×VhÑVhÐUiÐijÐkóð ô 	�z×#5Ñ#5°b°cÐ#:Ô;Ø×Ñ¤%§-¡-´·±Ð!@Ô@Ø'×-Ñ-Ó/ˆLØ×!×!Ð!¤m°J×&?Ò&?ð Ÿ™ˆJÜ,¨\ÇMÁMÐWZÔ[‰Lð Ÿ™ zÓ@ˆJØ$§Y¡YÕ/ˆKØŸ™ S¨+Ð%5Õ6ˆJÜ˜×)Ñ)¨"Õ-°Ñ1Ð3gÔhØ'¨¨Z¨Õ8ˆLÜ,¨\ÇMÁMÐWZÔ[ˆLØ×1Ñ1°,ÓKˆLØ'¨¨[Ð(8Õ9ˆLð ×Ñ¤§¡¬u¯~©~Ð>Ô>Ø#×)Ñ)Ó+ˆJØ'×-Ñ-Ó/ˆLØ×!Ñ!×+Ñ+¨BÓ/°*×2FÑ2FÀrÓ2JÕJˆØ×!Ñ!×+Ñ+¨BÓ/°,×2HÑ2HÈÓ2LÕLˆà×%Ñ% fÓ-ˆØ×%Ñ% fÓ-ˆô �^Š^¨×(;Ñ(;×(@Ñ(@È%×PÖPØ×"Ñ"×'Ñ'¨5Ô0°\×5GÑ5GÈÕ5KÔNiÔ5iÜ2°6ÔC^Ó_÷ QÒPô —<’<Ð 4°fÓE÷ Q×P×PÓPús   É=AK0ËK0Ë0L	c               ó$   € V ^8„  d   QhRRRRRR/# )r   r­   r   r®   r?   r   z/tuple[torch.Tensor, torch.Tensor, torch.Tensor]r   )r   s   "r   r   r‰   u  s)   € ÷ jñ jØ(ðjØ6Iðjà	8ñjr   c                ó¤   € V P                  WP                  V4      p\        V\        P                  ! VP
                  4      P                  R7      # )a'  Compute entropy measures between the reference signal and another signal.

Calculates joint entropy and marginal entropies based on the joint histogram of the two signals.

Args:
    other_signal (torch.Tensor): Signal to compare with the reference signal.
        Must have the same shape as the reference_signal passed at instantiation.
    other_mask (torch.Tensor): common mask of roi for all the samples in other_signal, defaults to None

Returns:
    tuple[torch.Tensor, torch.Tensor, torch.Tensor]: A tuple containing the entropies of the joint
    histogram's marginals and of the histogram itself, in this order:
        - Marginal entropy of other_signal
        - Marginal entropy of the reference signal
        - Joint entropy

    All tensors have the same batch dimensions as the input signals. Half-precision inputs produce
    float32 entropies; the loss subclasses cast their final result back to the reference dtype.

Note:
    Subclasses should implement specific loss functions based on these entropy
    measures (e.g., mutual information).
)rV   )r¿   rV   r‚   r    r–   r   )rŸ   r­   r®   rq   s   &&& r   Ú	entropiesÚEntropyBasedLossBase.entropiesu  s=   € ð4 ×7Ñ7¸ÇhÁhÐPZÓ[ˆÜ,¨_Ä%Ç+Â+Èo×NcÑNcÓBd×BhÑBhÔiÐir   )r”   r™   rˆ   rT   r   ©N)r5   r6   r7   r8   r9   r4   r:   r�   ÚpropertyrV   Ústaticmethodr•   r°   r¿   rÃ   r=   Ú__classcell__©r    s   @r   r„   r„   À   sg   ø† ñ
ð %)Ø$,§K¡KØØ"÷8vò 8vðt ô<ó ð<ð ô6ó ð6ò ,÷2=F÷~jõ jr   r„   c                  ó*   € ] tR tRtRtRR R lltRtR# )ÚMILossFromRefi“  a™  Compute the mutual-information loss of signals ``(*, N)`` against a reference (module form).

``criterion = MILossFromRef(reference_signal, mask)`` stores the reference. ``loss = criterion(other_signal)`` is
:func:`~kornia.losses.mutual_information_loss` with ``input=other_signal`` and ``target=reference_signal``.

Convention:
    - See the Convention block of :func:`~kornia.losses.mutual_information_loss`.
    - At construction the reference is restricted to its mask, min-max normalised and stored as the buffer
      ``signal``, next to a copy of the mask as the buffer ``mask``; later in-place changes to the reference
      tensor or to the mask tensor are not seen. The cache is not detached: a reference that requires grad
      receives a gradient from the first backward pass, and a second backward pass through the same module
      raises. Half-precision references are normalised and cached in float32. The final loss and constant-signal
      threshold follow the original reference dtype, including after ``.to(dtype)``; converting the cache
      itself to a lower precision can round its stored bin positions.

Args:
    reference_signal: reference signals ``(*, N)``.
    mask: boolean region of interest ``(N,)`` of the reference, common to the batch; ``None`` keeps
      every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Shape:
    - other_signal: signals with the shape of ``reference_signal``.
    - other_mask: boolean region of interest ``(N,)`` of ``other_signal``, or ``None``.
    - Output: the loss per leading index, in the dtype of the reference.

See Also:
    - :func:`~kornia.losses.mutual_information_loss`: the one-call form.
    - :class:`~kornia.losses.NMILossFromRef`: Studholme's normalization, in ``[-2, -1]``.
    - :class:`~kornia.losses.MILossFromRef2D`: the same loss for images ``(*, H, W)``.
    - :class:`~kornia.losses.MILossFromRef3D`: the same loss for volumes ``(*, D, H, W)``.

Example:
    >>> reference = torch.rand(2, 64)
    >>> criterion = MILossFromRef(reference)
    >>> loss = criterion(torch.rand(2, 64))

Nc               ó$   € V ^8„  d   QhRRRRRR/# ©r   r­   r   r®   r?   r   r   )r   s   "r   r   ÚMILossFromRef.__annotate__½  s#   € ÷ 5ñ 5 Lð 5Ð>Qð 5Ð]iñ 5r   c                ó”   € V P                  W4      w  r4pW4,           V,
          pV) P                  V P                  P                  4      # )aA  Compute the mutual-information loss of other_signal against the stored reference.

mi = (H(X) + H(Y) - H(X,Y))
To have a loss function, the opposite is returned.
Can also handle two batches of flat tensors, then a batch of loss values is returned.

Args:
    other_signal: Batch of flat tensors shape (B,N) where B is
        the tuple of batch dimensions for self.signal, possibly empty.
    other_mask (torch.Tensor): common boolean (N,) mask of roi for all the samples in other_signal, defaults
        to None

Returns:
    torch.Tensor: tensor of losses, shape B as above
©rÃ   r)   r‹   r   )rŸ   r­   r®   r€   r�   r   Úmis   &&&    r   ÚforwardÚMILossFromRef.forward½  s?   € ð  Ÿ™¨ÓA‰ˆ�$Ø�Y˜Õˆà��x‰x˜×-Ñ-×3Ñ3Ó4Ð4r   r   rÅ   ©r5   r6   r7   r8   r9   rÒ   r=   r   r   r   rË   rË   “  s   † ñ'÷R5ó 5r   rË   c                  ó*   € ] tR tRtRtRR R lltRtR# )ÚNMILossFromRefiÓ  aQ  Compute the normalized mutual-information loss of signals ``(*, N)`` against a reference (module form).

``criterion = NMILossFromRef(reference_signal, mask)`` stores the reference. ``loss = criterion(other_signal)`` is
:func:`~kornia.losses.normalized_mutual_information_loss` with ``input=other_signal`` and
``target=reference_signal``.

Convention:
    See the Convention blocks of :func:`~kornia.losses.normalized_mutual_information_loss` for the loss and of
    :class:`~kornia.losses.MILossFromRef` for the stored reference.

Args:
    reference_signal: reference signals ``(*, N)``.
    mask: boolean region of interest ``(N,)`` of the reference, common to the batch; ``None`` keeps
      every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Shape:
    - other_signal: signals with the shape of ``reference_signal``.
    - other_mask: boolean region of interest ``(N,)`` of ``other_signal``, or ``None``.
    - Output: the loss per leading index, in the dtype of the reference.

See Also:
    - :func:`~kornia.losses.normalized_mutual_information_loss`: the one-call form.
    - :class:`~kornia.losses.MILossFromRef`: the unnormalized mutual information, in nats.
    - :class:`~kornia.losses.NMILossFromRef2D`: the same loss for images ``(*, H, W)``.
    - :class:`~kornia.losses.NMILossFromRef3D`: the same loss for volumes ``(*, D, H, W)``.

Example:
    >>> reference = torch.rand(2, 64)
    >>> criterion = NMILossFromRef(reference)
    >>> loss = criterion(torch.rand(2, 64))

Nc               ó$   € V ^8„  d   QhRRRRRR/# rÍ   r   )r   s   "r   r   ÚNMILossFromRef.__annotate__ø  s#   € ÷ 6ñ 6 Lð 6Ð>Qð 6Ð]iñ 6r   c                ó”   € V P                  W4      w  r4pW4,           V,          pV) P                  V P                  P                  4      # )aM  Compute the normalized mutual-information loss of other_signal against the stored reference.

nmi = (H(X) + H(Y)) / H(X,Y)
To have a loss function, the opposite is returned.
Can also handle two batches of flat tensors, then a batch of loss values is returned.

Args:
    other_signal: Batch of flat tensors shape (B,N) where B is
        the tuple of batch dimensions for self.signal, possibly empty.
    other_mask (torch.Tensor): common boolean (N,) mask of roi for all the samples in other_signal, defaults
        to None

Returns:
    torch.Tensor: tensor of losses, shape B as above
rÐ   )rŸ   r­   r®   r€   r�   r   Únmis   &&&    r   rÒ   ÚNMILossFromRef.forwardø  s?   € ð  Ÿ™¨ÓA‰ˆ�$Ø�y˜DÕ ˆà��y‰y˜×.Ñ.×4Ñ4Ó5Ð5r   r   rÅ   rÔ   r   r   r   rÖ   rÖ   Ó  s   † ñ"÷H6ó 6r   rÖ   c                  ó~   a € ] tR tRtRtR]P                  ^@^3R V 3R lllt]R R l4       t	RR V 3R	 lllt
R
tV ;t# )ÚMILossFromRef2Di  a   Compute the mutual-information loss of images ``(*, H, W)`` against a reference (module form).

``criterion = MILossFromRef2D(reference_signal, mask)`` stores the reference. ``loss = criterion(other_signal)``
is :func:`~kornia.losses.mutual_information_loss_2d` with ``input=other_signal`` and ``target=reference_signal``.

Convention:
    See the Convention block of :class:`~kornia.losses.MILossFromRef`; the flattening and the batch axes are those
    of :func:`~kornia.losses.mutual_information_loss_2d`.

Args:
    reference_signal: reference images ``(*, H, W)``.
    mask: boolean region of interest ``(H, W)`` of the reference, common to the batch; ``None`` keeps
      every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Shape:
    - other_signal: images with the shape of ``reference_signal``.
    - other_mask: boolean region of interest ``(H, W)`` of ``other_signal``, or ``None``.
    - Output: the loss per image, in the dtype of the reference.

See Also:
    - :func:`~kornia.losses.mutual_information_loss_2d`: the one-call form.
    - :class:`~kornia.losses.NMILossFromRef2D`: Studholme's normalization, in ``[-2, -1]``.
    - :class:`~kornia.losses.MILossFromRef`: the same loss for signals ``(*, N)``.
    - :class:`~kornia.losses.MILossFromRef3D`: the same loss for volumes ``(*, D, H, W)``.
Nc               ó0   € V ^8„  d   QhRRRRRRRRR	R
RR/# r†   r   )r   s   "r   r   ÚMILossFromRef2D.__annotate__,  óF   € ÷ 7ñ 7à&ð7ð "ð7ð "ð	7ð
 ð7ð ð7ð 
ñ7r   c           	     óš   <€ \         SV `  V P                  V4      \        W!P                  RR 4      VVV4       VP                  V n        R# )a»  Initialize the 2D Mutual Information loss module.

Args:
    reference_signal (torch.Tensor): reference signal to which
        other signals will be compared by the forward method.
        batch of 2D images, shape (B,H,W) where B are the batch
        dimensions.
    mask (torch.Tensor | None): common boolean (H, W) mask of roi for all the samples in reference_signal,
        by default None
    kernel_function (MIKernel): Used kernel function for kernel
        density estimate, by default MIKernel.xu
    num_bins (int): number of signal value bins in kernel
        density estimate, by default 64
    window_radius (float): radius of the kernel's support
        interval, by default 1.0
Nrx   ©r�   r�   Úarrange_shaperM   r@   Ú_reference_shape©rŸ   r‡   r0   rˆ   rT   r   r    s   &&&&&&€r   r�   ÚMILossFromRef2D.__init__,  óO   ø€ ô0 	‰ÑØ×ÑÐ/Ó0Ü˜$× 6Ñ 6°r°sÐ ;Ó<ØØØô	
ð !1× 6Ñ 6ˆÖr   c               ó    € V ^8„  d   QhRRRR/# ©r   r"   r   r   r   )r   s   "r   r   rß   N  ó   € ÷ 8ñ 8˜lð 8¨|ñ 8r   c                ób   € V P                  \        V P                  4       ^,
          ^ 4      4      # )a  Flatten the spatial dimensions of a 2D signal batch.

Args:
    tensor: Signal tensor with shape ``(*, H, W)``, where ``*`` is
        any leading batch shape.

Returns:
    Tensor with shape ``(*, H * W)`` suitable for histogram-based
    mutual-information computation.
©Úflattenr\   rZ   ©r"   s   &r   rã   ÚMILossFromRef2D.arrange_shapeM  ó%   € ð �~‰~œc &§*¡*£,°Õ"2°AÓ6Ó7Ð7r   c               ó$   € V ^8„  d   QhRRRRRR/# rÍ   r   )r   s   "r   r   rß   [  ó-   € ÷ uñ uà"ðuð (ðuð 
ñ	ur   c           	     óê   <€ \        VP                  V P                  8H  RVP                   RV P                   R24       \        SV `  V P                  V4      \        W!P                  RR 4      4      # )a2  Compute the mutual-information loss of other_signal against the stored reference (both 2D).

mi = (H(X) + H(Y) - H(X,Y))
To have a loss function, the opposite is returned.
Can also handle two batches of 2D images, then a batch of loss values is returned.

Args:
    other_signal: Batch of 2D images, same shape (B,H,W) as
        reference_signal passed for instantiation
    other_mask (torch.Tensor): common boolean (H, W) mask of roi for all the samples in other_signal,
        defaults to None

Returns:
    torch.Tensor: tensor of losses, shape B as above
ú2input and reference must have the same shape. Got r´   rD   Nrx   ©r   r@   rä   r�   rÒ   rã   rM   ©rŸ   r­   r®   r    s   &&&€r   rÒ   ÚMILossFromRef2D.forward[  óv   ø€ ô( 	Ø×Ñ $×"7Ñ"7Ñ7Ø@À×ASÑASÐ@TÐTYÐZ^×ZoÑZoÐYpÐpqÐrô	
ô ‰w‰˜t×1Ñ1°,Ó?ÄÈz×[mÑ[mÐnpÐnqÐ[rÓAsÓtÐtr   ©rä   rÅ   ©r5   r6   r7   r8   r9   r4   r:   r�   rÇ   rã   rÒ   r=   rÈ   rÉ   s   @r   rÝ   rÝ     óL   ø† ñð@ %)Ø$,§K¡KØØ ÷7ò 7ðB ô8ó ð8÷u÷ uð ur   rÝ   c                  ó~   a € ] tR tRtRtR]P                  ^@^3R V 3R lllt]R R l4       t	RR V 3R	 lllt
R
tV ;t# )ÚMILossFromRef3Div  a¬  Compute the mutual-information loss of volumes ``(*, D, H, W)`` against a reference (module form).

``criterion = MILossFromRef3D(reference_signal, mask)`` stores the reference. ``loss = criterion(other_signal)``
is :func:`~kornia.losses.mutual_information_loss_3d` with ``input=other_signal`` and ``target=reference_signal``.

Convention:
    See the Convention block of :class:`~kornia.losses.MILossFromRef`; the flattening and the batch axes are those
    of :func:`~kornia.losses.mutual_information_loss_3d`.

Args:
    reference_signal: reference volumes ``(*, D, H, W)``.
    mask: boolean region of interest ``(D, H, W)`` of the reference, common to the batch; ``None`` keeps
      every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Shape:
    - other_signal: volumes with the shape of ``reference_signal``.
    - other_mask: boolean region of interest ``(D, H, W)`` of ``other_signal``, or ``None``.
    - Output: the loss per volume, in the dtype of the reference.

See Also:
    - :func:`~kornia.losses.mutual_information_loss_3d`: the one-call form.
    - :class:`~kornia.losses.NMILossFromRef3D`: Studholme's normalization, in ``[-2, -1]``.
    - :class:`~kornia.losses.MILossFromRef`: the same loss for signals ``(*, N)``.
    - :class:`~kornia.losses.MILossFromRef2D`: the same loss for images ``(*, H, W)``.
Nc               ó0   € V ^8„  d   QhRRRRRRRRR	R
RR/# r†   r   )r   s   "r   r   ÚMILossFromRef3D.__annotate__”  rà   r   c           	     óš   <€ \         SV `  V P                  V4      \        W!P                  RR 4      VVV4       VP                  V n        R# )aÀ  Initialize the 3D Mutual Information loss module.

Args:
    reference_signal (torch.Tensor): reference signal to which
        other signals will be compared by the forward method.
        batch of 3D images, shape (B,D,H,W) where B are the
        batch dimensions.
    mask (torch.Tensor | None): common boolean (D, H, W) mask of roi for all the samples in
        reference_signal, by default None
    kernel_function (MIKernel): Used kernel function for kernel
        density estimate, by default MIKernel.xu
    num_bins (int): number of signal value bins in kernel
        density estimate, by default 64
    window_radius (float): radius of the kernel's support
        interval, by default 1.0
Néýÿÿÿrâ   rå   s   &&&&&&€r   r�   ÚMILossFromRef3D.__init__”  rç   r   c               ó    € V ^8„  d   QhRRRR/# ré   r   )r   s   "r   r   rÿ   ¶  rê   r   c                ób   € V P                  \        V P                  4       ^,
          ^ 4      4      # )a  Flatten the spatial dimensions of a 3D signal batch.

Args:
    tensor: Signal tensor with shape ``(*, D, H, W)``, where
        :math:`D` is depth, :math:`H` is height, and :math:`W` is
        width.

Returns:
    Tensor with shape :math:`(*, D * H * W)` for entropy estimation.
rì   rî   s   &r   rã   ÚMILossFromRef3D.arrange_shapeµ  rð   r   c               ó$   € V ^8„  d   QhRRRRRR/# rÍ   r   )r   s   "r   r   rÿ   Ã  rò   r   c           	     óê   <€ \        VP                  V P                  8H  RVP                   RV P                   R24       \        SV `  V P                  V4      \        W!P                  RR 4      4      # )a9  Compute the mutual-information loss of other_signal against the stored reference (both 3D).

mi = (H(X) + H(Y) - H(X,Y))
To have a loss function, the opposite is returned.
Can also handle two batches of 3D volumes, then a batch of loss values is returned.

Args:
    other_signal: Batch of 3D volumes, same shape (B,D,H,W) as
        reference_signal passed for instantiation
    other_mask (torch.Tensor): common boolean (D, H, W) mask of roi for all the samples in other_signal,
        defaults to None

Returns:
    torch.Tensor: tensor of losses, shape B as above
rô   r´   rD   Nr  rõ   rö   s   &&&€r   rÒ   ÚMILossFromRef3D.forwardÃ  rø   r   rù   rÅ   rú   rÉ   s   @r   rý   rý   v  rû   r   rý   c                  ó~   a € ] tR tRtRtR]P                  ^@^3R V 3R lllt]R R l4       t	RR V 3R	 lllt
R
tV ;t# )ÚNMILossFromRef2DiÞ  aÑ  Compute the normalized mutual-information loss of images ``(*, H, W)`` against a reference (module form).

``criterion = NMILossFromRef2D(reference_signal, mask)`` stores the reference. ``loss = criterion(other_signal)``
is :func:`~kornia.losses.normalized_mutual_information_loss_2d` with ``input=other_signal`` and
``target=reference_signal``.

Convention:
    See the Convention block of :class:`~kornia.losses.NMILossFromRef`; the flattening and the batch axes are
    those of :func:`~kornia.losses.normalized_mutual_information_loss_2d`.

Args:
    reference_signal: reference images ``(*, H, W)``.
    mask: boolean region of interest ``(H, W)`` of the reference, common to the batch; ``None`` keeps
      every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Shape:
    - other_signal: images with the shape of ``reference_signal``.
    - other_mask: boolean region of interest ``(H, W)`` of ``other_signal``, or ``None``.
    - Output: the loss per image, in the dtype of the reference.

See Also:
    - :func:`~kornia.losses.normalized_mutual_information_loss_2d`: the one-call form.
    - :class:`~kornia.losses.MILossFromRef2D`: the unnormalized mutual information, in nats.
    - :class:`~kornia.losses.NMILossFromRef`: the same loss for signals ``(*, N)``.
    - :class:`~kornia.losses.NMILossFromRef3D`: the same loss for volumes ``(*, D, H, W)``.
Nc               ó0   € V ^8„  d   QhRRRRRRRRR	R
RR/# r†   r   )r   s   "r   r   ÚNMILossFromRef2D.__annotate__ý  rà   r   c           	     óš   <€ \         SV `  V P                  V4      \        W!P                  RR 4      VVV4       VP                  V n        R# )aÆ  Initialize the 2D Normalized Mutual Information loss module.

Args:
    reference_signal (torch.Tensor): reference signal to which
        other signals will be compared by the forward method.
        batch of 2D images, shape (B,H,W) where B are the batch
        dimensions.
    mask (torch.Tensor | None): common boolean (H, W) mask of roi for all the samples in reference_signal,
        by default None
    kernel_function (MIKernel): Used kernel function for kernel
        density estimate, by default MIKernel.xu
    num_bins (int): number of signal value bins in kernel
        density estimate, by default 64
    window_radius (float): radius of the kernel's support
        interval, by default 1.0
Nrx   râ   rå   s   &&&&&&€r   r�   ÚNMILossFromRef2D.__init__ý  rç   r   c               ó    € V ^8„  d   QhRRRR/# ré   r   )r   s   "r   r   r    ó   € ÷ 
8ñ 
8˜lð 
8¨|ñ 
8r   c                ób   € V P                  \        V P                  4       ^,
          ^ 4      4      # )zâFlatten the spatial dimensions of a 2D signal batch.

Args:
    tensor: Signal tensor with shape ``(*, H, W)``.

Returns:
    Tensor with shape ``(*, H * W)`` used by the normalized
    mutual-information base implementation.
rì   rî   s   &r   rã   ÚNMILossFromRef2D.arrange_shape  ó%   € ð �~‰~œc &§*¡*£,°Õ"2°AÓ6Ó7Ð7r   c               ó$   € V ^8„  d   QhRRRRRR/# rÍ   r   )r   s   "r   r   r  +  rò   r   c           	     óê   <€ \        VP                  V P                  8H  RVP                   RV P                   R24       \        SV `  V P                  V4      \        W!P                  RR 4      4      # )a>  Compute the normalized mutual-information loss of other_signal against the stored reference (both 2D).

nmi = (H(X) + H(Y)) / H(X,Y)
To have a loss function, the opposite is returned.
Can also handle two batches of 2D images, then a batch of loss values is returned.

Args:
    other_signal: Batch of 2D images, same shape (B,H,W) as
        reference_signal passed for instantiation
    other_mask (torch.Tensor): common boolean (H, W) mask of roi for all the samples in other_signal,
        defaults to None

Returns:
    torch.Tensor: tensor of losses, shape B as above
rô   r´   rD   Nrx   rõ   rö   s   &&&€r   rÒ   ÚNMILossFromRef2D.forward+  rø   r   rù   rÅ   rú   rÉ   s   @r   r
  r
  Þ  óL   ø† ñðB %)Ø$,§K¡KØØ ÷7ò 7ðB ô
8ó ð
8÷u÷ uð ur   r
  c                  ó~   a € ] tR tRtRtR]P                  ^@^3R V 3R lllt]R R l4       t	RR V 3R	 lllt
R
tV ;t# )ÚNMILossFromRef3DiF  aÝ  Compute the normalized mutual-information loss of volumes ``(*, D, H, W)`` against a reference (module form).

``criterion = NMILossFromRef3D(reference_signal, mask)`` stores the reference. ``loss = criterion(other_signal)``
is :func:`~kornia.losses.normalized_mutual_information_loss_3d` with ``input=other_signal`` and
``target=reference_signal``.

Convention:
    See the Convention block of :class:`~kornia.losses.NMILossFromRef`; the flattening and the batch axes are
    those of :func:`~kornia.losses.normalized_mutual_information_loss_3d`.

Args:
    reference_signal: reference volumes ``(*, D, H, W)``.
    mask: boolean region of interest ``(D, H, W)`` of the reference, common to the batch; ``None`` keeps
      every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Shape:
    - other_signal: volumes with the shape of ``reference_signal``.
    - other_mask: boolean region of interest ``(D, H, W)`` of ``other_signal``, or ``None``.
    - Output: the loss per volume, in the dtype of the reference.

See Also:
    - :func:`~kornia.losses.normalized_mutual_information_loss_3d`: the one-call form.
    - :class:`~kornia.losses.MILossFromRef3D`: the unnormalized mutual information, in nats.
    - :class:`~kornia.losses.NMILossFromRef`: the same loss for signals ``(*, N)``.
    - :class:`~kornia.losses.NMILossFromRef2D`: the same loss for images ``(*, H, W)``.
Nc               ó0   € V ^8„  d   QhRRRRRRRRR	R
RR/# r†   r   )r   s   "r   r   ÚNMILossFromRef3D.__annotate__e  rà   r   c           	     óš   <€ \         SV `  V P                  V4      \        W!P                  RR 4      VVV4       VP                  V n        R# )aË  Initialize the 3D Normalized Mutual Information loss module.

Args:
    reference_signal (torch.Tensor): reference signal to which
        other signals will be compared by the forward method.
        batch of 3D images, shape (B,D,H,W) where B are the
        batch dimensions.
    mask (torch.Tensor | None): common boolean (D, H, W) mask of roi for all the samples in
        reference_signal, by default None
    kernel_function (MIKernel): Used kernel function for kernel
        density estimate, by default MIKernel.xu
    num_bins (int): number of signal value bins in kernel
        density estimate, by default 64
    window_radius (float): radius of the kernel's support
        interval, by default 1.0
Nr  râ   rå   s   &&&&&&€r   r�   ÚNMILossFromRef3D.__init__e  rç   r   c               ó    € V ^8„  d   QhRRRR/# ré   r   )r   s   "r   r   r  ‡  r  r   c                ób   € V P                  \        V P                  4       ^,
          ^ 4      4      # )zíFlatten the spatial dimensions of a 3D signal batch.

Args:
    tensor: Signal tensor with shape ``(*, D, H, W)``.

Returns:
    Tensor with shape :math:`(*, D * H * W)` used by the normalized
    mutual-information base implementation.
rì   rî   s   &r   rã   ÚNMILossFromRef3D.arrange_shape†  r  r   c               ó$   € V ^8„  d   QhRRRRRR/# rÍ   r   )r   s   "r   r   r  “  rò   r   c           	     óê   <€ \        VP                  V P                  8H  RVP                   RV P                   R24       \        SV `  V P                  V4      \        W!P                  RR 4      4      # )aE  Compute the normalized mutual-information loss of other_signal against the stored reference (both 3D).

nmi = (H(X) + H(Y)) / H(X,Y)
To have a loss function, the opposite is returned.
Can also handle two batches of 3D volumes, then a batch of loss values is returned.

Args:
    other_signal: Batch of 3D volumes, same shape (B,D,H,W) as
        reference_signal passed for instantiation
    other_mask (torch.Tensor): common boolean (D, H, W) mask of roi for all the samples in other_signal,
        defaults to None

Returns:
    torch.Tensor: tensor of losses, shape B as above
rô   r´   rD   Nr  rõ   rö   s   &&&€r   rÒ   ÚNMILossFromRef3D.forward“  rø   r   rù   rÅ   rú   rÉ   s   @r   r  r  F  r  r   r  c               ó8   € V ^8„  d   QhRRRRRRRRRRR	R
RRRR/# ©r   Úinputr   ÚtargetÚ
input_maskr?   Útarget_maskrˆ   r4   rT   rU   r   r   r   r   )r   s   "r   r   r   ®  sb   € ÷ P8ñ P8ØðP8àðP8ð $ðP8ð %ð	P8ð
 ðP8ð ðP8ð ðP8ð ñP8r   c                ó\   € \        W4       \        VVVVVR7      pVP                  WR7      # )a‘  Compute the mutual-information loss of two flat signals ``(*, N)``.

``loss = mutual_information_loss(input, target)`` returns the negative mutual information of ``input`` and
``target`` from their kernel (Parzen-window) joint histogram, one value per leading index.

.. math::

    \text{loss} = -(H(X) + H(Y) - H(X, Y))

Convention:
    - The loss is in nats: minimising it maximises the mutual information. It is symmetric in ``input`` and
      ``target``. :ref:`Registration <mutual-information-porting>` maps the losses onto scikit-learn and
      scikit-image.
    - ``input`` and ``target`` are ``(*, N)`` tensors of one shape and one floating dtype; a single ``target`` is
      not broadcast over a batch of inputs. There is no ``reduction``
      (:ref:`Losses and metrics <losses-metrics-conventions>` lists the defaults of the other losses).
    - Each signal is min-max normalised per sample, over its mask, so no data range is assumed. A positive
      rescaling and a shift of one sample leave its loss unchanged up to roundoff when both its original and
      transformed ranges exceed the absolute threshold ``torch.finfo(dtype).eps``. One outlier
      squeezes the other values of its sample into a few bins. A sample whose range is at most that threshold
      counts as constant: its MI is 0 and it gets a zero gradient.
    - The joint histogram has ``num_bins`` bins per signal, and each value spreads over the bins within
      ``window_radius`` bin widths of it, weighted by ``kernel_function``, a :class:`~kornia.losses.MIKernel`
      member. With continuous values and the default ``window_radius``, this soft histogram scores an image
      against itself below its entropy. Values compare only at equal ``num_bins``, ``window_radius`` and kernel.
    - With ``MIKernel.xu`` (the default) and ``MIKernel.truncated_gaussian``, ``input`` and ``target`` both get
      gradients. ``MIKernel.rectangular`` is piecewise constant: its loss has no gradient and serves for
      evaluation only.
    - ``input_mask`` and ``target_mask`` are boolean ``(N,)`` masks, common to the batch. The histogram counts the
      positions inside both masks, while each signal is normalised over its own mask: a value inside one mask
      only is not counted, but it changes the loss when it is that signal's minimum or maximum. Values outside
      both masks have no effect. Masks of another shape, or with no position in common, raise an error.
    - For float16 and bfloat16 inputs, min-max normalisation, kernel evaluation, histogram accumulation and
      entropy arithmetic use float32, including under autocast, and the final loss is cast back to the input
      dtype. The empty-bin floor uses the histogram's computation dtype rather than the input dtype.
      The constant-signal threshold remains ``torch.finfo(input dtype).eps``.

Args:
    input: flat signals ``(*, N)``.
    target: flat signals with the shape of ``input``.
    input_mask: boolean region of interest ``(N,)`` of ``input``, common to the batch; ``None`` keeps
      every position.
    target_mask: boolean region of interest ``(N,)`` of ``target``, common to the batch; ``None``
      keeps every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Returns:
    the loss per leading index, with shape ``*``, in the input dtype.

See Also:
    - :class:`~kornia.losses.MILossFromRef`: the module form, built on the target.
    - :func:`~kornia.losses.normalized_mutual_information_loss`: Studholme's normalization, in ``[-2, -1]``.
    - :func:`~kornia.losses.mutual_information_loss_2d`: the same loss for images ``(*, H, W)``.
    - :func:`~kornia.losses.mutual_information_loss_3d`: the same loss for volumes ``(*, D, H, W)``.

Example:
    >>> input = torch.rand(2, 3, 64)
    >>> target = torch.rand(2, 3, 64)
    >>> loss = mutual_information_loss(input, target)

©r‡   r0   rˆ   rT   r   ©r®   )r	   rË   rÒ   ©r&  r'  r(  r)  rˆ   rT   r   Úmodules   &&&&&&& r   Úmutual_information_lossr/  ®  s9   € ôP ˜EÔ*ÜØØØ'ØØ#ô€Fð �>‰>˜%ˆ>Ó7Ð7r   c               ó8   € V ^8„  d   QhRRRRRRRRRRR	R
RRRR/# r%  r   )r   s   "r   r   r     óX   € ÷ 38ñ 38Øð38àð38ð $ð38ð %ð	38ð
 ð38ð ð38ð ð38ð ñ38r   c                ó\   € \        W4       \        VVVVVR7      pVP                  WR7      # )aB  Compute the mutual-information loss of two images ``(*, H, W)``.

``loss = mutual_information_loss_2d(input, target)`` returns the negative mutual information of ``input`` and
``target`` from their kernel (Parzen-window) joint histogram, one value per image.

.. math::

    \text{loss} = -(H(X) + H(Y) - H(X, Y))

Convention:
    See the Convention block of :func:`~kornia.losses.mutual_information_loss`; this function applies it to
    ``input.flatten(-2)`` and ``target.flatten(-2)``. Every axis before the last two is a batch axis, so a
    ``(B, C, H, W)`` input gives one loss per image and channel, ``(B, C)``.

Args:
    input: images ``(*, H, W)``.
    target: images with the shape of ``input``.
    input_mask: boolean region of interest ``(H, W)`` of ``input``, common to the batch; ``None`` keeps
      every position.
    target_mask: boolean region of interest ``(H, W)`` of ``target``, common to the batch; ``None``
      keeps every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Returns:
    the loss per image, with shape ``*``, in the input dtype.

See Also:
    - :class:`~kornia.losses.MILossFromRef2D`: the module form, built on the target.
    - :func:`~kornia.losses.normalized_mutual_information_loss_2d`: Studholme's normalization, in ``[-2, -1]``.
    - :func:`~kornia.losses.mutual_information_loss`: the same loss for flat signals ``(*, N)``.
    - :func:`~kornia.losses.mutual_information_loss_3d`: the same loss for volumes ``(*, D, H, W)``.
r+  r,  )r	   rÝ   rÒ   r-  s   &&&&&&& r   Úmutual_information_loss_2dr3    ó9   € ôV ˜EÔ*ÜØØØ'ØØ#ô€Fð �>‰>˜%ˆ>Ó7Ð7r   c               ó8   € V ^8„  d   QhRRRRRRRRRRR	R
RRRR/# r%  r   )r   s   "r   r   r   7  r1  r   c                ó\   € \        W4       \        VVVVVR7      pVP                  WR7      # )a\  Compute the mutual-information loss of two volumes ``(*, D, H, W)``.

``loss = mutual_information_loss_3d(input, target)`` returns the negative mutual information of ``input`` and
``target`` from their kernel (Parzen-window) joint histogram, one value per volume.

.. math::

    \text{loss} = -(H(X) + H(Y) - H(X, Y))

Convention:
    See the Convention block of :func:`~kornia.losses.mutual_information_loss`; this function applies it to
    ``input.flatten(-3)`` and ``target.flatten(-3)``. Every axis before the last three is a batch axis, so a
    ``(B, C, H, W)`` tensor is read as ``B`` volumes of depth ``C`` and gives ``(B,)``.

Args:
    input: volumes ``(*, D, H, W)``.
    target: volumes with the shape of ``input``.
    input_mask: boolean region of interest ``(D, H, W)`` of ``input``, common to the batch; ``None`` keeps
      every position.
    target_mask: boolean region of interest ``(D, H, W)`` of ``target``, common to the batch; ``None``
      keeps every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Returns:
    the loss per volume, with shape ``*``, in the input dtype.

See Also:
    - :class:`~kornia.losses.MILossFromRef3D`: the module form, built on the target.
    - :func:`~kornia.losses.normalized_mutual_information_loss_3d`: Studholme's normalization, in ``[-2, -1]``.
    - :func:`~kornia.losses.mutual_information_loss`: the same loss for flat signals ``(*, N)``.
    - :func:`~kornia.losses.mutual_information_loss_2d`: the same loss for images ``(*, H, W)``.
r+  r,  )r	   rý   rÒ   r-  s   &&&&&&& r   Úmutual_information_loss_3dr7  7  r4  r   c               ó8   € V ^8„  d   QhRRRRRRRRRRR	R
RRRR/# r%  r   )r   s   "r   r   r   m  sX   € ÷ >8ñ >8Øð>8àð>8ð $ð>8ð %ð	>8ð
 ð>8ð ð>8ð ð>8ð ñ>8r   c                ó\   € \        W4       \        VVVVVR7      pVP                  WR7      # )aØ  Compute the normalized mutual-information loss of two flat signals ``(*, N)``.

``loss = normalized_mutual_information_loss(input, target)`` returns the negative normalized mutual information of
``input`` and ``target`` from their kernel (Parzen-window) joint histogram, one value per leading index.

.. math::

    \text{loss} = -\frac{H(X) + H(Y)}{H(X, Y)}

Convention:
    - The loss is the negative of Studholme's normalized mutual information, which lies in :math:`[1, 2]`: the
      loss lies in ``[-2, -1]`` and is ``-1`` when one signal is constant and the other is not. Two constant
      signals give a finite value below ``-1`` that changes with the dtype, ``num_bins`` and the number of
      samples, because histogram cells are floored at machine epsilon. With continuous values and the default
      ``window_radius``, even an image against itself scores above ``-2``.
      :ref:`Registration <mutual-information-porting>` maps this normalisation onto scikit-image and
      scikit-learn.
    - Everything else is as in the Convention block of :func:`~kornia.losses.mutual_information_loss`.

Args:
    input: flat signals ``(*, N)``.
    target: flat signals with the shape of ``input``.
    input_mask: boolean region of interest ``(N,)`` of ``input``, common to the batch; ``None`` keeps
      every position.
    target_mask: boolean region of interest ``(N,)`` of ``target``, common to the batch; ``None``
      keeps every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Returns:
    the loss per leading index, with shape ``*``, in the input dtype.

See Also:
    - :class:`~kornia.losses.NMILossFromRef`: the module form, built on the target.
    - :func:`~kornia.losses.mutual_information_loss`: the unnormalized mutual information, in nats.
    - :func:`~kornia.losses.normalized_mutual_information_loss_2d`: the same loss for images ``(*, H, W)``.
    - :func:`~kornia.losses.normalized_mutual_information_loss_3d`: the same loss for volumes ``(*, D, H, W)``.

Example:
    >>> input = torch.rand(2, 3, 64)
    >>> target = torch.rand(2, 3, 64)
    >>> loss = normalized_mutual_information_loss(input, target)

)r‡   rˆ   r0   rT   r   r,  )r	   rÖ   rÒ   r-  s   &&&&&&& r   Ú"normalized_mutual_information_lossr:  m  s9   € ôl ˜EÔ*ÜØØ'ØØØ#ô€Fð �>‰>˜%ˆ>Ó7Ð7r   c               ó8   € V ^8„  d   QhRRRRRRRRRRR	R
RRRR/# r%  r   )r   s   "r   r   r   ®  óX   € ÷ 28ñ 28Øð28àð28ð $ð28ð %ð	28ð
 ð28ð ð28ð ð28ð ñ28r   c                ó\   € \        W4       \        VVVVVR7      pVP                  WR7      # )a  Compute the normalized mutual-information loss of two images ``(*, H, W)``.

``loss = normalized_mutual_information_loss_2d(input, target)`` returns the negative normalized mutual information
of ``input`` and ``target`` from their kernel (Parzen-window) joint histogram, one value per image.

.. math::

    \text{loss} = -\frac{H(X) + H(Y)}{H(X, Y)}

Convention:
    See the Convention block of :func:`~kornia.losses.normalized_mutual_information_loss`; the
    flattening and the batch axes are those of :func:`~kornia.losses.mutual_information_loss_2d`.

Args:
    input: images ``(*, H, W)``.
    target: images with the shape of ``input``.
    input_mask: boolean region of interest ``(H, W)`` of ``input``, common to the batch; ``None`` keeps
      every position.
    target_mask: boolean region of interest ``(H, W)`` of ``target``, common to the batch; ``None``
      keeps every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Returns:
    the loss per image, with shape ``*``, in the input dtype.

See Also:
    - :class:`~kornia.losses.NMILossFromRef2D`: the module form, built on the target.
    - :func:`~kornia.losses.mutual_information_loss_2d`: the unnormalized mutual information, in nats.
    - :func:`~kornia.losses.normalized_mutual_information_loss`: the same loss for flat signals ``(*, N)``.
    - :func:`~kornia.losses.normalized_mutual_information_loss_3d`: the same loss for volumes ``(*, D, H, W)``.
r+  r,  )r	   r
  rÒ   r-  s   &&&&&&& r   Ú%normalized_mutual_information_loss_2dr>  ®  ó9   € ôT ˜EÔ*ÜØØØ'ØØ#ô€Fð �>‰>˜%ˆ>Ó7Ð7r   c               ó8   € V ^8„  d   QhRRRRRRRRRRR	R
RRRR/# r%  r   )r   s   "r   r   r   ã  r<  r   c                ó\   € \        W4       \        VVVVVR7      pVP                  WR7      # )a  Compute the normalized mutual-information loss of two volumes ``(*, D, H, W)``.

``loss = normalized_mutual_information_loss_3d(input, target)`` returns the negative normalized mutual information
of ``input`` and ``target`` from their kernel (Parzen-window) joint histogram, one value per volume.

.. math::

    \text{loss} = -\frac{H(X) + H(Y)}{H(X, Y)}

Convention:
    See the Convention block of :func:`~kornia.losses.normalized_mutual_information_loss`; the
    flattening and the batch axes are those of :func:`~kornia.losses.mutual_information_loss_3d`.

Args:
    input: volumes ``(*, D, H, W)``.
    target: volumes with the shape of ``input``.
    input_mask: boolean region of interest ``(D, H, W)`` of ``input``, common to the batch; ``None`` keeps
      every position.
    target_mask: boolean region of interest ``(D, H, W)`` of ``target``, common to the batch; ``None``
      keeps every position.
    kernel_function: kernel that spreads each value over the bins.
    num_bins: number of bins per signal.
    window_radius: radius of the kernel in bin widths.

Returns:
    the loss per volume, with shape ``*``, in the input dtype.

See Also:
    - :class:`~kornia.losses.NMILossFromRef3D`: the module form, built on the target.
    - :func:`~kornia.losses.mutual_information_loss_3d`: the unnormalized mutual information, in nats.
    - :func:`~kornia.losses.normalized_mutual_information_loss`: the same loss for flat signals ``(*, N)``.
    - :func:`~kornia.losses.normalized_mutual_information_loss_2d`: the same loss for images ``(*, H, W)``.
r+  r,  )r	   r  rÒ   r-  s   &&&&&&& r   Ú%normalized_mutual_information_loss_3drB  ã  r?  r   )r   )g:Œ0âŽyE>))Ú
__future__r   Úenumr   r   Ú	functoolsr   r    Úkornia.core.checkr   r   r	   Úkornia.core.utilsr
   rº   r&   r*   r2   r4   rH   rM   rQ   re   rt   r‚   ÚnnÚModuler„   rË   rÖ   rÝ   rý   r
  r  r:   r/  r3  r7  r:  r>  rB  r   r   r   Ú<module>rJ     s~  ðõ" #ç Ý ã ç [Ñ [Ý *ð $Ð ÷÷.,÷ 0ô*;ˆtô ;õ:
õ6õ

>÷	cõ÷ô Pj˜5Ÿ8™8Ÿ?™?ô Pjôf=5Ð(ô =5ô@86Ð)ô 86ôveu�mô euôPeu�mô euôPeu�~ô euôPeu�~ô euðV '+Ø'+Ø (§¡ØØ÷P8ðl '+Ø'+Ø (§¡ØØ÷38ðr '+Ø'+Ø (§¡ØØ÷38ðr '+Ø'+Ø (§¡ØØ÷>8ðH '+Ø'+Ø (§¡ØØ÷28ðp '+Ø'+Ø (§¡ØØ÷28ñ 28r   