






import inspect
import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import (
      MODEL_MAPPING,
      SegformerForImageClassification,
      SegformerForSemanticSegmentation,
      SegformerModel,
  )
  from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import SegformerImageProcessor
class 		SCREAMING_SNAKE_CASE__	(  UpperCAmelCase     ):

  '''simple docstring'''







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


         """simple docstring"""
         _UpperCAmelCase							=    self.config_class(**self.inputs_dict							)
         self.parent.assertTrue(hasattr(lowerCamelCase       ,				"""hidden_sizes"""							)							)
         self.parent.assertTrue(hasattr(lowerCamelCase       ,				"""num_attention_heads"""							)							)
         self.parent.assertTrue(hasattr(lowerCamelCase       ,				"""num_encoder_blocks"""							)							)



class 		SCREAMING_SNAKE_CASE__	:

  '''simple docstring'''







  def __init__(      self		:			List[str]       ,				lowerCamelCase		:			int       ,				lowerCamelCase		:			int=13       ,				lowerCamelCase		:			Any=64       ,				lowerCamelCase		:			Union[str, Any]=3       ,				lowerCamelCase		:			str=4       ,				lowerCamelCase		:			List[str]=[2, 2, 2, 2]       ,				lowerCamelCase		:			Tuple=[8, 4, 2, 1]       ,				lowerCamelCase		:			Optional[int]=[16, 32, 64, 128]       ,				lowerCamelCase		:			int=[1, 4, 8, 16]       ,				lowerCamelCase		:			Optional[Any]=[1, 2, 4, 8]       ,				lowerCamelCase		:			str=True       ,				lowerCamelCase		:			Union[str, Any]=True       ,				lowerCamelCase		:			Optional[Any]="gelu"       ,				lowerCamelCase		:			Tuple=0.1       ,				lowerCamelCase		:			Optional[Any]=0.1       ,				lowerCamelCase		:			Tuple=0.02       ,				lowerCamelCase		:			List[Any]=3       ,				lowerCamelCase		:			Tuple=None       ,				)						->	List[Any]:


         """simple docstring"""
         _UpperCAmelCase							=    parent
         _UpperCAmelCase							=    batch_size
         _UpperCAmelCase							=    image_size
         _UpperCAmelCase							=    num_channels
         _UpperCAmelCase							=    num_encoder_blocks
         _UpperCAmelCase							=    sr_ratios
         _UpperCAmelCase							=    depths
         _UpperCAmelCase							=    hidden_sizes
         _UpperCAmelCase							=    downsampling_rates
         _UpperCAmelCase							=    num_attention_heads
         _UpperCAmelCase							=    is_training
         _UpperCAmelCase							=    use_labels
         _UpperCAmelCase							=    hidden_act
         _UpperCAmelCase							=    hidden_dropout_prob
         _UpperCAmelCase							=    attention_probs_dropout_prob
         _UpperCAmelCase							=    initializer_range
         _UpperCAmelCase							=    num_labels
         _UpperCAmelCase							=    scope


  def  lowerCamelCase       (      self		:			Optional[int]							)						->	Dict:


         """simple docstring"""
         _UpperCAmelCase							=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

         _UpperCAmelCase							=    None
         if self.use_labels:
                _UpperCAmelCase							=    ids_tensor([self.batch_size, self.image_size, self.image_size]       ,				self.num_labels							)

         _UpperCAmelCase							=    self.get_config()
         return config, pixel_values, labels


  def  lowerCamelCase       (      self		:			Optional[Any]							)						->	Optional[Any]:


         """simple docstring"""
         return SegformerConfig(
             image_size=self.image_size       ,				num_channels=self.num_channels       ,				num_encoder_blocks=self.num_encoder_blocks       ,				depths=self.depths       ,				hidden_sizes=self.hidden_sizes       ,				num_attention_heads=self.num_attention_heads       ,				hidden_act=self.hidden_act       ,				hidden_dropout_prob=self.hidden_dropout_prob       ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,				initializer_range=self.initializer_range       ,				)


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


         """simple docstring"""
         _UpperCAmelCase							=    SegformerModel(config=lowerCamelCase							)
         model.to(lowerCamelCase							)
         model.eval()
         _UpperCAmelCase							=    model(lowerCamelCase							)
         _UpperCAmelCase							=    _UpperCAmelCase							=    self.image_size // (self.downsampling_rates[-1] * 2)
         self.parent.assertEqual(
             result.last_hidden_state.shape       ,				(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)							)


  def  lowerCamelCase       (      self		:			str       ,				lowerCamelCase		:			List[str]       ,				lowerCamelCase		:			Any       ,				lowerCamelCase		:			List[str]							)						->	str:


         """simple docstring"""
         _UpperCAmelCase							=    self.num_labels
         _UpperCAmelCase							=    SegformerForSemanticSegmentation(lowerCamelCase							)
         model.to(lowerCamelCase							)
         model.eval()
         _UpperCAmelCase							=    model(lowerCamelCase							)
         self.parent.assertEqual(
             result.logits.shape       ,				(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)							)
         _UpperCAmelCase							=    model(lowerCamelCase       ,				labels=lowerCamelCase							)
         self.parent.assertEqual(
             result.logits.shape       ,				(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)							)
         self.parent.assertGreater(result.loss       ,				0.0							)


  def  lowerCamelCase       (      self		:			List[Any]       ,				lowerCamelCase		:			str       ,				lowerCamelCase		:			Any       ,				lowerCamelCase		:			List[str]							)						->	Any:


         """simple docstring"""
         _UpperCAmelCase							=    1
         _UpperCAmelCase							=    SegformerForSemanticSegmentation(config=lowerCamelCase							)
         model.to(lowerCamelCase							)
         model.eval()
         _UpperCAmelCase							=    torch.randint(0       ,				1       ,				(self.batch_size, self.image_size, self.image_size)							).to(lowerCamelCase							)
         _UpperCAmelCase							=    model(lowerCamelCase       ,				labels=lowerCamelCase							)
         self.parent.assertGreater(result.loss       ,				0.0							)





  def  lowerCamelCase       (      self		:			str							)						->	Any:


         """simple docstring"""
         _UpperCAmelCase							=    self.prepare_config_and_inputs()
         _UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase							=    config_and_inputs
         _UpperCAmelCase							=    {"""pixel_values""": pixel_values}
         return config, inputs_dict



