




'''simple docstring'''



from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


UpperCamelCase_       =							logging.get_logger(__name__)

# General docstring
UpperCamelCase_       =							"RegNetConfig"

# Base docstring
UpperCamelCase_       =							"facebook/regnet-y-040"
UpperCamelCase_       =							[1, 1_0_8_8, 7, 7]

# Image classification docstring
UpperCamelCase_       =							"facebook/regnet-y-040"
UpperCamelCase_       =							"tabby, tabby cat"

UpperCamelCase_       =							[
    "facebook/regnet-y-040",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]






class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       def __init__(	self,				A,				A = 3,				A = 1,				A = 1,				A = "relu",				**A,				):







             '''simple docstring'''







             super().__init__(**__lowercase   )
             # The padding and conv has been verified in
             # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2   )
             SCREAMING_SNAKE_CASE					:	Any   =		tf.keras.layers.ConvaD(
                 filters=__lowercase,				kernel_size=__lowercase,				strides=__lowercase,				padding='VALID',				groups=__lowercase,				use_bias=__lowercase,				name='convolution',				)
             SCREAMING_SNAKE_CASE					:	Tuple   =		tf.keras.layers.BatchNormalization(epsilon=1E-5,				momentum=0.9,				name='normalization'   )
             SCREAMING_SNAKE_CASE					:	List[str]   =		ACTaFN[activation] if activation is not None else tf.identity







       def     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[int]   =		self.convolution(self.padding(__lowercase   )   )
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		self.normalization(__lowercase   )
             SCREAMING_SNAKE_CASE					:	Tuple   =		self.activation(__lowercase   )
             return hidden_state






class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       def __init__(	self,				A,				**A   ):







             '''simple docstring'''







             super().__init__(**__lowercase   )
             SCREAMING_SNAKE_CASE					:	Tuple   =		config.num_channels
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		TFRegNetConvLayer(
                 out_channels=config.embedding_size,				kernel_size=3,				stride=2,				activation=config.hidden_act,				name='embedder',				)







       def     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Dict   =		shape_list(__lowercase   )[1]
             if tf.executing_eagerly() and num_channels != self.num_channels:
                   raise ValueError(
                       'Make sure that the channel dimension of the pixel values match with the one set in the configuration.'   )

             # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
             # So change the input format from `NCHW` to `NHWC`.
             # shape = (batch_size, in_height, in_width, in_channels=num_channels)
             SCREAMING_SNAKE_CASE					:	Dict   =		tf.transpose(__lowercase,				perm=(0, 2, 3, 1)   )
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		self.embedder(__lowercase   )
             return hidden_state






class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       def __init__(	self,				A,				A = 2,				**A   ):







             '''simple docstring'''







             super().__init__(**__lowercase   )
             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		tf.keras.layers.ConvaD(
                 filters=__lowercase,				kernel_size=1,				strides=__lowercase,				use_bias=__lowercase,				name='convolution'   )
             SCREAMING_SNAKE_CASE					:	int   =		tf.keras.layers.BatchNormalization(epsilon=1E-5,				momentum=0.9,				name='normalization'   )







       def     UpperCamelCase_				(	self,				A,				A = False   ):







             '''simple docstring'''







             return self.normalization(self.convolution(__lowercase   ),				training=__lowercase   )






class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       def __init__(	self,				A,				A,				**A   ):







             '''simple docstring'''







             super().__init__(**__lowercase   )
             SCREAMING_SNAKE_CASE					:	int   =		tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase,				name='pooler'   )
             SCREAMING_SNAKE_CASE					:	List[Any]   =		[
                 tf.keras.layers.ConvaD(filters=__lowercase,				kernel_size=1,				activation='relu',				name='attention.0'   ),
                 tf.keras.layers.ConvaD(filters=__lowercase,				kernel_size=1,				activation='sigmoid',				name='attention.2'   ),
             ]







       def     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	List[str]   =		self.pooler(__lowercase   )
             for layer_module in self.attention:
                   SCREAMING_SNAKE_CASE					:	List[str]   =		layer_module(__lowercase   )
             SCREAMING_SNAKE_CASE					:	int   =		hidden_state * pooled
             return hidden_state






