






'''simple docstring'''




from scipy.stats import pearsonr

import datasets


lowerCAmelCase__          =						'\nPearson correlation coefficient and p-value for testing non-correlation.\nThe 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.\nThe 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.\n'


lowerCAmelCase__          =						'\nArgs:\n    predictions (`list` of `int`): Predicted class labels, as returned by a model.\n    references (`list` of `int`): Ground truth labels.\n    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n    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.\n    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.\n\nExamples:\n\n    Example 1-A simple example using only predictions and references.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n\n    Example 2-The same as Example 1, but that also returns the `p-value`.\n        >>> pearsonr_metric = datasets.load_metric("pearsonr")\n        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n        >>> print(sorted(list(results.keys())))\n        [\'p-value\', \'pearsonr\']\n        >>> print(round(results[\'pearsonr\'], 2))\n        -0.74\n        >>> print(round(results[\'p-value\'], 2))\n        0.15\n'


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







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

	def      __UpperCamelCase							(      self   :						Tuple):
			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   :						str  ,					UpperCAmelCase_   :						int  ,					UpperCAmelCase_   :						Dict  ,					UpperCAmelCase_   :						Any=False):
			if return_pvalue:
					UpperCamelCase__				:					Dict					=					pearsonr(UpperCAmelCase_  ,					UpperCAmelCase_)
					return {"pearsonr": results[0], "p-value": results[1]}
			else:
					return {"pearsonr": float(pearsonr(UpperCAmelCase_  ,					UpperCAmelCase_)[0])}












'''simple docstring'''




import logging
import math
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union

import torch

from .tensor_utils import tensor_tree_map, tree_map







def       __UpperCAmelCase						(  lowerCamelCase_)							->     List[Tuple[int, ...]]:
		UpperCamelCase__				:					int					=					[]
		if isinstance(lowerCamelCase_     ,      lowerCamelCase_):
				for v in tree.values():
						shapes.extend(_fetch_dims(lowerCamelCase_))
		elif isinstance(lowerCamelCase_     ,      (list, tuple)):
				for t in tree:
						shapes.extend(_fetch_dims(lowerCamelCase_))
		elif isinstance(lowerCamelCase_     ,      torch.Tensor):
				shapes.append(tree.shape)
		else:
				raise ValueError('Not supported')

		return shapes







@torch.jit.ignore
def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_)							->     Tuple[int, ...]:
		UpperCamelCase__				:					int					=					[]
		for d in reversed(lowerCamelCase_):
				idx.append(flat_idx % d)
				UpperCamelCase__				:					Any					=					flat_idx // d

		return tuple(reversed(lowerCamelCase_))







