o
    )iÈ  ã                   @  sd   d dl mZ d dlZd dlmZ d dlmZmZ d dl	Z	d dl
mZ dgZdd„ Z		dddd„ZdS )é    )ÚannotationsN)Úrepeat)ÚListÚUnionÚbuild_sincos_position_embeddingc                   s   ‡ fdd„}|S )Nc                   s.   t | tjjƒrt | tƒst| ƒS tt| ˆ ƒƒS )N)Ú
isinstanceÚcollectionsÚabcÚIterableÚstrÚtupler   )Úx©Ún© úg/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/networks/blocks/pos_embed_utils.pyÚparse   s   z_ntuple.<locals>.parser   )r   r   r   r   r   Ú_ntuple   s   r   é   ç     ˆÃ@Ú	grid_sizeúUnion[int, List[int]]Ú	embed_dimÚintÚspatial_dimsÚtemperatureÚfloatÚreturnútorch.nn.Parameterc              	   C  sD  |dkr{t dƒ}|| ƒ}|\}}tj|tjd}tj|tjd}	t ||	¡\}}	|d dkr2tdƒ‚|d }
tj|
tjd|
 }d||  }t d| ¡ |g¡}t d|	 ¡ |g¡}tjt 	|¡t 
|¡t 	|¡t 
|¡gdd	d
d
d
…d
d
…f }n|dkrt dƒ}|| ƒ}|\}}}tj|tjd}tj|tjd}	tj|tjd}t ||	|¡\}}	}|d dkr¹tdƒ‚|d }
tj|
tjd|
 }d||  }t d| ¡ |g¡}t d|	 ¡ |g¡}t d| ¡ |g¡}tjt 	|¡t 
|¡t 	|¡t 
|¡t 	|¡t 
|¡gdd	d
d
d
…d
d
…f }ntdƒ‚t |¡}d|_|S )a  
    Builds a sin-cos position embedding based on the given grid size, embed dimension, spatial dimensions, and temperature.
    Reference: https://github.com/cvlab-stonybrook/SelfMedMAE/blob/68d191dfcc1c7d0145db93a6a570362de29e3b30/lib/models/mae3d.py

    Args:
        grid_size (List[int]): The size of the grid in each spatial dimension.
        embed_dim (int): The dimension of the embedding.
        spatial_dims (int): The number of spatial dimensions (2 for 2D, 3 for 3D).
        temperature (float): The temperature for the sin-cos position embedding.

    Returns:
        pos_embed (nn.Parameter): The sin-cos position embedding as a fixed parameter.
    é   )Údtypeé   r   zHEmbed dimension must be divisible by 4 for 2D sin-cos position embeddingg      ð?zm,d->mdé   )ÚdimNr   é   zHEmbed dimension must be divisible by 6 for 3D sin-cos position embeddingz6Spatial Dimension Size {spatial_dims} Not Implemented!F)r   ÚtorchÚarangeÚfloat32ÚmeshgridÚAssertionErrorÚeinsumÚflattenÚcatÚsinÚcosÚNotImplementedErrorÚnnÚ	ParameterÚrequires_grad)r   r   r   r   Z	to_2tupleZgrid_size_tÚhÚwZgrid_hZgrid_wZpos_dimÚomegaÚout_hÚout_wZpos_embZ	to_3tupleÚdZgrid_dÚout_dZ	pos_embedr   r   r   r   #   s^   B

ú÷
ö
)r   r   )
r   r   r   r   r   r   r   r   r   r   )Ú
__future__r   Úcollections.abcr   Ú	itertoolsr   Útypingr   r   r%   Útorch.nnr0   Ú__all__r   r   r   r   r   r   Ú<module>   s   ÿ