U
    ¸PÓh‘3  ã                   @  sŠ   d dl mZ d dlZd dlmZ d dlmZmZ dgZ	edƒ\Z
Zedded	ƒ\ZZed
dedƒ\ZZeddedƒ\ZZG dd„ dƒZdS )é    )ÚannotationsN)ÚNDArray)Úmin_versionÚoptional_importÚUltrasoundConfidenceMapÚcv2zscipy.sparsez1.7.1Ú
csc_matrixzscipy.sparse.linalgÚspsolvezscipy.signalÚhilbertc                   @  s¨   e Zd ZdZd'ddddœd	d
„Zdddddœdd„Zd(dddddœdd„Zdddœdd„Zddddœdd„Zdddddœdd„Z	d d!„ Z
d"d#„ Zd)dddd$œd%d&„ZdS )*r   a  Compute confidence map from an ultrasound image.
    This transform uses the method introduced by Karamalis et al. in https://doi.org/10.1016/j.media.2012.07.005.
    It generates a confidence map by setting source and sink points in the image and computing the probability
    for random walks to reach the source for each pixel.

    Args:
        alpha (float, optional): Alpha parameter. Defaults to 2.0.
        beta (float, optional): Beta parameter. Defaults to 90.0.
        gamma (float, optional): Gamma parameter. Defaults to 0.05.
        mode (str, optional): 'RF' or 'B' mode data. Defaults to 'B'.
        sink_mode (str, optional): Sink mode. Defaults to 'all'. If 'mask' is selected, a mask must be when calling
            the transform. Can be 'all', 'mid', 'min', or 'mask'.
    ç       @ç     €V@çš™™™™™©?ÚBÚallÚfloat)ÚalphaÚbetaÚgammac                 C  s@   || _ || _|| _|| _|| _t d¡j| _tjg dd| _	d S )NÚfloat64©Údtype)
r   r   r   ÚmodeÚ	sink_modeÚnpÚfinfoÚepsÚarrayÚ_sink_indices)Úselfr   r   r   r   r   © r   úY/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/data/ultrasound_confidence_map.pyÚ__init__*   s    z UltrasoundConfidenceMap.__init__ztuple[int, ...]r   )ÚsizeÚrowsÚcolsÚreturnc                 C  s   |||d   }|S )aà  Converts row and column subscripts into linear indices,
        basically the copy of the MATLAB function of the same name.
        https://www.mathworks.com/help/matlab/ref/sub2ind.html

        This function is Pythonic so the indices start at 0.

        Args:
            size Tuple[int]: Size of the matrix
            rows (NDArray): Row indices
            cols (NDArray): Column indices

        Returns:
            indices (NDArray): 1-D array of linear indices
        r   r   )r   r"   r#   r$   Úindicesr   r   r    Úsub2ind8   s    zUltrasoundConfidenceMap.sub2indNÚstrzNDArray | Noneztuple[NDArray, NDArray])Údatar   Ú	sink_maskr%   c                 C  sb  t jg dd}t jg dd}t j|jd dd}t  dg¡}|  |j||¡ d¡}t  |¡}t  ||f¡}t  |¡}	t  ||	f¡}|dkrÐt  |¡|jd d  }
t j|
|gdd| _	|  |j|
|¡ d¡}nV|dkr4t  |jd d g¡}t  |¡|jd d  }
t j|
|gdd| _	|  |j|
|¡ d¡}nò|d	krÔt
|jd d
 ƒ}t  |d|| …f ¡}t  |d|| …f |k¡d | }|}t  |¡|jd d  }
t j|
|gdd| _	|  |j|
|¡ d¡}nR|dkr&t  |dk¡}|d }
|d }t j|
|gdd| _	|  |j|
|¡ d¡}t  |¡}t  ||f¡}t  |¡d }	t  ||	f¡}||fS )aH  Get the seed and label arrays for the max-flow algorithm

        Args:
            data: Input array
            sink_mode (str, optional): Sink mode. Defaults to 'all'.
            sink_mask (NDArray, optional): Sink mask. Defaults to None.

        Returns:
            Tuple[NDArray, NDArray]: Seed and label arrays
        r   r   é   r   r   Úint32Úmidé   Úmingš™™™™™¹?éÿÿÿÿÚmask)r   r   ÚarangeÚshaper'   ÚastypeÚuniqueÚconcatenateÚ	ones_liker   Úintr/   Úwhere)r   r)   r   r*   ÚseedsÚlabelsÚscZsr_upÚseedÚlabelZsr_downZsc_downZten_percentÚmin_valZmin_idxsÚcoordsr   r   r    Úget_seed_and_labelsJ   sJ    



$