@torch.jit.ignore
def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_ = None     ,      lowerCamelCase_ = None     ,      )							->     List[Tuple[slice, ...]]:

		# start_edges and end_edges both indicate whether, starting from any given
		# dimension, the start/end index is at the top/bottom edge of the
		# corresponding tensor, modeled as a tree
		def reduce_edge_list(lowerCamelCase_) -> None:
				UpperCamelCase__				:					Tuple					=					True
				for i in range(len(lowerCamelCase_)):
						UpperCamelCase__				:					List[Any]					=					-1 * (i + 1)
						l[reversed_idx] &= tally
						UpperCamelCase__				:					Optional[Any]					=					l[reversed_idx]

		if start_edges is None:
				UpperCamelCase__				:					int					=					[s == 0 for s in start]
				reduce_edge_list(lowerCamelCase_)
		if end_edges is None:
				UpperCamelCase__				:					List[str]					=					[e == (d - 1) for e, d in zip(lowerCamelCase_     ,      lowerCamelCase_)]
				reduce_edge_list(lowerCamelCase_)

		# Base cases. Either start/end are empty and we're done, or the final,
		# one-dimensional tensor can be simply sliced
		if len(lowerCamelCase_) == 0:
				return [()]
		elif len(lowerCamelCase_) == 1:
				return [(slice(start[0]     ,      end[0] + 1),)]

		UpperCamelCase__				:					List[Tuple[slice, ...]]					=					[]
		UpperCamelCase__				:					List[slice]					=					[]

		# Dimensions common to start and end can be selected directly
		for s, e in zip(lowerCamelCase_     ,      lowerCamelCase_):
				if s == e:
						path_list.append(slice(lowerCamelCase_     ,      s + 1))
				else:
						break

		UpperCamelCase__				:					Tuple[slice, ...]					=					tuple(lowerCamelCase_)
		UpperCamelCase__				:					Dict					=					len(lowerCamelCase_)

		# start == end, and we're done
		if divergence_idx == len(lowerCamelCase_):
				return [path]

		def upper() -> Tuple[Tuple[slice, ...], ...]:
				assert start_edges is not None
				assert end_edges is not None

				UpperCamelCase__				:					str					=					start[divergence_idx]
				return tuple(
				    path + (slice(lowerCamelCase_     ,      sdi + 1),) + s
				    for s in _get_minimal_slice_set(
				        start[divergence_idx + 1 :]     ,      [d - 1 for d in dims[divergence_idx + 1 :]]     ,      dims[divergence_idx + 1 :]     ,      start_edges=start_edges[divergence_idx + 1 :]     ,      end_edges=[True for _ in end_edges[divergence_idx + 1 :]]     ,      ))

		def lower() -> Tuple[Tuple[slice, ...], ...]:
				assert start_edges is not None
				assert end_edges is not None

				UpperCamelCase__				:					Optional[int]					=					end[divergence_idx]
				return tuple(
				    path + (slice(lowerCamelCase_     ,      edi + 1),) + s
				    for s in _get_minimal_slice_set(
				        [0 for _ in start[divergence_idx + 1 :]]     ,      end[divergence_idx + 1 :]     ,      dims[divergence_idx + 1 :]     ,      start_edges=[True for _ in start_edges[divergence_idx + 1 :]]     ,      end_edges=end_edges[divergence_idx + 1 :]     ,      ))

		# If both start and end are at the edges of the subtree rooted at
		# divergence_idx, we can just select the whole subtree at once
		if start_edges[divergence_idx] and end_edges[divergence_idx]:
				slices.append(path + (slice(start[divergence_idx]     ,      end[divergence_idx] + 1),))
		# If just start is at the edge, we can grab almost all of the subtree,
		# treating only the ragged bottom edge as an edge case
		elif start_edges[divergence_idx]:
				slices.append(path + (slice(start[divergence_idx]     ,      end[divergence_idx]),))
				slices.extend(lower())
		# Analogous to the previous case, but the top is ragged this time
		elif end_edges[divergence_idx]:
				slices.extend(upper())
				slices.append(path + (slice(start[divergence_idx] + 1     ,      end[divergence_idx] + 1),))
		# If both sides of the range are ragged, we need to handle both sides
		# separately. If there's contiguous meat in between them, we can index it
		# in one big chunk
		else:
				slices.extend(upper())
				UpperCamelCase__				:					Dict					=					end[divergence_idx] - start[divergence_idx]
				if middle_ground > 1:
						slices.append(path + (slice(start[divergence_idx] + 1     ,      end[divergence_idx]),))
				slices.extend(lower())

		return slices







@torch.jit.ignore
def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_)							->     torch.Tensor:
		UpperCamelCase__				:					List[Any]					=					t.shape[:no_batch_dims]
		UpperCamelCase__				:					Optional[int]					=					list(_flat_idx_to_idx(lowerCamelCase_     ,      lowerCamelCase_))
		# _get_minimal_slice_set is inclusive
		UpperCamelCase__				:					Dict					=					list(_flat_idx_to_idx(flat_end - 1     ,      lowerCamelCase_))

		# Get an ordered list of slices to perform
		UpperCamelCase__				:					int					=					_get_minimal_slice_set(
		    lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_     ,      )

		UpperCamelCase__				:					List[Any]					=					[t[s] for s in slices]

		return torch.cat([s.view((-1,) + t.shape[no_batch_dims:]) for s in sliced_tensors])







