




"""simple docstring"""

from typing import Dict, Optional

import numpy as np

import datasets


a							      =     '''
IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union
between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,
the mean IoU of the image is calculated by taking the IoU of each class and averaging them.
'''

a							      =     '''
Args:
    predictions (`List[ndarray]`):
        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
    references (`List[ndarray]`):
        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.
    num_labels (`int`):
        Number of classes (categories).
    ignore_index (`int`):
        Index that will be ignored during evaluation.
    nan_to_num (`int`, *optional*):
        If specified, NaN values will be replaced by the number defined by the user.
    label_map (`dict`, *optional*):
        If specified, dictionary mapping old label indices to new label indices.
    reduce_labels (`bool`, *optional*, defaults to `False`):
        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,
        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.

Returns:
    `Dict[str, float | ndarray]` comprising various elements:
    - *mean_iou* (`float`):
        Mean Intersection-over-Union (IoU averaged over all categories).
    - *mean_accuracy* (`float`):
        Mean accuracy (averaged over all categories).
    - *overall_accuracy* (`float`):
        Overall accuracy on all images.
    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):
        Per category accuracy.
    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):
        Per category IoU.

Examples:

    >>> import numpy as np

    >>> mean_iou = datasets.load_metric("mean_iou")

    >>> # suppose one has 3 different segmentation maps predicted
    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])
    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])

    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])
    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])

    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])
    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])

    >>> predicted = [predicted_1, predicted_2, predicted_3]
    >>> ground_truth = [actual_1, actual_2, actual_3]

    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), \'per_category_accuracy\': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}
'''

a							      =     '''\
@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,
author = {{MMSegmentation Contributors}},
license = {Apache-2.0},
month = {7},
title = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},
url = {https://github.com/open-mmlab/mmsegmentation},
year = {2020}
}'''






def 		_snake_case	(   _snake_case				:   Any							,    _snake_case				:   Dict							,    _snake_case				:   Any							,    _snake_case				:   bool							,    _snake_case				:   Optional[Dict[int, int]] = None							,    _snake_case				:   bool = False							,    )       ->   List[Any]:






      '''simple docstring'''


      if label_map is not None:
            for old_id, new_id in label_map.items():
                  _A     =  new_id

    # turn into Numpy arrays
      _A     =  np.array(_snake_case				)
      _A     =  np.array(_snake_case				)

      if reduce_labels:
            _A     =  2_55
            _A     =  label - 1
            _A     =  2_55

      _A     =  label != ignore_index
      _A     =  np.not_equal(_snake_case							,    _snake_case				)
      _A     =  pred_label[mask]
      _A     =  np.array(_snake_case				)[mask]

      _A     =  pred_label[pred_label == label]

      _A     =  np.histogram(_snake_case							,    bins=_snake_case							,    range=(0, num_labels - 1)				)[0]
      _A     =  np.histogram(_snake_case							,    bins=_snake_case							,    range=(0, num_labels - 1)				)[0]
      _A     =  np.histogram(_snake_case							,    bins=_snake_case							,    range=(0, num_labels - 1)				)[0]

      _A     =  area_pred_label + area_label - area_intersect

      return area_intersect, area_union, area_pred_label, area_label






def 		_snake_case	(   _snake_case				:   int							,    _snake_case				:   int							,    _snake_case				:   List[Any]							,    _snake_case				:   bool							,    _snake_case				:   Optional[Dict[int, int]] = None							,    _snake_case				:   bool = False							,    )       ->   str:






      '''simple docstring'''


      _A     =  np.zeros((num_labels,)							,    dtype=np.floataa				)
      _A     =  np.zeros((num_labels,)							,    dtype=np.floataa				)
      _A     =  np.zeros((num_labels,)							,    dtype=np.floataa				)
      _A     =  np.zeros((num_labels,)							,    dtype=np.floataa				)
      for result, gt_seg_map in zip(_snake_case							,    _snake_case				):
            _A  ,       _A  ,       _A  ,       _A     =  intersect_and_union(
                _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case				)
            total_area_intersect += area_intersect
            total_area_union += area_union
            total_area_pred_label += area_pred_label
            total_area_label += area_label
      return total_area_intersect, total_area_union, total_area_pred_label, total_area_label