class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       def __init__(	self,				A,				A,				A,				A = 1,				**A   ):







             '''simple docstring'''







             super().__init__(**__lowercase   )
             SCREAMING_SNAKE_CASE					:	str   =		in_channels != out_channels or stride != 1
             SCREAMING_SNAKE_CASE					:	Any   =		max(1,				out_channels // config.groups_width   )
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		(
                 TFRegNetShortCut(__lowercase,				stride=__lowercase,				name='shortcut'   )
                 if should_apply_shortcut
                 else tf.keras.layers.Activation('linear',				name='shortcut'   )
             )
             # `self.layers` instead of `self.layer` because that is a reserved argument.
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		[
                 TFRegNetConvLayer(__lowercase,				kernel_size=1,				activation=config.hidden_act,				name='layer.0'   ),
                 TFRegNetConvLayer(
                     __lowercase,				stride=__lowercase,				groups=__lowercase,				activation=config.hidden_act,				name='layer.1'   ),
                 TFRegNetConvLayer(__lowercase,				kernel_size=1,				activation=__lowercase,				name='layer.2'   ),
             ]
             SCREAMING_SNAKE_CASE					:	Dict   =		ACTaFN[config.hidden_act]







       def     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[int]   =		hidden_state
             for layer_module in self.layers:
                   SCREAMING_SNAKE_CASE					:	Any   =		layer_module(__lowercase   )
             SCREAMING_SNAKE_CASE					:	Tuple   =		self.shortcut(__lowercase   )
             hidden_state += residual
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		self.activation(__lowercase   )
             return hidden_state






class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       def __init__(	self,				A,				A,				A,				A = 1,				**A   ):







             '''simple docstring'''







             super().__init__(**__lowercase   )
             SCREAMING_SNAKE_CASE					:	int   =		in_channels != out_channels or stride != 1
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		max(1,				out_channels // config.groups_width   )
             SCREAMING_SNAKE_CASE					:	Dict   =		(
                 TFRegNetShortCut(__lowercase,				stride=__lowercase,				name='shortcut'   )
                 if should_apply_shortcut
                 else tf.keras.layers.Activation('linear',				name='shortcut'   )
             )
             SCREAMING_SNAKE_CASE					:	Dict   =		[
                 TFRegNetConvLayer(__lowercase,				kernel_size=1,				activation=config.hidden_act,				name='layer.0'   ),
                 TFRegNetConvLayer(
                     __lowercase,				stride=__lowercase,				groups=__lowercase,				activation=config.hidden_act,				name='layer.1'   ),
                 TFRegNetSELayer(__lowercase,				reduced_channels=int(round(in_channels / 4   )   ),				name='layer.2'   ),
                 TFRegNetConvLayer(__lowercase,				kernel_size=1,				activation=__lowercase,				name='layer.3'   ),
             ]
             SCREAMING_SNAKE_CASE					:	Dict   =		ACTaFN[config.hidden_act]







       def     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	str   =		hidden_state
             for layer_module in self.layers:
                   SCREAMING_SNAKE_CASE					:	Optional[Any]   =		layer_module(__lowercase   )
             SCREAMING_SNAKE_CASE					:	List[Any]   =		self.shortcut(__lowercase   )
             hidden_state += residual
             SCREAMING_SNAKE_CASE					:	List[str]   =		self.activation(__lowercase   )
             return hidden_state






class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       def __init__(	self,				A,				A,				A,				A = 2,				A = 2,				**A   ):







             '''simple docstring'''







             super().__init__(**__lowercase   )

             SCREAMING_SNAKE_CASE					:	List[Any]   =		TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer
             SCREAMING_SNAKE_CASE					:	List[str]   =		[
                 # downsampling is done in the first layer with stride of 2
                 layer(__lowercase,				__lowercase,				__lowercase,				stride=__lowercase,				name='layers.0'   ),
                 *[layer(__lowercase,				__lowercase,				__lowercase,				name=F"layers.{i+1}"   ) for i in range(depth - 1   )],
             ]







       def     UpperCamelCase_				(	self,				A   ):







             '''simple docstring'''







             for layer_module in self.layers:
                   SCREAMING_SNAKE_CASE					:	Tuple   =		layer_module(__lowercase   )
             return hidden_state






class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       def __init__(	self,				A,				**A   ):







             '''simple docstring'''







             super().__init__(**__lowercase   )
             SCREAMING_SNAKE_CASE					:	Any   =		[]
             # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
             self.stages.append(
                 TFRegNetStage(
                     __lowercase,				config.embedding_size,				config.hidden_sizes[0],				stride=2 if config.downsample_in_first_stage else 1,				depth=config.depths[0],				name='stages.0',				)   )
             SCREAMING_SNAKE_CASE					:	str   =		zip(config.hidden_sizes,				config.hidden_sizes[1:]   )
             for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowercase,				config.depths[1:]   )   ):
                   self.stages.append(TFRegNetStage(__lowercase,				__lowercase,				__lowercase,				depth=__lowercase,				name=F"stages.{i+1}"   )   )







       def     UpperCamelCase_				(	self,				A,				A = False,				A = True   ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		() if output_hidden_states else None

             for stage_module in self.stages:
                   if output_hidden_states:
                         SCREAMING_SNAKE_CASE					:	Tuple   =		hidden_states + (hidden_state,)

                   SCREAMING_SNAKE_CASE					:	Optional[Any]   =		stage_module(__lowercase   )

             if output_hidden_states:
                   SCREAMING_SNAKE_CASE					:	Tuple   =		hidden_states + (hidden_state,)

             if not return_dict:
                   return tuple(v for v in [hidden_state, hidden_states] if v is not None   )

             return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowercase,				hidden_states=__lowercase   )






