o # i8@sddlmZddlZddlmZddlmZmZdgZ ed\Z Z edded \Z Z ed ded \Z Z ed ded \ZZ ed ded\ZZ edded\ZZ GdddZdS)) annotationsN)NDArray) min_versionoptional_importUltrasoundConfidenceMapcv2z scipy.sparsez1.12.0 csc_matrixzscipy.sparse.linalgspsolvecgz scipy.signalhilbertZpyamgz5.0.0ruge_stuben_solverc@s~eZdZdZ        d1d2ddZd3ddZ d4d5dd Zd6d"d#Zd7d%d&Zd8d)d*Z d+d,Z d-d.Z d9d:d/d0Z dS);ra.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@皙?BallFư>alphafloatbetagammac CsR||_||_||_||_||_||_||_||_t dj |_ tj gdd|_ dS)Nfloat64dtype) rrrmode sink_modeuse_cgcg_tol cg_maxiternpfinfoepsarray _sink_indices) selfrrrrrrrrr&f/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/data/ultrasound_confidence_map.py__init__4s z UltrasoundConfidenceMap.__init__sizetuple[int, ...]rowsrcolsreturncCs|||d}|S)aConverts 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 rr&)r%r)r+r,indicesr&r&r'sub2indOszUltrasoundConfidenceMap.sub2indNdatarstr sink_maskNDArray | Nonetuple[NDArray, NDArray]cCs\tjgdd}tjgdd}tj|jddd}tdg}||j||d}t|}t||f}t|} t|| f}|dkrgt||jdd} tj| |gdd|_ ||j| |d}n|dkrt|jddg} t| |jdd} tj| | gdd|_ ||j| | d}nx|d krt |jdd } t |d | | f} t |d | | f| kd| }|} t| |jdd} tj| | gdd|_ ||j| | d}n)|d krt |dk}|d} |d} tj| | gdd|_ ||j| | d}t|}t||f}t|d} t|| f}||fS) aHGet 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 rrrrint32midming?mask) r r#arangeshaper/astypeunique concatenate ones_liker$intr9where)r%r0rr2seedslabelsscZsr_upseedlabelZsr_downZsc_downZ ten_percentmin_valZmin_idxscoordsr&r&r'get_seed_and_labelsasJ   $  z+UltrasoundConfidenceMap.get_seed_and_labelsinpcCs"|t|t||j}|S)zNormalize an array to [0, 1])r r9ptpr")r%rLZnormalized_arrayr&r&r' normalizesz!UltrasoundConfidenceMap.normalizeimgcCsNtjdd|jddd}t|ddd|jdf}dt| |}|S)zCompute attenuation weighting Args: img (NDArray): Image alpha: Attenuation coefficient (see publication) Returns: w (NDArray): Weighting expressing depth-dependent attenuation rr5rrr:?)r linspacer=tilereshapeexp)r%rOrdwwr&r&r'attenuation_weightings z-UltrasoundConfidenceMap.attenuation_weighting padded_index padded_imagecCs|j\}}|j}|j}t|dkd}||d}||d} tj|dd} dd|d|d| d| d|| g} d} t| D]X\} }|||}t|dkd}|||d}t||f}||d}t| |f} t||||||}t| |f} | dkr| jd} qF| dkr| jdqF| | } | | d|7<| | } tj | | ddd } t | || ff}| dt|j dd jd}| ||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. rr5rrr:Ngh㈵>axis)r=Tflattenr rC zeros_like enumerater@absrNrTrsetdiagsumA)r%rXrYrrm_pijsZedge_templatesZ vertical_endZiter_idxkZ neigh_idxsqiijjrVlapdiagr&r&r'confidence_laplaciansR             z,UltrasoundConfidenceMap.confidence_laplaciancCsR|jr"|}t|dd}|jdd}t|||j|j|d\}}|St||}|S)Npinv)Z coarse_solverV)cycle)rtolmaxiterM)rtocsrr Zaspreconditionerr rrr )r%rorhsZ lap_sparsemlrexrfr&r&r'_solve_linear_systems   z,UltrasoundConfidenceMap._solve_linear_systemcCstd|jd|jdd|jd|jdj}d}tj|||fddd}tj|||fddd} ||| ||} | dd|f} t|dk} t t| | t } | | ddf} t t| jd|}t | |ddfdd|f} tj |jddfdd}|dk|dddf<| |}|| |}tj | fdd}||| <d |||dk t <||jd|jdfj}|S) aCompute 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. r5rconstant)rr)constant_valuesNrrrP)r r<r=rSr]padrqrcitem setdiff1dr>rBrzerosr|)r%rOrDrErridxrZ padded_idxZ padded_imgrobnZi_uZ keep_indicesreryr{Z probabilitiesr&r&r'confidence_estimation&s(6   z-UltrasoundConfidenceMap.confidence_estimationcCsz|d}||}|jdkrtt|ddd}|||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 rRFrr[) r>rNrr rar rKrrWrrrr)r%r0r2rDrErVmap_r&r&r'__call__`s  z UltrasoundConfidenceMap.__call__)r rrrrFrr)rrrrrr)r)r*r+rr,rr-r)rN)r0rrr1r2r3r-r4)rLrr-r)rOrrrr-r)rXrrYrrrrr)N)r0rr2r3r-r) __name__ __module__ __qualname____doc__r(r/rKrNrWrqr|rrr&r&r&r'rs(  J  W :) __future__rnumpyr numpy.typingr monai.utilsrr__all__rrfrr r r r rr&r&r&r's