import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 (
					    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
					    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
					    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
					    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
					    LayoutLMvaConfig,
					    LayoutLMvaForQuestionAnswering,
					    LayoutLMvaForSequenceClassification,
					    LayoutLMvaForTokenClassification,
					    LayoutLMvaModel,
					)
					from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
					from PIL import Image

					from transformers import LayoutLMvaImageProcessor


class 						lowercase    :




							def __init__(						self   :					Optional[Any]	,							_UpperCamelCase   :					int	,							_UpperCamelCase   :					int=2	,							_UpperCamelCase   :					Optional[int]=3	,							_UpperCamelCase   :					Any=4	,							_UpperCamelCase   :					Optional[Any]=2	,							_UpperCamelCase   :					str=7	,							_UpperCamelCase   :					List[str]=True	,							_UpperCamelCase   :					Optional[Any]=True	,							_UpperCamelCase   :					Optional[Any]=True	,							_UpperCamelCase   :					List[str]=True	,							_UpperCamelCase   :					List[str]=99	,							_UpperCamelCase   :					Tuple=36	,							_UpperCamelCase   :					Union[str, Any]=3	,							_UpperCamelCase   :					Optional[int]=4	,							_UpperCamelCase   :					List[Any]=37	,							_UpperCamelCase   :					List[str]="gelu"	,							_UpperCamelCase   :					Dict=0.1	,							_UpperCamelCase   :					List[str]=0.1	,							_UpperCamelCase   :					Optional[int]=512	,							_UpperCamelCase   :					Optional[int]=16	,							_UpperCamelCase   :					Optional[Any]=2	,							_UpperCamelCase   :					int=0.0_2	,							_UpperCamelCase   :					Optional[Any]=6	,							_UpperCamelCase   :					Optional[int]=6	,							_UpperCamelCase   :					Any=3	,							_UpperCamelCase   :					Union[str, Any]=4	,							_UpperCamelCase   :					Union[str, Any]=None	,							_UpperCamelCase   :					Dict=1_000	,							)					->				Optional[int]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       parent
												SCREAMING_SNAKE_CASE    			=       batch_size
												SCREAMING_SNAKE_CASE    			=       num_channels
												SCREAMING_SNAKE_CASE    			=       image_size
												SCREAMING_SNAKE_CASE    			=       patch_size
												SCREAMING_SNAKE_CASE    			=       text_seq_length
												SCREAMING_SNAKE_CASE    			=       is_training
												SCREAMING_SNAKE_CASE    			=       use_input_mask
												SCREAMING_SNAKE_CASE    			=       use_token_type_ids
												SCREAMING_SNAKE_CASE    			=       use_labels
												SCREAMING_SNAKE_CASE    			=       vocab_size
												SCREAMING_SNAKE_CASE    			=       hidden_size
												SCREAMING_SNAKE_CASE    			=       num_hidden_layers
												SCREAMING_SNAKE_CASE    			=       num_attention_heads
												SCREAMING_SNAKE_CASE    			=       intermediate_size
												SCREAMING_SNAKE_CASE    			=       hidden_act
												SCREAMING_SNAKE_CASE    			=       hidden_dropout_prob
												SCREAMING_SNAKE_CASE    			=       attention_probs_dropout_prob
												SCREAMING_SNAKE_CASE    			=       max_position_embeddings
												SCREAMING_SNAKE_CASE    			=       type_vocab_size
												SCREAMING_SNAKE_CASE    			=       type_sequence_label_size
												SCREAMING_SNAKE_CASE    			=       initializer_range
												SCREAMING_SNAKE_CASE    			=       coordinate_size
												SCREAMING_SNAKE_CASE    			=       shape_size
												SCREAMING_SNAKE_CASE    			=       num_labels
												SCREAMING_SNAKE_CASE    			=       num_choices
												SCREAMING_SNAKE_CASE    			=       scope
												SCREAMING_SNAKE_CASE    			=       range_bbox

												# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
												SCREAMING_SNAKE_CASE    			=       text_seq_length
												SCREAMING_SNAKE_CASE    			=       (image_size // patch_size) ** 2 + 1
												SCREAMING_SNAKE_CASE    			=       self.text_seq_length + self.image_seq_length




							def 	__snake_case(						self   :					Tuple      )					->				str:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       ids_tensor([self.batch_size, self.text_seq_length]	,							self.vocab_size      )

												SCREAMING_SNAKE_CASE    			=       ids_tensor([self.batch_size, self.text_seq_length, 4]	,							self.range_bbox      )
												# Ensure that bbox is legal
												for i in range(bbox.shape[0]      ):
																	for j in range(bbox.shape[1]      ):
																						if bbox[i, j, 3] < bbox[i, j, 1]:
																											SCREAMING_SNAKE_CASE    			=       bbox[i, j, 3]
																											SCREAMING_SNAKE_CASE    			=       bbox[i, j, 1]
																											SCREAMING_SNAKE_CASE    			=       t
																						if bbox[i, j, 2] < bbox[i, j, 0]:
																											SCREAMING_SNAKE_CASE    			=       bbox[i, j, 2]
																											SCREAMING_SNAKE_CASE    			=       bbox[i, j, 0]
																											SCREAMING_SNAKE_CASE    			=       t

												SCREAMING_SNAKE_CASE    			=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

												SCREAMING_SNAKE_CASE    			=       None
												if self.use_input_mask:
																	SCREAMING_SNAKE_CASE    			=       random_attention_mask([self.batch_size, self.text_seq_length]      )

												SCREAMING_SNAKE_CASE    			=       None
												if self.use_token_type_ids:
																	SCREAMING_SNAKE_CASE    			=       ids_tensor([self.batch_size, self.text_seq_length]	,							self.type_vocab_size      )

												SCREAMING_SNAKE_CASE    			=       None
												SCREAMING_SNAKE_CASE    			=       None
												if self.use_labels:
																	SCREAMING_SNAKE_CASE    			=       ids_tensor([self.batch_size]	,							self.type_sequence_label_size      )
																	SCREAMING_SNAKE_CASE    			=       ids_tensor([self.batch_size, self.text_seq_length]	,							self.num_labels      )

												SCREAMING_SNAKE_CASE    			=       LayoutLMvaConfig(
												    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	,							coordinate_size=self.coordinate_size	,							shape_size=self.shape_size	,							input_size=self.image_size	,							patch_size=self.patch_size	,							)

												return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels




							def 	__snake_case(						self   :					Any	,							_UpperCamelCase   :					Tuple	,							_UpperCamelCase   :					str	,							_UpperCamelCase   :					List[str]	,							_UpperCamelCase   :					Any	,							_UpperCamelCase   :					Optional[int]	,							_UpperCamelCase   :					List[str]	,							_UpperCamelCase   :					Any	,							_UpperCamelCase   :					Any      )					->				List[str]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       LayoutLMvaModel(config=UpperCAmelCase__      )
												model.to(UpperCAmelCase__      )
												model.eval()

												# text + image
												SCREAMING_SNAKE_CASE    			=       model(UpperCAmelCase__	,							pixel_values=UpperCAmelCase__      )
												SCREAMING_SNAKE_CASE    			=       model(
												    UpperCAmelCase__	,							bbox=UpperCAmelCase__	,							pixel_values=UpperCAmelCase__	,							attention_mask=UpperCAmelCase__	,							token_type_ids=UpperCAmelCase__      )
												SCREAMING_SNAKE_CASE    			=       model(UpperCAmelCase__	,							bbox=UpperCAmelCase__	,							pixel_values=UpperCAmelCase__	,							token_type_ids=UpperCAmelCase__      )
												SCREAMING_SNAKE_CASE    			=       model(UpperCAmelCase__	,							bbox=UpperCAmelCase__	,							pixel_values=UpperCAmelCase__      )

												self.parent.assertEqual(result.last_hidden_state.shape	,							(self.batch_size, self.seq_length, self.hidden_size)      )

												# text only
												SCREAMING_SNAKE_CASE    			=       model(UpperCAmelCase__      )
												self.parent.assertEqual(
												    result.last_hidden_state.shape	,							(self.batch_size, self.text_seq_length, self.hidden_size)      )

												# image only
												SCREAMING_SNAKE_CASE    			=       model(pixel_values=UpperCAmelCase__      )
												self.parent.assertEqual(
												    result.last_hidden_state.shape	,							(self.batch_size, self.image_seq_length, self.hidden_size)      )




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



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.num_labels
												SCREAMING_SNAKE_CASE    			=       LayoutLMvaForSequenceClassification(UpperCAmelCase__      )
												model.to(UpperCAmelCase__      )
												model.eval()
												SCREAMING_SNAKE_CASE    			=       model(
												    UpperCAmelCase__	,							bbox=UpperCAmelCase__	,							pixel_values=UpperCAmelCase__	,							attention_mask=UpperCAmelCase__	,							token_type_ids=UpperCAmelCase__	,							labels=UpperCAmelCase__	,							)
												self.parent.assertEqual(result.logits.shape	,							(self.batch_size, self.num_labels)      )




							def 	__snake_case(						self   :					Tuple	,							_UpperCamelCase   :					Union[str, Any]	,							_UpperCamelCase   :					str	,							_UpperCamelCase   :					Union[str, Any]	,							_UpperCamelCase   :					Tuple	,							_UpperCamelCase   :					List[str]	,							_UpperCamelCase   :					List[str]	,							_UpperCamelCase   :					Union[str, Any]	,							_UpperCamelCase   :					Dict      )					->				str:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.num_labels
												SCREAMING_SNAKE_CASE    			=       LayoutLMvaForTokenClassification(config=UpperCAmelCase__      )
												model.to(UpperCAmelCase__      )
												model.eval()
												SCREAMING_SNAKE_CASE    			=       model(
												    UpperCAmelCase__	,							bbox=UpperCAmelCase__	,							pixel_values=UpperCAmelCase__	,							attention_mask=UpperCAmelCase__	,							token_type_ids=UpperCAmelCase__	,							labels=UpperCAmelCase__	,							)
												self.parent.assertEqual(result.logits.shape	,							(self.batch_size, self.text_seq_length, self.num_labels)      )




							def 	__snake_case(						self   :					Optional[int]	,							_UpperCamelCase   :					List[str]	,							_UpperCamelCase   :					Optional[int]	,							_UpperCamelCase   :					Tuple	,							_UpperCamelCase   :					List[Any]	,							_UpperCamelCase   :					Optional[Any]	,							_UpperCamelCase   :					Any	,							_UpperCamelCase   :					List[Any]	,							_UpperCamelCase   :					Tuple      )					->				List[str]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       LayoutLMvaForQuestionAnswering(config=UpperCAmelCase__      )
												model.to(UpperCAmelCase__      )
												model.eval()
												SCREAMING_SNAKE_CASE    			=       model(
												    UpperCAmelCase__	,							bbox=UpperCAmelCase__	,							pixel_values=UpperCAmelCase__	,							attention_mask=UpperCAmelCase__	,							token_type_ids=UpperCAmelCase__	,							start_positions=UpperCAmelCase__	,							end_positions=UpperCAmelCase__	,							)
												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 	__snake_case(						self   :					Optional[Any]      )					->				Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.prepare_config_and_inputs()
												(
												    SCREAMING_SNAKE_CASE  
												)    			=       config_and_inputs
												SCREAMING_SNAKE_CASE    			=       {
												    '''input_ids''': input_ids,
												    '''bbox''': bbox,
												    '''pixel_values''': pixel_values,
												    '''token_type_ids''': token_type_ids,
												    '''attention_mask''': input_mask,
												}
												return config, inputs_dict



@require_torch
class 						lowercase    (     lowercase__				,       lowercase__				,       unittest.TestCase     ):
							lowercase__						:       Dict								=							False
							lowercase__						:       Any								=							False
							lowercase__						:       Optional[int]								=							False

							lowercase__						:       List[str]								=							(
							    (
							        LayoutLMvaModel,
							        LayoutLMvaForSequenceClassification,
							        LayoutLMvaForTokenClassification,
							        LayoutLMvaForQuestionAnswering,
							    )
							    if is_torch_available()
							    else ()
							)
							lowercase__						:       List[str]								=							(
							    {"""document-question-answering""": LayoutLMvaForQuestionAnswering, """feature-extraction""": LayoutLMvaModel}
							    if is_torch_available()
							    else {}
							)




							def 	__snake_case(						self   :					str	,							_UpperCamelCase   :					int	,							_UpperCamelCase   :					Optional[int]	,							_UpperCamelCase   :					List[Any]	,							_UpperCamelCase   :					List[str]	,							_UpperCamelCase   :					Tuple      )					->				Tuple:



												'''simple docstring'''

												return True




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



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       LayoutLMvaModelTester(self      )
												SCREAMING_SNAKE_CASE    			=       ConfigTester(self	,							config_class=UpperCAmelCase__	,							hidden_size=37      )




							def 	__snake_case(						self   :					str	,							_UpperCamelCase   :					List[Any]	,							_UpperCamelCase   :					Optional[int]	,							_UpperCamelCase   :					Dict=False      )					->				int:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       copy.deepcopy(UpperCAmelCase__      )
												if model_class in get_values(UpperCAmelCase__      ):
																	SCREAMING_SNAKE_CASE    			=       {
																	    k: v.unsqueeze(1      ).expand(-1	,							self.model_tester.num_choices	,							-1      ).contiguous()
																	    if isinstance(UpperCAmelCase__	,							torch.Tensor      ) and v.ndim > 1
																	    else v
																	    for k, v in inputs_dict.items()
																	}
												if return_labels:
																	if model_class in get_values(UpperCAmelCase__      ):
																						SCREAMING_SNAKE_CASE    			=       torch.ones(self.model_tester.batch_size	,							dtype=torch.long	,							device=UpperCAmelCase__      )
																	elif model_class in get_values(UpperCAmelCase__      ):
																						SCREAMING_SNAKE_CASE    			=       torch.zeros(
																						    self.model_tester.batch_size	,							dtype=torch.long	,							device=UpperCAmelCase__      )
																						SCREAMING_SNAKE_CASE    			=       torch.zeros(
																						    self.model_tester.batch_size	,							dtype=torch.long	,							device=UpperCAmelCase__      )
																	elif model_class in [
																	    *get_values(UpperCAmelCase__      ),
																	]:
																						SCREAMING_SNAKE_CASE    			=       torch.zeros(
																						    self.model_tester.batch_size	,							dtype=torch.long	,							device=UpperCAmelCase__      )
																	elif model_class in [
																	    *get_values(UpperCAmelCase__      ),
																	]:
																						SCREAMING_SNAKE_CASE    			=       torch.zeros(
																						    (self.model_tester.batch_size, self.model_tester.text_seq_length)	,							dtype=torch.long	,							device=UpperCAmelCase__	,							)

												return inputs_dict




							def 	__snake_case(						self   :					Tuple      )					->				str:



												'''simple docstring'''

												self.config_tester.run_common_tests()




							def 	__snake_case(						self   :					List[Any]      )					->				Any:



												'''simple docstring'''

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




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



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.model_tester.prepare_config_and_inputs()
												for type in ["absolute", "relative_key", "relative_key_query"]:
																	SCREAMING_SNAKE_CASE    			=       type
																	self.model_tester.create_and_check_model(*UpperCAmelCase__      )




							def 	__snake_case(						self   :					Optional[int]      )					->				Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__      )




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



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__      )




							def 	__snake_case(						self   :					List[Any]      )					->				List[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__      )





							@slow
							def 	__snake_case(						self   :					Any      )					->				int:



												'''simple docstring'''

												for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	SCREAMING_SNAKE_CASE    			=       LayoutLMvaModel.from_pretrained(UpperCAmelCase__      )
																	self.assertIsNotNone(UpperCAmelCase__      )





