






'''simple docstring'''




from abc import ABC, abstractmethod
from typing import List, Optional







class    A_	(a_							):
							"""simple docstring"""




							def __init__(		self			:Optional[Any]				)				->  List[Any]:


										'''simple docstring'''




										self.test()

							def 							_A	(		self			:Union[str, Any]				)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					Tuple   =       0
										snake_case_				:					int   =       False
										while not completed:
													if counter == 1:
																self.reset()
													snake_case_				:					Union[str, Any]   =       self.advance()
													if not self.does_advance(lowerCAmelCase__				):
																raise Exception(
																    "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."				)

													snake_case_,	snake_case_,	snake_case_				:					List[Any]   =       self.update(lowerCAmelCase__				)
													counter += 1

													if counter > 10_000:
																raise Exception("update() does not fulfill the constraint."				)

										if self.remaining() != 0:
													raise Exception("Custom Constraint is not defined correctly."				)

							@abstractmethod
							def 							_A	(		self			:Dict				)				->  Optional[Any]:


										'''simple docstring'''




										raise NotImplementedError(
										    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''				)

							@abstractmethod
							def 							_A	(		self			:Optional[Any]       ,							lowerCAmelCase__			:int				)				->  Any:


										'''simple docstring'''




										raise NotImplementedError(
										    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''				)

							@abstractmethod
							def 							_A	(		self			:Dict       ,							lowerCAmelCase__			:int				)				->  Tuple:


										'''simple docstring'''




										raise NotImplementedError(
										    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''				)

							@abstractmethod
							def 							_A	(		self			:Any				)				->  List[str]:


										'''simple docstring'''




										raise NotImplementedError(
										    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''				)

							@abstractmethod
							def 							_A	(		self			:Optional[Any]				)				->  Union[str, Any]:


										'''simple docstring'''




										raise NotImplementedError(
										    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''				)






							@abstractmethod
							def 							_A	(		self			:str       ,							lowerCAmelCase__			:List[str]=False				)				->  int:


										'''simple docstring'''




										raise NotImplementedError(
										    F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''				)







class    A_	(a_							):
							"""simple docstring"""




							def __init__(		self			:Any       ,							lowerCAmelCase__			:List[int]				)				->  List[str]:


										'''simple docstring'''




										super(lowerCAmelCase__       ,							self				).__init__()

										if not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				) or len(lowerCAmelCase__				) == 0:
													raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.'''				)
										if any((not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				) or token_id < 0) for token_id in token_ids				):
													raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.'''				)

										snake_case_				:					Any   =       token_ids

										snake_case_				:					Any   =       len(self.token_ids				)
										snake_case_				:					Tuple   =       -1  # the index of the currently fulfilled step
										snake_case_				:					Optional[int]   =       False

							def 							_A	(		self			:List[str]				)				->  Any:


										'''simple docstring'''




										if self.completed:
													return None
										return self.token_ids[self.fulfilled_idx + 1]

							def 							_A	(		self			:str       ,							lowerCAmelCase__			:int				)				->  Union[str, Any]:


										'''simple docstring'''




										if not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
													raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(lowerCAmelCase__				)}'''				)

										if self.completed:
													return False

										return token_id == self.token_ids[self.fulfilled_idx + 1]

							def 							_A	(		self			:List[str]       ,							lowerCAmelCase__			:int				)				->  str:


										'''simple docstring'''




										if not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
													raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(lowerCAmelCase__				)}'''				)

										snake_case_				:					Any   =       False
										snake_case_				:					List[Any]   =       False
										snake_case_				:					Any   =       False

										if self.does_advance(lowerCAmelCase__				):
													self.fulfilled_idx += 1
													snake_case_				:					Union[str, Any]   =       True
													if self.fulfilled_idx == (self.seqlen - 1):
																snake_case_				:					Dict   =       True
													snake_case_				:					List[str]   =       completed
										else:
													# failed to make progress.
													snake_case_				:					List[Any]   =       True
													self.reset()
										return stepped, completed, reset

							def 							_A	(		self			:str				)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					List[Any]   =       False
										snake_case_				:					Dict   =       0

							def 							_A	(		self			:int				)				->  Tuple:


										'''simple docstring'''




										return self.seqlen - (self.fulfilled_idx + 1)






							def 							_A	(		self			:int       ,							lowerCAmelCase__			:Union[str, Any]=False				)				->  str:


										'''simple docstring'''




										snake_case_				:					List[str]   =       PhrasalConstraint(self.token_ids				)

										if stateful:
													snake_case_				:					Dict   =       self.seqlen
													snake_case_				:					List[Any]   =       self.fulfilled_idx
													snake_case_				:					Dict   =       self.completed

										return new_constraint







