
'''simple docstring'''



import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
						import jax.numpy as jnp




class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						def __get__(   self       ,  _lowercase       ,  _lowercase=None ):

												"""simple docstring"""



												if obj is None:
																		return self
												if self.fget is None:
																		raise AttributeError("""unreadable attribute""" )
												_lowerCAmelCase    		=					"""__cached_""" + self.fget.__name__
												_lowerCAmelCase    		=					getattr(_lowercase       ,  _lowercase       ,  _lowercase )
												if cached is None:
																		_lowerCAmelCase    		=					self.fget(_lowercase )
																		setattr(_lowercase       ,  _lowercase       ,  _lowercase )
												return cached






def A (__lowerCamelCase :int						):
						_lowerCAmelCase    		=					val.lower()
						if val in {"y", "yes", "t", "true", "on", "1"}:
												return 1
						if val in {"n", "no", "f", "false", "off", "0"}:
												return 0
						raise ValueError(f'invalid truth value {val!r}'						)


def A (__lowerCamelCase :Union[str, Any]						):
						if is_torch_fx_proxy(__lowerCamelCase						):
												return True
						if is_torch_available():
												import torch

												if isinstance(__lowerCamelCase					,      torch.Tensor						):
																		return True
						if is_tf_available():
												import tensorflow as tf

												if isinstance(__lowerCamelCase					,      tf.Tensor						):
																		return True

						if is_flax_available():
												import jax.numpy as jnp
												from jax.core import Tracer

												if isinstance(__lowerCamelCase					,      (jnp.ndarray, Tracer)						):
																		return True

						return isinstance(__lowerCamelCase					,      np.ndarray						)


def A (__lowerCamelCase :List[Any]						):
						return isinstance(__lowerCamelCase					,      np.ndarray						)


def A (__lowerCamelCase :str						):
						return _is_numpy(__lowerCamelCase						)


def A (__lowerCamelCase :Dict						):
						import torch

						return isinstance(__lowerCamelCase					,      torch.Tensor						)


def A (__lowerCamelCase :Union[str, Any]						):
						return False if not is_torch_available() else _is_torch(__lowerCamelCase						)


def A (__lowerCamelCase :Union[str, Any]						):
						import torch

						return isinstance(__lowerCamelCase					,      torch.device						)


def A (__lowerCamelCase :List[str]						):
						return False if not is_torch_available() else _is_torch_device(__lowerCamelCase						)


def A (__lowerCamelCase :Dict						):
						import torch

						if isinstance(__lowerCamelCase					,      __lowerCamelCase						):
												if hasattr(__lowerCamelCase					,      __lowerCamelCase						):
																		_lowerCAmelCase    		=					getattr(__lowerCamelCase					,      __lowerCamelCase						)
												else:
																		return False
						return isinstance(__lowerCamelCase					,      torch.dtype						)


def A (__lowerCamelCase :Dict						):
						return False if not is_torch_available() else _is_torch_dtype(__lowerCamelCase						)


def A (__lowerCamelCase :str						):
						import tensorflow as tf

						return isinstance(__lowerCamelCase					,      tf.Tensor						)


def A (__lowerCamelCase :Optional[int]						):
						return False if not is_tf_available() else _is_tensorflow(__lowerCamelCase						)


def A (__lowerCamelCase :Tuple						):
						import tensorflow as tf

						# the `is_symbolic_tensor` predicate is only available starting with TF 2.14
						if hasattr(__lowerCamelCase					,      """is_symbolic_tensor"""						):
												return tf.is_symbolic_tensor(__lowerCamelCase						)
						return type(__lowerCamelCase						) == tf.Tensor


def A (__lowerCamelCase :int						):
						return False if not is_tf_available() else _is_tf_symbolic_tensor(__lowerCamelCase						)


def A (__lowerCamelCase :Optional[int]						):
						import jax.numpy as jnp  # noqa: F811

						return isinstance(__lowerCamelCase					,      jnp.ndarray						)