def 		_snake_case	(   _snake_case				:   Tuple							,    _snake_case				:   Optional[int]							,    _snake_case				:   List[Any]							,    _snake_case				:   bool							,    _snake_case				:   Optional[int] = None							,    _snake_case				:   Optional[Dict[int, int]] = None							,    _snake_case				:   bool = False							,    )       ->   int:






      '''simple docstring'''


      _A  ,       _A  ,       _A  ,       _A     =  total_intersect_and_union(
          _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case				)

      # compute metrics
      _A     =  {}

      _A     =  total_area_intersect.sum() / total_area_label.sum()
      _A     =  total_area_intersect / total_area_union
      _A     =  total_area_intersect / total_area_label

      _A     =  np.nanmean(_snake_case				)
      _A     =  np.nanmean(_snake_case				)
      _A     =  all_acc
      _A     =  iou
      _A     =  acc

      if nan_to_num is not None:
            _A     =  {metric: np.nan_to_num(_snake_case							,    nan=_snake_case				) for metric, metric_value in metrics.items()}

      return metrics







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION     ,      _KWARGS_DESCRIPTION				)
class 							lowercase_			(	datasets.Metric				):



 '''simple docstring'''

 def      lowerCAmelCase_				(					self			:			Any						):
       return datasets.MetricInfo(
           description=_DESCRIPTION       ,				citation=_CITATION       ,				inputs_description=_KWARGS_DESCRIPTION       ,				features=datasets.Features(
               # 1st Seq - height dim, 2nd - width dim
               {
                   'predictions': datasets.Sequence(datasets.Sequence(datasets.Value('uint16'						)						)						),
                   'references': datasets.Sequence(datasets.Sequence(datasets.Value('uint16'						)						)						),
               }						)       ,				reference_urls=[
               'https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py'
           ]       ,				)



 def      lowerCAmelCase_				(					self			:			Optional[int]       ,				_UpperCAmelCase			:			int       ,				_UpperCAmelCase			:			Union[str, Any]       ,				_UpperCAmelCase			:			int       ,				_UpperCAmelCase			:			bool       ,				_UpperCAmelCase			:			Optional[int] = None       ,				_UpperCAmelCase			:			Optional[Dict[int, int]] = None       ,				_UpperCAmelCase			:			bool = False       ,				):
       _A     =  mean_iou(
           results=_UpperCAmelCase       ,				gt_seg_maps=_UpperCAmelCase       ,				num_labels=_UpperCAmelCase       ,				ignore_index=_UpperCAmelCase       ,				nan_to_num=_UpperCAmelCase       ,				label_map=_UpperCAmelCase       ,				reduce_labels=_UpperCAmelCase       ,				)
       return iou_result








"""simple docstring"""





import os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment



