o
    #i8                     @  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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.12.0
csc_matrixzscipy.sparse.linalgspsolvecgzscipy.signalhilbertZpyamgz5.0.0ruge_stuben_solverc                   @  s~   e Zd ZdZ									d1d2ddZd3ddZ	d4d5dd Zd6d"d#Zd7d%d&Zd8d)d*Z	d+d, Z
d-d. Zd9d:d/d0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.

    The official code is available at:
    https://campar.in.tum.de/Main/AthanasiosKaramalisCode

    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'.
        use_cg (bool, optional): Use Conjugate Gradient method for solving the linear system. Defaults to False.
        cg_tol (float, optional): Tolerance for the Conjugate Gradient method. Defaults to 1e-6.
            Will be used only if `use_cg` is True.
        cg_maxiter (int, optional): Maximum number of iterations for the Conjugate Gradient method. Defaults to 200.
            Will be used only if `use_cg` is True.
           @     V@皙?BallFư>   alphafloatbetagammac	           	      C  sR   || _ || _|| _|| _|| _|| _|| _|| _t	dj
| _
tjg dd| _d S )Nfloat64dtype)r   r   r   mode	sink_modeuse_cgcg_tol
cg_maxiternpfinfoepsarray_sink_indices)	selfr   r   r   r   r   r   r   r    r&   f/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/data/ultrasound_confidence_map.py__init__4   s   z UltrasoundConfidenceMap.__init__sizetuple[int, ...]rowsr   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'   sub2indO   s   zUltrasoundConfidenceMap.sub2indNdatar   str	sink_maskNDArray | Nonetuple[NDArray, NDArray]c                 C  s\  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rgt ||jd d  }
t j|
|gdd| _	| |j|
|d}n|dkrt |jd d g}t ||jd d  }
t j|
|gdd| _	| |j|
|d}nx|d	krt
|jd d
 }t |d|| f }t |d|| f |kd | }|}t ||jd d  }
t j|
|gdd| _	| |j|
|d}n)|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$   intr9   where)r%   r0   r   r2   seedslabelsscZsr_upseedlabelZsr_downZsc_downZten_percentmin_valZmin_idxscoordsr&   r&   r'   get_seed_and_labelsa   sJ   

$

z+UltrasoundConfidenceMap.get_seed_and_labelsinpc                 C  s"   |t | t || j  }|S )zNormalize an array to [0, 1])r    r9   ptpr"   )r%   rL   Znormalized_arrayr&   r&   r'   	normalize   s   z!UltrasoundConfidenceMap.normalizeimgc                 C  sN   t jdd|jd dd}t |ddd|jd f}dt | |  }|S )zCompute attenuation weighting

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

        Returns:
            w (NDArray): Weighting expressing depth-dependent attenuation
        r   r5   r   r   r:         ?)r    linspacer=   tilereshapeexp)r%   rO   r   dwwr&   r&   r'   attenuation_weighting   s   z-UltrasoundConfidenceMap.attenuation_weightingpadded_indexpadded_imagec                 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 ]X\}}|||  }t|dkd }|||  d }t||f}|| d }t|	|f}	t|||  |||   }t|
|f}
|dkr|
j d }qF|dkr|
j d  qF| 	|
}
|
|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   r5   r   r   r:   N   gh㈵>axis)r=   Tflattenr    rC   
zeros_like	enumerater@   absrN   rT   r   setdiagsumA)r%   rX   rY   r   r   m_pijsZedge_templatesZvertical_endZiter_idxkZ
neigh_idxsqiijjrV   lapdiagr&   r&   r'   confidence_laplacian   sR   







z,UltrasoundConfidenceMap.confidence_laplacianc                 C  sR   | j r"| }t|dd}|jdd}t||| j| j|d\}}|S t||}|S )Npinv)Zcoarse_solverV)cycle)rtolmaxiterM)r   tocsrr   Zaspreconditionerr
   r   r   r	   )r%   ro   rhsZ
lap_sparsemlre   xrf   r&   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.
        r5   r   constant)r   r   )constant_valuesNr   r   rP   )r    r<   r=   rS   r]   padrq   rc   item	setdiff1dr>   rB   r   zerosr|   )r%   rO   rD   rE   r   r   idxr   Z
padded_idxZ
padded_imgro   bnZi_uZkeep_indicesre   ry   r{   Zprobabilitiesr&   r&   r'   confidence_estimation&  s(   6 
z-UltrasoundConfidenceMap.confidence_estimationc                 C  sz   | d}| |}| jdkrtt|dd d}| || j|\}}| || j	}|| }| 
|||| j| j}|S )zCompute 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   r[   )r>   rN   r   r    ra   r   rK   r   rW   r   r   r   r   )r%   r0   r2   rD   rE   rV   map_r&   r&   r'   __call__`  s   


z UltrasoundConfidenceMap.__call__)r   r   r   r   r   Fr   r   )r   r   r   r   r   r   )r)   r*   r+   r   r,   r   r-   r   )r   N)r0   r   r   r1   r2   r3   r-   r4   )rL   r   r-   r   )rO   r   r   r   r-   r   )rX   r   rY   r   r   r   r   r   )N)r0   r   r2   r3   r-   r   )__name__
__module____qualname____doc__r(   r/   rK   rN   rW   rq   r|   r   r   r&   r&   r&   r'   r      s(    

J

W:)
__future__r   numpyr    numpy.typingr   monai.utilsr   r   __all__r   rf   r   r	   r
   r   r   r   r&   r&   r&   r'   <module>   s   