o
    iAL                     @  s   d dl mZ d dlZd dlZd dlmZ d dlmZ d dlm	Z	 eddd\Z
Zed\ZZG d	d
 d
e	ZG dd dejZG dd dejZd(d)ddZd*d+ddZdd ZG dd dejZG d d! d!ejZd(d)d"d#Zd,d$d%Zd,d&d'ZdS )-    )annotationsN)optional_import)StrEnumZlpipsLPIPS)nametorchvisionc                   @  s(   e Zd ZdZdZdZdZdZdZdZ	dS )	PercetualNetworkTypealexvggsqueezeradimagenet_resnet50medicalnet_resnet10_23datasetsmedicalnet_resnet50_23datasetsresnet50N)
__name__
__module____qualname__r	   r
   r   r   r   r   r    r   r   Y/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/losses/perceptual.pyr      s    r   c                      sJ   e Zd ZdZejdddddddfd fddZd ddZd!ddZ  Z	S )"PerceptualLossag	  
    Perceptual loss using features from pretrained deep neural networks trained. The function supports networks
    pretrained on: ImageNet that use the LPIPS approach from Zhang, et al. "The unreasonable effectiveness of deep
    features as a perceptual metric." https://arxiv.org/abs/1801.03924 ; RadImagenet from Mei, et al. "RadImageNet: An
    Open Radiologic Deep Learning Research Dataset for Effective Transfer Learning"
    https://pubs.rsna.org/doi/full/10.1148/ryai.210315 ; MedicalNet from Chen et al. "Med3D: Transfer Learning for
    3D Medical Image Analysis" https://arxiv.org/abs/1904.00625 ;
    and ResNet50 from Torchvision: https://pytorch.org/vision/main/models/generated/torchvision.models.resnet50.html .

    The fake 3D implementation is based on a 2.5D approach where we calculate the 2D perceptual loss on slices from all
    three axes and average. The full 3D approach uses a 3D network to calculate the perceptual loss.
    MedicalNet networks are only compatible with 3D inputs and support channel-wise loss.

    Args:
        spatial_dims: number of spatial dimensions.
        network_type: {``"alex"``, ``"vgg"``, ``"squeeze"``, ``"radimagenet_resnet50"``,
        ``"medicalnet_resnet10_23datasets"``, ``"medicalnet_resnet50_23datasets"``, ``"resnet50"``}
            Specifies the network architecture to use. Defaults to ``"alex"``.
        is_fake_3d: if True use 2.5D approach for a 3D perceptual loss.
        fake_3d_ratio: ratio of how many slices per axis are used in the 2.5D approach.
        cache_dir: path to cache directory to save the pretrained network weights.
        pretrained: whether to load pretrained weights. This argument only works when using networks from
            LIPIS or Torchvision. Defaults to ``"True"``.
        pretrained_path: if `pretrained` is `True`, users can specify a weights file to be loaded
            via using this argument. This argument only works when ``"network_type"`` is "resnet50".
            Defaults to `None`.
        pretrained_state_dict_key: if `pretrained_path` is not `None`, this argument is used to
            extract the expected state dict. This argument only works when ``"network_type"`` is "resnet50".
            Defaults to `None`.
        channel_wise: if True, the loss is returned per channel. Otherwise the loss is averaged over the channels.
                Defaults to ``False``.
    Tg      ?NFspatial_dimsintnetwork_typestr
is_fake_3dboolfake_3d_ratiofloat	cache_dir
str | None
pretrainedpretrained_pathpretrained_state_dict_keychannel_wisec
           
        s  t    |dvrtd|dks|rd|v rtd|	r%d|vr%td| ttvr6tddt |rGtj	
| td	| d
 || _|  |dkr]|du r]t|d|	d| _n"d|v rit|dd| _n|dkrwt||||d| _nt||dd| _|| _|| _|	| _d S )N)      z1Perceptual loss is implemented only in 2D and 3D.r$   Zmedicalnet_ziMedicalNet networks are only compatible with ``spatial_dims=3``.Argument is_fake_3d must be set to False.z>Channel-wise loss is only compatible with MedicalNet networks.zGUnrecognised criterion entered for Adversarial Loss. Must be one in: %sz, zSetting cache_dir to z@, this may change the default cache dir for all torch.hub calls.r%   F)netverboser#   Zradimagenet_)r&   r'   r   )r&   r    r!   r"   )r    r&   r'   )super__init__NotImplementedError