class    A_	:
							"""simple docstring"""




							def __init__(		self			:int       ,							lowerCAmelCase__			:List[List[int]]       ,							lowerCAmelCase__			:Any=True				)				->  Union[str, Any]:


										'''simple docstring'''




										snake_case_				:					Dict   =       max([len(lowerCAmelCase__				) for one in nested_token_ids]				)

										snake_case_				:					List[str]   =       {}
										for token_ids in nested_token_ids:
													snake_case_				:					Union[str, Any]   =       root
													for tidx, token_id in enumerate(lowerCAmelCase__				):
																if token_id not in level:
																			snake_case_				:					int   =       {}

																snake_case_				:					Optional[Any]   =       level[token_id]

										if no_subsets and self.has_subsets(lowerCAmelCase__       ,							lowerCAmelCase__				):
													raise ValueError(
													    "Each list in `nested_token_ids` can't be a complete subset of another list, but is"
													    F''' {nested_token_ids}.'''				)

										snake_case_				:					Union[str, Any]   =       root

							def 							_A	(		self			:int       ,							lowerCAmelCase__			:Optional[int]				)				->  Tuple:


										'''simple docstring'''




										snake_case_				:					Any   =       self.trie

										for current_token in current_seq:
													snake_case_				:					str   =       start[current_token]

										snake_case_				:					List[Any]   =       list(start.keys()				)

										return next_tokens

							def 							_A	(		self			:Optional[int]       ,							lowerCAmelCase__			:str				)				->  List[Any]:


										'''simple docstring'''




										snake_case_				:					Optional[int]   =       self.next_tokens(lowerCAmelCase__				)

										return len(lowerCAmelCase__				) == 0

							def 							_A	(		self			:Union[str, Any]       ,							lowerCAmelCase__			:List[Any]				)				->  int:


										'''simple docstring'''




										snake_case_				:					Optional[int]   =       list(root.values()				)
										if len(lowerCAmelCase__				) == 0:
													return 1
										else:
													return sum([self.count_leaves(lowerCAmelCase__				) for nn in next_nodes]				)






							def 							_A	(		self			:int       ,							lowerCAmelCase__			:List[Any]       ,							lowerCAmelCase__			:Any				)				->  str:


										'''simple docstring'''




										snake_case_				:					str   =       self.count_leaves(lowerCAmelCase__				)
										return len(lowerCAmelCase__				) != leaf_count