def A (__lowerCamelCase :List[str]						):
						return False if not is_flax_available() else _is_jax(__lowerCamelCase						)


def A (__lowerCamelCase :Dict						):
						if isinstance(__lowerCamelCase					,      (dict, UserDict)						):
												return {k: to_py_obj(__lowerCamelCase						) for k, v in obj.items()}
						elif isinstance(__lowerCamelCase					,      (list, tuple)						):
												return [to_py_obj(__lowerCamelCase						) for o in obj]
						elif is_tf_tensor(__lowerCamelCase						):
												return obj.numpy().tolist()
						elif is_torch_tensor(__lowerCamelCase						):
												return obj.detach().cpu().tolist()
						elif is_jax_tensor(__lowerCamelCase						):
												return np.asarray(__lowerCamelCase						).tolist()
						elif isinstance(__lowerCamelCase					,      (np.ndarray, np.number)						):  # tolist also works on 0d np arrays
												return obj.tolist()
						else:
												return obj


def A (__lowerCamelCase :Optional[int]						):
						if isinstance(__lowerCamelCase					,      (dict, UserDict)						):
												return {k: to_numpy(__lowerCamelCase						) for k, v in obj.items()}
						elif isinstance(__lowerCamelCase					,      (list, tuple)						):
												return np.array(__lowerCamelCase						)
						elif is_tf_tensor(__lowerCamelCase						):
												return obj.numpy()
						elif is_torch_tensor(__lowerCamelCase						):
												return obj.detach().cpu().numpy()
						elif is_jax_tensor(__lowerCamelCase						):
												return np.asarray(__lowerCamelCase						)
						else:
												return obj