ValueErrorlowerlistr   jointorchhubset_dirwarningswarnr   MedicalNetPerceptualSimilarityperceptual_functionRadImageNetPerceptualSimilarity$TorchvisionModelPerceptualSimilarityr   r   r   r#   )
selfr   r   r   r   r   r    r!   r"   r#   	__class__r   r   r)   F   sN   




zPerceptualLoss.__init__inputtorch.Tensortargetspatial_axisreturnc                 C  s   ddd}g d}| | d	}||||ft| d
}t|jd dt|jd | j  |j}tj	|d|d}||||ft| d
}	tj	|	d|d}	t
| ||	}
|
S )a  
        Calculate perceptual loss in one of the axis used in the 2.5D approach. After the slices of one spatial axis
        is transformed into different instances in the batch, we compute the loss using the 2D approach.

        Args:
            input: input 5D tensor. BNHWD
            target: target 5D tensor. BNHWD
            spatial_axis: spatial axis to obtain the 2D slices.
        xr<   fake_3d_permtupler?   c                 S  sH   |   d|  }|d| j|d  | j|d  | j|d  }|S )zg
            Transform slices from one spatial axis into different instances in the batch.
            )r      r$   r%   )r   permute
contiguousviewshape)r@   rA   slicesr   r   r   batchify_axis   s   .z:PerceptualLoss._calculate_axis_loss.<locals>.batchify_axisr$   r%      rD   )r@   rA   r   N)dimindex)r@   r<   rA   rB   r?   r<   )removerB   r/   randpermrH   r   r   todeviceindex_selectmeanr5   )r8   r;   r=   r>   rJ   Zpreserved_axeschannel_axisZinput_slicesindicesZtarget_slicesZ	axis_lossr   r   r   _calculate_axis_loss   s   
	
(z#PerceptualLoss._calculate_axis_lossc                 C  s   |j |j krtd|j  d|j  d| jdkr:| jr:| j||dd}| j||dd}| j||dd}|| | }n| ||}| jrNtj|	 dd	}|S t|}|S )
zx
        Args:
            input: the shape should be BNHW[D].
            target: the shape should be BNHW[D].
        z"ground truth has differing shape (z) from input ()r%   r$   )r>   rL   r   rM   )
rH   r+   r   r   rW   r5   r#   r/   rT   r   )r8   r;   r=   Zloss_sagittalZloss_coronalZ
loss_axiallossr   r   r   forward   s   
zPerceptualLoss.forward)r   r   r   r   r   r   r   r   r   r   r    r   r!   r   r"   r   r#   r   )r;   r<   r=   r<   r>   r   r?   r<   r;   r<   r=   r<   r?   r<   )
r   r   r   __doc__r   r	   r)   rW   r[   __classcell__r   r   r9   r   r   $   s    $
<$r   c                      s0   e Zd ZdZ	dd fddZdddZ  ZS )r4   a  
    Component to perform the perceptual evaluation with the networks pretrained by Chen, et al. "Med3D: Transfer
    Learning for 3D Medical Image Analysis". This class uses torch Hub to download the networks from
    "Warvito/MedicalNet-models".

    Args:
        net: {``"medicalnet_resnet10_23datasets"``, ``"medicalnet_resnet50_23datasets"``}
            Specifies the network architecture to use. Defaults to ``"medicalnet_resnet10_23datasets"``.
        verbose: if false, mute messages from torch Hub load function.
        channel_wise: if True, the loss is returned per channel. Otherwise the loss is averaged over the channels.
                Defaults to ``False``.
    r   Fr&   r   r'   r   r#   r?   Nonec                   sR   t    dd tj_tjjd||dd| _|   || _| 	 D ]}d|_