def 					lowerCAmelCase_      (   SCREAMING_SNAKE_CASE							:				Any     ,    SCREAMING_SNAKE_CASE							:				List[str]=()     ,    SCREAMING_SNAKE_CASE							:				Union[str, Any]=None     ,    SCREAMING_SNAKE_CASE							:				Dict="no"     ,    SCREAMING_SNAKE_CASE							:				int="29500" ):


							'''simple docstring'''







							__lowerCamelCase   :   Optional[int]       =False
							__lowerCamelCase   :   Tuple       =False
							if any(key.startswith('''KAGGLE''' ) for key in os.environ.keys() ):
														__lowerCamelCase   :   Optional[int]       =True
							elif "IPython" in sys.modules:
														__lowerCamelCase   :   int       ='''google.colab''' in str(sys.modules['''IPython'''].get_ipython() )

							try:
														__lowerCamelCase   :   str       =PrecisionType(mixed_precision.lower() )
							except ValueError:
														raise ValueError(
														    F'Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.' )

							if (in_colab or in_kaggle) and (os.environ.get('''TPU_NAME'''     ,    SCREAMING_SNAKE_CASE ) is not None):
														# TPU launch
														import torch_xla.distributed.xla_multiprocessing as xmp

														if len(AcceleratorState._shared_state ) > 0:
																					raise ValueError(
																					    '''To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside '''
																					    '''your training function. Restart your notebook and make sure no cells initializes an '''
																					    '''`Accelerator`.''' )
														if num_processes is None:
																					__lowerCamelCase   :   int       =8

														__lowerCamelCase   :   Optional[Any]       =PrepareForLaunch(SCREAMING_SNAKE_CASE     ,    distributed_type='''TPU''' )
														print(F'Launching a training on {num_processes} TPU cores.' )
														xmp.spawn(SCREAMING_SNAKE_CASE     ,    args=SCREAMING_SNAKE_CASE     ,    nprocs=SCREAMING_SNAKE_CASE     ,    start_method='''fork''' )
							elif in_colab:
														# No need for a distributed launch otherwise as it's either CPU or one GPU.
														if torch.cuda.is_available():
																					print('''Launching training on one GPU.''' )
														else:
																					print('''Launching training on one CPU.''' )
														function(*SCREAMING_SNAKE_CASE )
							else:
														if num_processes is None:
																					raise ValueError(
																					    '''You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.''' )

														if num_processes > 1:
																					# Multi-GPU launch
																					from torch.multiprocessing import start_processes
																					from torch.multiprocessing.spawn import ProcessRaisedException

																					if len(AcceleratorState._shared_state ) > 0:
																												raise ValueError(
																												    '''To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized '''
																												    '''inside your training function. Restart your notebook and make sure no cells initializes an '''
																												    '''`Accelerator`.''' )

																					if torch.cuda.is_initialized():
																												raise ValueError(
																												    '''To launch a multi-GPU training from your notebook, you need to avoid running any instruction '''
																												    '''using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA '''
																												    '''function.''' )

																					# torch.distributed will expect a few environment variable to be here. We set the ones common to each
																					# process here (the other ones will be set be the launcher).
																					with patch_environment(
																					    world_size=SCREAMING_SNAKE_CASE     ,    master_addr='''127.0.01'''     ,    master_port=SCREAMING_SNAKE_CASE     ,    mixed_precision=SCREAMING_SNAKE_CASE ):
																												__lowerCamelCase   :   List[str]       =PrepareForLaunch(SCREAMING_SNAKE_CASE     ,    distributed_type='''MULTI_GPU''' )
																												print(F'Launching training on {num_processes} GPUs.' )
																												try:
																																			start_processes(SCREAMING_SNAKE_CASE     ,    args=SCREAMING_SNAKE_CASE     ,    nprocs=SCREAMING_SNAKE_CASE     ,    start_method='''fork''' )
																												except ProcessRaisedException as e:
																																			if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
																																										raise RuntimeError(
																																										    '''CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. '''
																																										    '''This likely stems from an outside import causing issues once the `notebook_launcher()` is called. '''
																																										    '''Please review your imports and test them when running the `notebook_launcher()` to identify '''
																																										    '''which one is problematic.''' ) from e

														else:
																					# No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
																					if is_mps_available():
																												__lowerCamelCase   :   Optional[Any]       ='''1'''
																												print('''Launching training on MPS.''' )
																					elif torch.cuda.is_available():
																												print('''Launching training on one GPU.''' )
																					else:
																												print('''Launching training on CPU.''' )
																					function(*SCREAMING_SNAKE_CASE )



def 					lowerCAmelCase_      (   SCREAMING_SNAKE_CASE							:				str     ,    SCREAMING_SNAKE_CASE							:				Optional[int]=()     ,    SCREAMING_SNAKE_CASE							:				Optional[Any]=2 ):


							'''simple docstring'''







							from torch.multiprocessing import start_processes

							with tempfile.NamedTemporaryFile() as tmp_file:
														# torch.distributed will expect a few environment variable to be here. We set the ones common to each
														# process here (the other ones will be set be the launcher).
														with patch_environment(
														    world_size=SCREAMING_SNAKE_CASE     ,    master_addr='''127.0.01'''     ,    master_port='''29500'''     ,    accelerate_mixed_precision='''no'''     ,    accelerate_debug_rdv_file=tmp_file.name     ,    accelerate_use_cpu='''yes'''     ,    ):
																					__lowerCamelCase   :   Tuple       =PrepareForLaunch(SCREAMING_SNAKE_CASE     ,    debug=SCREAMING_SNAKE_CASE )
																					start_processes(SCREAMING_SNAKE_CASE     ,    args=SCREAMING_SNAKE_CASE     ,    nprocs=SCREAMING_SNAKE_CASE     ,    start_method='''fork''' )