def       __UpperCAmelCase						(  lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_     ,      lowerCamelCase_ = False     ,      lowerCamelCase_ = None     ,      lowerCamelCase_ = False     ,      )							->     Any:
		if not (len(lowerCamelCase_) > 0):
				raise ValueError('Must provide at least one input')

		UpperCamelCase__				:					int					=					[shape[:no_batch_dims] for shape in _fetch_dims(lowerCamelCase_)]
		UpperCamelCase__				:					int					=					tuple([max(lowerCamelCase_) for s in zip(*lowerCamelCase_)])

		def _prep_inputs(lowerCamelCase_) -> torch.Tensor:
				if not low_mem:
						if not sum(t.shape[:no_batch_dims]) == no_batch_dims:
								UpperCamelCase__				:					List[Any]					=					t.expand(orig_batch_dims + t.shape[no_batch_dims:])
						UpperCamelCase__				:					Optional[int]					=					t.reshape(-1     ,      *t.shape[no_batch_dims:])
				else:
						UpperCamelCase__				:					Optional[int]					=					t.expand(orig_batch_dims + t.shape[no_batch_dims:])
				return t

		UpperCamelCase__				:					Dict[str, Any]					=					tensor_tree_map(_prep_inputs     ,      lowerCamelCase_)
		UpperCamelCase__				:					int					=					None
		if _out is not None:
				UpperCamelCase__				:					Optional[int]					=					tensor_tree_map(lambda lowerCamelCase_: t.view([-1] + list(t.shape[no_batch_dims:]))     ,      _out)

		UpperCamelCase__				:					Dict					=					1
		for d in orig_batch_dims:
				flat_batch_dim *= d

		UpperCamelCase__				:					int					=					flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0)

		def _select_chunk(lowerCamelCase_) -> torch.Tensor:
				return t[i : i + chunk_size] if t.shape[0] != 1 else t

		UpperCamelCase__				:					List[Any]					=					0
		UpperCamelCase__				:					Optional[Any]					=					prepped_outputs
		for _ in range(lowerCamelCase_):
				# Chunk the input
				if not low_mem:
						UpperCamelCase__				:					str					=					_select_chunk
				else:
						UpperCamelCase__				:					List[Any]					=					partial(
						    _chunk_slice     ,      flat_start=lowerCamelCase_     ,      flat_end=min(lowerCamelCase_     ,      i + chunk_size)     ,      no_batch_dims=len(lowerCamelCase_)     ,      )

				UpperCamelCase__				:					Dict[str, Any]					=					tensor_tree_map(lowerCamelCase_     ,      lowerCamelCase_)

				# Run the layer on the chunk
				UpperCamelCase__				:					List[Any]					=					layer(**lowerCamelCase_)

				# Allocate space for the output
				if out is None:
						UpperCamelCase__				:					Optional[int]					=					tensor_tree_map(lambda lowerCamelCase_: t.new_zeros((flat_batch_dim,) + t.shape[1:])     ,      lowerCamelCase_)

				# Put the chunk in its pre-allocated space
				if isinstance(lowerCamelCase_     ,      lowerCamelCase_):

						def assign(lowerCamelCase_     ,      lowerCamelCase_) -> None:
								for k, v in da.items():
										if isinstance(lowerCamelCase_     ,      lowerCamelCase_):
												assign(lowerCamelCase_     ,      da[k])
										else:
												if _add_into_out:
														v[i : i + chunk_size] += da[k]
												else:
														UpperCamelCase__				:					List[str]					=					da[k]

						assign(lowerCamelCase_     ,      lowerCamelCase_)
				elif isinstance(lowerCamelCase_     ,      lowerCamelCase_):
						for xa, xa in zip(lowerCamelCase_     ,      lowerCamelCase_):
								if _add_into_out:
										xa[i : i + chunk_size] += xa
								else:
										UpperCamelCase__				:					int					=					xa
				elif isinstance(lowerCamelCase_     ,      torch.Tensor):
						if _add_into_out:
								out[i : i + chunk_size] += output_chunk
						else:
								UpperCamelCase__				:					Dict					=					output_chunk
				else:
						raise ValueError('Not supported')

				i += chunk_size

		UpperCamelCase__				:					int					=					tensor_tree_map(lambda lowerCamelCase_: t.view(orig_batch_dims + t.shape[1:])     ,      lowerCamelCase_)

		return out