q!d S )Nc                 S  s   dS )NTr   )abcr   r   r   <lambda>   s    z9MedicalNetPerceptualSimilarity.__init__.<locals>.<lambda>zwarvito/MedicalNet-modelsTmodelr'   
trust_repoF)r(   r)   r/   r0   _validate_not_a_forked_repoloadre   evalr#   
parametersrequires_grad)r8   r&   r'   r#   paramr9   r   r   r)      s   
z'MedicalNetPerceptualSimilarity.__init__r;   r<   r=   c                 C  s  t |}t |}d}t|jd D ]J}|dd|df d}|dd|df d}|dkrA| j|}| j|}|jd }qtj|| j|gdd}tj|| j|gdd}qt|}	t|}
|	|
 d }| j	rt
|jd |jd |jd |jd |jd }t|jd D ]$}|| }|d | }|dd||| df jdd|dd|df< qn|jdd	d
}t|d	d}|S )a,  
        Compute perceptual loss using MedicalNet 3D networks. The input and target tensors are inputted in the
        pre-trained MedicalNet that is used for feature extraction. Then, these extracted features are normalised across
        the channels. Finally, we compute the difference between the input and target features and calculate the mean
        value from the spatial dimensions to obtain the perceptual loss.

        Args:
            input: 3D input tensor with shape BCDHW.
            target: 3D target tensor with shape BCDHW.

        r   rD   N.rY   r$   r%   rL   TrM   keepdimrn   )"medicalnet_intensity_normalisationrangerH   	unsqueezere   r[   r/   catnormalize_tensorr#   zerossumspatial_average_3d)r8   r;   r=   Zfeats_per_chZch_idxinput_channelZtarget_channel
outs_inputouts_targetfeats_inputfeats_targetZ
feats_diffresultsiZl_idxr_idxr   r   r   r[      s6   (2z&MedicalNetPerceptualSimilarity.forward)r   FF)r&   r   r'   r   r#   r   r?   r_   r\   r   r   r   r]   r)   r[   r^   r   r   r9   r   r4      s
    r4   Tr@   r<   rn   r   r?   c                 C  s   | j g d|dS )NrK   ro   rT   r@   rn   r   r   r   rw        rw   绽|=epsr   c                 C  s&   t t j| d ddd}| ||  S )Nr$   rD   Trm   )r/   sqrtrv   )r@   r   norm_factorr   r   r   rt     s   rt   c                 C  s   |   }|  }| | | S )zvBased on https://github.com/Tencent/MedicalNet/blob/18c8bb6cd564eb1b964bffef1f4c2283f1ae6e7b/datasets/brains18.py#L133)rT   std)volumerT   r   r   r   r   rp     s   rp   c                      s.   e Zd ZdZdd fd
dZdddZ  ZS )r6   a  
    Component to perform the perceptual evaluation with the networks pretrained on RadImagenet (pretrained by Mei, et
    al. "RadImageNet: An Open Radiologic Deep Learning Research Dataset for Effective Transfer Learning"). This class
    uses torch Hub to download the networks from "Warvito/radimagenet-models".

    Args:
        net: {``"radimagenet_resnet50"``}
            Specifies the network architecture to use. Defaults to ``"radimagenet_resnet50"``.
        verbose: if false, mute messages from torch Hub load function.
    r   Fr&   r   r'   r   r?   r_   c                   s@   t    tjjd||dd| _|   |  D ]}d|_qd S )NzWarvito/radimagenet-modelsTrd   F)	r(   r)   r/   r0   rh   re   ri   rj   rk   )r8   r&   r'   rl   r9   r   r   r)   *  s   