class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					fields(self )

												# Safety and consistency checks
												if not len(_lowercase ):
																		raise ValueError(F'{self.__class__.__name__} has no fields.' )
												if not all(field.default is None for field in class_fields[1:] ):
																		raise ValueError(F'{self.__class__.__name__} should not have more than one required field.' )

												_lowerCAmelCase    		=					getattr(self       ,  class_fields[0].name )
												_lowerCAmelCase    		=					all(getattr(self       ,  field.name ) is None for field in class_fields[1:] )

												if other_fields_are_none and not is_tensor(_lowercase ):
																		if isinstance(_lowercase       ,  _lowercase ):
																								_lowerCAmelCase    		=					first_field.items()
																								_lowerCAmelCase    		=					True
																		else:
																								try:
																														_lowerCAmelCase    		=					iter(_lowercase )
																														_lowerCAmelCase    		=					True
																								except TypeError:
																														_lowerCAmelCase    		=					False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
																		if first_field_iterator:
																								for idx, element in enumerate(_lowercase ):
																														if (
																														    not isinstance(_lowercase       ,  (list, tuple) )
																														    or not len(_lowercase ) == 2
																														    or not isinstance(element[0]       ,  _lowercase )
																														):
																																				if idx == 0:
																																										# If we do not have an iterator of key/values, set it as attribute
																																										_lowerCAmelCase    		=					first_field
																																				else:
																																										# If we have a mixed iterator, raise an error
																																										raise ValueError(
																																										    F'Cannot set key/value for {element}. It needs to be a tuple (key, value).' )
																																				break
																														setattr(self       ,  element[0]       ,  element[1] )
																														if element[1] is not None:
																																				_lowerCAmelCase    		=					element[1]
																		elif first_field is not None:
																								_lowerCAmelCase    		=					first_field
												else:
																		for field in class_fields:
																								_lowerCAmelCase    		=					getattr(self       ,  field.name )
																								if v is not None:
																														_lowerCAmelCase    		=					v




						def __delitem__(   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												raise Exception(F'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.' )




						def    _lowercase      (   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												raise Exception(F'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.' )




						def    _lowercase      (   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												raise Exception(F'You cannot use ``pop`` on a {self.__class__.__name__} instance.' )




						def    _lowercase      (   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												raise Exception(F'You cannot use ``update`` on a {self.__class__.__name__} instance.' )




						def __getitem__(   self       ,  _lowercase ):

												"""simple docstring"""



												if isinstance(_lowercase       ,  _lowercase ):
																		_lowerCAmelCase    		=					dict(self.items() )
																		return inner_dict[k]
												else:
																		return self.to_tuple()[k]




						def __setattr__(   self       ,  _lowercase       ,  _lowercase ):

												"""simple docstring"""



												if name in self.keys() and value is not None:
																		# Don't call self.__setitem__ to avoid recursion errors
																		super().__setitem__(_lowercase       ,  _lowercase )
												super().__setattr__(_lowercase       ,  _lowercase )




						def __setitem__(   self       ,  _lowercase       ,  _lowercase ):

												"""simple docstring"""



												super().__setitem__(_lowercase       ,  _lowercase )
												# Don't call self.__setattr__ to avoid recursion errors
												super().__setattr__(_lowercase       ,  _lowercase )




						def    _lowercase      (   self ):

												"""simple docstring"""



												return tuple(self[k] for k in self.keys() )






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE			,				_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						@classmethod
						def    _lowercase      (   cls       ,  _lowercase ):

												"""simple docstring"""



												raise ValueError(
												    F'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}' )






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: int										=  '''longest'''
						_lowercase						: str										=  '''max_length'''
						_lowercase						: List[Any]										=  '''do_not_pad'''






class     UpperCAmelCase_	(						_SCREAMING_SNAKE_CASE					):






						'''simple docstring'''






						_lowercase						: List[Any]										=  '''pt'''
						_lowercase						: Optional[Any]										=  '''tf'''
						_lowercase						: List[str]										=  '''np'''
						_lowercase						: int										=  '''jax'''






class     UpperCAmelCase_	:






						'''simple docstring'''






						def __init__(   self       ,  _lowercase ):

												"""simple docstring"""



												_lowerCAmelCase    		=					context_managers
												_lowerCAmelCase    		=					ExitStack()




						def __enter__(   self ):

												"""simple docstring"""



												for context_manager in self.context_managers:
																		self.stack.enter_context(_lowercase )




						def __exit__(   self       ,  *_lowercase       ,  **_lowercase ):

												"""simple docstring"""



												self.stack.__exit__(*_lowercase       ,  **_lowercase )






def A (__lowerCamelCase :str						):
						_lowerCAmelCase    		=					infer_framework(__lowerCamelCase						)
						if framework == "tf":
												_lowerCAmelCase    		=					inspect.signature(model_class.call						)  # TensorFlow models
						elif framework == "pt":
												_lowerCAmelCase    		=					inspect.signature(model_class.forward						)  # PyTorch models
						else:
												_lowerCAmelCase    		=					inspect.signature(model_class.__call__						)  # Flax models

						for p in signature.parameters:
												if p == "return_loss" and signature.parameters[p].default is True:
																		return True

						return False


def A (__lowerCamelCase :List[str]						):
						_lowerCAmelCase    		=					model_class.__name__
						_lowerCAmelCase    		=					infer_framework(__lowerCamelCase						)
						if framework == "tf":
												_lowerCAmelCase    		=					inspect.signature(model_class.call						)  # TensorFlow models
						elif framework == "pt":
												_lowerCAmelCase    		=					inspect.signature(model_class.forward						)  # PyTorch models
						else:
												_lowerCAmelCase    		=					inspect.signature(model_class.__call__						)  # Flax models

						if "QuestionAnswering" in model_name:
												return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
						else:
												return [p for p in signature.parameters if "label" in p]


def A (__lowerCamelCase :MutableMapping					,      __lowerCamelCase :str = ""					,      __lowerCamelCase :str = "."						):

						def _flatten_dict(__lowerCamelCase :Optional[Any]					,      __lowerCamelCase :Optional[int]=""					,      __lowerCamelCase :Dict="."						):
												for k, v in d.items():
																		_lowerCAmelCase    		=					str(__lowerCamelCase						) + delimiter + str(__lowerCamelCase						) if parent_key else k
																		if v and isinstance(__lowerCamelCase					,      __lowerCamelCase						):
																								yield from flatten_dict(__lowerCamelCase					,      __lowerCamelCase					,      delimiter=__lowerCamelCase						).items()
																		else:
																								yield key, v

						return dict(_flatten_dict(__lowerCamelCase					,      __lowerCamelCase					,      __lowerCamelCase						)						)


@contextmanager
def A (__lowerCamelCase :Any					,      __lowerCamelCase :bool = False						):
						if use_temp_dir:
												with tempfile.TemporaryDirectory() as tmp_dir:
																		yield tmp_dir
						else:
												yield working_dir


def A (__lowerCamelCase :Dict					,      __lowerCamelCase :List[str]=None						):
						if is_numpy_array(__lowerCamelCase						):
												return np.transpose(__lowerCamelCase					,      axes=__lowerCamelCase						)
						elif is_torch_tensor(__lowerCamelCase						):
												return array.T if axes is None else array.permute(*__lowerCamelCase						)
						elif is_tf_tensor(__lowerCamelCase						):
												import tensorflow as tf

												return tf.transpose(__lowerCamelCase					,      perm=__lowerCamelCase						)
						elif is_jax_tensor(__lowerCamelCase						):
												return jnp.transpose(__lowerCamelCase					,      axes=__lowerCamelCase						)
						else:
												raise ValueError(f'Type not supported for transpose: {type(__lowerCamelCase						)}.'						)


def A (__lowerCamelCase :Tuple					,      __lowerCamelCase :List[Any]						):
						if is_numpy_array(__lowerCamelCase						):
												return np.reshape(__lowerCamelCase					,      __lowerCamelCase						)
						elif is_torch_tensor(__lowerCamelCase						):
												return array.reshape(*__lowerCamelCase						)
						elif is_tf_tensor(__lowerCamelCase						):
												import tensorflow as tf

												return tf.reshape(__lowerCamelCase					,      __lowerCamelCase						)
						elif is_jax_tensor(__lowerCamelCase						):
												return jnp.reshape(__lowerCamelCase					,      __lowerCamelCase						)
						else:
												raise ValueError(f'Type not supported for reshape: {type(__lowerCamelCase						)}.'						)


def A (__lowerCamelCase :str					,      __lowerCamelCase :Any=None						):
						if is_numpy_array(__lowerCamelCase						):
												return np.squeeze(__lowerCamelCase					,      axis=__lowerCamelCase						)
						elif is_torch_tensor(__lowerCamelCase						):
												return array.squeeze() if axis is None else array.squeeze(dim=__lowerCamelCase						)
						elif is_tf_tensor(__lowerCamelCase						):
												import tensorflow as tf

												return tf.squeeze(__lowerCamelCase					,      axis=__lowerCamelCase						)
						elif is_jax_tensor(__lowerCamelCase						):
												return jnp.squeeze(__lowerCamelCase					,      axis=__lowerCamelCase						)
						else:
												raise ValueError(f'Type not supported for squeeze: {type(__lowerCamelCase						)}.'						)


def A (__lowerCamelCase :Union[str, Any]					,      __lowerCamelCase :Dict						):
						if is_numpy_array(__lowerCamelCase						):
												return np.expand_dims(__lowerCamelCase					,      __lowerCamelCase						)
						elif is_torch_tensor(__lowerCamelCase						):
												return array.unsqueeze(dim=__lowerCamelCase						)
						elif is_tf_tensor(__lowerCamelCase						):
												import tensorflow as tf

												return tf.expand_dims(__lowerCamelCase					,      axis=__lowerCamelCase						)
						elif is_jax_tensor(__lowerCamelCase						):
												return jnp.expand_dims(__lowerCamelCase					,      axis=__lowerCamelCase						)
						else:
												raise ValueError(f'Type not supported for expand_dims: {type(__lowerCamelCase						)}.'						)


def A (__lowerCamelCase :Optional[Any]						):
						if is_numpy_array(__lowerCamelCase						):
												return np.size(__lowerCamelCase						)
						elif is_torch_tensor(__lowerCamelCase						):
												return array.numel()
						elif is_tf_tensor(__lowerCamelCase						):
												import tensorflow as tf

												return tf.size(__lowerCamelCase						)
						elif is_jax_tensor(__lowerCamelCase						):
												return array.size
						else:
												raise ValueError(f'Type not supported for expand_dims: {type(__lowerCamelCase						)}.'						)


def A (__lowerCamelCase :List[Any]					,      __lowerCamelCase :Optional[int]						):
						for key, value in auto_map.items():
												if isinstance(__lowerCamelCase					,      (tuple, list)						):
																		_lowerCAmelCase    		=					[f'{repo_id}--{v}' if (v is not None and """--""" not in v) else v for v in value]
												elif value is not None and "--" not in value:
																		_lowerCAmelCase    		=					f'{repo_id}--{value}'

						return auto_map





def A (__lowerCamelCase :Tuple						):
						for base_class in inspect.getmro(__lowerCamelCase						):
												_lowerCAmelCase    		=					base_class.__module__
												_lowerCAmelCase    		=					base_class.__name__
												if module.startswith("""tensorflow"""						) or module.startswith("""keras"""						) or name == "TFPreTrainedModel":
																		return "tf"
												elif module.startswith("""torch"""						) or name == "PreTrainedModel":
																		return "pt"
												elif module.startswith("""flax"""						) or module.startswith("""jax"""						) or name == "FlaxPreTrainedModel":
																		return "flax"
						else:
												raise TypeError(f'Could not infer framework from class {model_class}.'						)








import numpy as np





def    __lowerCAmelCase   (    __snake_case       ,			__snake_case       ,			__snake_case = 1E-12       ,			__snake_case = 100       ,			):
     assert np.shape(__snake_case							)[0] == np.shape(__snake_case							)[1]
     # Ensure proper dimensionality.
     assert np.shape(__snake_case							)[0] == np.shape(__snake_case							)[0]
     # Ensure inputs are either both complex or both real
     assert np.iscomplexobj(__snake_case							) == np.iscomplexobj(__snake_case							)
     __lowerCAmelCase             =       np.iscomplexobj(__snake_case							)
     if is_complex:
          # Ensure complex input_matrix is Hermitian
          assert np.array_equal(__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.

     __lowerCAmelCase             =       False
     __lowerCAmelCase             =       0
     __lowerCAmelCase             =       0
     __lowerCAmelCase             =       1E12

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

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

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

          __lowerCAmelCase             =       lambda_

     if is_complex:
          __lowerCAmelCase             =       np.real(lambda_							)

     return lambda_, vector





def    __lowerCAmelCase   (    ):
     __lowerCAmelCase             =       np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]							)
     __lowerCAmelCase             =       np.array([41, 4, 20]							)
     __lowerCAmelCase             =       real_input_matrix.astype(np.complexaaa							)
     __lowerCAmelCase             =       np.triu(1J * complex_input_matrix       ,			1							)
     complex_input_matrix += imag_matrix
     complex_input_matrix += -1 * imag_matrix.T
     __lowerCAmelCase             =       np.array([41, 4, 20]							).astype(np.complexaaa							)

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

          # Our implementation.
          __lowerCAmelCase      ,			__lowerCAmelCase             =       power_iteration(__snake_case       ,			__snake_case							)

          # Numpy implementation.

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


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 test_power_iteration()