def 	__lowerCamelCase							():
					SCREAMING_SNAKE_CASE    			=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
					return image


@require_torch
class 						lowercase    (     unittest.TestCase     ):




							@cached_property
							def 	__snake_case(						self   :					Optional[Any]      )					->				Optional[int]:



												'''simple docstring'''

												return LayoutLMvaImageProcessor(apply_ocr=UpperCAmelCase__      ) if is_vision_available() else None





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



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       LayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base"      ).to(UpperCAmelCase__      )

												SCREAMING_SNAKE_CASE    			=       self.default_image_processor
												SCREAMING_SNAKE_CASE    			=       prepare_img()
												SCREAMING_SNAKE_CASE    			=       image_processor(images=UpperCAmelCase__	,							return_tensors="pt"      ).pixel_values.to(UpperCAmelCase__      )

												SCREAMING_SNAKE_CASE    			=       torch.tensor([[1, 2]]      )
												SCREAMING_SNAKE_CASE    			=       torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]      ).unsqueeze(0      )

												# forward pass
												SCREAMING_SNAKE_CASE    			=       model(
												    input_ids=input_ids.to(UpperCAmelCase__      )	,							bbox=bbox.to(UpperCAmelCase__      )	,							pixel_values=pixel_values.to(UpperCAmelCase__      )	,							)

												# verify the logits
												SCREAMING_SNAKE_CASE    			=       torch.Size((1, 199, 768)      )
												self.assertEqual(outputs.last_hidden_state.shape	,							UpperCAmelCase__      )

												SCREAMING_SNAKE_CASE    			=       torch.tensor(
												    [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]      ).to(UpperCAmelCase__      )

												self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]	,							UpperCAmelCase__	,							atol=1e-4      )      )