class    A_	(a_							):
							"""simple docstring"""




							def __init__(		self			:Any       ,							lowerCAmelCase__			:List[List[int]]				)				->  List[Any]:


										'''simple docstring'''




										super(lowerCAmelCase__       ,							self				).__init__()

										if not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				) or len(lowerCAmelCase__				) == 0:
													raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.'''				)
										if any(not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				) for token_ids in nested_token_ids				):
													raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.'''				)
										if any(
										    any((not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				) or token_id < 0) for token_id in token_ids				)
										    for token_ids in nested_token_ids				):
													raise ValueError(
													    F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.'''				)

										snake_case_				:					Any   =       DisjunctiveTrie(lowerCAmelCase__				)
										snake_case_				:					Optional[int]   =       nested_token_ids

										snake_case_				:					List[str]   =       self.trie.max_height
										snake_case_				:					Tuple   =       []
										snake_case_				:					int   =       False

							def 							_A	(		self			:Optional[Any]				)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					Any   =       self.trie.next_tokens(self.current_seq				)

										if len(lowerCAmelCase__				) == 0:
													return None
										else:
													return token_list

							def 							_A	(		self			:Optional[Any]       ,							lowerCAmelCase__			:int				)				->  Dict:


										'''simple docstring'''




										if not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
													raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowerCAmelCase__				)}'''				)

										snake_case_				:					List[Any]   =       self.trie.next_tokens(self.current_seq				)

										return token_id in next_tokens

							def 							_A	(		self			:Any       ,							lowerCAmelCase__			:int				)				->  Any:


										'''simple docstring'''




										if not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
													raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(lowerCAmelCase__				)}'''				)

										snake_case_				:					Optional[int]   =       False
										snake_case_				:					Union[str, Any]   =       False
										snake_case_				:					Tuple   =       False

										if self.does_advance(lowerCAmelCase__				):
													self.current_seq.append(lowerCAmelCase__				)
													snake_case_				:					Dict   =       True
										else:
													snake_case_				:					Optional[Any]   =       True
													self.reset()

										snake_case_				:					Optional[int]   =       self.trie.reached_leaf(self.current_seq				)
										snake_case_				:					Tuple   =       completed

										return stepped, completed, reset

							def 							_A	(		self			:List[str]				)				->  Any:


										'''simple docstring'''




										snake_case_				:					str   =       False
										snake_case_				:					List[str]   =       []

							def 							_A	(		self			:Any				)				->  Any:


										'''simple docstring'''




										if self.completed:
													# since this can be completed without reaching max height
													return 0
										else:
													return self.seqlen - len(self.current_seq				)






							def 							_A	(		self			:List[Any]       ,							lowerCAmelCase__			:Optional[int]=False				)				->  Any:


										'''simple docstring'''




										snake_case_				:					str   =       DisjunctiveConstraint(self.token_ids				)

										if stateful:
													snake_case_				:					int   =       self.seqlen
													snake_case_				:					Tuple   =       self.current_seq
													snake_case_				:					Optional[Any]   =       self.completed

										return new_constraint







class    A_	:
							"""simple docstring"""




							def __init__(		self			:Optional[Any]       ,							lowerCAmelCase__			:List[Constraint]				)				->  Tuple:


										'''simple docstring'''




										snake_case_				:					Optional[int]   =       constraints

										# max # of steps required to fulfill a given constraint
										snake_case_				:					Dict   =       max([c.seqlen for c in constraints]				)
										snake_case_				:					Optional[Any]   =       len(lowerCAmelCase__				)
										snake_case_				:					Optional[Any]   =       False

										self.init_state()

							def 							_A	(		self			:str				)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					Any   =       []
										snake_case_				:					Optional[int]   =       None
										snake_case_				:					Any   =       [constraint.copy(stateful=lowerCAmelCase__				) for constraint in self.constraints]

							def 							_A	(		self			:int				)				->  str:


										'''simple docstring'''




										snake_case_				:					Union[str, Any]   =       0
										if self.inprogress_constraint:
													# extra points for having a constraint mid-fulfilled
													add += self.max_seqlen - self.inprogress_constraint.remaining()

										return (len(self.complete_constraints				) * self.max_seqlen) + add

							def 							_A	(		self			:Optional[Any]				)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					Any   =       []
										if self.inprogress_constraint is None:
													for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
																snake_case_				:					Optional[int]   =       constraint.advance()
																if isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
																			token_list.append(lowerCAmelCase__				)
																elif isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
																			token_list.extend(lowerCAmelCase__				)
										else:
													snake_case_				:					Union[str, Any]   =       self.inprogress_constraint.advance()
													if isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
																token_list.append(lowerCAmelCase__				)
													elif isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
																token_list.extend(lowerCAmelCase__				)

										if len(lowerCAmelCase__				) == 0:
													return None
										else:
													return token_list

							def 							_A	(		self			:Optional[int]       ,							lowerCAmelCase__			:Optional[List[int]]				)				->  List[str]:


										'''simple docstring'''




										self.init_state()

										if token_ids is not None:
													for token in token_ids:
																# completes or steps **one** constraint
																snake_case_,	snake_case_				:					Tuple   =       self.add(lowerCAmelCase__				)

																# the entire list of constraints are fulfilled
																if self.completed:
																			break

							def 							_A	(		self			:int       ,							lowerCAmelCase__			:int				)				->  Dict:


										'''simple docstring'''




										if not isinstance(lowerCAmelCase__       ,							lowerCAmelCase__				):
													raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.'''				)

										snake_case_,	snake_case_				:					List[str]   =       False, False

										if self.completed:
													snake_case_				:					Any   =       True
													snake_case_				:					Optional[Any]   =       False
													return complete, stepped

										if self.inprogress_constraint is not None:
													# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
													# job, simply update the state

													snake_case_,	snake_case_,	snake_case_				:					Any   =       self.inprogress_constraint.update(lowerCAmelCase__				)
													if reset:
																# 1. If the next token breaks the progress, then we must restart.
																#     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

																#     But that doesn't mean we self.init_state(), since we only reset the state for this particular
																#     constraint, not the full list of constraints.

																self.pending_constraints.append(self.inprogress_constraint.copy(stateful=lowerCAmelCase__				)				)
																snake_case_				:					List[Any]   =       None

													if complete:
																# 2. If the next token completes the constraint, move it to completed list, set
																#     inprogress to None. If there are no pending constraints either, then this full list of constraints
																#     is complete.

																self.complete_constraints.append(self.inprogress_constraint				)
																snake_case_				:					int   =       None

																if len(self.pending_constraints				) == 0:
																			# we're done!
																			snake_case_				:					List[str]   =       True

										else:
													# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
													# of constraints?

													for cidx, pending_constraint in enumerate(self.pending_constraints				):
																if pending_constraint.does_advance(lowerCAmelCase__				):
																			snake_case_,	snake_case_,	snake_case_				:					Tuple   =       pending_constraint.update(lowerCAmelCase__				)

																			if not stepped:
																						raise Exception(
																						    "`constraint.update(token_id)` is not yielding incremental progress, "
																						    "even though `constraint.does_advance(token_id)` is true."				)

																			if complete:
																						self.complete_constraints.append(lowerCAmelCase__				)
																						snake_case_				:					Union[str, Any]   =       None

																			if not complete and stepped:
																						snake_case_				:					Optional[Any]   =       pending_constraint

																			if complete or stepped:
																						# If we made any progress at all, then it's at least not a "pending constraint".

																						snake_case_				:					Union[str, Any]   =       (
																						    self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
																						)

																						if len(self.pending_constraints				) == 0 and self.inprogress_constraint is None:
																									# If there's no longer any pending after this and no inprogress either, then we must be
																									# complete.

																									snake_case_				:					Union[str, Any]   =       True

																						break  # prevent accidentally stepping through multiple constraints with just one token.

										return complete, stepped






							def 							_A	(		self			:Union[str, Any]       ,							lowerCAmelCase__			:Dict=True				)				->  int:


										'''simple docstring'''




										snake_case_				:					int   =       ConstraintListState(self.constraints				)  # we actually never though self.constraints objects
										# throughout this process. So it's at initialization state.

										if stateful:
													snake_case_				:					Dict   =       [
													    constraint.copy(stateful=lowerCAmelCase__				) for constraint in self.complete_constraints
													]
													if self.inprogress_constraint is not None:
																snake_case_				:					Tuple   =       self.inprogress_constraint.copy(stateful=lowerCAmelCase__				)
													snake_case_				:					List[str]   =       [constraint.copy() for constraint in self.pending_constraints]

										return new_state












'''simple docstring'''




from scipy.stats import spearmanr

import datasets


__lowerCamelCase   :					str   							=					'''
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.
'''

__lowerCamelCase   :					int   							=					'''
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
'''

__lowerCamelCase   :					List[str]   							=					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    A_	(datasets.Metric							):
							"""simple docstring"""




							def 							_A	(		self			:str				)				->  Union[str, Any]:


										'''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 							_A	(		self			:Optional[int]       ,							lowerCAmelCase__			:Optional[Any]       ,							lowerCAmelCase__			:int       ,							lowerCAmelCase__			:Optional[Any]=False				)				->  List[Any]:


										'''simple docstring'''




										snake_case_				:					Optional[Any]   =       spearmanr(lowerCAmelCase__       ,							lowerCAmelCase__				)
										if return_pvalue:
													return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
										else:
													return {"spearmanr": results[0]}