z(RadImageNetPerceptualSimilarity.__init__r;   r<   r=   c                 C  s   |j d dkr|j d dkr|dddd}|dddd}|ddg ddf }|ddg ddf }t|}t|}| j|}| j|}t|}t|}|| d }t|jddddd	}|S )
a  
        We expect that the input is normalised between [0, 1]. Given the preprocessing performed during the training at
        https://github.com/BMEII-AI/RadImageNet, we make sure that the input and target have 3 channels, reorder it from
         'RGB' to 'BGR', and then remove the mean components of each input data channel. The outputs are normalised
        across the channels, and we obtain the mean from the spatial dimensions (similar approach to the lpips package).
        rD   r%   N)r$   rD   r   .r$   Trm   ro   )rH   repeatsubtract_meanre   r[   rt   spatial_averagerv   r8   r;   r=   ry   rz   r{   r|   r}   r   r   r   r[   2  s   z'RadImageNetPerceptualSimilarity.forward)r   F)r&   r   r'   r   r?   r_   r\   r   r   r   r9   r   r6     s    r6   c                      s6   e Zd ZdZ				dd fddZdddZ  ZS )r7   a  
    Component to perform the perceptual evaluation with TorchVision models.
    Currently, only ResNet50 is supported. The network structure is based on:
    https://pytorch.org/vision/main/models/generated/torchvision.models.resnet50.html

    Args:
        net: {``"resnet50"``}
            Specifies the network architecture to use. Defaults to ``"resnet50"``.
        pretrained: whether to load pretrained weights. Defaults to `True`.
        pretrained_path: if `pretrained` is `True`, users can specify a weights file to be loaded
            via using this argument. Defaults to `None`.
        pretrained_state_dict_key: if `pretrained_path` is not `None`, this argument is used to
            extract the expected state dict. Defaults to `None`.
    r   TNr&   r   r    r   r!   r   r"   r?   r_   c           	        s   t    dg}||vrtd| d| d|d u r*tjj|r%tjjjnd d}ntjjd d}|du rItj	|dd}|d urD|| }|
| d| _tjj|| jg| _|   |  D ]}d	|_q_d S )
Nr   z'net' z0 is not supported, please select a network from .)weightsT)weights_onlyzlayer4.2.relu_2F)r(   r)   r*   r   modelsr   ResNet50_WeightsDEFAULTr/   rh   load_state_dictfinal_layerfeature_extractioncreate_feature_extractorre   ri   rj   rk   )	r8   r&   r    r!   r"   Zsupported_networksnetwork
state_dictrl   r9   r   r   r)   d  s,   

z-TorchvisionModelPerceptualSimilarity.__init__r;   r<   r=   c                 C  s   |j d dkr|j d dkr|dddd}|dddd}t|}t|}| j|| j }| j|| j }t|}t|}|| d }t|jddddd}|S )a  
        We expect that the input is normalised between [0, 1]. Given the preprocessing performed during the training at
        https://pytorch.org/vision/main/models/generated/torchvision.models.resnet50.html#torchvision.models.ResNet50_Weights,
        we make sure that the input and target have 3 channels, and then do Z-Score normalization.
        The outputs are normalised across the channels, and we obtain the mean from the spatial dimensions (similar
        approach to the lpips package).
        rD   r%   r$   Trm   ro   )	rH   r   torchvision_zscore_normre   r[   r   rt   r   rv   r   r   r   r   r[     s   	z,TorchvisionModelPerceptualSimilarity.forward)r   TNN)
r&   r   r    r   r!   r   r"   r   r?   r_   r\   r   r   r   r9   r   r7   T  s     r7   c                 C  s   | j ddg|dS )Nr$   r%   ro   r   r   r   r   r   r     r   r   c                 C  s   g d}g d}| d d dd d d d f |d  |d  | d d dd d d d f< | d d dd d d d f |d  |d  | d d dd d d d f< | d d dd d d d f |d  |d  | d d dd d d d f< | S )N)
ףp=
?v/?Cl?)gZd;O?gy&1?g?r   rD   r$   r   )r@   rT   r   r   r   r   r     s   DDDr   c                 C  s   g d}| d d dd d d d f  |d 8  < | d d dd d d d f  |d 8  < | d d dd d d d f  |d 8  < | S )N)r   r   r   r   rD   r$   r   )r@   rT   r   r   r   r     s
   (((r   )T)r@   r<   rn   r   r?   r<   )r   )r@   r<   r   r   r?   r<   )r@   r<   r?   r<   )
__future__r   r2   r/   torch.nnnnmonai.utilsr   monai.utils.enumsr   r   _r   r   Moduler   r4   rw   rt   rp   r6   r7   r   r   r   r   r   r   r   <module>   s(   
 M6O
	