import numpy as np





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

					SCREAMING_SNAKE_CASE    			=       False
					SCREAMING_SNAKE_CASE    			=       0
					SCREAMING_SNAKE_CASE    			=       0
					SCREAMING_SNAKE_CASE    			=       1e12

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

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

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

										SCREAMING_SNAKE_CASE    			=       lambda_

					if is_complex:
										SCREAMING_SNAKE_CASE    			=       np.real(lambda_  )

					return lambda_, vector





def 	__lowerCamelCase							():
					SCREAMING_SNAKE_CASE    			=       np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]]  )
					SCREAMING_SNAKE_CASE    			=       np.array([4_1, 4, 2_0]  )
					SCREAMING_SNAKE_CASE    			=       real_input_matrix.astype(np.complexaaa  )
					SCREAMING_SNAKE_CASE    			=       np.triu(1j * complex_input_matrix      , 1  )
					complex_input_matrix += imag_matrix
					complex_input_matrix += -1 * imag_matrix.T
					SCREAMING_SNAKE_CASE    			=       np.array([4_1, 4, 2_0]  ).astype(np.complexaaa  )

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

										# Our implementation.
										SCREAMING_SNAKE_CASE			,   SCREAMING_SNAKE_CASE    			=       power_iteration(UpperCAmelCase__      , UpperCAmelCase__  )

										# Numpy implementation.

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


if __name__ == "__main__":
							import doctest

							doctest.testmod()
							test_power_iteration()




