U
    “PÓhHF  ã                   @  s´   d dl mZ d dlZd dlmZ edƒ\ZZddddgZG d	d„ dejj	ƒZ
G d
d„ dejj	ƒZG dd„ dejj	ƒZG dd„ dejjƒZG dd„ dejj	ƒZG dd„ dejjƒZdS )é    )ÚannotationsN)Úoptional_importzmonai._CÚBilateralFilterÚ	PHLFilterÚTrainableBilateralFilterÚTrainableJointBilateralFilterc                   @  s*   e Zd ZdZed
dd„ƒZedd„ ƒZd	S )r   a:  
    Blurs the input tensor spatially whilst preserving edges. Can run on 1D, 2D, or 3D,
    tensors (on top of Batch and Channel dimensions). Two implementations are provided,
    an exact solution and a much faster approximation which uses a permutohedral lattice.

    See:
        https://en.wikipedia.org/wiki/Bilateral_filter
        https://graphics.stanford.edu/papers/permutohedral/

    Args:
        input: input tensor.
        spatial_sigma: the standard deviation of the spatial blur. Higher values can
            hurt performance when not using the approximate method (see fast approx).
        color_sigma: the standard deviation of the color blur. Lower values preserve
            edges better whilst higher values tend to a simple gaussian spatial blur.
        fast approx: This flag chooses between two implementations. The approximate method may
            produce artifacts in some scenarios whereas the exact solution may be intolerably
            slow for high spatial standard deviations.

    Returns:
        output (torch.Tensor): output tensor.
    é   ç      à?Tc                 C  s&   || _ || _|| _t ||||¡}|S )zautograd forward©ÚssÚcsÚfaÚ_CZbilateral_filter)ÚctxÚinputÚspatial_sigmaÚcolor_sigmaÚfast_approxÚoutput_data© r   úT/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/networks/layers/filtering.pyÚforward/   s
    zBilateralFilter.forwardc                 C  s2   | j | j| j  }}}t ||||¡}|dddfS )zautograd backwardNr
   )r   Úgrad_outputr   r   r   Ú
grad_inputr   r   r   Úbackward8   s    zBilateralFilter.backwardN)r   r	   T©Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ústaticmethodr   r   r   r   r   r   r      s
   c                   @  s*   e Zd ZdZeddd„ƒZedd„ ƒZdS )r   ab  
    Filters input based on arbitrary feature vectors. Uses a permutohedral
    lattice data structure to efficiently approximate n-dimensional gaussian
    filtering. Complexity is broadly independent of kernel size. Most applicable
    to higher filter dimensions and larger kernel sizes.

    See:
        https://graphics.stanford.edu/papers/permutohedral/

    Args:
        input: input tensor to be filtered.
        features: feature tensor used to filter the input.
        sigmas: the standard deviations of each feature in the filter.

    Returns:
        output (torch.Tensor): output tensor.
    Nc                 C  sX   |}|d k	r>t | d¡ƒD ]"}|d d …|df  ||   < q|  |¡ t ||¡}|S )Né   .)ÚrangeÚsizeÚsave_for_backwardr   Z
phl_filter)r   r   ÚfeaturesÚsigmasZscaled_featuresÚir   r   r   r   r   S   s     
zPHLFilter.forwardc                 C  s   t dƒ‚d S )Nz4PHLFilter does not currently support Backpropagation)ÚNotImplementedError)r   r   r   r   r   r   ^   s    zPHLFilter.backward)Nr   r   r   r   r   r   @   s
   
