from __future__ import annotations

import unittest

from transformers import RoFormerConfig, 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 import (
          TFRoFormerForCausalLM,
          TFRoFormerForMaskedLM,
          TFRoFormerForMultipleChoice,
          TFRoFormerForQuestionAnswering,
          TFRoFormerForSequenceClassification,
          TFRoFormerForTokenClassification,
          TFRoFormerModel,
      )
      from transformers.models.roformer.modeling_tf_roformer import (
          TFRoFormerSelfAttention,
          TFRoFormerSinusoidalPositionalEmbedding,
      )






class 		_lowerCamelCase		:
    def __init__(	self			,			lowerCAmelCase			,			lowerCAmelCase=13			,			lowerCAmelCase=7			,			lowerCAmelCase=True			,			lowerCAmelCase=True			,			lowerCAmelCase=True			,			lowerCAmelCase=True			,			lowerCAmelCase=99			,			lowerCAmelCase=32			,			lowerCAmelCase=2			,			lowerCAmelCase=4			,			lowerCAmelCase=37			,			lowerCAmelCase="gelu"			,			lowerCAmelCase=0.1			,			lowerCAmelCase=0.1			,			lowerCAmelCase=512			,			lowerCAmelCase=16			,			lowerCAmelCase=2			,			lowerCAmelCase=0.02			,			lowerCAmelCase=3			,			lowerCAmelCase=4			,			lowerCAmelCase=None			,			)							->       str:
     SCREAMING_SNAKE_CASE__: Any=   parent
     SCREAMING_SNAKE_CASE__: str=   13
     SCREAMING_SNAKE_CASE__: Any=   7
     SCREAMING_SNAKE_CASE__: str=   True
     SCREAMING_SNAKE_CASE__: List[Any]=   True
     SCREAMING_SNAKE_CASE__: Tuple=   True
     SCREAMING_SNAKE_CASE__: List[str]=   True
     SCREAMING_SNAKE_CASE__: List[Any]=   99
     SCREAMING_SNAKE_CASE__: str=   32
     SCREAMING_SNAKE_CASE__: Dict=   2
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   4
     SCREAMING_SNAKE_CASE__: Dict=   37
     SCREAMING_SNAKE_CASE__: Dict=   '''gelu'''
     SCREAMING_SNAKE_CASE__: List[str]=   0.1
     SCREAMING_SNAKE_CASE__: List[str]=   0.1
     SCREAMING_SNAKE_CASE__: Optional[int]=   512
     SCREAMING_SNAKE_CASE__: Any=   16
     SCREAMING_SNAKE_CASE__: List[Any]=   2
     SCREAMING_SNAKE_CASE__: Optional[Any]=   0.02
     SCREAMING_SNAKE_CASE__: Optional[int]=   3
     SCREAMING_SNAKE_CASE__: Optional[int]=   4
     SCREAMING_SNAKE_CASE__: Optional[int]=   None
    def     UpperCamelCase_					(	self )							->       Optional[int]:
     SCREAMING_SNAKE_CASE__: Tuple=   ids_tensor([self.batch_size, self.seq_length]			,			self.vocab_size )

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

     SCREAMING_SNAKE_CASE__: str=   None
     if self.use_token_type_ids:
      SCREAMING_SNAKE_CASE__: Dict=   ids_tensor([self.batch_size, self.seq_length]			,			self.type_vocab_size )

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

     SCREAMING_SNAKE_CASE__: Union[str, Any]=   RoFormerConfig(
         vocab_size=self.vocab_size			,			hidden_size=self.hidden_size			,			num_hidden_layers=self.num_hidden_layers			,			num_attention_heads=self.num_attention_heads			,			intermediate_size=self.intermediate_size			,			hidden_act=self.hidden_act			,			hidden_dropout_prob=self.hidden_dropout_prob			,			attention_probs_dropout_prob=self.attention_probs_dropout_prob			,			max_position_embeddings=self.max_position_embeddings			,			type_vocab_size=self.type_vocab_size			,			initializer_range=self.initializer_range			,			return_dict=lowerCamelCase_			,			)

     return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       int:
     SCREAMING_SNAKE_CASE__: List[str]=   TFRoFormerModel(config=lowerCamelCase_ )
     SCREAMING_SNAKE_CASE__: str=   {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}

     SCREAMING_SNAKE_CASE__: str=   [input_ids, input_mask]
     SCREAMING_SNAKE_CASE__: Any=   model(lowerCamelCase_ )

     SCREAMING_SNAKE_CASE__: List[Any]=   model(lowerCamelCase_ )

     self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.seq_length, self.hidden_size) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Tuple:
     SCREAMING_SNAKE_CASE__: Optional[int]=   True
     SCREAMING_SNAKE_CASE__: Any=   TFRoFormerForCausalLM(config=lowerCamelCase_ )
     SCREAMING_SNAKE_CASE__: List[str]=   {
         '''input_ids''': input_ids,
         '''attention_mask''': input_mask,
         '''token_type_ids''': token_type_ids,
     }
     SCREAMING_SNAKE_CASE__: int=   model(lowerCamelCase_ )['''logits''']
     self.parent.assertListEqual(
         list(prediction_scores.numpy().shape )			,			[self.batch_size, self.seq_length, self.vocab_size] )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       List[str]:
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   TFRoFormerForMaskedLM(config=lowerCamelCase_ )
     SCREAMING_SNAKE_CASE__: Dict=   {
         '''input_ids''': input_ids,
         '''attention_mask''': input_mask,
         '''token_type_ids''': token_type_ids,
     }
     SCREAMING_SNAKE_CASE__: Dict=   model(lowerCamelCase_ )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.seq_length, self.vocab_size) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: Optional[Any]=   self.num_labels
     SCREAMING_SNAKE_CASE__: List[Any]=   TFRoFormerForSequenceClassification(config=lowerCamelCase_ )
     SCREAMING_SNAKE_CASE__: List[Any]=   {
         '''input_ids''': input_ids,
         '''attention_mask''': input_mask,
         '''token_type_ids''': token_type_ids,
     }

     SCREAMING_SNAKE_CASE__: Union[str, Any]=   model(lowerCamelCase_ )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Dict:
     SCREAMING_SNAKE_CASE__: int=   self.num_choices
     SCREAMING_SNAKE_CASE__: Optional[int]=   TFRoFormerForMultipleChoice(config=lowerCamelCase_ )
     SCREAMING_SNAKE_CASE__: Tuple=   tf.tile(tf.expand_dims(lowerCamelCase_			,			1 )			,			(1, self.num_choices, 1) )
     SCREAMING_SNAKE_CASE__: Optional[Any]=   tf.tile(tf.expand_dims(lowerCamelCase_			,			1 )			,			(1, self.num_choices, 1) )
     SCREAMING_SNAKE_CASE__: Dict=   tf.tile(tf.expand_dims(lowerCamelCase_			,			1 )			,			(1, self.num_choices, 1) )
     SCREAMING_SNAKE_CASE__: Optional[int]=   {
         '''input_ids''': multiple_choice_inputs_ids,
         '''attention_mask''': multiple_choice_input_mask,
         '''token_type_ids''': multiple_choice_token_type_ids,
     }
     SCREAMING_SNAKE_CASE__: str=   model(lowerCamelCase_ )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_choices) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Any:
     SCREAMING_SNAKE_CASE__: Dict=   self.num_labels
     SCREAMING_SNAKE_CASE__: Optional[Any]=   TFRoFormerForTokenClassification(config=lowerCamelCase_ )
     SCREAMING_SNAKE_CASE__: Dict=   {
         '''input_ids''': input_ids,
         '''attention_mask''': input_mask,
         '''token_type_ids''': token_type_ids,
     }
     SCREAMING_SNAKE_CASE__: Optional[int]=   model(lowerCamelCase_ )
     self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.seq_length, self.num_labels) )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Optional[int]:
     SCREAMING_SNAKE_CASE__: Optional[Any]=   TFRoFormerForQuestionAnswering(config=lowerCamelCase_ )
     SCREAMING_SNAKE_CASE__: Any=   {
         '''input_ids''': input_ids,
         '''attention_mask''': input_mask,
         '''token_type_ids''': token_type_ids,
     }

     SCREAMING_SNAKE_CASE__: int=   model(lowerCamelCase_ )
     self.parent.assertEqual(result.start_logits.shape			,			(self.batch_size, self.seq_length) )
     self.parent.assertEqual(result.end_logits.shape			,			(self.batch_size, self.seq_length) )



    def     UpperCamelCase_					(	self )							->       Any:
     SCREAMING_SNAKE_CASE__: Optional[Any]=   self.prepare_config_and_inputs()
     (
         SCREAMING_SNAKE_CASE__   
     ): List[Any]=   config_and_inputs
     SCREAMING_SNAKE_CASE__: Optional[int]=   {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
     return config, inputs_dict






@require_tf
class 		_lowerCamelCase		( UpperCamelCase_     ,  UpperCamelCase_     ,  unittest.TestCase     ):
    __a						=   (
        (
            TFRoFormerModel,
            TFRoFormerForCausalLM,
            TFRoFormerForMaskedLM,
            TFRoFormerForQuestionAnswering,
            TFRoFormerForSequenceClassification,
            TFRoFormerForTokenClassification,
            TFRoFormerForMultipleChoice,
        )
        if is_tf_available()
        else ()
    )
    __a						=   (
        {
            '''feature-extraction''': TFRoFormerModel,
            '''fill-mask''': TFRoFormerForMaskedLM,
            '''question-answering''': TFRoFormerForQuestionAnswering,
            '''text-classification''': TFRoFormerForSequenceClassification,
            '''text-generation''': TFRoFormerForCausalLM,
            '''token-classification''': TFRoFormerForTokenClassification,
            '''zero-shot''': TFRoFormerForSequenceClassification,
        }
        if is_tf_available()
        else {}
    )

    __a						=   False
    __a						=   False
    def     UpperCamelCase_					(	self			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase			,			lowerCAmelCase )							->       Any:



     if pipeline_test_casse_name == "TextGenerationPipelineTests":
      return True

     return False
    def     UpperCamelCase_					(	self )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: List[Any]=   TFRoFormerModelTester(self )
     SCREAMING_SNAKE_CASE__: int=   ConfigTester(self			,			config_class=lowerCamelCase_			,			hidden_size=37 )
    def     UpperCamelCase_					(	self )							->       Dict:
     self.config_tester.run_common_tests()
    def     UpperCamelCase_					(	self )							->       List[Any]:
     SCREAMING_SNAKE_CASE__: Any=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCamelCase_ )
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     SCREAMING_SNAKE_CASE__: Tuple=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase_ )
    def     UpperCamelCase_					(	self )							->       List[Any]:
     SCREAMING_SNAKE_CASE__: str=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_lm_head(*lowerCamelCase_ )
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     SCREAMING_SNAKE_CASE__: Optional[int]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase_ )
    def     UpperCamelCase_					(	self )							->       Any:
     SCREAMING_SNAKE_CASE__: List[str]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_question_answering(*lowerCamelCase_ )
    def     UpperCamelCase_					(	self )							->       str:
     SCREAMING_SNAKE_CASE__: Optional[int]=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase_ )
    def     UpperCamelCase_					(	self )							->       List[Any]:
     SCREAMING_SNAKE_CASE__: str=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_token_classification(*lowerCamelCase_ )



    @slow
    def     UpperCamelCase_					(	self )							->       Union[str, Any]:
     SCREAMING_SNAKE_CASE__: List[str]=   TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' )
     self.assertIsNotNone(lowerCamelCase_ )






