






"""simple docstring"""





from copy import deepcopy
from typing import Optional, Union

import numpy as np

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_tf_available, is_torch_available


if is_torch_available():
  import torch

if is_tf_available():
  import tensorflow as tf






class 	a		(   __snake_case						):
    SCREAMING_SNAKE_CASE		:	Union[str, Any]		=					["""image_processor"""]
    SCREAMING_SNAKE_CASE		:	List[Any]		=					"""SamImageProcessor"""






    def __init__(			self	:				Tuple			,		__SCREAMING_SNAKE_CASE	:				Optional[int]   )	->						Optional[int]:
      super().__init__(__SCREAMING_SNAKE_CASE   )
      lowerCamelCase_       	=		self.image_processor
      lowerCamelCase_       	=		-10
      lowerCamelCase_       	=		self.image_processor.size['longest_edge']






    def __call__(			self	:				Tuple			,		__SCREAMING_SNAKE_CASE	:				int=None			,		__SCREAMING_SNAKE_CASE	:				Dict=None			,		__SCREAMING_SNAKE_CASE	:				Tuple=None			,		__SCREAMING_SNAKE_CASE	:				Any=None			,		__SCREAMING_SNAKE_CASE	:				Optional[Union[str, TensorType]] = None			,		**__SCREAMING_SNAKE_CASE	:				List[Any]			,		)	->						BatchEncoding:
      lowerCamelCase_       	=		self.image_processor(
          __SCREAMING_SNAKE_CASE			,		return_tensors=__SCREAMING_SNAKE_CASE			,		**__SCREAMING_SNAKE_CASE			,		)

      # pop arguments that are not used in the foward but used nevertheless
      lowerCamelCase_       	=		encoding_image_processor['original_sizes']

      if hasattr(__SCREAMING_SNAKE_CASE			,		'numpy'   ):  # Checks if Torch or TF tensor
        lowerCamelCase_       	=		original_sizes.numpy()

      lowerCamelCase_	,      lowerCamelCase_	,      lowerCamelCase_       	=		self._check_and_preprocess_points(
          input_points=__SCREAMING_SNAKE_CASE			,		input_labels=__SCREAMING_SNAKE_CASE			,		input_boxes=__SCREAMING_SNAKE_CASE			,		)

      lowerCamelCase_       	=		self._normalize_and_convert(
          __SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		input_points=__SCREAMING_SNAKE_CASE			,		input_labels=__SCREAMING_SNAKE_CASE			,		input_boxes=__SCREAMING_SNAKE_CASE			,		return_tensors=__SCREAMING_SNAKE_CASE			,		)

      return encoding_image_processor






    def   UpperCamelCase			(			self	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				int			,		__SCREAMING_SNAKE_CASE	:				List[str]			,		__SCREAMING_SNAKE_CASE	:				Dict=None			,		__SCREAMING_SNAKE_CASE	:				Union[str, Any]=None			,		__SCREAMING_SNAKE_CASE	:				Optional[int]=None			,		__SCREAMING_SNAKE_CASE	:				int="pt"			,		)	->						str:
      if input_points is not None:
        if len(__SCREAMING_SNAKE_CASE   ) != len(__SCREAMING_SNAKE_CASE   ):
          lowerCamelCase_       	=		[
              self._normalize_coordinates(self.target_size			,		__SCREAMING_SNAKE_CASE			,		original_sizes[0]   ) for point in input_points
          ]
        else:
          lowerCamelCase_       	=		[
              self._normalize_coordinates(self.target_size			,		__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )
              for point, original_size in zip(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )
          ]
        # check that all arrays have the same shape
        if not all(point.shape == input_points[0].shape for point in input_points   ):
          if input_labels is not None:
            lowerCamelCase_	,      lowerCamelCase_       	=		self._pad_points_and_labels(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )

        lowerCamelCase_       	=		np.array(__SCREAMING_SNAKE_CASE   )

      if input_labels is not None:
        lowerCamelCase_       	=		np.array(__SCREAMING_SNAKE_CASE   )

      if input_boxes is not None:
        if len(__SCREAMING_SNAKE_CASE   ) != len(__SCREAMING_SNAKE_CASE   ):
          lowerCamelCase_       	=		[
              self._normalize_coordinates(self.target_size			,		__SCREAMING_SNAKE_CASE			,		original_sizes[0]			,		is_bounding_box=__SCREAMING_SNAKE_CASE   )
              for box in input_boxes
          ]
        else:
          lowerCamelCase_       	=		[
              self._normalize_coordinates(self.target_size			,		__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE			,		is_bounding_box=__SCREAMING_SNAKE_CASE   )
              for box, original_size in zip(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )
          ]
        lowerCamelCase_       	=		np.array(__SCREAMING_SNAKE_CASE   )

      if input_boxes is not None:
        if return_tensors == "pt":
          lowerCamelCase_       	=		torch.from_numpy(__SCREAMING_SNAKE_CASE   )
          # boxes batch size of 1 by default
          lowerCamelCase_       	=		input_boxes.unsqueeze(1   ) if len(input_boxes.shape   ) != 3 else input_boxes
        elif return_tensors == "tf":
          lowerCamelCase_       	=		tf.convert_to_tensor(__SCREAMING_SNAKE_CASE   )
          # boxes batch size of 1 by default
          lowerCamelCase_       	=		tf.expand_dims(__SCREAMING_SNAKE_CASE			,		1   ) if len(input_boxes.shape   ) != 3 else input_boxes
        encoding_image_processor.update({'input_boxes': input_boxes}   )
      if input_points is not None:
        if return_tensors == "pt":
          lowerCamelCase_       	=		torch.from_numpy(__SCREAMING_SNAKE_CASE   )
          # point batch size of 1 by default
          lowerCamelCase_       	=		input_points.unsqueeze(1   ) if len(input_points.shape   ) != 4 else input_points
        elif return_tensors == "tf":
          lowerCamelCase_       	=		tf.convert_to_tensor(__SCREAMING_SNAKE_CASE   )
          # point batch size of 1 by default
          lowerCamelCase_       	=		tf.expand_dims(__SCREAMING_SNAKE_CASE			,		1   ) if len(input_points.shape   ) != 4 else input_points
        encoding_image_processor.update({'input_points': input_points}   )
      if input_labels is not None:
        if return_tensors == "pt":
          lowerCamelCase_       	=		torch.from_numpy(__SCREAMING_SNAKE_CASE   )
          # point batch size of 1 by default
          lowerCamelCase_       	=		input_labels.unsqueeze(1   ) if len(input_labels.shape   ) != 3 else input_labels
        elif return_tensors == "tf":
          lowerCamelCase_       	=		tf.convert_to_tensor(__SCREAMING_SNAKE_CASE   )
          # point batch size of 1 by default
          lowerCamelCase_       	=		tf.expand_dims(__SCREAMING_SNAKE_CASE			,		1   ) if len(input_labels.shape   ) != 3 else input_labels
        encoding_image_processor.update({'input_labels': input_labels}   )

      return encoding_image_processor






    def   UpperCamelCase			(			self	:				Optional[Any]			,		__SCREAMING_SNAKE_CASE	:				Tuple			,		__SCREAMING_SNAKE_CASE	:				str   )	->						Optional[Any]:
      lowerCamelCase_       	=		max([point.shape[0] for point in input_points]   )
      lowerCamelCase_       	=		[]
      for i, point in enumerate(__SCREAMING_SNAKE_CASE   ):
        if point.shape[0] != expected_nb_points:
          lowerCamelCase_       	=		np.concatenate(
              [point, np.zeros((expected_nb_points - point.shape[0], 2)   ) + self.point_pad_value]			,		axis=0   )
          lowerCamelCase_       	=		np.append(input_labels[i]			,		[self.point_pad_value]   )
        processed_input_points.append(__SCREAMING_SNAKE_CASE   )
      lowerCamelCase_       	=		processed_input_points
      return input_points, input_labels






    def   UpperCamelCase			(			self	:				Any			,		__SCREAMING_SNAKE_CASE	:				int			,		__SCREAMING_SNAKE_CASE	:				np.ndarray			,		__SCREAMING_SNAKE_CASE	:				Dict			,		__SCREAMING_SNAKE_CASE	:				List[Any]=False   )	->						np.ndarray:
      lowerCamelCase_	,      lowerCamelCase_       	=		original_size
      lowerCamelCase_	,      lowerCamelCase_       	=		self.image_processor._get_preprocess_shape(__SCREAMING_SNAKE_CASE			,		longest_edge=__SCREAMING_SNAKE_CASE   )
      lowerCamelCase_       	=		deepcopy(__SCREAMING_SNAKE_CASE   ).astype(__SCREAMING_SNAKE_CASE   )

      if is_bounding_box:
        lowerCamelCase_       	=		coords.reshape(-1			,		2			,		2   )

      lowerCamelCase_       	=		coords[..., 0] * (new_w / old_w)
      lowerCamelCase_       	=		coords[..., 1] * (new_h / old_h)

      if is_bounding_box:
        lowerCamelCase_       	=		coords.reshape(-1			,		4   )

      return coords






    def   UpperCamelCase			(			self	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				Optional[Any]=None			,		__SCREAMING_SNAKE_CASE	:				int=None			,		__SCREAMING_SNAKE_CASE	:				List[str]=None			,		)	->						Any:
      if input_points is not None:
        if hasattr(__SCREAMING_SNAKE_CASE			,		'numpy'   ):  # Checks for TF or Torch tensor
          lowerCamelCase_       	=		input_points.numpy().tolist()

        if not isinstance(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   ) or not isinstance(input_points[0]			,		__SCREAMING_SNAKE_CASE   ):
          raise ValueError('Input points must be a list of list of floating points.'   )
        lowerCamelCase_       	=		[np.array(__SCREAMING_SNAKE_CASE   ) for input_point in input_points]
      else:
        lowerCamelCase_       	=		None

      if input_labels is not None:
        if hasattr(__SCREAMING_SNAKE_CASE			,		'numpy'   ):
          lowerCamelCase_       	=		input_labels.numpy().tolist()

        if not isinstance(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   ) or not isinstance(input_labels[0]			,		__SCREAMING_SNAKE_CASE   ):
          raise ValueError('Input labels must be a list of list integers.'   )
        lowerCamelCase_       	=		[np.array(__SCREAMING_SNAKE_CASE   ) for label in input_labels]
      else:
        lowerCamelCase_       	=		None

      if input_boxes is not None:
        if hasattr(__SCREAMING_SNAKE_CASE			,		'numpy'   ):
          lowerCamelCase_       	=		input_boxes.numpy().tolist()

        if (
            not isinstance(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )
            or not isinstance(input_boxes[0]			,		__SCREAMING_SNAKE_CASE   )
            or not isinstance(input_boxes[0][0]			,		__SCREAMING_SNAKE_CASE   )
        ):
          raise ValueError('Input boxes must be a list of list of list of floating points.'   )
        lowerCamelCase_       	=		[np.array(__SCREAMING_SNAKE_CASE   ).astype(np.floataa   ) for box in input_boxes]
      else:
        lowerCamelCase_       	=		None

      return input_points, input_labels, input_boxes






    @property
    def   UpperCamelCase			(			self	:				Union[str, Any]   )	->						Any:
      lowerCamelCase_       	=		self.image_processor.model_input_names
      return list(dict.fromkeys(__SCREAMING_SNAKE_CASE   )   )






    def   UpperCamelCase			(			self	:				int			,		*__SCREAMING_SNAKE_CASE	:				List[Any]			,		**__SCREAMING_SNAKE_CASE	:				Optional[int]   )	->						Optional[int]:
      return self.image_processor.post_process_masks(*__SCREAMING_SNAKE_CASE			,		**__SCREAMING_SNAKE_CASE   )












