+
    åûjÅ8  ã                  ó°   € R t ^ RIHt ^ RIHt ^ RIt^ RIHu Ht	 ^ RI
HtHtHt ^ RIHt ^ RIHt R R ltR	 R
 ltRR R lltRR R lltRR R lltR# )a  Spatial softmax, the expected coordinate of a probability map, and Gaussian heatmaps (DSNT).

The "differentiable spatial to numerical" (soft-argmax) operations, as described in the paper "Numerical Coordinate
Regression with Convolutional Neural Networks" by Nibali et al.
)Úannotations)ÚOptionalN)ÚKORNIA_CHECK_IS_TENSORÚKORNIA_CHECK_SHAPEÚ_check_async)Úis_compiling)Úcreate_meshgridc               ó    € V ^8„  d   QhRRRR/# )é   Útensorútorch.TensorÚreturnÚNone© )Úformats   "ÚWC:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\geometry\subpix\dsnt.pyÚ__annotate__r   $   s   € ÷ 5ñ 5°ð 5À$ñ 5ó    c                ó8   € \        V 4       \        V . RO4       R# )ÚBN)r   ÚCÚHÚW)r   r   )r   s   &r   Ú$_validate_batched_image_tensor_inputr   $   s   € Ü˜6Ô"Ü�vÒ3Ö4r   c               ó    € V ^8„  d   QhRRRR/# )r
   Útemperatureztorch.Tensor | floatr   r   r   )r   s   "r   r   r   )   s   € ÷ bñ bÐ-Að bÀdñ br   c                óÚ   € \        V \        P                  4      '       d6   \        4       '       g#   \	        V ^ 8„  P                  4       4      '       d   R# M	V ^ 8”  d   R# \        RV  24      h)a	  Raise ``ValueError`` unless ``temperature`` is positive; ``NaN`` is rejected as well.