@require_torch
class 		SCREAMING_SNAKE_CASE__	(  UpperCAmelCase					,      UpperCAmelCase					,      unittest.TestCase     ):

  '''simple docstring'''







  _lowerCamelCase    =  (
      (
          SegformerModel,
          SegformerForSemanticSegmentation,
          SegformerForImageClassification,
      )
      if is_torch_available()
      else ()
  )
  _lowerCamelCase    =  (
      {
          '''feature-extraction''': SegformerModel,
          '''image-classification''': SegformerForImageClassification,
          '''image-segmentation''': SegformerForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  _lowerCamelCase    =  True
  _lowerCamelCase    =  False
  _lowerCamelCase    =  False
  _lowerCamelCase    =  False


  def  lowerCamelCase       (      self		:			Any							)						->	Optional[Any]:


         """simple docstring"""
         _UpperCAmelCase							=    SegformerModelTester(self							)
         _UpperCAmelCase							=    SegformerConfigTester(self       ,				config_class=lowerCamelCase							)


  def  lowerCamelCase       (      self		:			Tuple							)						->	List[Any]:


         """simple docstring"""
         self.config_tester.run_common_tests()


  def  lowerCamelCase       (      self		:			Union[str, Any]							)						->	List[str]:


         """simple docstring"""
         _UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*lowerCamelCase							)


  def  lowerCamelCase       (      self		:			Optional[int]							)						->	int:


         """simple docstring"""
         _UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_binary_image_segmentation(*lowerCamelCase							)


  def  lowerCamelCase       (      self		:			Union[str, Any]							)						->	str:


         """simple docstring"""
         _UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_segmentation(*lowerCamelCase							)


  @unittest.skip("""SegFormer does not use inputs_embeds"""							)
  def  lowerCamelCase       (      self		:			Optional[Any]							)						->	Optional[Any]:


         """simple docstring"""
         pass


  @unittest.skip("""SegFormer does not have get_input_embeddings method and get_output_embeddings methods"""							)
  def  lowerCamelCase       (      self		:			List[str]							)						->	List[Any]:


         """simple docstring"""
         pass


  def  lowerCamelCase       (      self		:			List[str]							)						->	Union[str, Any]:


         """simple docstring"""
         _UpperCAmelCase	,			_UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
                _UpperCAmelCase							=    model_class(lowerCamelCase							)
                _UpperCAmelCase							=    inspect.signature(model.forward							)
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                _UpperCAmelCase							=    [*signature.parameters.keys()]

                _UpperCAmelCase							=    ["""pixel_values"""]
                self.assertListEqual(arg_names[:1]       ,				lowerCamelCase							)


  def  lowerCamelCase       (      self		:			str							)						->	List[str]:


         """simple docstring"""
         _UpperCAmelCase	,			_UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs_for_common()
         _UpperCAmelCase							=    True

         for model_class in self.all_model_classes:
                _UpperCAmelCase							=    True
                _UpperCAmelCase							=    False
                _UpperCAmelCase							=    True
                _UpperCAmelCase							=    model_class(lowerCamelCase							)
                model.to(lowerCamelCase							)
                model.eval()
                with torch.no_grad():
                       _UpperCAmelCase							=    model(**self._prepare_for_class(lowerCamelCase       ,				lowerCamelCase							)							)
                _UpperCAmelCase							=    outputs.attentions

                _UpperCAmelCase							=    sum(self.model_tester.depths							)
                self.assertEqual(len(lowerCamelCase							)       ,				lowerCamelCase							)

                # check that output_attentions also work using config
                del inputs_dict["output_attentions"]
                _UpperCAmelCase							=    True
                _UpperCAmelCase							=    model_class(lowerCamelCase							)
                model.to(lowerCamelCase							)
                model.eval()
                with torch.no_grad():
                       _UpperCAmelCase							=    model(**self._prepare_for_class(lowerCamelCase       ,				lowerCamelCase							)							)
                _UpperCAmelCase							=    outputs.attentions

                self.assertEqual(len(lowerCamelCase							)       ,				lowerCamelCase							)

                # verify the first attentions (first block, first layer)
                _UpperCAmelCase							=    (self.model_tester.image_size // 4) ** 2
                _UpperCAmelCase							=    (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
                self.assertListEqual(
                    list(attentions[0].shape[-3:]							)       ,				[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]       ,				)

                # verify the last attentions (last block, last layer)
                _UpperCAmelCase							=    (self.model_tester.image_size // 32) ** 2
                _UpperCAmelCase							=    (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
                self.assertListEqual(
                    list(attentions[-1].shape[-3:]							)       ,				[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]       ,				)
                _UpperCAmelCase							=    len(lowerCamelCase							)

                # Check attention is always last and order is fine
                _UpperCAmelCase							=    True
                _UpperCAmelCase							=    True
                _UpperCAmelCase							=    model_class(lowerCamelCase							)
                model.to(lowerCamelCase							)
                model.eval()
                with torch.no_grad():
                       _UpperCAmelCase							=    model(**self._prepare_for_class(lowerCamelCase       ,				lowerCamelCase							)							)

                self.assertEqual(out_len + 1       ,				len(lowerCamelCase							)							)

                _UpperCAmelCase							=    outputs.attentions

                self.assertEqual(len(lowerCamelCase							)       ,				lowerCamelCase							)
                # verify the first attentions (first block, first layer)
                _UpperCAmelCase							=    (self.model_tester.image_size // 4) ** 2
                _UpperCAmelCase							=    (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
                self.assertListEqual(
                    list(self_attentions[0].shape[-3:]							)       ,				[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]       ,				)


  def  lowerCamelCase       (      self		:			str							)						->	int:


         """simple docstring"""
         def check_hidden_states_output(lowerCamelCase		:			List[str]       ,				lowerCamelCase		:			str       ,				lowerCamelCase		:			Optional[int]							):
                _UpperCAmelCase							=    model_class(lowerCamelCase							)
                model.to(lowerCamelCase							)
                model.eval()

                with torch.no_grad():
                       _UpperCAmelCase							=    model(**self._prepare_for_class(lowerCamelCase       ,				lowerCamelCase							)							)

                _UpperCAmelCase							=    outputs.hidden_states

                _UpperCAmelCase							=    self.model_tester.num_encoder_blocks
                self.assertEqual(len(lowerCamelCase							)       ,				lowerCamelCase							)

                # verify the first hidden states (first block)
                self.assertListEqual(
                    list(hidden_states[0].shape[-3:]							)       ,				[
                        self.model_tester.hidden_sizes[0],
                        self.model_tester.image_size // 4,
                        self.model_tester.image_size // 4,
                    ]       ,				)

         _UpperCAmelCase	,			_UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
                _UpperCAmelCase							=    True
                check_hidden_states_output(lowerCamelCase       ,				lowerCamelCase       ,				lowerCamelCase							)

                # check that output_hidden_states also work using config
                del inputs_dict["output_hidden_states"]
                _UpperCAmelCase							=    True

                check_hidden_states_output(lowerCamelCase       ,				lowerCamelCase       ,				lowerCamelCase							)


  def  lowerCamelCase       (      self		:			Optional[int]							)						->	str:


         """simple docstring"""
         if not self.model_tester.is_training:
                return

         _UpperCAmelCase	,			_UpperCAmelCase							=    self.model_tester.prepare_config_and_inputs_for_common()
         _UpperCAmelCase							=    True

         for model_class in self.all_model_classes:
                if model_class in get_values(lowerCamelCase							):
                       continue

                _UpperCAmelCase							=    model_class(lowerCamelCase							)
                model.to(lowerCamelCase							)
                model.train()
                _UpperCAmelCase							=    self._prepare_for_class(lowerCamelCase       ,				lowerCamelCase       ,				return_labels=lowerCamelCase							)
                _UpperCAmelCase							=    model(**lowerCamelCase							).loss
                loss.backward()


  @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""							)
  def  lowerCamelCase       (      self		:			Dict							)						->	str:


         """simple docstring"""
         pass





  @slow
  def  lowerCamelCase       (      self		:			List[str]							)						->	List[Any]:


         """simple docstring"""
         for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                _UpperCAmelCase							=    SegformerModel.from_pretrained(lowerCamelCase							)
                self.assertIsNotNone(lowerCamelCase							)




def       _SCREAMING_SNAKE_CASE (							)				->						Optional[int]:
       _UpperCAmelCase							=    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
       return image





@require_torch
class 		SCREAMING_SNAKE_CASE__	(  unittest.TestCase     ):

  '''simple docstring'''







  @slow
  def  lowerCamelCase       (      self		:			Optional[Any]							)						->	Dict:


         """simple docstring"""
         # only resize + normalize
         _UpperCAmelCase							=    SegformerImageProcessor(
             image_scale=(512, 512)       ,				keep_ratio=lowerCamelCase       ,				align=lowerCamelCase       ,				do_random_crop=lowerCamelCase							)
         _UpperCAmelCase							=    SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512"""							).to(
             lowerCamelCase							)

         _UpperCAmelCase							=    prepare_img()
         _UpperCAmelCase							=    image_processor(images=lowerCamelCase       ,				return_tensors="""pt"""							)
         _UpperCAmelCase							=    encoded_inputs.pixel_values.to(lowerCamelCase							)

         with torch.no_grad():
                _UpperCAmelCase							=    model(lowerCamelCase							)

         _UpperCAmelCase							=    torch.Size((1, model.config.num_labels, 128, 128)							)
         self.assertEqual(outputs.logits.shape       ,				lowerCamelCase							)

         _UpperCAmelCase							=    torch.tensor(
             [
                 [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
                 [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
                 [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
             ]							).to(lowerCamelCase							)
         self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]       ,				lowerCamelCase       ,				atol=1E-4							)							)


  @slow
  def  lowerCamelCase       (      self		:			str							)						->	int:


         """simple docstring"""
         # only resize + normalize
         _UpperCAmelCase							=    SegformerImageProcessor(
             image_scale=(512, 512)       ,				keep_ratio=lowerCamelCase       ,				align=lowerCamelCase       ,				do_random_crop=lowerCamelCase							)
         _UpperCAmelCase							=    SegformerForSemanticSegmentation.from_pretrained(
             """nvidia/segformer-b1-finetuned-cityscapes-1024-1024"""							).to(lowerCamelCase							)

         _UpperCAmelCase							=    prepare_img()
         _UpperCAmelCase							=    image_processor(images=lowerCamelCase       ,				return_tensors="""pt"""							)
         _UpperCAmelCase							=    encoded_inputs.pixel_values.to(lowerCamelCase							)

         with torch.no_grad():
                _UpperCAmelCase							=    model(lowerCamelCase							)

         _UpperCAmelCase							=    torch.Size((1, model.config.num_labels, 128, 128)							)
         self.assertEqual(outputs.logits.shape       ,				lowerCamelCase							)

         _UpperCAmelCase							=    torch.tensor(
             [
                 [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
                 [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
                 [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
             ]							).to(lowerCamelCase							)
         self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]       ,				lowerCamelCase       ,				atol=1E-1							)							)





  @slow
  def  lowerCamelCase       (      self		:			int							)						->	Tuple:


         """simple docstring"""
         # only resize + normalize
         _UpperCAmelCase							=    SegformerImageProcessor(
             image_scale=(512, 512)       ,				keep_ratio=lowerCamelCase       ,				align=lowerCamelCase       ,				do_random_crop=lowerCamelCase							)
         _UpperCAmelCase							=    SegformerForSemanticSegmentation.from_pretrained("""nvidia/segformer-b0-finetuned-ade-512-512"""							).to(
             lowerCamelCase							)

         _UpperCAmelCase							=    prepare_img()
         _UpperCAmelCase							=    image_processor(images=lowerCamelCase       ,				return_tensors="""pt"""							)
         _UpperCAmelCase							=    encoded_inputs.pixel_values.to(lowerCamelCase							)

         with torch.no_grad():
                _UpperCAmelCase							=    model(lowerCamelCase							)

         _UpperCAmelCase							=    outputs.logits.detach().cpu()

         _UpperCAmelCase							=    image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase       ,				target_sizes=[(500, 300)]							)
         _UpperCAmelCase							=    torch.Size((500, 300)							)
         self.assertEqual(segmentation[0].shape       ,				lowerCamelCase							)

         _UpperCAmelCase							=    image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase							)
         _UpperCAmelCase							=    torch.Size((128, 128)							)
         self.assertEqual(segmentation[0].shape       ,				lowerCamelCase							)







from __future__ import annotations
class 		SCREAMING_SNAKE_CASE__	:

  '''simple docstring'''







  def __init__(      self		:			Optional[Any]       ,				lowerCamelCase		:			list[list[int]]							)						->	Any:


         """simple docstring"""
         _UpperCAmelCase							=    TypeError(
             """Matrices must be formed from a list of zero or more lists containing at """
             """least one and the same number of values, each of which must be of type """
             """int or float."""							)
         if len(lowerCamelCase							) != 0:
                _UpperCAmelCase							=    len(rows[0]							)
                if cols == 0:
                       raise error
                for row in rows:
                       if len(lowerCamelCase							) != cols:
                              raise error
                       for value in row:
                              if not isinstance(lowerCamelCase       ,				(int, float)							):
                                     raise error
                _UpperCAmelCase							=    rows
         else:
                _UpperCAmelCase							=    []


  def  lowerCamelCase       (      self		:			Optional[Any]							)						->	list[list[int]]:


         """simple docstring"""
         return [[row[i] for row in self.rows] for i in range(len(self.rows[0]							)							)]


  @property
  def  lowerCamelCase       (      self		:			int							)						->	int:


         """simple docstring"""
         return len(self.rows							)


  @property
  def  lowerCamelCase       (      self		:			int							)						->	int:


         """simple docstring"""
         return len(self.rows[0]							)


  @property
  def  lowerCamelCase       (      self		:			Tuple							)						->	tuple[int, int]:


         """simple docstring"""
         return (self.num_rows, self.num_columns)


  @property
  def  lowerCamelCase       (      self		:			Tuple							)						->	bool:


         """simple docstring"""
         return self.order[0] == self.order[1]


  def  lowerCamelCase       (      self		:			Optional[int]							)						->	Matrix:


         """simple docstring"""
         _UpperCAmelCase							=    [
             [0 if column_num != row_num else 1 for column_num in range(self.num_rows							)]
             for row_num in range(self.num_rows							)
         ]
         return Matrix(lowerCamelCase							)


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


         """simple docstring"""
         if not self.is_square:
                return 0
         if self.order == (0, 0):
                return 1
         if self.order == (1, 1):
                return int(self.rows[0][0]							)
         if self.order == (2, 2):
                return int(
                    (self.rows[0][0] * self.rows[1][1])
                    - (self.rows[0][1] * self.rows[1][0])							)
         else:
                return sum(
                    self.rows[0][column] * self.cofactors().rows[0][column]
                    for column in range(self.num_columns							)							)


  def  lowerCamelCase       (      self		:			Optional[Any]							)						->	bool:


         """simple docstring"""
         return bool(self.determinant()							)


  def  lowerCamelCase       (      self		:			Tuple       ,				lowerCamelCase		:			int       ,				lowerCamelCase		:			int							)						->	int:


         """simple docstring"""
         _UpperCAmelCase							=    [
             [
                 self.rows[other_row][other_column]
                 for other_column in range(self.num_columns							)
                 if other_column != column
             ]
             for other_row in range(self.num_rows							)
             if other_row != row
         ]
         return Matrix(lowerCamelCase							).determinant()


  def  lowerCamelCase       (      self		:			int       ,				lowerCamelCase		:			int       ,				lowerCamelCase		:			int							)						->	int:


         """simple docstring"""
         if (row + column) % 2 == 0:
                return self.get_minor(lowerCamelCase       ,				lowerCamelCase							)
         return -1 * self.get_minor(lowerCamelCase       ,				lowerCamelCase							)


  def  lowerCamelCase       (      self		:			str							)						->	Matrix:


         """simple docstring"""
         return Matrix(
             [
                 [self.get_minor(lowerCamelCase       ,				lowerCamelCase							) for column in range(self.num_columns							)]
                 for row in range(self.num_rows							)
             ]							)


  def  lowerCamelCase       (      self		:			Dict							)						->	Matrix:


         """simple docstring"""
         return Matrix(
             [
                 [
                     self.minors().rows[row][column]
                     if (row + column) % 2 == 0
                     else self.minors().rows[row][column] * -1
                     for column in range(self.minors().num_columns							)
                 ]
                 for row in range(self.minors().num_rows							)
             ]							)


  def  lowerCamelCase       (      self		:			Optional[Any]							)						->	Matrix:


         """simple docstring"""
         _UpperCAmelCase							=    [
             [self.cofactors().rows[column][row] for column in range(self.num_columns							)]
             for row in range(self.num_rows							)
         ]
         return Matrix(lowerCamelCase							)


  def  lowerCamelCase       (      self		:			Any							)						->	Matrix:


         """simple docstring"""
         _UpperCAmelCase							=    self.determinant()
         if not determinant:
                raise TypeError("""Only matrices with a non-zero determinant have an inverse"""							)
         return self.adjugate() * (1 / determinant)


  def __repr__(      self		:			List[str]							)						->	str:


         """simple docstring"""
         return str(self.rows							)


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


         """simple docstring"""
         if self.num_rows == 0:
                return "[]"
         if self.num_rows == 1:
                return "[[" + ". ".join(str(self.rows[0]							)							) + "]]"
         return (
             "["
             + "\n ".join(
                 [
                     """[""" + """. """.join([str(lowerCamelCase							) for value in row]							) + """.]"""
                     for row in self.rows
                 ]							)
             + "]"
         )


  def  lowerCamelCase       (      self		:			Tuple       ,				lowerCamelCase		:			list[int]       ,				lowerCamelCase		:			int | None = None							)						->	None:


         """simple docstring"""
         _UpperCAmelCase							=    TypeError("""Row must be a list containing all ints and/or floats"""							)
         if not isinstance(lowerCamelCase       ,				lowerCamelCase							):
                raise type_error
         for value in row:
                if not isinstance(lowerCamelCase       ,				(int, float)							):
                       raise type_error
         if len(lowerCamelCase							) != self.num_columns:
                raise ValueError(
                    """Row must be equal in length to the other rows in the matrix"""							)
         if position is None:
                self.rows.append(lowerCamelCase							)
         else:
                _UpperCAmelCase							=    self.rows[0:position] + [row] + self.rows[position:]


  def  lowerCamelCase       (      self		:			List[Any]       ,				lowerCamelCase		:			list[int]       ,				lowerCamelCase		:			int | None = None							)						->	None:


         """simple docstring"""
         _UpperCAmelCase							=    TypeError(
             """Column must be a list containing all ints and/or floats"""							)
         if not isinstance(lowerCamelCase       ,				lowerCamelCase							):
                raise type_error
         for value in column:
                if not isinstance(lowerCamelCase       ,				(int, float)							):
                       raise type_error
         if len(lowerCamelCase							) != self.num_rows:
                raise ValueError(
                    """Column must be equal in length to the other columns in the matrix"""							)
         if position is None:
                _UpperCAmelCase							=    [self.rows[i] + [column[i]] for i in range(self.num_rows							)]
         else:
                _UpperCAmelCase							=    [
                    self.rows[i][0:position] + [column[i]] + self.rows[i][position:]
                    for i in range(self.num_rows							)
                ]


  def __eq__(      self		:			Dict       ,				lowerCamelCase		:			object							)						->	bool:


         """simple docstring"""
         if not isinstance(lowerCamelCase       ,				lowerCamelCase							):
                return NotImplemented
         return self.rows == other.rows


  def __ne__(      self		:			List[str]       ,				lowerCamelCase		:			object							)						->	bool:


         """simple docstring"""
         return not self == other


  def __neg__(      self		:			Union[str, Any]							)						->	Matrix:


         """simple docstring"""
         return self * -1


  def __add__(      self		:			Any       ,				lowerCamelCase		:			Matrix							)						->	Matrix:


         """simple docstring"""
         if self.order != other.order:
                raise ValueError("""Addition requires matrices of the same order"""							)
         return Matrix(
             [
                 [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns							)]
                 for i in range(self.num_rows							)
             ]							)


  def __sub__(      self		:			Optional[Any]       ,				lowerCamelCase		:			Matrix							)						->	Matrix:


         """simple docstring"""
         if self.order != other.order:
                raise ValueError("""Subtraction requires matrices of the same order"""							)
         return Matrix(
             [
                 [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns							)]
                 for i in range(self.num_rows							)
             ]							)


  def __mul__(      self		:			List[Any]       ,				lowerCamelCase		:			Matrix | int | float							)						->	Matrix:


         """simple docstring"""
         if isinstance(lowerCamelCase       ,				(int, float)							):
                return Matrix(
                    [[int(element * other							) for element in row] for row in self.rows]							)
         elif isinstance(lowerCamelCase       ,				lowerCamelCase							):
                if self.num_columns != other.num_rows:
                       raise ValueError(
                           """The number of columns in the first matrix must """
                           """be equal to the number of rows in the second"""							)
                return Matrix(
                    [
                        [Matrix.dot_product(lowerCamelCase       ,				lowerCamelCase							) for column in other.columns()]
                        for row in self.rows
                    ]							)
         else:
                raise TypeError(
                    """A Matrix can only be multiplied by an int, float, or another matrix"""							)


  def __pow__(      self		:			Any       ,				lowerCamelCase		:			int							)						->	Matrix:


         """simple docstring"""
         if not isinstance(lowerCamelCase       ,				lowerCamelCase							):
                raise TypeError("""A Matrix can only be raised to the power of an int"""							)
         if not self.is_square:
                raise ValueError("""Only square matrices can be raised to a power"""							)
         if other == 0:
                return self.identity()
         if other < 0:
                if self.is_invertable():
                       return self.inverse() ** (-other)
                raise ValueError(
                    """Only invertable matrices can be raised to a negative power"""							)
         _UpperCAmelCase							=    self
         for _ in range(other - 1							):
                result *= self
         return result





  @classmethod
  def  lowerCamelCase       (      cls		:			Tuple       ,				lowerCamelCase		:			list[int]       ,				lowerCamelCase		:			list[int]							)						->	int:


         """simple docstring"""
         return sum(row[i] * column[i] for i in range(len(lowerCamelCase							)							)							)


if __name__ == "__main__":
  import doctest

  doctest.testmod()