
"""simple docstring"""
import os
import sys
import unittest


__magic_name__									=					os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__magic_name__									=					os.path.join(git_repo_path, '''src''', '''diffusers''')


class  _lowerCAmelCase    (    unittest.TestCase    ):



							def    _a (   self )				->				Any:
								_UpperCAmelCase			=    find_backend("    if not is_torch_available():" )
								self.assertEqual(__UpperCamelCase			,    "torch" )

								# backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
								# self.assertEqual(backend_with_underscore, "tensorflow_text")

								_UpperCAmelCase			=    find_backend("    if not (is_torch_available() and is_transformers_available()):" )
								self.assertEqual(__UpperCamelCase			,    "torch_and_transformers" )

								# double_backend_with_underscore = find_backend(
								#    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
								# )
								# self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

								_UpperCAmelCase			=    find_backend(
								    "    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):" )
								self.assertEqual(__UpperCamelCase			,    "torch_and_transformers_and_onnx" )



							def    _a (   self )				->				Tuple:
								_UpperCAmelCase			=    read_init()
								# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
								self.assertIn("torch"			,    __UpperCamelCase )
								self.assertIn("torch_and_transformers"			,    __UpperCamelCase )
								self.assertIn("flax_and_transformers"			,    __UpperCamelCase )
								self.assertIn("torch_and_transformers_and_onnx"			,    __UpperCamelCase )

								# Likewise, we can't assert on the exact content of a key
								self.assertIn("UNet2DModel"			,    objects["torch"] )
								self.assertIn("FlaxUNet2DConditionModel"			,    objects["flax"] )
								self.assertIn("StableDiffusionPipeline"			,    objects["torch_and_transformers"] )
								self.assertIn("FlaxStableDiffusionPipeline"			,    objects["flax_and_transformers"] )
								self.assertIn("LMSDiscreteScheduler"			,    objects["torch_and_scipy"] )
								self.assertIn("OnnxStableDiffusionPipeline"			,    objects["torch_and_transformers_and_onnx"] )



							def    _a (   self )				->				Optional[Any]:
								_UpperCAmelCase			=    create_dummy_object("CONSTANT"			,    "'torch'" )
								self.assertEqual(__UpperCamelCase			,    "\nCONSTANT = None\n" )

								_UpperCAmelCase			=    create_dummy_object("function"			,    "'torch'" )
								self.assertEqual(
								    __UpperCamelCase			,    "\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n" )

								_UpperCAmelCase			=    "\nclass FakeClass(metaclass=DummyObject):\n    _backends = 'torch'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, 'torch')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, 'torch')\n"
								_UpperCAmelCase			=    create_dummy_object("FakeClass"			,    "'torch'" )
								self.assertEqual(__UpperCamelCase			,    __UpperCamelCase )



							def    _a (   self )				->				Any:
								_UpperCAmelCase			=    "# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = [\"torch\"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, [\"torch\"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, [\"torch\"])\n"
								_UpperCAmelCase			=    create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]} )
								self.assertEqual(dummy_files["torch"]			,    __UpperCamelCase )












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()