@require_tf
class 		_lowerCamelCase		( unittest.TestCase     ):
    @slow
    def     UpperCamelCase_					(	self )							->       Dict:
     SCREAMING_SNAKE_CASE__: List[Any]=   TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' )
     SCREAMING_SNAKE_CASE__: Dict=   tf.constant([[0, 1, 2, 3, 4, 5]] )
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   model(lowerCamelCase_ )[0]

     # TODO Replace vocab size
     SCREAMING_SNAKE_CASE__: List[str]=   50000

     SCREAMING_SNAKE_CASE__: int=   [1, 6, vocab_size]
     self.assertEqual(output.shape			,			lowerCamelCase_ )

     print(output[:, :3, :3] )

     # TODO Replace values below with what was printed above.
     SCREAMING_SNAKE_CASE__: Tuple=   tf.constant(
         [
             [
                 [-0.12053341, -1.0264901, 0.29221946],
                 [-1.5133783, 0.197433, 0.15190607],
                 [-5.0135403, -3.900256, -0.84038764],
             ]
         ] )
     tf.debugging.assert_near(output[:, :3, :3]			,			lowerCamelCase_			,			atol=1e-4 )






@require_tf
class 		_lowerCamelCase		( unittest.TestCase     ):
    __a						=   1e-4
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   tf.constant([[4, 10]] )
     SCREAMING_SNAKE_CASE__: List[str]=   TFRoFormerSinusoidalPositionalEmbedding(num_positions=6			,			embedding_dim=6 )

     SCREAMING_SNAKE_CASE__: Optional[Any]=   emba(input_ids.shape )
     SCREAMING_SNAKE_CASE__: List[str]=   tf.constant(
         [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] )

     tf.debugging.assert_near(lowerCamelCase_			,			lowerCamelCase_			,			atol=self.tolerance )



    def     UpperCamelCase_					(	self )							->       List[str]:
     SCREAMING_SNAKE_CASE__: Any=   tf.constant(
         [
             [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
             [0.8415, 0.8219, 0.8020, 0.7819, 0.7617],
             [0.9093, 0.9364, 0.9581, 0.9749, 0.9870],
         ] )
     SCREAMING_SNAKE_CASE__: Dict=   TFRoFormerSinusoidalPositionalEmbedding(num_positions=512			,			embedding_dim=512 )
     emba([2, 16, 512] )
     SCREAMING_SNAKE_CASE__: Optional[int]=   emba.weight[:3, :5]

     tf.debugging.assert_near(lowerCamelCase_			,			lowerCamelCase_			,			atol=self.tolerance )






@require_tf
class 		_lowerCamelCase		( unittest.TestCase     ):
    __a						=   1e-4
    def     UpperCamelCase_					(	self )							->       List[str]:
     SCREAMING_SNAKE_CASE__: Optional[int]=   tf.reshape(tf.range(2 * 12 * 16 * 64			,			dtype=tf.floataa )			,			shape=(2, 12, 16, 64) ) / 100

     SCREAMING_SNAKE_CASE__: int=   -tf.reshape(tf.range(2 * 12 * 16 * 64			,			dtype=tf.floataa )			,			shape=(2, 12, 16, 64) ) / 100

     SCREAMING_SNAKE_CASE__: Optional[Any]=   TFRoFormerSinusoidalPositionalEmbedding(num_positions=32			,			embedding_dim=64 )
     SCREAMING_SNAKE_CASE__: int=   embed_positions([2, 16, 768] )[None, None, :, :]

     SCREAMING_SNAKE_CASE__: Dict=   TFRoFormerSelfAttention.apply_rotary_position_embeddings(
         lowerCamelCase_			,			lowerCamelCase_			,			lowerCamelCase_ )

     SCREAMING_SNAKE_CASE__: Any=   tf.constant(
         [
             [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700],
             [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343],
             [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985],
             [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871],
             [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980],
             [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253],
         ] )
     SCREAMING_SNAKE_CASE__: List[str]=   tf.constant(
         [
             [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700],
             [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343],
             [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985],
             [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871],
             [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980],
             [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253],
         ] )

     tf.debugging.assert_near(query_layer[0, 0, :6, :8]			,			lowerCamelCase_			,			atol=self.tolerance )
     tf.debugging.assert_near(key_layer[0, 0, :6, :8]			,			lowerCamelCase_			,			atol=self.tolerance )


'''simple docstring'''

import numpy as np







def __UpperCamelCase( _A       :					np.ndarray	,      _A       :					np.ndarray	,      _A       :					float = 1e-12	,      _A       :					int = 1_00	,      ):
   '''simple docstring'''
   assert np.shape(_A     )[0] == np.shape(_A     )[1]
   # Ensure proper dimensionality.
   assert np.shape(_A     )[0] == np.shape(_A     )[0]
   # Ensure inputs are either both complex or both real
   assert np.iscomplexobj(_A     ) == np.iscomplexobj(_A     )
   UpperCAmelCase__				:					int 					=	np.iscomplexobj(_A     )
   if is_complex:
      # Ensure complex input_matrix is Hermitian
      assert np.array_equal(_A	,      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.

   UpperCAmelCase__				:					Any 					=	False
   UpperCAmelCase__				:					str 					=	0
   UpperCAmelCase__				:					Optional[int] 					=	0
   UpperCAmelCase__				:					Optional[int] 					=	1e12

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

      # Check convergence.
      UpperCAmelCase__				:					List[Any] 					=	np.abs(lambda_ - lambda_previous     ) / lambda_
      iterations += 1

      if error <= error_tol or iterations >= max_iterations:
         UpperCAmelCase__				:					Optional[Any] 					=	True

      UpperCAmelCase__				:					Optional[int] 					=	lambda_

   if is_complex:
      UpperCAmelCase__				:					Tuple 					=	np.real(lambda_     )

   return lambda_, vector







def __UpperCamelCase( ):
   '''simple docstring'''
   UpperCAmelCase__				:					Optional[int] 					=	np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]     )
   UpperCAmelCase__				:					int 					=	np.array([41, 4, 20]     )
   UpperCAmelCase__				:					str 					=	real_input_matrix.astype(np.complexaaa     )
   UpperCAmelCase__				:					Union[str, Any] 					=	np.triu(1J * complex_input_matrix	,      1     )
   complex_input_matrix += imag_matrix
   complex_input_matrix += -1 * imag_matrix.T
   UpperCAmelCase__				:					Tuple 					=	np.array([41, 4, 20]     ).astype(np.complexaaa     )

   for problem_type in ["real", "complex"]:
      if problem_type == "real":
         UpperCAmelCase__				:					Optional[int] 					=	real_input_matrix
         UpperCAmelCase__				:					int 					=	real_vector
      elif problem_type == "complex":
         UpperCAmelCase__				:					int 					=	complex_input_matrix
         UpperCAmelCase__				:					Tuple 					=	complex_vector

      # Our implementation.
      UpperCAmelCase__					,   UpperCAmelCase__				:					str 					=	power_iteration(_A	,      _A     )

      # Numpy implementation.

      # Get eigenvalues and eigenvectors using built-in numpy
      # eigh (eigh used for symmetric or hermetian matrices).
      UpperCAmelCase__					,   UpperCAmelCase__				:					Tuple 					=	np.linalg.eigh(_A     )
      # Last eigenvalue is the maximum one.
      UpperCAmelCase__				:					Dict 					=	eigen_values[-1]
      # Last column in this matrix is eigenvector corresponding to largest eigenvalue.
      UpperCAmelCase__				:					Union[str, Any] 					=	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(_A     ) - np.abs(_A     )     ) <= 1e-6


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  test_power_iteration()




