





'''simple docstring'''





from scipy.stats import spearmanr

import datasets


SCREAMING_SNAKE_CASE_		     = """
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_		     = """
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_		     = 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        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	Optional[int]:




           '''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        SCREAMING_SNAKE_CASE__						(							self		:					int		,lowerCamelCase__		:					Dict		,lowerCamelCase__		:					Any		,lowerCamelCase__		:					str=False )  ->	Union[str, Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		spearmanr(lowerCamelCase__		,lowerCamelCase__ )
           if return_pvalue:
                 return {"spearmanr": results[0], "spearmanr_pvalue": results[1]}
           else:
                 return {"spearmanr": results[0]}









import inspect
import unittest

from transformers import DecisionTransformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import DecisionTransformerModel
      from transformers.models.decision_transformer.modeling_decision_transformer import (
          DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
      )

class 	UpperCamelCase__				:



     '''simple docstring'''

     def __init__(							self		:					Optional[Any]		,lowerCamelCase__		:					int		,lowerCamelCase__		:					Dict=13		,lowerCamelCase__		:					Tuple=7		,lowerCamelCase__		:					Optional[Any]=6		,lowerCamelCase__		:					List[str]=17		,lowerCamelCase__		:					Union[str, Any]=23		,lowerCamelCase__		:					Tuple=11		,lowerCamelCase__		:					Any=True		,)  ->	List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		parent
           SCREAMING_SNAKE_CASE	=		batch_size
           SCREAMING_SNAKE_CASE	=		seq_length
           SCREAMING_SNAKE_CASE	=		act_dim
           SCREAMING_SNAKE_CASE	=		state_dim
           SCREAMING_SNAKE_CASE	=		hidden_size
           SCREAMING_SNAKE_CASE	=		max_length
           SCREAMING_SNAKE_CASE	=		is_training






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		floats_tensor((self.batch_size, self.seq_length, self.state_dim) )
           SCREAMING_SNAKE_CASE	=		floats_tensor((self.batch_size, self.seq_length, self.act_dim) )
           SCREAMING_SNAKE_CASE	=		floats_tensor((self.batch_size, self.seq_length, 1) )
           SCREAMING_SNAKE_CASE	=		floats_tensor((self.batch_size, self.seq_length, 1) )
           SCREAMING_SNAKE_CASE	=		ids_tensor((self.batch_size, self.seq_length)		,vocab_size=1000 )
           SCREAMING_SNAKE_CASE	=		random_attention_mask((self.batch_size, self.seq_length) )

           SCREAMING_SNAKE_CASE	=		self.get_config()

           return (
               config,
               states,
               actions,
               rewards,
               returns_to_go,
               timesteps,
               attention_mask,
           )






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	List[str]:




           '''simple docstring'''


           return DecisionTransformerConfig(
               batch_size=self.batch_size		,seq_length=self.seq_length		,act_dim=self.act_dim		,state_dim=self.state_dim		,hidden_size=self.hidden_size		,max_length=self.max_length		,)






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any]		,lowerCamelCase__		:					int		,lowerCamelCase__		:					Optional[int]		,lowerCamelCase__		:					Union[str, Any]		,lowerCamelCase__		:					Any		,lowerCamelCase__		:					List[Any]		,lowerCamelCase__		:					Any		,lowerCamelCase__		:					Union[str, Any]		,)  ->	Dict:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		DecisionTransformerModel(config=lowerCamelCase__ )
           model.to(lowerCamelCase__ )
           model.eval()
           SCREAMING_SNAKE_CASE	=		model(lowerCamelCase__		,lowerCamelCase__		,lowerCamelCase__		,lowerCamelCase__		,lowerCamelCase__		,lowerCamelCase__ )

           self.parent.assertEqual(result.state_preds.shape		,states.shape )
           self.parent.assertEqual(result.action_preds.shape		,actions.shape )
           self.parent.assertEqual(result.return_preds.shape		,returns_to_go.shape )
           self.parent.assertEqual(
               result.last_hidden_state.shape		,(self.batch_size, self.seq_length * 3, self.hidden_size) )  # seq length *3 as there are 3 modelities: states, returns and actions






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any] )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.prepare_config_and_inputs()
           (
               (
               SCREAMING_SNAKE_CASE
           ),      (
               SCREAMING_SNAKE_CASE
           ),      (
               SCREAMING_SNAKE_CASE
           ),      (
               SCREAMING_SNAKE_CASE
           ),      (
               SCREAMING_SNAKE_CASE
           ),      (
               SCREAMING_SNAKE_CASE
           ),      (
               SCREAMING_SNAKE_CASE
           ),      
           )	=		config_and_inputs
           SCREAMING_SNAKE_CASE	=		{
               """states""": states,
               """actions""": actions,
               """rewards""": rewards,
               """returns_to_go""": returns_to_go,
               """timesteps""": timesteps,
               """attention_mask""": attention_mask,
           }
           return config, inputs_dict

@require_torch
class 	UpperCamelCase__				(   lowerCAmelCase_							,   lowerCAmelCase_							,   lowerCAmelCase_							,   unittest.TestCase     ):



     '''simple docstring'''

     __snake_case					:			Tuple				=    (DecisionTransformerModel,) if is_torch_available() else ()
     __snake_case					:			Dict				=    ()
     __snake_case					:			List[Any]				=    {"feature-extraction": DecisionTransformerModel} if is_torch_available() else {}

     # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids
     __snake_case					:			int				=    False

     # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features
     __snake_case					:			Optional[Any]				=    False
     __snake_case					:			Optional[Any]				=    False
     __snake_case					:			int				=    False
     __snake_case					:			str				=    False
     __snake_case					:			Union[str, Any]				=    False
     __snake_case					:			Union[str, Any]				=    False
     __snake_case					:			List[Any]				=    False
     __snake_case					:			Optional[int]				=    False
     __snake_case					:			List[Any]				=    False






     def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	Dict:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		DecisionTransformerModelTester(self )
           SCREAMING_SNAKE_CASE	=		ConfigTester(self		,config_class=lowerCamelCase__		,hidden_size=37 )






     def        SCREAMING_SNAKE_CASE__						(							self		:					Dict )  ->	Dict:




           '''simple docstring'''


           self.config_tester.run_common_tests()






     def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase__ )






     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any] )  ->	Union[str, Any]:




           '''simple docstring'''


           for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 SCREAMING_SNAKE_CASE	=		DecisionTransformerModel.from_pretrained(lowerCamelCase__ )
                 self.assertIsNotNone(lowerCamelCase__ )






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 SCREAMING_SNAKE_CASE	=		model_class(lowerCamelCase__ )
                 SCREAMING_SNAKE_CASE	=		inspect.signature(model.forward )
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 SCREAMING_SNAKE_CASE	=		[*signature.parameters.keys()]

                 SCREAMING_SNAKE_CASE	=		[
                     """states""",
                     """actions""",
                     """rewards""",
                     """returns_to_go""",
                     """timesteps""",
                     """attention_mask""",
                 ]

                 self.assertListEqual(arg_names[: len(lowerCamelCase__ )]		,lowerCamelCase__ )

@require_torch
class 	UpperCamelCase__				(   unittest.TestCase     ):



     '''simple docstring'''

     @slow
     def        SCREAMING_SNAKE_CASE__						(							self		:					Dict )  ->	Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		2  # number of steps of autoregressive prediction we will perform
           SCREAMING_SNAKE_CASE	=		10  # defined by the RL environment, may be normalized
           SCREAMING_SNAKE_CASE	=		DecisionTransformerModel.from_pretrained("""edbeeching/decision-transformer-gym-hopper-expert""" )
           SCREAMING_SNAKE_CASE	=		model.to(lowerCamelCase__ )
           SCREAMING_SNAKE_CASE	=		model.config
           torch.manual_seed(0 )
           SCREAMING_SNAKE_CASE	=		torch.randn(1		,1		,config.state_dim ).to(device=lowerCamelCase__		,dtype=torch.floataa )  # env.reset()

           SCREAMING_SNAKE_CASE	=		torch.tensor(
               [[0.242793, -0.28693074, 0.8742613], [0.67815274, -0.08101085, -0.12952147]]		,device=lowerCamelCase__ )

           SCREAMING_SNAKE_CASE	=		torch.tensor(lowerCamelCase__		,device=lowerCamelCase__		,dtype=torch.floataa ).reshape(1		,1		,1 )
           SCREAMING_SNAKE_CASE	=		state
           SCREAMING_SNAKE_CASE	=		torch.zeros(1		,0		,config.act_dim		,device=lowerCamelCase__		,dtype=torch.floataa )
           SCREAMING_SNAKE_CASE	=		torch.zeros(1		,0		,device=lowerCamelCase__		,dtype=torch.floataa )
           SCREAMING_SNAKE_CASE	=		torch.tensor(0		,device=lowerCamelCase__		,dtype=torch.long ).reshape(1		,1 )

           for step in range(lowerCamelCase__ ):
                 SCREAMING_SNAKE_CASE	=		torch.cat([actions, torch.zeros(1		,1		,config.act_dim		,device=lowerCamelCase__ )]		,dim=1 )
                 SCREAMING_SNAKE_CASE	=		torch.cat([rewards, torch.zeros(1		,1		,device=lowerCamelCase__ )]		,dim=1 )

                 SCREAMING_SNAKE_CASE	=		torch.ones(1		,states.shape[1] ).to(dtype=torch.long		,device=states.device )

                 with torch.no_grad():
                       SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		model(
                           states=lowerCamelCase__		,actions=lowerCamelCase__		,rewards=lowerCamelCase__		,returns_to_go=lowerCamelCase__		,timesteps=lowerCamelCase__		,attention_mask=lowerCamelCase__		,return_dict=lowerCamelCase__		,)

                 self.assertEqual(action_pred.shape		,actions.shape )
                 self.assertTrue(torch.allclose(action_pred[0, -1]		,expected_outputs[step]		,atol=1e-4 ) )
                 SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		(  # env.step(action)
                     torch.randn(1		,1		,config.state_dim ).to(device=lowerCamelCase__		,dtype=torch.floataa ),
                     1.0,
                     False,
                     {},
                 )

                 SCREAMING_SNAKE_CASE	=		action_pred[0, -1]
                 SCREAMING_SNAKE_CASE	=		torch.cat([states, state]		,dim=1 )
                 SCREAMING_SNAKE_CASE	=		returns_to_go[0, -1] - reward
                 SCREAMING_SNAKE_CASE	=		torch.cat([returns_to_go, pred_return.reshape(1		,1		,1 )]		,dim=1 )
                 SCREAMING_SNAKE_CASE	=		torch.cat(
                     [timesteps, torch.ones((1, 1)		,device=lowerCamelCase__		,dtype=torch.long ) * (step + 1)]		,dim=1 )


