
from __future__ import annotations

import unittest

from transformers import CTRLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
							import tensorflow as tf

							from transformers.models.ctrl.modeling_tf_ctrl import (
							    TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
							    TFCTRLForSequenceClassification,
							    TFCTRLLMHeadModel,
							    TFCTRLModel,
							)





class 						lowercase       (  __UpperCamelCase					):
					def __init__(		self ,	SCREAMING_SNAKE_CASE__ ,	):
								"""simple docstring"""







								lowerCAmelCase__ :    int				      =			parent
								lowerCAmelCase__ :    Any				      =			13
								lowerCAmelCase__ :    Any				      =			7
								lowerCAmelCase__ :    List[Any]				      =			True
								lowerCAmelCase__ :    Tuple				      =			True
								lowerCAmelCase__ :    List[str]				      =			True
								lowerCAmelCase__ :    Union[str, Any]				      =			True
								lowerCAmelCase__ :    str				      =			True
								lowerCAmelCase__ :    Dict				      =			99
								lowerCAmelCase__ :    Union[str, Any]				      =			32
								lowerCAmelCase__ :    Any				      =			2
								lowerCAmelCase__ :    List[Any]				      =			4
								lowerCAmelCase__ :    Union[str, Any]				      =			37
								lowerCAmelCase__ :    Optional[int]				      =			'''gelu'''
								lowerCAmelCase__ :    int				      =			0.1
								lowerCAmelCase__ :    int				      =			0.1
								lowerCAmelCase__ :    List[Any]				      =			512
								lowerCAmelCase__ :    Dict				      =			16
								lowerCAmelCase__ :    Tuple				      =			2
								lowerCAmelCase__ :    Optional[Any]				      =			0.02
								lowerCAmelCase__ :    Optional[Any]				      =			3
								lowerCAmelCase__ :    Optional[Any]				      =			4
								lowerCAmelCase__ :    str				      =			None
								lowerCAmelCase__ :    List[str]				      =			self.vocab_size - 1
					def lowercase_			(		self    ):
								"""simple docstring"""







								lowerCAmelCase__ :    str				      =			ids_tensor([self.batch_size, self.seq_length] ,	self.vocab_size    )

								lowerCAmelCase__ :    str				      =			None
								if self.use_input_mask:
											lowerCAmelCase__ :    List[Any]				      =			random_attention_mask([self.batch_size, self.seq_length]    )

								lowerCAmelCase__ :    List[Any]				      =			None
								if self.use_token_type_ids:
											lowerCAmelCase__ :    str				      =			ids_tensor([self.batch_size, self.seq_length] ,	self.type_vocab_size    )

								lowerCAmelCase__ :    Tuple				      =			None
								if self.use_mc_token_ids:
											lowerCAmelCase__ :    Optional[Any]				      =			ids_tensor([self.batch_size, self.num_choices] ,	self.seq_length    )

								lowerCAmelCase__ :    List[Any]				      =			None
								lowerCAmelCase__ :    Any				      =			None
								lowerCAmelCase__ :    Optional[int]				      =			None
								if self.use_labels:
											lowerCAmelCase__ :    Dict				      =			ids_tensor([self.batch_size] ,	self.type_sequence_label_size    )
											lowerCAmelCase__ :    Tuple				      =			ids_tensor([self.batch_size, self.seq_length] ,	self.num_labels    )
											lowerCAmelCase__ :    Any				      =			ids_tensor([self.batch_size] ,	self.num_choices    )

								lowerCAmelCase__ :    Any				      =			CTRLConfig(
								    vocab_size=self.vocab_size ,	n_embd=self.hidden_size ,	n_layer=self.num_hidden_layers ,	n_head=self.num_attention_heads ,	n_positions=self.max_position_embeddings ,	pad_token_id=self.pad_token_id ,	)

								lowerCAmelCase__ :    Tuple				      =			ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,	2    )

								return (
								    config,
								    input_ids,
								    input_mask,
								    head_mask,
								    token_type_ids,
								    mc_token_ids,
								    sequence_labels,
								    token_labels,
								    choice_labels,
								)
					def lowercase_			(		self ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	*SCREAMING_SNAKE_CASE__    ):
								"""simple docstring"""







								lowerCAmelCase__ :    str				      =			TFCTRLModel(config=SCREAMING_SNAKE_CASE__    )
								lowerCAmelCase__ :    List[str]				      =			{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
								lowerCAmelCase__ :    Optional[int]				      =			model(SCREAMING_SNAKE_CASE__    )

								lowerCAmelCase__ :    List[str]				      =			[input_ids, None, input_mask]  # None is the input for 'past'
								lowerCAmelCase__ :    Union[str, Any]				      =			model(SCREAMING_SNAKE_CASE__    )

								lowerCAmelCase__ :    Tuple				      =			model(SCREAMING_SNAKE_CASE__    )

								self.parent.assertEqual(result.last_hidden_state.shape ,	(self.batch_size, self.seq_length, self.hidden_size)    )
					def lowercase_			(		self ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	*SCREAMING_SNAKE_CASE__    ):
								"""simple docstring"""







								lowerCAmelCase__ :    Any				      =			TFCTRLLMHeadModel(config=SCREAMING_SNAKE_CASE__    )
								lowerCAmelCase__ :    Any				      =			{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
								lowerCAmelCase__ :    Union[str, Any]				      =			model(SCREAMING_SNAKE_CASE__    )
								self.parent.assertEqual(result.logits.shape ,	(self.batch_size, self.seq_length, self.vocab_size)    )
					def lowercase_			(		self ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	*SCREAMING_SNAKE_CASE__    ):
								"""simple docstring"""







								lowerCAmelCase__ :    List[Any]				      =			self.num_labels
								lowerCAmelCase__ :    Any				      =			ids_tensor([self.batch_size] ,	self.type_sequence_label_size    )
								lowerCAmelCase__ :    int				      =			{
								    '''input_ids''': input_ids,
								    '''token_type_ids''': token_type_ids,
								    '''labels''': sequence_labels,
								}
								lowerCAmelCase__ :    Optional[Any]				      =			TFCTRLForSequenceClassification(SCREAMING_SNAKE_CASE__    )
								lowerCAmelCase__ :    Union[str, Any]				      =			model(SCREAMING_SNAKE_CASE__    )
								self.parent.assertEqual(result.logits.shape ,	(self.batch_size, self.num_labels)    )
					def lowercase_			(		self    ):
								"""simple docstring"""







								lowerCAmelCase__ :    Any				      =			self.prepare_config_and_inputs()

								(
								    lowerCAmelCase__				
								) :    str				      =			config_and_inputs

								lowerCAmelCase__ :    Union[str, Any]				      =			{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
								return config, inputs_dict





@require_tf
class 						lowercase       (  __UpperCamelCase	,		__UpperCamelCase	,		unittest.TestCase					):
					__a					=    (TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
					__a					=    (TFCTRLLMHeadModel,) if is_tf_available() else ()
					__a					=    (
					    {
					        """feature-extraction""": TFCTRLModel,
					        """text-classification""": TFCTRLForSequenceClassification,
					        """text-generation""": TFCTRLLMHeadModel,
					        """zero-shot""": TFCTRLForSequenceClassification,
					    }
					    if is_tf_available()
					    else {}
					)
					__a					=    False
					__a					=    False
					def lowercase_			(		self ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__    ):
								"""simple docstring"""







								if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
											# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
											# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
											# config could not be created.
											return True

								return False
					def lowercase_			(		self    ):
								"""simple docstring"""







								lowerCAmelCase__ :    int				      =			TFCTRLModelTester(self    )
								lowerCAmelCase__ :    str				      =			ConfigTester(self ,	config_class=SCREAMING_SNAKE_CASE__ ,	n_embd=37    )
					def lowercase_			(		self    ):
								"""simple docstring"""







								self.config_tester.run_common_tests()
					def lowercase_			(		self    ):
								"""simple docstring"""







								lowerCAmelCase__ :    List[str]				      =			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_ctrl_model(*SCREAMING_SNAKE_CASE__    )
					def lowercase_			(		self    ):
								"""simple docstring"""







								lowerCAmelCase__ :    List[str]				      =			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_ctrl_lm_head(*SCREAMING_SNAKE_CASE__    )
					def lowercase_			(		self    ):
								"""simple docstring"""







								lowerCAmelCase__ :    Any				      =			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_ctrl_for_sequence_classification(*SCREAMING_SNAKE_CASE__    )
					def lowercase_			(		self    ):
								"""simple docstring"""







								lowerCAmelCase__ :    List[Any]				      =			self.model_tester.prepare_config_and_inputs_for_common()
								lowerCAmelCase__ :    str				      =			[TFCTRLLMHeadModel]
								lowerCAmelCase__ :    str				      =			[TFCTRLForSequenceClassification]

								for model_class in self.all_model_classes:
											lowerCAmelCase__ :    List[str]				      =			model_class(SCREAMING_SNAKE_CASE__    )
											model.build()  # may be needed for the get_bias() call below
											assert isinstance(model.get_input_embeddings() ,	tf.keras.layers.Layer    )

											if model_class in list_lm_models:
														lowerCAmelCase__ :    str				      =			model.get_output_embeddings()
														assert isinstance(SCREAMING_SNAKE_CASE__ ,	tf.keras.layers.Layer    )
														lowerCAmelCase__ :    List[str]				      =			model.get_bias()
														assert isinstance(SCREAMING_SNAKE_CASE__ ,	SCREAMING_SNAKE_CASE__    )
														for k, v in name.items():
																	assert isinstance(SCREAMING_SNAKE_CASE__ ,	tf.Variable    )
											elif model_class in list_other_models_with_output_ebd:
														lowerCAmelCase__ :    int				      =			model.get_output_embeddings()
														assert isinstance(SCREAMING_SNAKE_CASE__ ,	tf.keras.layers.Layer    )
														lowerCAmelCase__ :    Dict				      =			model.get_bias()
														assert name is None
											else:
														lowerCAmelCase__ :    int				      =			model.get_output_embeddings()
														assert x is None
														lowerCAmelCase__ :    Union[str, Any]				      =			model.get_bias()
														assert name is None
					@slow
					def lowercase_			(		self    ):
								"""simple docstring"""







								for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCAmelCase__ :    int				      =			TFCTRLModel.from_pretrained(SCREAMING_SNAKE_CASE__    )
											self.assertIsNotNone(SCREAMING_SNAKE_CASE__    )





@require_tf
class 						lowercase       (  unittest.TestCase					):
					@slow
					def lowercase_			(		self    ):
								"""simple docstring"""







								lowerCAmelCase__ :    str				      =			TFCTRLLMHeadModel.from_pretrained('''ctrl'''    )
								lowerCAmelCase__ :    Optional[int]				      =			tf.convert_to_tensor([[11859, 0, 1611, 8]] ,	dtype=tf.intaa    )  # Legal the president is
								lowerCAmelCase__ :    List[Any]				      =			[
								    11859,
								    0,
								    1611,
								    8,
								    5,
								    150,
								    26449,
								    2,
								    19,
								    348,
								    469,
								    3,
								    2595,
								    48,
								    20740,
								    246533,
								    246533,
								    19,
								    30,
								    5,
								]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

								lowerCAmelCase__ :    Dict				      =			model.generate(SCREAMING_SNAKE_CASE__ ,	do_sample=SCREAMING_SNAKE_CASE__    )
								self.assertListEqual(output_ids[0].numpy().tolist() ,	SCREAMING_SNAKE_CASE__    )





from math import radians as angle_to_radians
from math import sin

# Acceleration Constant on Earth (unit m/s^2)
A__       :   str   						=					9.8_0665



def      _a     (   __UpperCamelCase       :  float	,__UpperCamelCase       :  float    ):

			# Ensure valid instance
			if not isinstance(__UpperCamelCase	,(int, float)    ):
						raise TypeError('''Invalid velocity. Should be a positive number.'''    )

			if not isinstance(__UpperCamelCase	,(int, float)    ):
						raise TypeError('''Invalid angle. Range is 1-90 degrees.'''    )

			# Ensure valid angle
			if angle > 90 or angle < 1:
						raise ValueError('''Invalid angle. Range is 1-90 degrees.'''    )

			# Ensure valid velocity
			if init_velocity < 0:
						raise ValueError('''Invalid velocity. Should be a positive number.'''    )



def      _a     (   __UpperCamelCase       :  float	,__UpperCamelCase       :  float    ):
			check_args(__UpperCamelCase	,__UpperCamelCase    )
			lowerCAmelCase__ :    Union[str, Any]				      =			angle_to_radians(2 * angle    )
			return round(init_velocity**2 * sin(__UpperCamelCase    ) / g	,2    )



def      _a     (   __UpperCamelCase       :  float	,__UpperCamelCase       :  float    ):
			check_args(__UpperCamelCase	,__UpperCamelCase    )
			lowerCAmelCase__ :    List[str]				      =			angle_to_radians(__UpperCamelCase    )
			return round(init_velocity**2 * sin(__UpperCamelCase    ) ** 2 / (2 * g)	,2    )



def      _a     (   __UpperCamelCase       :  float	,__UpperCamelCase       :  float    ):
			check_args(__UpperCamelCase	,__UpperCamelCase    )
			lowerCAmelCase__ :    Dict				      =			angle_to_radians(__UpperCamelCase    )
			return round(2 * init_velocity * sin(__UpperCamelCase    ) / g	,2    )



def      _a     (   ):
			lowerCAmelCase__      ,				lowerCAmelCase__ :    List[Any]				      =			25, 20
			assert horizontal_distance(__UpperCamelCase	,__UpperCamelCase    ) == 40.97
			assert max_height(__UpperCamelCase	,__UpperCamelCase    ) == 3.73
			assert total_time(__UpperCamelCase	,__UpperCamelCase    ) == 1.74


if __name__ == "__main__":
							from doctest import testmod

							testmod()

							# Get input from user
							A__       :   List[Any]   						=					float(input("""Initial Velocity: """).strip())

							# Get input from user
							A__       :   Optional[Any]   						=					float(input("""angle: """).strip())

							# Print results
							print()
							print("""Results: """)
							print(f"""Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]""")
							print(f"""Maximum Height: {max_height(init_vel, angle)!s} [m]""")
							print(f"""Total Time: {total_time(init_vel, angle)!s} [s]""")



