
    i                     |   d dl mZmZ d dlZd dlmZ d dlmc mZ ddZ	 G d dej
                  Z	 dd	ej        d
ededej        fdZdd
edej        dedej        fdZ	 	 	 d dedededej        dej        dej        fdZ	 	 	 	 d!dej        deeeef         df         deedf         dededej        fdZdS )"    )TupleUnionNnorm_expexpp1c                 ^   |                      dddd          }|dn|}|ddddddd| f         }|dk    r|dddddddf         n|dddddd| df         }|dk    rH|                    dd	                              d
          }||z  }|t          j        |          z  }	n|dk    r||                    dd	          z  }	nl|dk    rt          j        |          }	nQ|dk    rt          j        |          }	n6|dk    rt          j        |          }	n|dk    r|}	nt          d|           |dk    rd|                                z   }
nQ|dk    r|                                }
n6|dk    rt          j        |          }
n|dk    r|}
nt          d|           |	|
fS )aq  
    Process network output to extract GS params and density values.
    Density could be view-dependent as SH coefficient


    Args:
        out: Network output tensor (B, C, H, W)
        activation: Activation type for 3D points
        conf_activation: Activation type for confidence values

    Returns:
        Tuple of (3D points tensor, confidence tensor)
    r            Nr   T)dimkeepdimg:0yE>)minnormexprelusigmoidlinearzUnknown activation: r   expp0zUnknown conf_activation: )
permuter   clamptorchexpm1r   Fr   r   
ValueError)out
activationconf_activationconf_dimfmapxyzconfd
xyz_normedpts3dconf_outs              K/home/robot-lab/lab/da3_repo/src/depth_anything_3/model/utils/head_utils.pyactivate_head_gsr'      s    ;;q!Q""D $qq(H
qqq!!!QQQ
(
"
#C (A4111aaa4111aaa(8K3LDZHHTH**00T0::1W
U[^^+	v		chh2th444	u			#	v		s	y	 	 c""	x		<
<<==='!!txxzz>	G	#	#88::	I	%	%=&&	H	$	$F_FFGGG(?    c                   |     e Zd ZU dZeedf         ed<   deedf         ddf fdZdej	        dej	        fdZ
 xZS )	PermutezHnn.Module wrapper around Tensor.permute for cleaner nn.Sequential usage..dimsreturnNc                 V    t                                                       || _        d S N)super__init__r+   )selfr+   	__class__s     r&   r0   zPermute.__init__X   s$    			r(   xc                       |j         | j         S r.   )r   r+   )r1   r3   s     r&   forwardzPermute.forward\   s    qy$)$$r(   )__name__
__module____qualname____doc__r   int__annotations__r0   r   Tensorr5   __classcell__)r2   s   @r&   r*   r*   S   s         RR
S/U38_       % %%, % % % % % % % %r(   r*   d   pos_grid	embed_dimomega_0r,   c                 .   | j         \  }}}|dk    sJ |                     d|          }t          |dz  |dddf         |          }t          |dz  |dddf         |          }t          j        ||gd          }	|	                    |||          S )a*  
    Convert 2D position grid (HxWx2) to sinusoidal embeddings (HxWxC)

    Args:
        pos_grid: Tensor of shape (H, W, 2) containing 2D coordinates
        embed_dim: Output channel dimension for embeddings

    Returns:
        Tensor of shape (H, W, embed_dim) with positional embeddings
    r   r   Nr   )rA   r
   r   )shapereshapemake_sincos_pos_embedr   catview)
