



"""simple docstring"""
from scipy.stats import spearmanr

import datasets


__SCREAMING_SNAKE_CASE  :						Optional[Any]    							=      '''
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.
'''

__SCREAMING_SNAKE_CASE  :						Tuple    							=      '''
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
'''

__SCREAMING_SNAKE_CASE  :						Dict    							=      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 							lowerCamelCase_(   datasets.Metric    ):





				'''simple docstring'''



				def 			snake_case__      (    self   ):
								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 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__=False   ):
								_lowerCamelCase        =				spearmanr(lowerCamelCase__				,       lowerCamelCase__   )
								if return_pvalue:
												return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
								else:
												return {"spearmanr": results[0]}





"""simple docstring"""
import numpy as np



def        lowerCAmelCase_(   lowercase_     :							np.ndarray						,   lowercase_     :							np.ndarray						,   lowercase_     :							float = 1e-12						,   lowercase_     :							int = 1_00						,   )	->       tuple[float, np.ndarray]:
				assert np.shape(lowercase_							)[0] == np.shape(lowercase_							)[1]
				# Ensure proper dimensionality.
				assert np.shape(lowercase_							)[0] == np.shape(lowercase_							)[0]
				# Ensure inputs are either both complex or both real
				assert np.iscomplexobj(lowercase_							) == np.iscomplexobj(lowercase_							)
				_lowerCamelCase        =				np.iscomplexobj(lowercase_							)
				if is_complex:
								# Ensure complex input_matrix is Hermitian
								assert np.array_equal(lowercase_						,   input_matrix.conj().T							)

				# Set convergence to False. Will define convergence when we exceed max_iterations
				# or when we have small changes from one iteration to next.

				_lowerCamelCase        =				False
				_lowerCamelCase        =				0
				_lowerCamelCase        =				0
				_lowerCamelCase        =				1e12

				while not convergence:
								# Multiple matrix by the vector.
								_lowerCamelCase        =				np.dot(lowercase_						,   lowercase_							)
								# Normalize the resulting output vector.
								_lowerCamelCase        =				w / np.linalg.norm(lowercase_							)
								# Find rayleigh quotient
								# (faster than usual b/c we know vector is normalized already)
								_lowerCamelCase        =				vector.conj().T if is_complex else vector.T
								_lowerCamelCase        =				np.dot(lowercase_						,   np.dot(lowercase_						,   lowercase_							)							)

								# Check convergence.
								_lowerCamelCase        =				np.abs(lambda_ - lambda_previous							) / lambda_
								iterations += 1

								if error <= error_tol or iterations >= max_iterations:
												_lowerCamelCase        =				True

								_lowerCamelCase        =				lambda_

				if is_complex:
								_lowerCamelCase        =				np.real(lambda_							)

				return lambda_, vector



def        lowerCAmelCase_(   )	->       None:
				_lowerCamelCase        =				np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]							)
				_lowerCamelCase        =				np.array([41, 4, 20]							)
				_lowerCamelCase        =				real_input_matrix.astype(np.complexaaa							)
				_lowerCamelCase        =				np.triu(1j * complex_input_matrix						,   1							)
				complex_input_matrix += imag_matrix
				complex_input_matrix += -1 * imag_matrix.T
				_lowerCamelCase        =				np.array([41, 4, 20]							).astype(np.complexaaa							)

				for problem_type in ["real", "complex"]:
								if problem_type == "real":
												_lowerCamelCase        =				real_input_matrix
												_lowerCamelCase        =				real_vector
								elif problem_type == "complex":
												_lowerCamelCase        =				complex_input_matrix
												_lowerCamelCase        =				complex_vector

								# Our implementation.
								_lowerCamelCase  ,     _lowerCamelCase        =				power_iteration(lowercase_						,   lowercase_							)

								# Numpy implementation.

								# Get eigenvalues and eigenvectors using built-in numpy
								# eigh (eigh used for symmetric or hermetian matrices).
								_lowerCamelCase  ,     _lowerCamelCase        =				np.linalg.eigh(lowercase_							)
								# Last eigenvalue is the maximum one.
								_lowerCamelCase        =				eigen_values[-1]
								# Last column in this matrix is eigenvector corresponding to largest eigenvalue.
								_lowerCamelCase        =				eigen_vectors[:, -1]

								# Check our implementation and numpy gives close answers.
								assert np.abs(eigen_value - eigen_value_max							) <= 1e-6
								# Take absolute values element wise of each eigenvector.
								# as they are only unique to a minus sign.
								assert np.linalg.norm(np.abs(lowercase_							) - np.abs(lowercase_							)							) <= 1e-6


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			test_power_iteration()
