U
    vPhe                     @  s   d dl mZ d dlm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 d dlmZ d dlmZmZ d d	lmZ ed
ejed\ZZerd dlmZ ned
ejeddd\ZZejfddddddZG dd de	ZG dd dZeZdS )    )annotations)defaultdict)CallableMappingSequence)Enum)RLock)TYPE_CHECKINGAny)
IgniteInfo)min_versionoptional_import)
CommonKeyszignite.engineEvents)Enginer   	decorator)as_typezSequence[Mapping[str, Any]]strr
   )outputloss_keyreturnc                 C  s   | d | S Nr    )r   r   r   r   Q/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/handlers/metric_logger.py_get_loss_from_output!   s    r   c                   @  s   e Zd ZdZdZdS )MetricLoggerKeysZMetricsLossN)__name__
__module____qualname__METRICSLOSSr   r   r   r   r   %   s   r   c                   @  s   e Zd ZdZedd dfdddddd	d
ZdddddZdddddZdddddZdddddZ	dd Z
dd ZdS )MetricLoggera#  
    Collect per-iteration metrics and loss value from the attached trainer. This will also collect metric values from
    a given evaluator object which is expected to perform evaluation at the end of training epochs. This class is
    useful for collecting loss and metric values in one place for storage with checkpoint savers (`state_dict` and
    `load_state_dict` methods provided as expected by Pytorch and Ignite) and for graphing during training.

    Example::
        # construct an evaluator saving mean dice metric values in the key "val_mean_dice"
        evaluator = SupervisedEvaluator(..., key_val_metric={"val_mean_dice": MeanDice(...)})

        # construct the logger and associate with evaluator to extract metric values from
        logger = MetricLogger(evaluator=evaluator)

        # construct the trainer with the logger passed in as a handler so that it logs loss values
        trainer = SupervisedTrainer(..., train_handlers=[logger, ValidationHandler(1, evaluator)])

        # run training, logger.loss will be a list of (iteration, loss) values, logger.metrics a dict with key
        # "val_mean_dice" storing a list of (iteration, metric) values
        trainer.run()

    Args:
        loss_transform: Converts the `output` value from the trainer's state into a loss value
            `engine.state` and `loss_transform` inherit from the ignite concept:
            https://pytorch.org/ignite/concepts.html#state, explanation and usage example are in the tutorial:
            https://github.com/Project-MONAI/tutorials/blob/master/modules/batch_output_transform.ipynb.
        metric_transform: Converts the metric value coming from the trainer/evaluator's state into a storable value
        evaluator: Optional evaluator to consume metric results from at the end of its evaluation run
    c                 C  s   | S Nr   )xr   r   r   <lambda>K       zMetricLogger.<lambda>Nr   zEngine | NoneNone)loss_transformmetric_transform	evaluatorr   c                 C  s@   || _ || _g | _tt| _d| _t | _|d k	r<| 	| d S r   )
r(   r)   lossr   listmetrics	iterationr   lockattach_evaluator)selfr(   r)   r*   r   r   r   __init__H   s    
zMetricLogger.__init__r   )enginer   c                 C  s   | tj|  dS zg
        Args:
            engine: Ignite Engine, it can be a trainer, validator or evaluator.
        N)add_event_handlerr   ITERATION_COMPLETED)r1   r3   r   r   r   attachX   s    zMetricLogger.attach)r*   r   c                 C  s   | tj| j dS )z
        Attach event  handlers to the given evaluator to log metric values from it.

        Args:
            evaluator: Ignite Engine implementing network evaluation
        N)r5   r   	COMPLETEDlog_metrics)r1   r*   r   r   r   r0   _   s    zMetricLogger.attach_evaluatorc              	   C  sJ   | j : |jj| _| |jj}| j| j|f | | W 5 Q R X dS r4   )r/   stater.   r(   r   r+   appendr9   )r1   r3   Zlossvalr   r   r   __call__h   s
    
zMetricLogger.__call__c              	   C  sL   | j < |jj D ](\}}| |}| j| | j|f qW 5 Q R X dS )z
        Log metrics from the given Engine's state member.

        Args:
            engine: Ignite Engine to log from
        N)r/   r:   r-   itemsr)   r;   r.   )r1   r3   mvr   r   r   r9   t   s    
zMetricLogger.log_metricsc                 C  s   t j| jt j| jiS r#   )r   r!   r+   r    r-   )r1   r   r   r   
state_dict   s    zMetricLogger.state_dictc                 C  s4   |t j | jd d < | j  | j|t j  d S r#   )r   r!   r+   r-   clearupdater    )r1   r@   r   r   r   load_state_dict   s    
zMetricLogger.load_state_dict)r   r   r   __doc__r   r2   r7   r0   r<   r9   r@   rC   r   r   r   r   r"   *   s   	r"   N) 
__future__r   collectionsr   collections.abcr   r   r   enumr   	threadingr   typingr	   r
   monai.configr   monai.utilsr   r   monai.utils.enumsr   OPT_IMPORT_VERSIONr   _ignite.enginer   r!   r   r   r"   Zmetricloggerr   r   r   r   <module>   s,       
_