

'''simple docstring'''



import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







class 						lowerCAmelCase__   (      a ,					a ,					unittest.TestCase					):



 """simple docstring"""



 lowerCAmelCase__  					=      StableDiffusionDiffEditPipeline
 lowerCAmelCase__  					=      TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"}
 lowerCAmelCase__  					=      TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"}
 lowerCAmelCase__  					=      frozenset(
     []					)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
 lowerCAmelCase__  					=      frozenset([]					)
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> Union[str, Any]:


      """simple docstring"""




      torch.manual_seed(0			)
      __SCREAMING_SNAKE_CASE     =      UNetaDConditionModel(
          block_out_channels=(32, 64)					,							layers_per_block=2					,							sample_size=32					,							in_channels=4					,							out_channels=4					,							down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")					,							up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")					,							cross_attention_dim=32					,							attention_head_dim=(2, 4)					,							use_linear_projection=__SCREAMING_SNAKE_CASE					,							)
      __SCREAMING_SNAKE_CASE     =      DDIMScheduler(
          beta_start=0.00085					,							beta_end=0.012					,							beta_schedule="""scaled_linear"""					,							clip_sample=__SCREAMING_SNAKE_CASE					,							set_alpha_to_one=__SCREAMING_SNAKE_CASE					,							)
      __SCREAMING_SNAKE_CASE     =      DDIMInverseScheduler(
          beta_start=0.00085					,							beta_end=0.012					,							beta_schedule="""scaled_linear"""					,							clip_sample=__SCREAMING_SNAKE_CASE					,							set_alpha_to_zero=__SCREAMING_SNAKE_CASE					,							)
      torch.manual_seed(0			)
      __SCREAMING_SNAKE_CASE     =      AutoencoderKL(
          block_out_channels=[32, 64]					,							in_channels=3					,							out_channels=3					,							down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]					,							up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]					,							latent_channels=4					,							sample_size=128					,							)
      torch.manual_seed(0			)
      __SCREAMING_SNAKE_CASE     =      CLIPTextConfig(
          bos_token_id=0					,							eos_token_id=2					,							hidden_size=32					,							intermediate_size=37					,							layer_norm_eps=1E-05					,							num_attention_heads=4					,							num_hidden_layers=5					,							pad_token_id=1					,							vocab_size=1_000					,							hidden_act="""gelu"""					,							projection_dim=512					,							)
      __SCREAMING_SNAKE_CASE     =      CLIPTextModel(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""			)

      __SCREAMING_SNAKE_CASE     =      {
          """unet""": unet,
          """scheduler""": scheduler,
          """inverse_scheduler""": inverse_scheduler,
          """vae""": vae,
          """text_encoder""": text_encoder,
          """tokenizer""": tokenizer,
          """safety_checker""": None,
          """feature_extractor""": None,
      }

      return components
 def       UpperCAmelCase__		(		self					:       List[Any]					,							__SCREAMING_SNAKE_CASE					:       Dict					,							__SCREAMING_SNAKE_CASE					:       List[Any]=0			)  -> Union[str, Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      floats_tensor((1, 16, 16)					,							rng=random.Random(__SCREAMING_SNAKE_CASE			)			).to(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      floats_tensor((1, 2, 4, 16, 16)					,							rng=random.Random(__SCREAMING_SNAKE_CASE			)			).to(__SCREAMING_SNAKE_CASE			)
      if str(__SCREAMING_SNAKE_CASE			).startswith("""mps"""			):
           __SCREAMING_SNAKE_CASE     =      torch.manual_seed(__SCREAMING_SNAKE_CASE			)
      else:
           __SCREAMING_SNAKE_CASE     =      torch.Generator(device=__SCREAMING_SNAKE_CASE			).manual_seed(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      {
          """prompt""": """a dog and a newt""",
          """mask_image""": mask,
          """image_latents""": latents,
          """generator""": generator,
          """num_inference_steps""": 2,
          """inpaint_strength""": 1.0,
          """guidance_scale""": 6.0,
          """output_type""": """numpy""",
      }

      return inputs
 def       UpperCAmelCase__		(		self					:       Optional[int]					,							__SCREAMING_SNAKE_CASE					:       Optional[Any]					,							__SCREAMING_SNAKE_CASE					:       Optional[int]=0			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      floats_tensor((1, 3, 32, 32)					,							rng=random.Random(__SCREAMING_SNAKE_CASE			)			).to(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      image.cpu().permute(0					,							2					,							3					,							1			)[0]
      __SCREAMING_SNAKE_CASE     =      Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE			)			).convert("""RGB"""			)
      if str(__SCREAMING_SNAKE_CASE			).startswith("""mps"""			):
           __SCREAMING_SNAKE_CASE     =      torch.manual_seed(__SCREAMING_SNAKE_CASE			)
      else:
           __SCREAMING_SNAKE_CASE     =      torch.Generator(device=__SCREAMING_SNAKE_CASE			).manual_seed(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      {
          """image""": image,
          """source_prompt""": """a cat and a frog""",
          """target_prompt""": """a dog and a newt""",
          """generator""": generator,
          """num_inference_steps""": 2,
          """num_maps_per_mask""": 2,
          """mask_encode_strength""": 1.0,
          """guidance_scale""": 6.0,
          """output_type""": """numpy""",
      }

      return inputs
 def       UpperCAmelCase__		(		self					:       List[str]					,							__SCREAMING_SNAKE_CASE					:       str					,							__SCREAMING_SNAKE_CASE					:       Optional[int]=0			)  -> int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      floats_tensor((1, 3, 32, 32)					,							rng=random.Random(__SCREAMING_SNAKE_CASE			)			).to(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      image.cpu().permute(0					,							2					,							3					,							1			)[0]
      __SCREAMING_SNAKE_CASE     =      Image.fromarray(np.uinta(__SCREAMING_SNAKE_CASE			)			).convert("""RGB"""			)
      if str(__SCREAMING_SNAKE_CASE			).startswith("""mps"""			):
           __SCREAMING_SNAKE_CASE     =      torch.manual_seed(__SCREAMING_SNAKE_CASE			)
      else:
           __SCREAMING_SNAKE_CASE     =      torch.Generator(device=__SCREAMING_SNAKE_CASE			).manual_seed(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      {
          """image""": image,
          """prompt""": """a cat and a frog""",
          """generator""": generator,
          """num_inference_steps""": 2,
          """inpaint_strength""": 1.0,
          """guidance_scale""": 6.0,
          """decode_latents""": True,
          """output_type""": """numpy""",
      }
      return inputs
 def       UpperCAmelCase__		(		self					:       Tuple			)  -> str:


      """simple docstring"""




      if not hasattr(self.pipeline_class					,							"""_optional_components"""			):
           return

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_components()
      __SCREAMING_SNAKE_CASE     =      self.pipeline_class(**__SCREAMING_SNAKE_CASE			)
      pipe.to(__SCREAMING_SNAKE_CASE			)
      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      # set all optional components to None and update pipeline config accordingly
      for optional_component in pipe._optional_components:
           setattr(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			)
      pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}			)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe(**__SCREAMING_SNAKE_CASE			)[0]

      with tempfile.TemporaryDirectory() as tmpdir:
           pipe.save_pretrained(__SCREAMING_SNAKE_CASE			)
           __SCREAMING_SNAKE_CASE     =      self.pipeline_class.from_pretrained(__SCREAMING_SNAKE_CASE			)
           pipe_loaded.to(__SCREAMING_SNAKE_CASE			)
           pipe_loaded.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      for optional_component in pipe._optional_components:
           self.assertTrue(
               getattr(__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE			) is None					,							f'`{optional_component}` did not stay set to None after loading.'					,							)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inputs(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe_loaded(**__SCREAMING_SNAKE_CASE			)[0]

      __SCREAMING_SNAKE_CASE     =      np.abs(output - output_loaded			).max()
      self.assertLess(__SCREAMING_SNAKE_CASE					,							1E-4			)
 def       UpperCAmelCase__		(		self					:       List[Any]			)  -> int:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      """cpu"""

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_components()
      __SCREAMING_SNAKE_CASE     =      self.pipeline_class(**__SCREAMING_SNAKE_CASE			)
      pipe.to(__SCREAMING_SNAKE_CASE			)
      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_mask_inputs(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe.generate_mask(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      mask[0, -3:, -3:]

      self.assertEqual(mask.shape					,							(1, 16, 16)			)
      __SCREAMING_SNAKE_CASE     =      np.array([0] * 9			)
      __SCREAMING_SNAKE_CASE     =      np.abs(mask_slice.flatten() - expected_slice			).max()
      self.assertLessEqual(__SCREAMING_SNAKE_CASE					,							1E-3			)
      self.assertEqual(mask[0, -3, -4]					,							0			)
 def       UpperCAmelCase__		(		self					:       Optional[int]			)  -> List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      """cpu"""

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_components()
      __SCREAMING_SNAKE_CASE     =      self.pipeline_class(**__SCREAMING_SNAKE_CASE			)
      pipe.to(__SCREAMING_SNAKE_CASE			)
      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inversion_inputs(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe.invert(**__SCREAMING_SNAKE_CASE			).images
      __SCREAMING_SNAKE_CASE     =      image[0, -1, -3:, -3:]

      self.assertEqual(image.shape					,							(2, 32, 32, 3)			)
      __SCREAMING_SNAKE_CASE     =      np.array(
          [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]					,							)
      __SCREAMING_SNAKE_CASE     =      np.abs(image_slice.flatten() - expected_slice			).max()
      self.assertLessEqual(__SCREAMING_SNAKE_CASE					,							1E-3			)
 def       UpperCAmelCase__		(		self					:       List[str]			)  -> Optional[int]:


      """simple docstring"""




      super().test_inference_batch_single_identical(expected_max_diff=5E-3			)


 def       UpperCAmelCase__		(		self					:       Dict			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      """cpu"""

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_components()

      __SCREAMING_SNAKE_CASE     =      {"""beta_start""": 0.00085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""}
      __SCREAMING_SNAKE_CASE     =      DPMSolverMultistepScheduler(**__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      DPMSolverMultistepInverseScheduler(**__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      self.pipeline_class(**__SCREAMING_SNAKE_CASE			)
      pipe.to(__SCREAMING_SNAKE_CASE			)
      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      self.get_dummy_inversion_inputs(__SCREAMING_SNAKE_CASE			)
      __SCREAMING_SNAKE_CASE     =      pipe.invert(**__SCREAMING_SNAKE_CASE			).images
      __SCREAMING_SNAKE_CASE     =      image[0, -1, -3:, -3:]

      self.assertEqual(image.shape					,							(2, 32, 32, 3)			)
      __SCREAMING_SNAKE_CASE     =      np.array(
          [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]					,							)
      __SCREAMING_SNAKE_CASE     =      np.abs(image_slice.flatten() - expected_slice			).max()
      self.assertLessEqual(__SCREAMING_SNAKE_CASE					,							1E-3			)







@require_torch_gpu
@slow
class 						lowerCAmelCase__   (      unittest.TestCase					):



 """simple docstring"""



 def       UpperCAmelCase__		(		self					:       List[str]			)  -> Optional[Any]:


      """simple docstring"""




      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()
 @classmethod
 def       UpperCAmelCase__		(		cls					:       List[str]			)  -> Any:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      load_image(
          """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png"""			)

      __SCREAMING_SNAKE_CASE     =      raw_image.convert("""RGB"""			).resize((768, 768)			)

      __SCREAMING_SNAKE_CASE     =      raw_image
 def       UpperCAmelCase__		(		self					:       Dict			)  -> str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      torch.manual_seed(0			)

      __SCREAMING_SNAKE_CASE     =      StableDiffusionDiffEditPipeline.from_pretrained(
          """stabilityai/stable-diffusion-2-1"""					,							safety_checker=__SCREAMING_SNAKE_CASE					,							torch_dtype=torch.floataa			)
      __SCREAMING_SNAKE_CASE     =      DDIMScheduler.from_config(pipe.scheduler.config			)
      __SCREAMING_SNAKE_CASE     =      DDIMInverseScheduler.from_config(pipe.scheduler.config			)
      pipe.enable_model_cpu_offload()
      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      """a bowl of fruit"""
      __SCREAMING_SNAKE_CASE     =      """a bowl of pears"""

      __SCREAMING_SNAKE_CASE     =      pipe.generate_mask(
          image=self.raw_image					,							source_prompt=__SCREAMING_SNAKE_CASE					,							target_prompt=__SCREAMING_SNAKE_CASE					,							generator=__SCREAMING_SNAKE_CASE					,							)

      __SCREAMING_SNAKE_CASE     =      pipe.invert(
          prompt=__SCREAMING_SNAKE_CASE					,							image=self.raw_image					,							inpaint_strength=0.7					,							generator=__SCREAMING_SNAKE_CASE			).latents

      __SCREAMING_SNAKE_CASE     =      pipe(
          prompt=__SCREAMING_SNAKE_CASE					,							mask_image=__SCREAMING_SNAKE_CASE					,							image_latents=__SCREAMING_SNAKE_CASE					,							generator=__SCREAMING_SNAKE_CASE					,							negative_prompt=__SCREAMING_SNAKE_CASE					,							inpaint_strength=0.7					,							output_type="""numpy"""					,							).images[0]

      __SCREAMING_SNAKE_CASE     =      (
          np.array(
              load_image(
                  """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                  """/diffedit/pears.png"""			).resize((768, 768)			)			)
          / 255
      )
      assert np.abs((expected_image - image).max()			) < 5E-1


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


      """simple docstring"""




      __SCREAMING_SNAKE_CASE     =      torch.manual_seed(0			)

      __SCREAMING_SNAKE_CASE     =      StableDiffusionDiffEditPipeline.from_pretrained(
          """stabilityai/stable-diffusion-2-1"""					,							safety_checker=__SCREAMING_SNAKE_CASE					,							torch_dtype=torch.floataa			)
      __SCREAMING_SNAKE_CASE     =      DPMSolverMultistepScheduler.from_config(pipe.scheduler.config			)
      __SCREAMING_SNAKE_CASE     =      DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config			)
      pipe.enable_model_cpu_offload()
      pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE			)

      __SCREAMING_SNAKE_CASE     =      """a bowl of fruit"""
      __SCREAMING_SNAKE_CASE     =      """a bowl of pears"""

      __SCREAMING_SNAKE_CASE     =      pipe.generate_mask(
          image=self.raw_image					,							source_prompt=__SCREAMING_SNAKE_CASE					,							target_prompt=__SCREAMING_SNAKE_CASE					,							generator=__SCREAMING_SNAKE_CASE					,							)

      __SCREAMING_SNAKE_CASE     =      pipe.invert(
          prompt=__SCREAMING_SNAKE_CASE					,							image=self.raw_image					,							inpaint_strength=0.7					,							generator=__SCREAMING_SNAKE_CASE					,							num_inference_steps=25					,							).latents

      __SCREAMING_SNAKE_CASE     =      pipe(
          prompt=__SCREAMING_SNAKE_CASE					,							mask_image=__SCREAMING_SNAKE_CASE					,							image_latents=__SCREAMING_SNAKE_CASE					,							generator=__SCREAMING_SNAKE_CASE					,							negative_prompt=__SCREAMING_SNAKE_CASE					,							inpaint_strength=0.7					,							num_inference_steps=25					,							output_type="""numpy"""					,							).images[0]

      __SCREAMING_SNAKE_CASE     =      (
          np.array(
              load_image(
                  """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                  """/diffedit/pears.png"""			).resize((768, 768)			)			)
          / 255
      )
      assert np.abs((expected_image - image).max()			) < 5E-1









'''simple docstring'''



import numpy as np







def    a__       (  a__      ,    a__      ,    a__ = 1E-1_2      ,    a__ = 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__						)
     __SCREAMING_SNAKE_CASE     =      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.

     __SCREAMING_SNAKE_CASE     =      False
     __SCREAMING_SNAKE_CASE     =      0
     __SCREAMING_SNAKE_CASE     =      0
     __SCREAMING_SNAKE_CASE     =      1E1_2

     while not convergence:
          # Multiple matrix by the vector.
          __SCREAMING_SNAKE_CASE     =      np.dot(a__      ,    a__						)
          # Normalize the resulting output vector.
          __SCREAMING_SNAKE_CASE     =      w / np.linalg.norm(a__						)
          # 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(a__      ,    np.dot(a__      ,    a__						)						)

          # 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    a__       (  ):




     """simple docstring"""


     __SCREAMING_SNAKE_CASE     =      np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]]						)
     __SCREAMING_SNAKE_CASE     =      np.array([41, 4, 20]						)
     __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([41, 4, 20]						).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(a__      ,    a__						)

          # 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(a__						)
          # 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(a__						) - np.abs(a__						)						) <= 1E-6


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  test_power_iteration()