@keras_serializable
class 				_a							(       tf.keras.layers.Layer      ):





       '''simple docstring'''






       A		:							Optional[Any]								=		RegNetConfig







       def __init__(	self,				A,				**A   ):







             '''simple docstring'''







             super().__init__(**__lowercase   )
             SCREAMING_SNAKE_CASE					:	List[str]   =		config
             SCREAMING_SNAKE_CASE					:	List[Any]   =		TFRegNetEmbeddings(__lowercase,				name='embedder'   )
             SCREAMING_SNAKE_CASE					:	Any   =		TFRegNetEncoder(__lowercase,				name='encoder'   )
             SCREAMING_SNAKE_CASE					:	Optional[int]   =		tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase,				name='pooler'   )







       @unpack_inputs
       def     UpperCamelCase_				(	self,				A,				A = None,				A = None,				A = False,				):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		return_dict if return_dict is not None else self.config.use_return_dict

             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		self.embedder(__lowercase,				training=__lowercase   )

             SCREAMING_SNAKE_CASE					:	Any   =		self.encoder(
                 __lowercase,				output_hidden_states=__lowercase,				return_dict=__lowercase,				training=__lowercase   )

             SCREAMING_SNAKE_CASE					:	List[str]   =		encoder_outputs[0]
             SCREAMING_SNAKE_CASE					:	List[str]   =		self.pooler(__lowercase   )

             # Change to NCHW output format have uniformity in the modules
             SCREAMING_SNAKE_CASE					:	str   =		tf.transpose(__lowercase,				perm=(0, 3, 1, 2)   )
             SCREAMING_SNAKE_CASE					:	List[Any]   =		tf.transpose(__lowercase,				perm=(0, 3, 1, 2)   )

             # Change the other hidden state outputs to NCHW as well
             if output_hidden_states:
                   SCREAMING_SNAKE_CASE					:	List[str]   =		tuple([tf.transpose(__lowercase,				perm=(0, 3, 1, 2)   ) for h in encoder_outputs[1]]   )

             if not return_dict:
                   return (last_hidden_state, pooled_output) + encoder_outputs[1:]

             return TFBaseModelOutputWithPoolingAndNoAttention(
                 last_hidden_state=__lowercase,				pooler_output=__lowercase,				hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states,				)