c                   @  s(   e Zd ZdZedd„ ƒZedd„ ƒZdS )Ú TrainableBilateralFilterFunctiona,  
    torch.autograd.Function for the TrainableBilateralFilter layer.

    See:
        F. Wagner, et al., Ultralow-parameter denoising: Trainable bilateral filter layers in
        computed tomography, Medical Physics (2022), https://doi.org/10.1002/mp.15718

    Args:
        input: input tensor to be filtered.
        sigma x: trainable standard deviation of the spatial filter kernel in x direction.
        sigma y: trainable standard deviation of the spatial filter kernel in y direction.
        sigma z: trainable standard deviation of the spatial filter kernel in z direction.
        color sigma: trainable standard deviation of the intensity range kernel. This filter
            parameter determines the degree of edge preservation.

    Returns:
        output (torch.Tensor): filtered tensor.
    c                 C  sD   t  |||||¡\}}}}	}
}}|  |||||||||	|
||¡ |S ©N)r   Ztbf_forwardr$   )r   Ú	input_imgÚsigma_xÚsigma_yÚsigma_zr   Úoutput_tensorÚoutput_weights_tensorÚdo_dx_kiÚ	do_dsig_rÚ	do_dsig_xÚ	do_dsig_yÚ	do_dsig_zr   r   r   r   z   s,        ÿôz(TrainableBilateralFilterFunction.forwardc                 C  sØ   | j d }| j d }| j d }| j d }| j d }| j d }| j d }| j d }	| j d	 }
| j d
 }| j d }| j d }t ||
 ¡}t || ¡}t || ¡}t || ¡}t |||||	||||¡	}|||||fS )Nr   r!   é   é   é   r   é   é   é   é	   é
   é   )Úsaved_tensorsÚtorchÚsumr   Ztbf_backward)r   r   r+   r,   r-   r.   r   r/   r0   r1   r2   r3   r4   r5   Úgrad_color_sigmaÚ
grad_sig_xÚ
grad_sig_yÚ
grad_sig_zÚgrad_output_tensorr   r   r   r   ‘   s8    











÷z)TrainableBilateralFilterFunction.backwardNr   r   r   r   r   r)   f   s
   
r)   c                      s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )r   a.  
    Implementation of a trainable bilateral filter layer as proposed in the corresponding publication.
    All filter parameters can be trained data-driven. The spatial filter kernels x, y, and z determine
    image smoothing whereas the color parameter specifies the amount of edge preservation.
    Can run on 1D, 2D, or 3D tensors (on top of Batch and Channel dimensions).

    See:
        F. Wagner, et al., Ultralow-parameter denoising: Trainable bilateral filter layers in
        computed tomography, Medical Physics (2022), https://doi.org/10.1002/mp.15718

    Args:
        input: input tensor to be filtered.
        spatial_sigma: tuple (sigma_x, sigma_y, sigma_z) initializing the trainable standard
            deviations of the spatial filter kernels. Tuple length must equal the number of
            spatial input dimensions.
        color_sigma: trainable standard deviation of the intensity range kernel. This filter
            parameter determines the degree of edge preservation.

    Returns:
        output (torch.Tensor): filtered tensor.
    c                   s  t ƒ  ¡  t|tƒr&|||g}d| _nŠt|ƒdkrH|d ddg}d| _nht|ƒdkrn|d |d dg}d| _nBt|ƒdkr˜|d |d |d g}d| _ntd|› d| j› dƒ‚tj	 
t |d ¡¡| _tj	 
t |d ¡¡| _tj	 
t |d ¡¡| _tj	 
t |¡¡| _d S ©	Nr7   r!   r   g{®Gáz„?r6   zlen(spatial_sigma) z# must match number of spatial dims Ú.©ÚsuperÚ__init__Ú
isinstanceÚfloatÚlen_spatial_sigmaÚlenÚ
ValueErrorZken_spatial_sigmar@   ÚnnÚ	ParameterÚtensorr,   r-   r.   Úsigma_color©Úselfr   r   ©Ú	__class__r   r   rK   Ì   s(    


ÿz!TrainableBilateralFilter.__init__c                 C  s¾   |j d dkr$td|j d › dƒ‚t|j ƒ}|dkrH| d¡ d¡}n|dkrZ| d¡}| j|krttd|› dƒ‚t || j| j| j	| j
¡}|dkr¨| d¡ d¡}n|dkrº| d¡}|S )Nr!   ú!Currently channel dimensions >1 (úh) are not supported. Please use multiple parallel filter layers if you want to filter multiple channels.r7   r8   úSpatial dimension (ú,) must match initialized len(spatial_sigma).)ÚshaperP   rO   Ú	unsqueezerN   r)   Úapplyr,   r-   r.   rT   Úsqueeze)rV   Úinput_tensorÚ	len_inputÚ
predictionr   r   r   r   æ   s.    ÿ


    ÿ
