o
    i                     @   s   d dl mZ d dlZd dlmZ z
d dlmZmZ W n ey.   d dl	m
Z
 e
d Y nw dejdejfd	d
ZdejdejdejfddZdS )    )isqrtN)einsum)matrix_to_angleswigner_D)loggerzLDependency 'e3nn' not found. Required for rotating the camera space SH coeffMreturnc              	   C   s   | j dd  dkrtdtj| \}}}|j}t|}t|}|| dk }t|d tjg d| j	| j
dtjg d| j	| j
d}t|}	||	 }
|
|dd	 }t|}t|d
d }|| }|S )N)   r
   z@Input must be a batch of 3x3 matrices (i.e., shape [..., 3, 3]).r   ).N)   r   g      )devicedtype)r   r   g      ?gUUUUUUտ).NN)shape
ValueErrortorchlinalgsvdmHdetwheretensorr   r   
diag_embed	transposepow)r   USVhVZdet_UZdet_Vis_reflectionZcorrection_signZcorrection_matrixZU_correctedZR_so3_initialZcurrent_detZdet_correction_factorZR_so3_final r    ?/data/cameron/da3_repo/src/depth_anything_3/utils/sh_helpers.pyproject_to_so3_strict   s&   



r"   sh_coefficients	rotationsc              
   C   s:  | j }| j}| j^ }}tj|j jddy |tj}tg dg dg dg	d|}tj
|| | }t|}	t|	\}
}}g }tt|D ]9}t | t||
| ||}W d    n1 sjw   Y  t|| d|d |d	 d f d
}|| qMW d    n1 sw   Y  tj|ddS )NF)device_typeenabled)r   r   r   )r   r   r   )r   r   r   r   .   r   z... i j, ... j -> ... ir   )dim)r   r   r   r   autocasttypetofloat32r   	unsqueezer   invr"   r   ranger   r   r   appendcat)r#   r$   r   r   _nZrotations_float32PZpermuted_rotationsZpermuted_rotations_so3alphabetagammaresultdegreeZsh_rotationsZ
sh_rotatedr    r    r!   	rotate_sh8   s.   (r:   )mathr   r   einopsr   Ze3nn.o3r   r   ImportErrordepth_anything_3.utils.loggerr   warnTensorr"   r:   r    r    r    r!   <module>   s"   