class 				_a							(       UpperCAmelCase_      ):





       '''simple docstring'''






       A		:							int								=		RegNetConfig
       A		:							List[str]								=		"""regnet"""
       A		:							Optional[int]								=		"""pixel_values"""







       @property
       def     UpperCamelCase_				(	self   ):







             '''simple docstring'''







             return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224),				dtype=tf.floataa   )}

UpperCamelCase_       =							R"\n    Parameters:\n    This model is a Tensorflow\n    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n    regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n    behavior.\n        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n"

UpperCamelCase_       =							R"\n    Args:\n        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConveNextImageProcessor.__call__`] for details.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"






@add_start_docstrings(
    '''The bare RegNet model outputting raw features without any specific head on top.'''      ,	UpperCAmelCase_      ,	)
class 				_a							(       UpperCAmelCase_      ):





       '''simple docstring'''






       def __init__(	self,				A,				*A,				**A   ):







             '''simple docstring'''







             super().__init__(__lowercase,				*__lowercase,				**__lowercase   )
             SCREAMING_SNAKE_CASE					:	Tuple   =		TFRegNetMainLayer(__lowercase,				name='regnet'   )







       @unpack_inputs
       @add_start_docstrings_to_model_forward(__lowercase   )
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC,				output_type=__lowercase,				config_class=_CONFIG_FOR_DOC,				modality='vision',				expected_output=_EXPECTED_OUTPUT_SHAPE,				)
       def     UpperCamelCase_				(	self,				A,				A = None,				A = None,				A=False,				):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	int   =		(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		return_dict if return_dict is not None else self.config.use_return_dict

             SCREAMING_SNAKE_CASE					:	List[Any]   =		self.regnet(
                 pixel_values=__lowercase,				output_hidden_states=__lowercase,				return_dict=__lowercase,				training=__lowercase,				)
             if not return_dict:
                   return (outputs[0],) + outputs[1:]

             return TFBaseModelOutputWithPoolingAndNoAttention(
                 last_hidden_state=outputs.last_hidden_state,				pooler_output=outputs.pooler_output,				hidden_states=outputs.hidden_states,				)






@add_start_docstrings(
    '''
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''      ,	UpperCAmelCase_      ,	)
class 				_a							(       UpperCAmelCase_      ,	UpperCAmelCase_      ):





       '''simple docstring'''






       def __init__(	self,				A,				*A,				**A   ):







             '''simple docstring'''







             super().__init__(__lowercase,				*__lowercase,				**__lowercase   )
             SCREAMING_SNAKE_CASE					:	Optional[Any]   =		config.num_labels
             SCREAMING_SNAKE_CASE					:	str   =		TFRegNetMainLayer(__lowercase,				name='regnet'   )
             # classification head
             SCREAMING_SNAKE_CASE					:	List[Any]   =		[
                 tf.keras.layers.Flatten(),
                 tf.keras.layers.Dense(config.num_labels,				name='classifier.1'   ) if config.num_labels > 0 else tf.identity,
             ]







       @unpack_inputs
       @add_start_docstrings_to_model_forward(__lowercase   )
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT,				output_type=__lowercase,				config_class=_CONFIG_FOR_DOC,				expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,				)
       def     UpperCamelCase_				(	self,				A = None,				A = None,				A = None,				A = None,				A=False,				):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					:	Optional[int]   =		(
                 output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
             )
             SCREAMING_SNAKE_CASE					:	int   =		return_dict if return_dict is not None else self.config.use_return_dict

             SCREAMING_SNAKE_CASE					:	Union[str, Any]   =		self.regnet(
                 __lowercase,				output_hidden_states=__lowercase,				return_dict=__lowercase,				training=__lowercase   )

             SCREAMING_SNAKE_CASE					:	List[str]   =		outputs.pooler_output if return_dict else outputs[1]

             SCREAMING_SNAKE_CASE					:	str   =		self.classifier[0](__lowercase   )
             SCREAMING_SNAKE_CASE					:	List[Any]   =		self.classifier[1](__lowercase   )

             SCREAMING_SNAKE_CASE					:	Tuple   =		None if labels is None else self.hf_compute_loss(labels=__lowercase,				logits=__lowercase   )

             if not return_dict:
                   SCREAMING_SNAKE_CASE					:	Tuple   =		(logits,) + outputs[2:]
                   return ((loss,) + output) if loss is not None else output

             return TFSequenceClassifierOutput(loss=__lowercase,				logits=__lowercase,				hidden_states=outputs.hidden_states   )



import numpy as np



def lowerCamelCase  (   SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE = 1e-12  ,			SCREAMING_SNAKE_CASE = 100  ,			):
    '''simple docstring'''







    assert np.shape(SCREAMING_SNAKE_CASE	)[0] == np.shape(SCREAMING_SNAKE_CASE	)[1]
    # Ensure proper dimensionality.
    assert np.shape(SCREAMING_SNAKE_CASE	)[0] == np.shape(SCREAMING_SNAKE_CASE	)[0]
    # Ensure inputs are either both complex or both real
    assert np.iscomplexobj(SCREAMING_SNAKE_CASE	) == np.iscomplexobj(SCREAMING_SNAKE_CASE	)
    __UpperCamelCase     :List[Any]			  =		np.iscomplexobj(SCREAMING_SNAKE_CASE	)
    if is_complex:
        # Ensure complex input_matrix is Hermitian
        assert np.array_equal(SCREAMING_SNAKE_CASE  ,			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     :str			  =		False
    __UpperCamelCase     :int			  =		0
    __UpperCamelCase     :Optional[Any]			  =		0
    __UpperCamelCase     :Union[str, Any]			  =		1e12

    while not convergence:
        # Multiple matrix by the vector.
        __UpperCamelCase     :List[str]			  =		np.dot(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)
        # Normalize the resulting output vector.
        __UpperCamelCase     :Tuple			  =		w / np.linalg.norm(SCREAMING_SNAKE_CASE	)
        # 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     :Optional[int]			  =		np.dot(SCREAMING_SNAKE_CASE  ,			np.dot(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)	)

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

        if error <= error_tol or iterations >= max_iterations:
            __UpperCamelCase     :Dict			  =		True

        __UpperCamelCase     :List[Any]			  =		lambda_

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

    return lambda_, vector



def lowerCamelCase  (   ):
    '''simple docstring'''







    __UpperCamelCase     :int			  =		np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]	)
    __UpperCamelCase     :Optional[Any]			  =		np.array([41, 4, 20]	)
    __UpperCamelCase     :Any			  =		real_input_matrix.astype(np.complexaaa	)
    __UpperCamelCase     :Dict			  =		np.triu(1j * complex_input_matrix  ,			1	)
    complex_input_matrix += imag_matrix
    complex_input_matrix += -1 * imag_matrix.T
    __UpperCamelCase     :Optional[int]			  =		np.array([41, 4, 20]	).astype(np.complexaaa	)

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

        # Our implementation.
        __UpperCamelCase  ,       __UpperCamelCase     :Dict			  =		power_iteration(SCREAMING_SNAKE_CASE  ,			SCREAMING_SNAKE_CASE	)

        # Numpy implementation.

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


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    test_power_iteration()