"""simple docstring"""





from scipy.stats import pearsonr

import datasets


_SCREAMING_SNAKE_CASE   :							List[str]          =		'''
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
'''


_SCREAMING_SNAKE_CASE   :							int          =		'''
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric("pearsonr")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results[\'pearsonr\'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric("pearsonr")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        [\'p-value\', \'pearsonr\']
        >>> print(round(results[\'pearsonr\'], 2))
        -0.74
        >>> print(round(results[\'p-value\'], 2))
        0.15
'''


_SCREAMING_SNAKE_CASE   :							Dict          =		'''
@article{2020SciPy-NMeth,
author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
      Haberland, Matt and Reddy, Tyler and Cournapeau, David and
      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
      Kern, Robert and Larson, Eric and Carey, C J and
      Polat, Ilhan and Feng, Yu and Moore, Eric W. and
      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
      Harris, Charles R. and Archibald, Anne M. and
      Ribeiro, Antonio H. and Pedregosa, Fabian and
      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
      Computing in Python}},
journal = {Nature Methods},
year    = {2020},
volume  = {17},
pages   = {261--272},
adsurl  = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
'''






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






    def   UpperCamelCase			(			self	:				Dict   )	->						Any:
      return datasets.MetricInfo(
          description=_DESCRIPTION			,		citation=_CITATION			,		inputs_description=_KWARGS_DESCRIPTION			,		features=datasets.Features(
              {
                  'predictions': datasets.Value('float'   ),
                  'references': datasets.Value('float'   ),
              }   )			,		reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html']			,		)






    def   UpperCamelCase			(			self	:				Union[str, Any]			,		__SCREAMING_SNAKE_CASE	:				List[Any]			,		__SCREAMING_SNAKE_CASE	:				Tuple			,		__SCREAMING_SNAKE_CASE	:				Tuple=False   )	->						Tuple:
      if return_pvalue:
        lowerCamelCase_       	=		pearsonr(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )
        return {"pearsonr": results[0], "p-value": results[1]}
      else:
        return {"pearsonr": float(pearsonr(__SCREAMING_SNAKE_CASE			,		__SCREAMING_SNAKE_CASE   )[0]   )}