class       __lowercase					:

	def __init__(      self   :						List[str]  ,					UpperCAmelCase_   :						int = 512  ,					):
			UpperCamelCase__				:					str					=					max_chunk_size
			UpperCamelCase__				:					Optional[int]					=					None
			UpperCamelCase__				:					Optional[tuple]					=					None

	def      __UpperCamelCase							(      self   :						str  ,					UpperCAmelCase_   :						Callable  ,					UpperCAmelCase_   :						tuple  ,					UpperCAmelCase_   :						int):
			logging.info('Tuning chunk size...')

			if min_chunk_size >= self.max_chunk_size:
					return min_chunk_size

			UpperCamelCase__				:					List[int]					=					[2**l for l in range(int(math.log(self.max_chunk_size  ,					2)) + 1)]
			UpperCamelCase__				:					List[Any]					=					[c for c in candidates if c > min_chunk_size]
			UpperCamelCase__				:					List[Any]					=					[min_chunk_size] + candidates
			candidates[-1] += 4

			def test_chunk_size(UpperCAmelCase_   :						int) -> bool:
					try:
							with torch.no_grad():
									fn(*UpperCAmelCase_  ,					chunk_size=UpperCAmelCase_)
							return True
					except RuntimeError:
							return False

			UpperCamelCase__				:					Tuple					=					0
			UpperCamelCase__				:					Dict					=					len(UpperCAmelCase_) - 1
			while i > min_viable_chunk_size_index:
					UpperCamelCase__				:					Optional[int]					=					test_chunk_size(candidates[i])
					if not viable:
							UpperCamelCase__				:					Tuple					=					(min_viable_chunk_size_index + i) // 2
					else:
							UpperCamelCase__				:					Optional[int]					=					i
							UpperCamelCase__				:					Dict					=					(i + len(UpperCAmelCase_) - 1) // 2

			return candidates[min_viable_chunk_size_index]

	def      __UpperCamelCase							(      self   :						Any  ,					UpperCAmelCase_   :						Iterable  ,					UpperCAmelCase_   :						Iterable):
			UpperCamelCase__				:					List[str]					=					True
			for aa, aa in zip(UpperCAmelCase_  ,					UpperCAmelCase_):
					assert type(UpperCAmelCase_) == type(UpperCAmelCase_)
					if isinstance(UpperCAmelCase_  ,					(list, tuple)):
							consistent &= self._compare_arg_caches(UpperCAmelCase_  ,					UpperCAmelCase_)
					elif isinstance(UpperCAmelCase_  ,					UpperCAmelCase_):
							UpperCamelCase__				:					Union[str, Any]					=					[v for _, v in sorted(aa.items()  ,					key=lambda UpperCAmelCase_: x[0])]
							UpperCamelCase__				:					str					=					[v for _, v in sorted(aa.items()  ,					key=lambda UpperCAmelCase_: x[0])]
							consistent &= self._compare_arg_caches(UpperCAmelCase_  ,					UpperCAmelCase_)
					else:
							consistent &= aa == aa

			return consistent





	def      __UpperCamelCase							(      self   :						List[Any]  ,					UpperCAmelCase_   :						Callable  ,					UpperCAmelCase_   :						tuple  ,					UpperCAmelCase_   :						int  ,					):
			UpperCamelCase__				:					List[Any]					=					True
			UpperCamelCase__				:					tuple					=					tree_map(lambda UpperCAmelCase_: a.shape if isinstance(UpperCAmelCase_  ,					torch.Tensor) else a  ,					UpperCAmelCase_  ,					UpperCAmelCase_)
			if self.cached_arg_data is not None:
					# If args have changed shape/value, we need to re-tune
					assert len(self.cached_arg_data) == len(UpperCAmelCase_)
					UpperCamelCase__				:					Union[str, Any]					=					self._compare_arg_caches(self.cached_arg_data  ,					UpperCAmelCase_)
			else:
					# Otherwise, we can reuse the precomputed value
					UpperCamelCase__				:					Optional[int]					=					False

			if not consistent:
					UpperCamelCase__				:					Tuple					=					self._determine_favorable_chunk_size(
					    UpperCAmelCase_  ,					UpperCAmelCase_  ,					UpperCAmelCase_  ,					)
					UpperCamelCase__				:					Optional[Any]					=					arg_data

			assert self.cached_chunk_size is not None

			return self.cached_chunk_size