A tensor is read only outside graph capture: under ``torch.compile`` or export, reading its value would be a
data-dependent branch, so a tensor temperature is not checked there.
Nz;Temperature should be positive float or torch.Tensor. Got: )Ú
isinstanceÚtorchÚTensorr   ÚboolÚallÚ
ValueError)r   s   &r   Ú_check_positive_temperaturer#   )   sZ   € ô �+œuŸ|™|×,Ò,Ü�>Š>œT ;°¡?×"7Ñ"7Ó"9×:Ò:Ùð ;à	�qŒÙÜ
ÐRÐS^ÐR_Ð`Ó
aÐar   c               ó$   € V ^8„  d   QhRRRRRR/# )r
   Úinputr   r   zOptional[torch.Tensor | float]r   r   )r   s   "r   r   r   7   s(   € ÷ A<ñ A<˜\ð A<Ð8Vð A<Ðbnñ A<r   c                óR  € \        V 4       V P                  w  r#rEVf   Rp\        V4       V P                  W#WE,          4      pVP	                  4       '       g%   VP                  \        P                  ! 4       4      p\        V\        P                  4      '       d(   VP                  V P                  VP                  R7      pWE,          ^ 8”  d(   WfP                  RRR7      P                  4       ,
          p\        P                  ! Wa,          RR7      pVP!                  W#WE4      # )a«  Turn each heatmap channel into a probability map by a softmax over all its pixels.

``probs = spatial_softmax2d(heatmap, temperature)`` takes a ``(B, N, H, W)`` heatmap and returns, for each of its
``B x N`` channels, the softmax of ``heatmap / temperature`` over all ``H x W`` pixels, ``(B, N, H, W)``: each map
sums to one. This differs from :py:class:`torch.nn.Softmax2d`, which applies the softmax across channels at each
pixel. An integer heatmap returns torch's default floating dtype, with a float or a tensor ``temperature``. Pass the
result to
:func:`spatial_expectation2d` for its expected ``(x, y)``, or use :func:`spatial_soft_argmax2d` for both steps in
one call.

Args:
    input: the input torch.Tensor with shape ``(B, N, H, W)``.
    temperature: softmax temperature: the input is divided by it; smaller is sharper. Must be positive.
      ``None`` means ``1.0``. A tensor temperature is not checked under ``torch.compile`` or export; it broadcasts
      against the flattened ``(B, N, H * W)`` logits, so a ``(1, N, 1)`` tensor sets one per channel.

Returns:
   a 2D probability distribution per image channel with shape ``(B, N, H, W)``.

Raises:
    ValueError: if ``temperature``, or any element of a tensor ``temperature``, is not positive (``NaN``
      included).

See Also:
    - :func:`spatial_expectation2d`: the expected ``(x, y)`` of the probability maps this returns.
    - :func:`spatial_soft_argmax2d`: this softmax and the expectation in one call.
    - :func:`conv_soft_argmax2d`: a softmax over each sliding window instead of the whole map.
    - :func:`render_gaussian2d`: a probability map from a mean and a standard deviation instead of a heatmap.

Examples:
    >>> heatmaps = torch.tensor([[[
    ... [0., 0., 0.],
    ... [0., 0., 0.],
    ... [0., 1., 2.]]]])
    >>> spatial_softmax2d(heatmaps)
    tensor([[[[0.0585, 0.0585, 0.0585],
              [0.0585, 0.0585, 0.0585],
              [0.0585, 0.1589, 0.4319]]]])

g      ð?©ÚdeviceÚdtypeT)ÚdimÚkeepdim©r*   éÿÿÿÿ)r   Úshaper#   ÚreshapeÚis_floating_pointÚtor   Úget_default_dtyper   r   r(   r)   ÚamaxÚdetachÚFÚsoftmaxÚview)r%   r   Ú
batch_sizeÚchannelsÚheightÚwidthÚxÚx_softs   &&      r   Úspatial_softmax2dr>   7   sâ   € ôR )¨Ô/à*/¯+©+Ñ'€J˜&ØÒØˆÜ Ô,Ø�‰�j¨F­NÓ;€Að ×Ñ× Ò Ø�D‰D”×(Ò(Ó*Ó+ˆÜ�+œuŸ|™|×,Ò,ð "—n‘n¨E¯L©LÀÇÁ�nÓHˆð …~˜ÔØ—‘˜2 t�Ó,×3Ñ3Ó5Õ5ˆÜ�YŠY�q•¨BÔ/€Fà�;‰;�z¨VÓ;Ð;r   c               ó$   € V ^8„  d   QhRRRRRR/# )r
   r%   r   Únormalized_coordinatesr    r   r   )r   s   "r   r   r   {   s"   € ÷ :0ñ :0 ð :0Àtð :0ÐWcñ :0r   c                ó�  € \        V 4       V P                  w  r#rEV P                  \        P                  \        P
                  39   d   \        P                  MV P                  p\        WEWP                  V4      pVP                  V P                  4      pVR,          P                  R4      pVR,          P                  R4      p	V P                  W#WE,          4      p
\        P                  ! Wš,          RRR7      p\        P                  ! WŠ,          RRR7      p\        P                  ! WË.R4      pVP                  W#^4      # )a1  Compute the expected (x, y) coordinate of each channel of a probability map.

``coords = spatial_expectation2d(probs)`` takes ``(B, N, H, W)`` maps, each summing to one, and returns the
probability-weighted mean position of each map, ``(B, N, 2)`` in ``(x, y)`` order: normalized to :math:`[-1, 1]`,
corner-aligned, by default, or in pixels with ``normalized_coordinates=False``. Make the maps from a heatmap with
:func:`spatial_softmax2d`, or use :func:`spatial_soft_argmax2d` for both steps in one call.

Convention:
    - Coordinates follow :ref:`Coordinates and sizes <coordinate-conventions>`. The input is used as given, not
      renormalized, so each map should sum to one, as the output of
      :func:`~kornia.geometry.subpix.spatial_softmax2d` does: a map summing to ``s`` scales the result by ``s``.

Args:
    input: the input torch.Tensor representing dense spatial probabilities with shape ``(B, N, H, W)``.
    normalized_coordinates: whether to return the coordinates normalized in the range
      of :math:`[-1, 1]`. Otherwise, it will return the coordinates in the range of the input shape.

Returns:
   expected value of the 2D coordinates with shape ``(B, N, 2)``. Output order of the coordinates is (x, y).

See Also:
    - :func:`spatial_softmax2d`: makes the probability maps this function expects from a heatmap.
    - :func:`spatial_soft_argmax2d`: the softmax and this expectation in one call.
    - :func:`render_gaussian2d`: the other direction, a probability map around a given ``(x, y)`` mean.
    - :func:`~kornia.geometry.grid.create_meshgrid`: the coordinate grid the expectation weighs, in the same
      convention.

Examples:
    >>> heatmaps = torch.tensor([[[
    ... [0., 0., 0.],
    ... [0., 0., 0.],
    ... [0., 1., 0.]]]])
    >>> spatial_expectation2d(heatmaps, False)
    tensor([[[1., 2.]]])

T)r+   ©.é    r-   ©.é   )r   r.   r)   r   Úfloat16Úbfloat16Úfloat32r   r(   r1   r/   ÚsumÚcatr7   )r%   r@   r8   r9   r:   r;   Ú
grid_dtypeÚgridÚpos_xÚpos_yÚ
input_flatÚ
expected_yÚ
expected_xÚoutputs   &&            r   Úspatial_expectation2drS   {   s÷   € ôJ )¨Ô/à*/¯+©+Ñ'€J˜&ð #(§+¡+´%·-±-ÄÇÁÐ1PÔ"P”—’ÐV[×VaÑVa€JÜ˜6Ð*@Ç,Á,ÐPZÓ[€DØ�7‰7�5—;‘;Ó€Dà��L× Ñ  Ó$€EØ��L× Ñ  Ó$€Eà—‘˜z°Vµ^ÓD€Jô —’˜5Õ-¨r¸4Ô@€JÜ—’˜5Õ-¨r¸4Ô@€Jä�YŠY˜
Ð/°Ó4€Fà�;‰;�z¨QÓ/Ð/r   c          
     ó,   € V ^8„  d   QhRRRRRRRRRR/# )	r
   Úmeanr   ÚstdÚsizeztuple[int, int]r@   r    r   r   )r   s   "r   r   r   ¸   sB   € ÷ bMñ bMØ
ðbMØ)ðbMØ1@ðbMØZ^ðbMàñbMr   c                ób  € VP                   V P                   8X  d   VP                  V P                  8X  g   \        R4      h\        V^ 8g  P	                  4       R4       Vw  rEV P                   pV P                  pV\
        P                  \
        P                  39   d   \
        P                  MTpV'       d6   \
        P                  ! R^WWVR7      p	\
        P                  ! R^WGVR7      p
MB\
        P                  ! ^ V^,
          WWVR7      p	\
        P                  ! ^ V^,
          WGVR7      p
V\
        P                  8X  d#   V P                  V4      p VP                  V4      pV R,          P                  R4      pV R,          P                  R4      pVR,          P                  R4      pVR,          P                  R4      pW›,
          ^,          pW¬,
          ^,          pR\
        P                  ! V^,          4      ,          pR\
        P                  ! V^,          4      ,          p\
        P                  ! VV,          RR7      p\
        P                  ! VV,          RR7      pVP                  V4      P                  R4      VP                  V4      P                  R	4      ,          # )
a$  Render an axis-aligned 2D Gaussian heatmap that sums to one over an (H, W) grid.

``heatmap = render_gaussian2d(mean, std, (H, W))`` takes means ``(*, 2)`` and standard deviations ``(*, 2)``,
both in ``(x, y)`` order, and returns one ``(*, H, W)`` map per Gaussian: the product of a 1D Gaussian along ``x``
and one along ``y``, each normalised over the grid, so the map sums to one instead of holding the values of the
continuous density. ``mean`` and ``std`` are in normalized :math:`[-1, 1]` units by default, or in pixels with
``normalized_coordinates=False``. For the other direction, the expected coordinate of a probability map, use
:func:`spatial_expectation2d`.

A mean outside the grid renders the part of the Gaussian that falls on the grid, rescaled to sum to one; far
outside, that mass sits on the nearest border.

Convention:
    - ``mean`` and ``std`` follow :ref:`Coordinates and sizes <coordinate-conventions>`; ``size`` is
      ``(height, width)``. The default normalized coordinates are corner-aligned.
    - Float16 parameters are evaluated in float32; the heatmap retains the input dtype.

Args:
    mean: the mean location of the Gaussian to render, :math:`(\mu_x, \mu_y)`. Shape: ``(*, 2)``.
    std: the standard deviation of the Gaussian to render, :math:`(\sigma_x, \sigma_y)`.
      Shape ``(*, 2)``. Should be able to be broadcast with `mean`. Its sign is ignored. Every entry must be
      nonzero: a zero raises :class:`~kornia.core.exceptions.AsyncCheckError`, a :exc:`RuntimeError`, during
      the call on the CPU and on MPS before torch 2.13. On CUDA and on MPS from torch 2.13, torch raises a
      ``RuntimeError`` of its own by the next synchronization. A compiled call raises torch's ``RuntimeError``
      on the CPU, on CUDA and on MPS from torch 2.13, with Inductor from torch 2.9. With checks disabled
      nothing is raised, and the heatmap of a Gaussian whose ``std`` has a zero is NaN.
    size: the (height, width) of the output image.
    normalized_coordinates: whether ``mean`` and ``std`` are assumed to use coordinates normalized
      in the range of :math:`[-1, 1]`. Otherwise, coordinates are assumed to be in the range of the output shape.

Returns:
    torch.Tensor including rendered points with shape ``(*, H, W)``.

Raises:
    TypeError: if ``mean`` and ``std`` differ in dtype or device.

See Also:
    - :func:`spatial_expectation2d`: the other direction, the expected ``(x, y)`` of a probability map.
    - :func:`spatial_softmax2d`: a probability map from a heatmap instead of a mean and a standard deviation.
    - :func:`spatial_soft_argmax2d`: the other direction from a heatmap of logits: softmax, then expectation.
    - :func:`~kornia.filters.get_gaussian_kernel2d`: a Gaussian filter kernel centred in its window, for
      filtering rather than a heatmap at a given position.

z1Expected inputs to have the same dtype and devicezstd should be nonzeror'   r,   r-   rB   rD   g      à¿éþÿÿÿ)r)   r(   Ú	TypeErrorr   r!   r   rF   rG   rH   Úlinspacer1   Ú	unsqueezeÚ
reciprocalr6   )rU   rV   rW   r@   r:   r;   r)   r(   Úcompute_dtypeÚxsÚysÚmu_xÚmu_yÚsigma_xÚsigma_yÚ	dist_x_sqÚ	dist_y_sqÚk_xÚk_yÚgauss_xÚgauss_ys   &&&&                 r   Úrender_gaussian2drk   ¸   s  € ð^ �I‰I˜Ÿ™Ô#¨¯
©
°d·k±kÔ(AÜÐKÓLÐLô �#˜‘(—‘Ó!Ð#:Ô;à�M€FØ�J‰J€EØ�[‰[€Fð
 &+¬u¯}©}¼e¿n¹nÐ.MÔ%M”E—M’MÐSX€MßÜ�^Š^˜B  5¸}ÔMˆÜ�^Š^˜B  6ÀÔN‰ä�^Š^˜A˜u q�y¨%ÀmÔTˆÜ�^Š^˜A˜v¨�z¨6ÈÔVˆð ”—‘ÔØ�w‰w�}Ó%ˆØ�f‰f�]Ó#ˆØ��<×!Ñ! "Ó%€DØ��<×!Ñ! "Ó%€DØ�&�k×#Ñ# BÓ'€GØ�&�k×#Ñ# BÓ'€Gð •˜qÕ €IØ•˜qÕ €Ið ”×!Ò! '¨1¥*Ó-Õ
-€CØ
”×!Ò! '¨1¥*Ó-Õ
-€Cô
 �mŠm˜I¨�O°Ô4€GÜ�mŠm˜I¨�O°Ô4€Gð �:‰:�eÓ×&Ñ& rÓ*¨W¯Z©Z¸Ó->×-HÑ-HÈÓ-LÕLÐLr   )N)T)Ú__doc__Ú
__future__r   Útypingr   r   Útorch.nn.functionalÚnnÚ
functionalr5   Úkornia.core.checkr   r   r   Úkornia.core.utilsr   Úkornia.geometry.gridr   r   r#   r>   rS   rk   r   r   r   Ú<module>ru      sM   ðñ$õ #å ã ß Ð ç VÑ VÝ *Ý 0õ5õ
b÷A<÷H:0÷zbMñ bMr   