o
    i                     @  s   d dl mZ d dlmZ d dlmZmZ d dlZd dl	m
Z
mZmZ d dlmZ d dlmZ d dlmZmZmZ d d	lmZmZ erKd d
lmZ dZn	edded\ZZesZdd ZG dd dZdS )    )annotations)Iterable)TYPE_CHECKINGAnyN)PathologyProbNMScompute_isolated_tumor_cellscompute_multi_instance_mask)NdarrayOrTensor)	WSIReader)compute_fp_tp_probscompute_froc_curve_datacompute_froc_score)min_versionoptional_import)tqdmTr   z4.47.0c                 C  s   | S )N )xr   r   j/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/apps/pathology/metrics/lesion_froc.pyr   "   s   c                   @  sL   e Zd ZdZ							d&d'ddZd(ddZdd  Zd!d" Zd#d$ Zd%S ))
LesionFROCa  
    Evaluate with Free Response Operating Characteristic (FROC) score.

    Args:
        data: either the list of dictionaries containing probability maps (inference result) and
            tumor mask (ground truth), as below, or the path to a json file containing such list.
            `{
            "prob_map": "path/to/prob_map_1.npy",
            "tumor_mask": "path/to/ground_truth_1.tiff",
            "level": 6,
            "pixel_spacing": 0.243
            }`
        grow_distance: Euclidean distance (in micrometer) by which to grow the label the ground truth's tumors.
            Defaults to 75, which is the equivalent size of 5 tumor cells.
        itc_diameter: the maximum diameter of a region (in micrometer) to be considered as an isolated tumor cell.
            Defaults to 200.
        eval_thresholds: the false positive rates for calculating the average sensitivity.
            Defaults to (0.25, 0.5, 1, 2, 4, 8) which is the same as the CAMELYON 16 Challenge.
        nms_sigma: the standard deviation for gaussian filter of non-maximal suppression. Defaults to 0.0.
        nms_prob_threshold: the probability threshold of non-maximal suppression. Defaults to 0.5.
        nms_box_size: the box size (in pixel) to be removed around the pixel for non-maximal suppression.
        image_reader_name: the name of library to be used for loading whole slide imaging, either CuCIM or OpenSlide.
            Defaults to CuCIM.

    Note:
        For more info on `nms_*` parameters look at monai.utils.prob_nms.ProbNMS`.

    K      g      ?      ?                    r   0   cuCIMdata
list[dict]grow_distanceintitc_diametereval_thresholdstuple	nms_sigmafloatnms_prob_thresholdnms_box_sizeimage_reader_namestrreturnNonec	           	      C  s6   || _ || _|| _|| _t|| _t|||d| _d S )N)sigmaprob_thresholdbox_size)r    r"   r$   r%   r
   image_readerr   nms)	selfr    r"   r$   r%   r'   r)   r*   r+   r   r   r   __init__D   s   
zLesionFROC.__init__sampledict)tuple[np.ndarray, np.ndarray, np.ndarray]c                 C  s`   t |d }| j||d d}|rt| \}}}ng g g }}}t |t |t |fS )zH
        Prepare the probability map for detection evaluation.

        prob_maplevel)Z	probs_mapresolution_level)nploadr3   ziparray)r4   r6   r9   Znms_outputsprobsx_coordy_coordr   r   r   prepare_inference_resultV   s   z#LesionFROC.prepare_inference_resultc                 C  s   | j |d }| j j||d dd d }|d td|d  }| j|d  }t||d}| j| j | }t||d}||fS )	zY
        Prepare the ground truth for evaluation based on the binary tumor mask

        
tumor_maskr:   )r:   r   pixel_spacingr   )mask	threshold)rD   rG   )r2   readget_datapowr"   r   r$   r   )r4   r6   Zimg_objrD   Zmask_pixel_spacingZgrow_pixel_thresholdZitc_threshold
itc_labelsr   r   r   prepare_ground_truthl   s   zLesionFROC.prepare_ground_truthc              	   C  s   g }g }d}t | j}t| jD ].}| |\}}}| |\}	}
t||||	|
|d d\}}}|| || ||7 }qt|t|||fS )z
        Compute false positive and true positive probabilities for tumor detection,
        by comparing the model outputs with the prepared ground truths for all samples

        r   r:   )r@   rB   rA   evaluation_masklabels_to_excluder;   )	lenr    r   rC   rL   r   extendr<   r?   )r4   Ztotal_fp_probsZtotal_tp_probsZtotal_num_targets
num_imagesr6   r@   rB   rA   Zground_truthrK   fp_probstp_probsnum_targetsr   r   r   compute_fp_tp   s&   



zLesionFROC.compute_fp_tpc                 C  s8   |   \}}}}t||||d\}}t||| jd}|S )z
        Evaluate the detection performance of a model based on the model probability map output,
        the ground truth tumor mask, and their associated metadata (e.g., pixel_spacing, level)
        )rR   rS   rT   rQ   )fps_per_imagetotal_sensitivityr%   )rU   r   r   r%   )r4   rR   rS   rT   rQ   rV   rW   Z
froc_scorer   r   r   evaluate   s   
zLesionFROC.evaluateN)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.   )r6   r7   r-   r8   )	__name__
__module____qualname____doc__r5   rC   rL   rU   rX   r   r   r   r   r   &   s     
r   )
__future__r   collections.abcr   typingr   r   numpyr<   Zmonai.apps.pathology.utilsr   r   r   monai.configr	   monai.data.wsi_readerr
   monai.metricsr   r   r   monai.utilsr   r   r   has_tqdmr   r   r   r   r   <module>   s    