o  i@sddlmZddlZddlZddlmZddlmZddlZddl m Z m Z ddl m Z ddl mZddl mZmZmZmZed e jed \ZZed e jed \ZZer[dd lmZn ed e jed\ZZGdddZdS)) annotationsN)Callable) TYPE_CHECKING)CSVSaverdecollate_batch) IgniteInfo) ImageMetaKey)evenly_divisible_all_gather min_versionoptional_importstring_list_all_gatherignite distributedz ignite.engineEvents)Enginerc @s^eZdZdZddddddddd d d f d)ddZd*d d!Zd+d#d$Zd*d%d&Zd+d'd(Zd S),ClassificationSaverz Event handler triggered on completing every iteration to save the classification predictions as CSV file. If running in distributed data parallel, only saves CSV file in the specified rank. z./zpredictions.csv,TcC|SNxrre/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/handlers/classification_saver.py/zClassificationSaver.cCrrrrrrrr0rNr output_dirstrfilename delimiter overwriteboolbatch_transformroutput_transformname str | None save_rankintsaverCSVSaver | NonereturnNonec CsR||_||_||_||_||_||_||_| |_t ||_ ||_ g|_ g|_ dS)a Args: output_dir: if `saver=None`, output CSV file directory. filename: if `saver=None`, name of the saved CSV file name. delimiter: the delimiter character in the saved file, default to "," as the default output type is `csv`. to be consistent with: https://docs.python.org/3/library/csv.html#csv.Dialect.delimiter. overwrite: if `saver=None`, whether to overwriting existing file content, if True, will clear the file before saving. otherwise, will append new content to the file. batch_transform: a callable that is used to extract the `meta_data` dictionary of the input images from `ignite.engine.state.batch`. the purpose is to get the input filenames from the `meta_data` and store with classification results together. `engine.state` and `batch_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. output_transform: a callable that is used to extract the model prediction data from `ignite.engine.state.output`. the first dimension of its output will be treated as the batch dimension. each item in the batch will be saved individually. `engine.state` and `output_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. name: identifier of logging.logger to use, defaulting to `engine.logger`. save_rank: only the handler on specified rank will save to CSV file in multi-gpus validation, default to 0. saver: the saver instance to save classification results, if None, create a CSVSaver internally. the saver must provide `save_batch(batch_data, meta_data)` and `finalize()` APIs. N)r%rrrrr!r"r'logging getLoggerlogger_name_outputs _filenames) selfrrrrr!r"r#r%r'rrr__init__)s'  zClassificationSaver.__init__enginercCsv|jdur |j|_||jtjs|tj|j||tjs'|tj|||jtj s9|tj |jdSdS)zg Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. N) r.r-Zhas_event_handler_startedr EPOCH_STARTEDadd_event_handlerITERATION_COMPLETED _finalizeEPOCH_COMPLETED)r1r3rrrattach^s zClassificationSaver.attach_enginecCsg|_g|_dS)zs Initialize internal buffers. Args: _engine: Ignite Engine, unused argument. N)r/r0)r1r;rrrr4ls zClassificationSaver._startedcCs|||jj}t|trt|}||jj}t||D]\}}|j | t j t|tjr5|}|j |qdS)z This method assumes self.batch_transform will extract metadata from the input batch. Args: engine: Ignite Engine, it can be a trainer, validator or evaluator. N)r!statebatch isinstancedictrr"outputzipr0appendgetKeyFILENAME_OR_OBJtorchTensordetachr/)r1r3 meta_dataZ engine_outputmorrr__call__ws  zClassificationSaver.__call__cCst}|j|kr tdtj|jdd}|j}|dkr&t|dd}t |}t |dkr/d}nt |t |krGt dt |d t |d t j|i}t|jkrn|jpat|j|j|j|jd }||||dSdS) z All gather classification results from ranks and save to CSV file. Args: _engine: Ignite Engine, unused argument. zs