z+UltrasoundConfidenceMap.get_seed_and_labels)Úinpr%   c                 C  s"   |t  |¡ t  |¡| j  }|S )zNormalize an array to [0, 1])r   r/   Úptpr   )r   rB   Znormalized_arrayr   r   r    Ú	normalize”   s    z!UltrasoundConfidenceMap.normalize)Úimgr   r%   c                 C  sN   t jdd|jd dd}t  | dd¡d|jd f¡}dt  | | ¡ }|S )zïCompute attenuation weighting

        Args:
            img (NDArray): Image
            alpha: Attenuation coefficient (see publication)

        Returns:
            w (NDArray): Weighting expressing depth-dependent attenuation
        r   r+   r   r   r0   ç      ð?)r   Úlinspacer3   ÚtileÚreshapeÚexp)r   rE   r   ÚdwÚwr   r   r    Úattenuation_weighting™   s    z-UltrasoundConfidenceMap.attenuation_weighting)Úpadded_indexÚpadded_imager   r   c                 C  sÂ  |j \}}|j ¡ }|j ¡ }t |dk¡d }|| d }|| d }	tj|dd}
dd|d |d | d | d || g}d}t|ƒD ]²\}}|||  }t |dk¡d }|||  d }t ||f¡}|| d }t |	|f¡}	t |||  |||   ¡}t |
|f¡}
|dkr,|
j d }qŒ|dkrŒ|
j d  qŒ|  	|
¡}
|
d|…  |7  < |  	|
¡}
tj
| |
 ddd  }
t|
||	ffƒ}| d¡ t |jdd	j¡d }| |¡ |S )
a>  Compute 6-Connected Laplacian for confidence estimation problem

        Args:
            padded_index (NDArray): The index matrix of the image with boundary padding.
            padded_image (NDArray): The padded image.
            beta (float): Random walks parameter that defines the sensitivity of the Gaussian weighting function.
            gamma (float): Horizontal penalty factor that adjusts the weight of horizontal edges in the Laplacian.

        Returns:
            L (csc_matrix): The 6-connected Laplacian matrix used for confidence map estimation.
        r   r+   r   r   r0   Né   gíµ ÷Æ°>©Úaxis)r3   ÚTÚflattenr   r9   Ú
zeros_likeÚ	enumerater6   ÚabsrD   rJ   r   ÚsetdiagÚsumÚA)r   rN   rO   r   r   ÚmÚ_ÚpÚiÚjÚsZedge_templatesZvertical_endZiter_idxÚkZ
neigh_idxsÚqÚiiÚjjrL   ÚlapÚdiagr   r   r    Úconfidence_laplacian¬   sP    


ø


ÿ

z,UltrasoundConfidenceMap.confidence_laplacianc                 C  s   t ||ƒ}|S )N)r	   )r   re   ÚrhsÚxr   r   r    Ú_solve_linear_system  s    
z,UltrasoundConfidenceMap._solve_linear_systemc                 C  sˆ  t  d|jd |jd  d ¡ |jd |jd ¡j}d}t j|||fddd}t j|||fddd}	|  ||	||¡}
|
dd…|f }t  |dk¡ ¡ }t  	t  |¡| 
t¡¡}||dd…f }t  	t  |
jd ¡|¡}t|
|dd…f dd…|f ƒ}
t j|jd dfdd}|dk|dd…df< | | }|  |
|¡}t j|fdd}|||< d	|||dk  
t¡< | |jd |jd f¡j}|S )
až  Compute confidence map

        Args:
            img (NDArray): Processed image.
            seeds (NDArray): Seeds for the random walks framework. These are indices of the source and sink nodes.
            labels (NDArray): Labels for the random walks framework. These represent the classes or groups of the seeds.
            beta: Random walks parameter that defines the sensitivity of the Gaussian weighting function.
            gamma: Horizontal penalty factor that adjusts the weight of horizontal edges in the Laplacian.

        Returns:
            map: Confidence map which shows the probability of each pixel belonging to the source or sink group.
        r+   r   Úconstant)r   r   )Úconstant_valuesNr   r   rF   )r   r2   r3   rI   rS   Úpadrg   rY   ÚitemÚ	setdiff1dr4   r8   r   Úzerosrj   )r   rE   r:   r;   r   r   Úidxrm   Z
padded_idxZ
padded_imgre   ÚbÚnZi_uZkeep_indicesr[   rh   ri   Zprobabilitiesr   r   r    Úconfidence_estimation  s(    6 
z-UltrasoundConfidenceMap.confidence_estimation)r)   r*   r%   c                 C  sz   |  d¡}|  |¡}| jdkr6t t|dd¡  d¡}|  || j|¡\}}|  || j	¡}|| }|  
|||| j| j¡}|S )zÙCompute the confidence map

        Args:
            data (NDArray): RF ultrasound data (one scanline per column) [H x W] 2D array

        Returns:
            map (NDArray): Confidence map [H x W] 2D array
        r   ÚRFr   rQ   )r4   rD   r   r   rW   r
   rA   r   rM   r   rt   r   r   )r   r)   r*   r:   r;   rL   Úmap_r   r   r    Ú__call__A  s    


z UltrasoundConfidenceMap.__call__)r   r   r   r   r   )r   N)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r!   r'   rA   rD   rM   rg   rj   rt   rw   r   r   r   r    r      s      ÿJV:)Ú
__future__r   Únumpyr   Únumpy.typingr   Úmonai.utilsr   r   Ú__all__r   r\   r   r	   r
   r   r   r   r   r    Ú<module>   s   