z TrainableBilateralFilter.forward©r   r   r   r   rK   r   Ú__classcell__r   r   rW   r   r   µ   s   c                   @  s(   e Zd ZdZedd„ ƒZedd„ ƒZdS )Ú%TrainableJointBilateralFilterFunctiona|  
    torch.autograd.Function for the TrainableJointBilateralFilter layer.

    See:
        F. Wagner, et al., Trainable joint bilateral filters for enhanced prediction stability in
        low-dose CT, Scientific Reports (2022), https://doi.org/10.1038/s41598-022-22530-4

    Args:
        input: input tensor to be filtered.
        guide: guidance image tensor to be used during filtering.
        sigma x: trainable standard deviation of the spatial filter kernel in x direction.
        sigma y: trainable standard deviation of the spatial filter kernel in y direction.
        sigma z: trainable standard deviation of the spatial filter kernel in z direction.
        color sigma: trainable standard deviation of the intensity range kernel. This filter
            parameter determines the degree of edge preservation.

    Returns:
        output (torch.Tensor): filtered tensor.
    c                 C  sH   t  ||||||¡\}}}	}
}}}|  ||||||||	|
||||¡ |S r*   )r   Ztjbf_forwardr$   )r   r+   Úguidance_imgr,   r-   r.   r   r/   r0   r1   r2   r3   r4   r5   r   r   r   r     s0         ÿóz-TrainableJointBilateralFilterFunction.forwardc                 C  sê   | j d }| j d }| j d }| j d }| j d }| j d }| j d }| j d }	| j d	 }
| j d
 }| j d }| j d }| j d }t ||
 ¡}t || ¡}t || ¡}t || ¡}t ||||||	||||¡
\}}||||||fS )Nr   r!   r6   r7   r8   r   r9   r:   r;   r<   r=   r>   é   )r?   r@   rA   r   Ztjbf_backward)r   r   r+   r,   r-   r.   r   r/   r0   r1   r2   r3   r4   r5   rg   rB   rC   rD   rE   rF   Zgrad_guidance_tensorr   r   r   r   3  s<    












öz.TrainableJointBilateralFilterFunction.backwardNr   r   r   r   r   rf     s
   
rf   c                      s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )r   a!  
    Implementation of a trainable joint bilateral filter layer as proposed in the corresponding publication.
    The guidance image is used as additional (edge) information during filtering. All filter parameters and the
    guidance image can be trained data-driven. The spatial filter kernels x, y, and z determine
    image smoothing whereas the color parameter specifies the amount of edge preservation.
    Can run on 1D, 2D, or 3D tensors (on top of Batch and Channel dimensions). Input tensor shape must match
    guidance tensor shape.

    See:
        F. Wagner, et al., Trainable joint bilateral filters for enhanced prediction stability in
        low-dose CT, Scientific Reports (2022), https://doi.org/10.1038/s41598-022-22530-4

    Args:
        input: input tensor to be filtered.
        guide: guidance image tensor to be used during filtering.
        spatial_sigma: tuple (sigma_x, sigma_y, sigma_z) initializing the trainable standard
            deviations of the spatial filter kernels. Tuple length must equal the number of
            spatial input dimensions.
        color_sigma: trainable standard deviation of the intensity range kernel. This filter
            parameter determines the degree of edge preservation.

    Returns:
        output (torch.Tensor): filtered tensor.
    c                   s  t ƒ  ¡  t|tƒr&|||g}d| _nŠt|ƒdkrH|d ddg}d| _nht|ƒdkrn|d |d dg}d| _nBt|ƒdkr˜|d |d |d g}d| _ntd|› d| j› dƒ‚tj	 
t |d ¡¡| _tj	 
t |d ¡¡| _tj	 
t |d ¡¡| _tj	 
t |¡¡| _d S rG   rI   rU   rW   r   r   rK   s  s(    


ÿz&TrainableJointBilateralFilter.__init__c                 C  s   |j d dkr$td|j d › dƒ‚|j |j krJtd|j › d|j › dƒ‚t|j ƒ}|dkr~| d¡ d¡}| d¡ d¡}n|dkrš| d¡}| d¡}| j|kr´td	|› d
ƒ‚t ||| j| j| j	| j
¡}|dkrê| d¡ d¡}n|dkrü| d¡}|S )Nr!   rY   rZ   z<Shape of input image must equal shape of guidance image.Got z and rH   r7   r8   r[   r\   )r]   rP   rO   r^   rN   rf   r_   r,   r-   r.   rT   r`   )rV   ra   Zguidance_tensorrb   rc   r   r   r   r     s<    ÿÿ



     ÿ
z%TrainableJointBilateralFilter.forwardrd   r   r   rW   r   r   Y  s   )Ú
__future__r   r@   Úmonai.utils.moduler   r   Ú_Ú__all__ÚautogradÚFunctionr   r   r)   rQ   ÚModuler   rf   r   r   r   r   r   Ú<module>   s   )&OQS