






"""simple docstring"""







import os
import tempfile
from functools import partial
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pytest

from datasets.arrow_dataset import Dataset
from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex

from .utils import require_elasticsearch, require_faiss


a			:    List[Any]				 =		pytest.mark.integration


@require_faiss
class    __UpperCAmelCase(       SCREAMING_SNAKE_CASE__							):




						"""simple docstring"""




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Tuple=	Dataset.from_dict({"filename": ["my_name-train" + "_" + str(snake_case__      ) for x in np.arange(30      ).tolist()]}      )
												return dset




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												import faiss

												lowercase__    :				Dataset=	self._create_dummy_dataset()
												lowercase__    :				Optional[Any]=	dset.map(
												    lambda snake_case__	,  snake_case__      : {"vecs": i * np.ones(5	,  dtype=np.floataa      )}	,  with_indices=snake_case__	,  keep_in_memory=snake_case__      )
												lowercase__    :				Optional[Any]=	dset.add_faiss_index("vecs"	,  batch_size=100	,  metric_type=faiss.METRIC_INNER_PRODUCT      )
												lowercase__,     lowercase__    :				Any=	dset.get_nearest_examples("vecs"	,  np.ones(5	,  dtype=np.floataa      )      )
												self.assertEqual(examples["filename"][0]	,  "my_name-train_29"      )
												dset.drop_index("vecs"      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												import faiss

												lowercase__    :				Dataset=	self._create_dummy_dataset()
												dset.add_faiss_index_from_external_arrays(
												    external_arrays=np.ones((30, 5)      ) * np.arange(30      ).reshape(-1	,  1      )	,  index_name="vecs"	,  batch_size=100	,  metric_type=faiss.METRIC_INNER_PRODUCT	,  )
												lowercase__,     lowercase__    :				Optional[Any]=	dset.get_nearest_examples("vecs"	,  np.ones(5	,  dtype=np.floataa      )      )
												self.assertEqual(examples["filename"][0]	,  "my_name-train_29"      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												import faiss

												lowercase__    :				Dataset=	self._create_dummy_dataset()
												dset.add_faiss_index_from_external_arrays(
												    external_arrays=np.ones((30, 5)      ) * np.arange(30      ).reshape(-1	,  1      )	,  index_name="vecs"	,  metric_type=faiss.METRIC_INNER_PRODUCT	,  )

												# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
												# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
												# see https://bugs.python.org/issue14243 and
												# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
												with tempfile.NamedTemporaryFile(delete=snake_case__      ) as tmp_file:
																		dset.save_faiss_index("vecs"	,  tmp_file.name      )
																		dset.load_faiss_index("vecs2"	,  tmp_file.name      )
												os.unlink(tmp_file.name      )

												lowercase__,     lowercase__    :				Any=	dset.get_nearest_examples("vecs2"	,  np.ones(5	,  dtype=np.floataa      )      )
												self.assertEqual(examples["filename"][0]	,  "my_name-train_29"      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Dataset=	self._create_dummy_dataset()
												dset.add_faiss_index_from_external_arrays(
												    external_arrays=np.ones((30, 5)      ) * np.arange(30      ).reshape(-1	,  1      )	,  index_name="vecs"      )
												dset.drop_index("vecs"      )
												self.assertRaises(snake_case__	,  partial(dset.get_nearest_examples	,  "vecs2"	,  np.ones(5	,  dtype=np.floataa      )      )      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												from elasticsearch import Elasticsearch

												lowercase__    :				Dataset=	self._create_dummy_dataset()
												with patch("elasticsearch.Elasticsearch.search"      ) as mocked_search, patch(
												    "elasticsearch.client.IndicesClient.create"      ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk"      ) as mocked_bulk:
																		lowercase__    :				Dict=	{"acknowledged": True}
																		mocked_bulk.return_value([(True, None)] * 30      )
																		lowercase__    :				Optional[int]=	{"hits": {"hits": [{"_score": 1, "_id": 29}]}}
																		lowercase__    :				List[Any]=	Elasticsearch()

																		dset.add_elasticsearch_index("filename"	,  es_client=snake_case__      )
																		lowercase__,     lowercase__    :				List[str]=	dset.get_nearest_examples("filename"	,  "my_name-train_29"      )
																		self.assertEqual(examples["filename"][0]	,  "my_name-train_29"      )


@require_faiss
class    __UpperCAmelCase(       SCREAMING_SNAKE_CASE__							):




						"""simple docstring"""




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												import faiss

												lowercase__    :				Any=	FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT      )

												# add vectors
												index.add_vectors(np.eye(5	,  dtype=np.floataa      )      )
												self.assertIsNotNone(index.faiss_index      )
												self.assertEqual(index.faiss_index.ntotal	,  5      )
												index.add_vectors(np.zeros((5, 5)	,  dtype=np.floataa      )      )
												self.assertEqual(index.faiss_index.ntotal	,  10      )

												# single query
												lowercase__    :				Dict=	np.zeros(5	,  dtype=np.floataa      )
												lowercase__    :				Tuple=	1
												lowercase__,     lowercase__    :				int=	index.search(snake_case__      )
												self.assertRaises(snake_case__	,  index.search	,  query.reshape(-1	,  1      )      )
												self.assertGreater(scores[0]	,  0      )
												self.assertEqual(indices[0]	,  1      )

												# batched queries
												lowercase__    :				Union[str, Any]=	np.eye(5	,  dtype=np.floataa      )[::-1]
												lowercase__,     lowercase__    :				int=	index.search_batch(snake_case__      )
												self.assertRaises(snake_case__	,  index.search_batch	,  queries[0]      )
												lowercase__    :				Optional[Any]=	[scores[0] for scores in total_scores]
												lowercase__    :				Any=	[indices[0] for indices in total_indices]
												self.assertGreater(np.min(snake_case__      )	,  0      )
												self.assertListEqual([4, 3, 2, 1, 0]	,  snake_case__      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												import faiss

												lowercase__    :				Dict=	FaissIndex(string_factory="Flat"      )
												index.add_vectors(np.eye(5	,  dtype=np.floataa      )      )
												self.assertIsInstance(index.faiss_index	,  faiss.IndexFlat      )
												lowercase__    :				int=	FaissIndex(string_factory="LSH"      )
												index.add_vectors(np.eye(5	,  dtype=np.floataa      )      )
												self.assertIsInstance(index.faiss_index	,  faiss.IndexLSH      )
												with self.assertRaises(snake_case__      ):
																		lowercase__    :				Tuple=	FaissIndex(string_factory="Flat"	,  custom_index=faiss.IndexFlat(5      )      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												import faiss

												lowercase__    :				str=	faiss.IndexFlat(5      )
												lowercase__    :				Union[str, Any]=	FaissIndex(custom_index=snake_case__      )
												index.add_vectors(np.eye(5	,  dtype=np.floataa      )      )
												self.assertIsInstance(index.faiss_index	,  faiss.IndexFlat      )




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												import faiss

												lowercase__    :				Any=	FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT      )
												index.add_vectors(np.eye(5	,  dtype=np.floataa      )      )

												# Setting delete=False and unlinking manually is not pretty... but it is required on Windows to
												# ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue.
												# see https://bugs.python.org/issue14243 and
												# https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515
												with tempfile.NamedTemporaryFile(delete=snake_case__      ) as tmp_file:
																		index.save(tmp_file.name      )
																		lowercase__    :				Tuple=	FaissIndex.load(tmp_file.name      )
												os.unlink(tmp_file.name      )

												lowercase__    :				Optional[int]=	np.zeros(5	,  dtype=np.floataa      )
												lowercase__    :				Dict=	1
												lowercase__,     lowercase__    :				List[str]=	index.search(snake_case__      )
												self.assertGreater(scores[0]	,  0      )
												self.assertEqual(indices[0]	,  1      )





@require_faiss
def 						lowercase__(A						)    ->str:




						"""simple docstring"""



						import faiss

						lowercase__    :				List[str]=	FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT						)
						index.add_vectors(np.eye(5 ,		dtype=np.floataa						)						)

						lowercase__    :				Any=	"index.faiss"
						lowercase__    :				List[Any]=	f'''mock://{index_name}'''
						index.save(A ,		storage_options=mockfs.storage_options						)
						lowercase__    :				Optional[Any]=	FaissIndex.load(A ,		storage_options=mockfs.storage_options						)

						lowercase__    :				int=	np.zeros(5 ,		dtype=np.floataa						)
						lowercase__    :				str=	1
						lowercase__,     lowercase__    :				str=	index.search(A						)
						assert scores[0] > 0
						assert indices[0] == 1







@require_elasticsearch
class    __UpperCAmelCase(       SCREAMING_SNAKE_CASE__							):




						"""simple docstring"""




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												from elasticsearch import Elasticsearch

												with patch("elasticsearch.Elasticsearch.search"      ) as mocked_search, patch(
												    "elasticsearch.client.IndicesClient.create"      ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk"      ) as mocked_bulk:
																		lowercase__    :				Union[str, Any]=	Elasticsearch()
																		lowercase__    :				Any=	{"acknowledged": True}
																		lowercase__    :				List[str]=	ElasticSearchIndex(es_client=snake_case__      )
																		mocked_bulk.return_value([(True, None)] * 3      )
																		index.add_documents(["foo", "bar", "foobar"]      )

																		# single query
																		lowercase__    :				Tuple=	"foo"
																		lowercase__    :				int=	{"hits": {"hits": [{"_score": 1, "_id": 0}]}}
																		lowercase__,     lowercase__    :				List[Any]=	index.search(snake_case__      )
																		self.assertEqual(scores[0]	,  1      )
																		self.assertEqual(indices[0]	,  0      )

																		# single query with timeout
																		lowercase__    :				Optional[Any]=	"foo"
																		lowercase__    :				Union[str, Any]=	{"hits": {"hits": [{"_score": 1, "_id": 0}]}}
																		lowercase__,     lowercase__    :				Union[str, Any]=	index.search(snake_case__	,  request_timeout=30      )
																		self.assertEqual(scores[0]	,  1      )
																		self.assertEqual(indices[0]	,  0      )

																		# batched queries
																		lowercase__    :				str=	["foo", "bar", "foobar"]
																		lowercase__    :				Tuple=	{"hits": {"hits": [{"_score": 1, "_id": 1}]}}
																		lowercase__,     lowercase__    :				str=	index.search_batch(snake_case__      )
																		lowercase__    :				str=	[scores[0] for scores in total_scores]
																		lowercase__    :				List[str]=	[indices[0] for indices in total_indices]
																		self.assertGreater(np.min(snake_case__      )	,  0      )
																		self.assertListEqual([1, 1, 1]	,  snake_case__      )

																		# batched queries with timeout
																		lowercase__    :				str=	["foo", "bar", "foobar"]
																		lowercase__    :				List[Any]=	{"hits": {"hits": [{"_score": 1, "_id": 1}]}}
																		lowercase__,     lowercase__    :				Optional[int]=	index.search_batch(snake_case__	,  request_timeout=30      )
																		lowercase__    :				List[Any]=	[scores[0] for scores in total_scores]
																		lowercase__    :				Optional[int]=	[indices[0] for indices in total_indices]
																		self.assertGreater(np.min(snake_case__      )	,  0      )
																		self.assertListEqual([1, 1, 1]	,  snake_case__      )














"""simple docstring"""







from scipy.stats import spearmanr

import datasets


a			:    Dict				 =		"""
The Spearman rank-order correlation coefficient is a measure of the
relationship between two datasets. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Positive correlations imply that as data in dataset x increases, so
does data in dataset y. Negative correlations imply that as x increases,
y decreases. Correlations of -1 or +1 imply an exact monotonic relationship.

Unlike the Pearson correlation, the Spearman correlation does not
assume that both datasets are normally distributed.

The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
"""

a			:    List[Any]				 =		"""
Args:
    predictions (`List[float]`): Predicted labels, as returned by a model.
    references (`List[float]`): Ground truth labels.
    return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns
            only the spearmanr score. Defaults to `False`.
Returns:
    spearmanr (`float`): Spearman correlation coefficient.
    p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.
Examples:
    Example 1:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])
        >>> print(results)
        {'spearmanr': -0.7}

    Example 2:
        >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")
        >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],
        ...                                     predictions=[10, 9, 2.5, 6, 4],
        ...                                     return_pvalue=True)
        >>> print(results['spearmanr'])
        -0.7
        >>> print(round(results['spearmanr_pvalue'], 2))
        0.19
"""

a			:    int				 =		r"""\
@book{kokoska2000crc,
  title={CRC standard probability and statistics tables and formulae},
  author={Kokoska, Stephen and Zwillinger, Daniel},
  year={2000},
  publisher={Crc Press}
}
@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, {\.I}lhan 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, Ant{\^o}nio 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    __UpperCAmelCase(       datasets.Metric							):




						"""simple docstring"""




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												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.spearmanr.html"]	,  )




						def 		UpperCAmelCase_	(       self	,  snake_case__	,  snake_case__	,  snake_case__=False      ):
												'''simple docstring'''
												lowercase__    :				Optional[int]=	spearmanr(snake_case__	,  snake_case__      )
												if return_pvalue:
																		return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
												else:
																		return {"spearmanr": results[0]}






