o
    _{j“$  ã                   @   s`   d dl Z d dlZd dlmZ ddlmZ ddlmZm	Z	 G dd„ dƒZ
e d	d
d¡fdd„ZdS )é    N)Ú	print_logé   )Úget_root_loggeré   )Úinterpolated_precision_recallÚpairwise_temporal_iouc                   @   sP   e Zd ZdZdde ddd¡dfdd„Zed	d
„ ƒZdd„ Z	dd„ Z
dd„ ZdS )ÚActivityNetLocalizationaä  Class to evaluate detection results on ActivityNet.

    Args:
        ground_truth_filename (str | None): The filename of groundtruth.
            Default: None.
        prediction_filename (str | None): The filename of action detection
            results. Default: None.
        tiou_thresholds (np.ndarray): The thresholds of temporal iou to
            evaluate. Default: ``np.linspace(0.5, 0.95, 10)``.
        verbose (bool): Whether to print verbose logs. Default: False.
    Nç      à?çffffffî?é
   Fc              
   C   s¬   |st dƒ‚|st dƒ‚|| _|| _|| _|| _d | _tƒ | _|  |¡\| _	| _
|  |¡| _| jrTd| j› d| j› dt| j	ƒ› dt| jƒ› d| j› �
}t|| jd� d S d S )	Nz'Please input a valid ground truth file.z%Please input a valid prediction file.z [INIT] Loaded ground_truth from z, prediction from z$.
Number of ground truth instances: z
Number of predictions: z!
Fixed threshold for tiou score: )Úlogger)ÚIOErrorÚground_truth_filenameÚprediction_filenameÚtiou_thresholdsÚverboseÚapr   r   Ú_import_ground_truthÚground_truthÚactivity_indexÚ_import_predictionÚ
predictionÚlenr   )Úselfr   r   r   r   Zlog_msg© r   ú=/root/disk_3tb/HAC/mmaction/core/evaluation/eval_detection.pyÚ__init__   s:   ÿÿþýüûÿøz ActivityNetLocalization.__init__c           
      C   sà   t | dƒ�}t |¡}W d  ƒ n1 sw   Y  i d}}g }| ¡ D ]F\}}|d D ]=}|d |vr?|||d < |d7 }i }	|dd… |	d< t|d	 d ƒ|	d
< t|d	 d ƒ|	d< ||d  |	d< | |	¡ q-q%||fS )aÑ  Read ground truth file and return the ground truth instances and the
        activity classes.

        Args:
            ground_truth_filename (str): Full path to the ground truth json
                file.

        Returns:
            tuple[list, dict]: (ground_truth, activity_index).
                ground_truth contains the ground truth instances, which is in a
                    dict format.
                activity_index contains classes index.
        ÚrNr   ÚannotationsÚlabelr   é   úvideo-idÚsegmentút-startút-end)ÚopenÚjsonÚloadÚitemsÚfloatÚappend)
r   ÚfÚdatar   Z	class_idxr   Úvideo_idÚ
video_infoÚannoZground_truth_itemr   r   r   r   5   s$   ÿ
öz,ActivityNetLocalization._import_ground_truthc           	      C   sº   t |dƒ�}t |¡}W d  ƒ n1 sw   Y  g }|d  ¡ D ]8\}}|D ]1}tƒ }||d< | j|d  |d< t|d d ƒ|d< t|d d	 ƒ|d
< |d |d< | |¡ q(q"|S )züRead prediction file and return the prediction instances.

        Args:
            prediction_filename (str): Full path to the prediction json file.

        Returns:
            List: List containing the prediction instances (dictionaries).
        r   NÚresultsr!   r   r"   r   r#   r   r$   Úscore)r%   r&   r'   r(   Údictr   r)   r*   )	r   r   r+   r,   r   r-   r.   ÚresultZprediction_itemr   r   r   r   X   s   	ÿù	z*ActivityNetLocalization._import_predictionc                 C   sÄ   t  t| jƒt| jƒf¡}g }g }tt| jƒƒD ]}| g ¡ | g ¡ q| jD ]}||d   |¡ q(| jD ]}||d   |¡ q7tt| jƒƒD ]}t	|| || | jƒ}||dd…|f< qJ|S )z*Computes average precision for each class.r   N)
ÚnpÚzerosr   r   r   Úranger*   r   r   Ú#compute_average_precision_detection)r   r   Zground_truth_by_labelZprediction_by_labelÚiÚgtÚpredZ	ap_resultr   r   r   Ú!wrapper_compute_average_precisionq   s"   


þz9ActivityNetLocalization.wrapper_compute_average_precisionc                 C   s2   |   ¡ | _| jjdd�| _| j ¡ | _| j| jfS )z¨Evaluates a prediction file.

        For the detection task we measure the interpolated mean average
        precision to measure the performance of a method.
        r   ©Úaxis)r;   r   ÚmeanÚmAPZaverage_mAP)r   r   r   r   Úevaluateˆ   s   
z ActivityNetLocalization.evaluate)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r4   Úlinspacer   Ústaticmethodr   r   r;   r@   r   r   r   r   r   
   s    
ü
"r   r	   r
   r   c                 C   sN  t |ƒ}t | ƒ}t |ƒ}t |¡}t |ƒdkr|S t|ƒ}t ||f¡d }|jdd„ d� t ||f¡}	t ||f¡}
i }t| ƒD ]\}}||d< | |d g ¡ |¡ qBt|ƒD ]�\}}|d |v rk||d  }n	d|
d	d	…|f< qZt	t 
|d
 |d g¡t 
dd„ |D ƒ¡ƒ}| d¡}| ¡ d	d	d… }t|ƒD ]J\}}|D ]-}|| |k r²d|
||f<  n|||| d f dkr¿q¢d|	||f< ||||| d f<  |
||f dkræ|	||f dkræd|
||f< qœqZtj|	dd� tj¡}tj|
dd� tj¡}|| }|||  }tt |ƒƒD ]}t||d	d	…f ||d	d	…f ƒ||< �q|S )a|  Compute average precision (detection task) between ground truth and
    predictions data frames. If multiple predictions occurs for the same
    predicted segment, only the one with highest score is matches as true
    positive. This code is greatly inspired by Pascal VOC devkit.

    Args:
        ground_truth (list[dict]): List containing the ground truth instances
            (dictionaries). Required keys are 'video-id', 't-start' and
            't-end'.
        prediction (list[dict]): List containing the prediction instances
            (dictionaries). Required keys are: 'video-id', 't-start', 't-end'
            and 'score'.
        tiou_thresholds (np.ndarray): A 1darray indicates the temporal
            intersection over union threshold, which is optional.
            Default: ``np.linspace(0.5, 0.95, 10)``.

    Returns:
        Float: ap, Average precision score.
    r   éÿÿÿÿc                 S   s
   | d  S )Nr1   r   )Úxr   r   r   Ú<lambda>·   s   
 z5compute_average_precision_detection.<locals>.<lambda>)ÚkeyÚindexr!   r   Nr#   r$   c                 S   s"   g | ]}t  |d  |d g¡‘qS )r#   r$   )r4   Úarray)Ú.0r9   r   r   r   Ú
<listcomp>Ì   s   " z7compute_average_precision_detection.<locals>.<listcomp>r<   )r   r4   r5   r)   ÚonesÚsortÚ	enumerateÚ
setdefaultr*   r   rL   ÚreshapeÚargsortÚcumsumÚastyper6   r   )r   r   r   Znum_thresholdsÚnum_gtsZ	num_predsr   Znum_positiveÚlock_gtÚtpÚfpZground_truth_by_videoidr8   ÚitemÚidxr:   ZgtsZtiou_arrZtiou_sorted_idxÚt_idxZtiou_thresholdZj_idxÚ	tp_cumsumÚ	fp_cumsumÚrecall_cumsumÚprecision_cumsumr   r   r   r7   –   sb   
þ
 €óÿr7   )r&   Únumpyr4   Ú
mmcv.utilsr   Úutilsr   Úaccuracyr   r   r   rE   r7   r   r   r   r   Ú<module>   s     ÿþ