U
    Ph                     @  s   d dl mZ d dlmZ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rd d	lmZ d
Znedded\ZZesdd ZG dd dZdS )    )annotations)TYPE_CHECKINGAnyIterableN)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   ]/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/apps/pathology/metrics/lesion_froc.pyr   !   s    c                   @  sX   e Zd ZdZdd	d
d
dddd
ddd	ddZdd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   cuCIMz
list[dict]inttuplefloatstrNone)	datagrow_distanceitc_diametereval_thresholds	nms_sigmanms_prob_thresholdnms_box_sizeimage_reader_namereturnc	           	      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__C   s    
zLesionFROC.__init__dictz)tuple[np.ndarray, np.ndarray, np.ndarray])sampler-   c                 C  s`   t |d }| j||d d}|r4t| \}}}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loadr2   ziparray)r3   r6   r7   Znms_outputsprobsx_coordy_coordr   r   r   prepare_inference_resultU   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_maskr8   )r8   r   pixel_spacingr   )mask	threshold)rB   rE   )r1   readget_datapowr&   r   r'   r   )r3   r6   Zimg_objrB   Zmask_pixel_spacingZgrow_pixel_thresholdZitc_threshold
itc_labelsr   r   r   prepare_ground_truthk   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   r8   )r>   r@   r?   evaluation_masklabels_to_excluder9   )	lenr%   r   rA   rJ   r   extendr:   r=   )r3   Ztotal_fp_probsZtotal_tp_probsZtotal_num_targets
num_imagesr6   r>   r@   r?   Zground_truthrI   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)
        )rP   rQ   rR   rO   )fps_per_imagetotal_sensitivityr(   )rS   r   r   r(   )r3   rP   rQ   rR   rO   rT   rU   Z
froc_scorer   r   r   evaluate   s       
  zLesionFROC.evaluateN)r   r   r   r   r   r   r   )	__name__
__module____qualname____doc__r4   rA   rJ   rS   rV   r   r   r   r   r   %   s            r   )
__future__r   typingr   r   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   