r?   r@   rA   HWgrid_dimpos_flatemb_xemb_yembs
             r&   position_grid_to_embedrP   `   s     ^NAq(q====H--H ")q.(111a4.'RRRE!)q.(111a4.'RRRE )UEN
+
+
+C88Aq)$$$r(   posc                    | dz  dk    sJ t          j        | dz  t           j        |j                  }|| dz  z  }d||z  z  }|                    d          }t          j        d||          }t          j        |          }t          j        |          }t          j        ||gd	          }|	                                S )
a"  
    This function generates a 1D positional embedding from a given grid using sine and cosine functions. # noqa

    Args:
    - embed_dim: The embedding dimension.
    - pos: The position to generate the embedding from.

    Returns:
    - emb: The generated 1D positional embedding.
    r   r   )dtypedeviceg       @      ?r   zm,d->mdr
   rC   )
r   arangefloat32rT   rE   einsumsincosrG   float)r@   rQ   rA   omegar   emb_sinemb_cosrO   s           r&   rF   rF   {   s     q=ALau}SZPPPE	Y_E'5. E
++b//C
,y#u
-
-CinnGinnG
)Wg&A
.
.
.C99;;r(   widthheightaspect_ratiorS   rT   c                    |t          |           t          |          z  }|dz  dz   dz  }||z  }d|z  }| | dz
  z  | z  }|| dz
  z  | z  }	| |dz
  z  |z  }
||dz
  z  |z  }t          j        ||	| ||          }t          j        |
||||          }t          j        ||d          \  }}t          j        ||fd	
          }|S )a  
    Create a normalized UV grid of shape (width, height, 2).

    The grid spans horizontally and vertically according to an aspect ratio,
    ensuring the top-left corner is at (-x_span, -y_span) and the bottom-right
    corner is at (x_span, y_span), normalized by the diagonal of the plane.

    Args:
        width (int): Number of points horizontally.
        height (int): Number of points vertically.
        aspect_ratio (float, optional): Width-to-height ratio. Defaults to width/height.
        dtype (torch.dtype, optional): Data type of the resulting tensor.
        device (torch.device, optional): Device on which the tensor is created.

    Returns:
        torch.Tensor: A (width, height, 2) tensor of UV coordinates.
    Nr   rU   g      ?r
   )stepsrS   rT   xy)indexingr   rC   )r[   r   linspacemeshgridstack)r_   r`   ra   rS   rT   diag_factorspan_xspan_yleft_xright_xtop_ybottom_yx_coordsy_coordsuuvvuv_grids                    r&   create_uv_gridru      s   2 U||eFmm3  ?S(S0KK'F;F W	"U*F	"U*GGvz"V+E!$v-H ~fgU%PVWWWH~eXV5QWXXXH ^Hh>>>FBk2r(+++GNr(   bilinearTr3   sizescale_factormodealign_cornersc                    F|
J d            t          | j        d         |z            t          | j        d         |z            fd}d         d         z  | j        d         z  | j        d         z  }||k    rUt          j        | ||z  dz   d          }fd	|D             }t          j        |d
                                          S t          j                            |           S )zi
    Safe interpolation implementation to avoid INT_MAX overflow in torch.nn.functional.interpolate.
    Nz-Either size or scale_factor must be provided.r   i   `r   r
   )chunksr   c                 V    g | ]%}t           j                            |           &S )rw   ry   rz   )nn
functionalinterpolate).0crz   ry   rw   s     r&   
<listcomp>z&custom_interpolate.<locals>.<listcomp>   sB     
 
 
 M%%ad]%[[
 
 
r(   rC   r   )	r:   rD   r   chunkrG   
contiguousr   r   r   )	r3   rw   rx   ry   rz   INT_MAXtotalr}   outss	    ` ``    r&   custom_interpolater      s    |'')X'''AGBK,.//QWR[<5O1P1PQGGd1g
*QWQZ7EwQ(8A'=1EEE
 
 
 
 
 

 
 
 y1%%%00222=$$QTM$ZZZr(   )r   r   N)r>   )NNN)NNrv   T)typingr   r   r   torch.nnr   torch.nn.functionalr   r   r'   Moduler*   r<   r:   r[   rP   rF   rS   rT   ru   strboolr    r(   r&   <module>r      s                           2 2 2 2t
% 
% 
% 
% 
%bi 
% 
% 
% >A% %l%'*%5:%
\% % % %6 S u| e V[Vb    @ / /// / ;	/
 L/ \/ / / /n *.'+[ [|[
c3h%
&[ t$[ 	[
 [ \[ [ [ [ [ [r(   