






import collections
import inspect
import unittest

from transformers import FocalNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
       import torch
       from torch import nn

       from transformers import (
           FocalNetBackbone,
           FocalNetForImageClassification,
           FocalNetForMaskedImageModeling,
           FocalNetModel,
       )
       from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor







class 		_A						:

  def __init__(    self						:	str   ,				lowerCamelCase__						:	Dict   ,				lowerCamelCase__						:	Union[str, Any]=13   ,				lowerCamelCase__						:	Tuple=32   ,				lowerCamelCase__						:	int=2   ,				lowerCamelCase__						:	Optional[int]=3   ,				lowerCamelCase__						:	Tuple=16   ,				lowerCamelCase__						:	Any=[32, 64, 1_28]   ,				lowerCamelCase__						:	List[Any]=[1, 2, 1]   ,				lowerCamelCase__						:	int=[2, 2, 4]   ,				lowerCamelCase__						:	List[Any]=2   ,				lowerCamelCase__						:	Optional[Any]=2.0   ,				lowerCamelCase__						:	List[Any]=True   ,				lowerCamelCase__						:	List[str]=0.0   ,				lowerCamelCase__						:	Dict=0.0   ,				lowerCamelCase__						:	Union[str, Any]=0.1   ,				lowerCamelCase__						:	List[Any]="gelu"   ,				lowerCamelCase__						:	Optional[Any]=False   ,				lowerCamelCase__						:	Optional[Any]=True   ,				lowerCamelCase__						:	Optional[int]=0.02   ,				lowerCamelCase__						:	List[Any]=1e-5   ,				lowerCamelCase__						:	int=True   ,				lowerCamelCase__						:	List[Any]=None   ,				lowerCamelCase__						:	Tuple=True   ,				lowerCamelCase__						:	Tuple=10   ,				lowerCamelCase__						:	Tuple=8   ,				lowerCamelCase__						:	Union[str, Any]=["stage1", "stage2"]   ,				lowerCamelCase__						:	List[str]=[1, 2]   ,				):
     """simple docstring"""

     __UpperCamelCase	:			List[str]					=					parent
     __UpperCamelCase	:			Optional[int]					=					batch_size
     __UpperCamelCase	:			Dict					=					image_size
     __UpperCamelCase	:			Union[str, Any]					=					patch_size
     __UpperCamelCase	:			Any					=					num_channels
     __UpperCamelCase	:			List[Any]					=					embed_dim
     __UpperCamelCase	:			str					=					hidden_sizes
     __UpperCamelCase	:			Any					=					depths
     __UpperCamelCase	:			str					=					num_heads
     __UpperCamelCase	:			Tuple					=					window_size
     __UpperCamelCase	:			Tuple					=					mlp_ratio
     __UpperCamelCase	:			Any					=					qkv_bias
     __UpperCamelCase	:			Any					=					hidden_dropout_prob
     __UpperCamelCase	:			List[str]					=					attention_probs_dropout_prob
     __UpperCamelCase	:			str					=					drop_path_rate
     __UpperCamelCase	:			Optional[Any]					=					hidden_act
     __UpperCamelCase	:			List[str]					=					use_absolute_embeddings
     __UpperCamelCase	:			Union[str, Any]					=					patch_norm
     __UpperCamelCase	:			Optional[int]					=					layer_norm_eps
     __UpperCamelCase	:			Union[str, Any]					=					initializer_range
     __UpperCamelCase	:			List[Any]					=					is_training
     __UpperCamelCase	:			Any					=					scope
     __UpperCamelCase	:			int					=					use_labels
     __UpperCamelCase	:			Optional[Any]					=					type_sequence_label_size
     __UpperCamelCase	:			Optional[Any]					=					encoder_stride
     __UpperCamelCase	:			int					=					out_features
     __UpperCamelCase	:			int					=					out_indices

  def    a					(    self						:	List[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Dict					=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

     __UpperCamelCase	:			str					=					None
     if self.use_labels:
        __UpperCamelCase	:			Any					=					ids_tensor([self.batch_size]   ,				self.type_sequence_label_size			)

     __UpperCamelCase	:			int					=					self.get_config()

     return config, pixel_values, labels

  def    a					(    self						:	Any			):
     """simple docstring"""

     return FocalNetConfig(
         image_size=self.image_size   ,				patch_size=self.patch_size   ,				num_channels=self.num_channels   ,				embed_dim=self.embed_dim   ,				hidden_sizes=self.hidden_sizes   ,				depths=self.depths   ,				num_heads=self.num_heads   ,				window_size=self.window_size   ,				mlp_ratio=self.mlp_ratio   ,				qkv_bias=self.qkv_bias   ,				hidden_dropout_prob=self.hidden_dropout_prob   ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,				drop_path_rate=self.drop_path_rate   ,				hidden_act=self.hidden_act   ,				use_absolute_embeddings=self.use_absolute_embeddings   ,				path_norm=self.patch_norm   ,				layer_norm_eps=self.layer_norm_eps   ,				initializer_range=self.initializer_range   ,				encoder_stride=self.encoder_stride   ,				out_features=self.out_features   ,				out_indices=self.out_indices   ,				)

  def    a					(    self						:	Optional[Any]   ,				lowerCamelCase__						:	List[str]   ,				lowerCamelCase__						:	Any   ,				lowerCamelCase__						:	List[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			int					=					FocalNetModel(config=lowerCamelCase__			)
     model.to(lowerCamelCase__			)
     model.eval()
     __UpperCamelCase	:			Optional[Any]					=					model(lowerCamelCase__			)

     __UpperCamelCase	:			Optional[int]					=					((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
     __UpperCamelCase	:			Dict					=					int(config.embed_dim * 2 ** (len(config.depths			) - 1)			)

     self.parent.assertEqual(result.last_hidden_state.shape   ,				(self.batch_size, expected_seq_len, expected_dim)			)

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	Optional[Any]   ,				lowerCamelCase__						:	Dict   ,				lowerCamelCase__						:	Any			):
     """simple docstring"""

     __UpperCamelCase	:			int					=					FocalNetBackbone(config=lowerCamelCase__			)
     model.to(lowerCamelCase__			)
     model.eval()
     __UpperCamelCase	:			List[str]					=					model(lowerCamelCase__			)

     # verify feature maps
     self.parent.assertEqual(len(result.feature_maps			)   ,				len(config.out_features			)			)
     self.parent.assertListEqual(list(result.feature_maps[0].shape			)   ,				[self.batch_size, self.image_size, 8, 8]			)

     # verify channels
     self.parent.assertEqual(len(model.channels			)   ,				len(config.out_features			)			)
     self.parent.assertListEqual(model.channels   ,				config.hidden_sizes[:-1]			)

     # verify backbone works with out_features=None
     __UpperCamelCase	:			List[str]					=					None
     __UpperCamelCase	:			str					=					FocalNetBackbone(config=lowerCamelCase__			)
     model.to(lowerCamelCase__			)
     model.eval()
     __UpperCamelCase	:			Optional[Any]					=					model(lowerCamelCase__			)

     # verify feature maps
     self.parent.assertEqual(len(result.feature_maps			)   ,				1			)
     self.parent.assertListEqual(list(result.feature_maps[0].shape			)   ,				[self.batch_size, self.image_size * 2, 4, 4]			)

     # verify channels
     self.parent.assertEqual(len(model.channels			)   ,				1			)
     self.parent.assertListEqual(model.channels   ,				[config.hidden_sizes[-1]]			)

  def    a					(    self						:	Tuple   ,				lowerCamelCase__						:	Union[str, Any]   ,				lowerCamelCase__						:	Tuple   ,				lowerCamelCase__						:	Optional[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			int					=					FocalNetForMaskedImageModeling(config=lowerCamelCase__			)
     model.to(lowerCamelCase__			)
     model.eval()
     __UpperCamelCase	:			Tuple					=					model(lowerCamelCase__			)
     self.parent.assertEqual(
         result.reconstruction.shape   ,				(self.batch_size, self.num_channels, self.image_size, self.image_size)			)

     # test greyscale images
     __UpperCamelCase	:			Optional[int]					=					1
     __UpperCamelCase	:			List[str]					=					FocalNetForMaskedImageModeling(lowerCamelCase__			)
     model.to(lowerCamelCase__			)
     model.eval()

     __UpperCamelCase	:			Optional[Any]					=					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
     __UpperCamelCase	:			Tuple					=					model(lowerCamelCase__			)
     self.parent.assertEqual(result.reconstruction.shape   ,				(self.batch_size, 1, self.image_size, self.image_size)			)

  def    a					(    self						:	Optional[Any]   ,				lowerCamelCase__						:	List[Any]   ,				lowerCamelCase__						:	str   ,				lowerCamelCase__						:	Any			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					self.type_sequence_label_size
     __UpperCamelCase	:			Union[str, Any]					=					FocalNetForImageClassification(lowerCamelCase__			)
     model.to(lowerCamelCase__			)
     model.eval()
     __UpperCamelCase	:			Tuple					=					model(lowerCamelCase__   ,				labels=lowerCamelCase__			)
     self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.type_sequence_label_size)			)

     # test greyscale images
     __UpperCamelCase	:			List[str]					=					1
     __UpperCamelCase	:			Optional[Any]					=					FocalNetForImageClassification(lowerCamelCase__			)
     model.to(lowerCamelCase__			)
     model.eval()

     __UpperCamelCase	:			Union[str, Any]					=					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
     __UpperCamelCase	:			Dict					=					model(lowerCamelCase__			)
     self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.type_sequence_label_size)			)

  def    a					(    self						:	int			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[Any]					=					self.prepare_config_and_inputs()

     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	:			Optional[int]					=					config_and_inputs
     __UpperCamelCase	:			Optional[int]					=					{"""pixel_values""": pixel_values}
     return config, inputs_dict







@require_torch
class 		_A						( UpperCAmelCase_	,				UpperCAmelCase_	,				unittest.TestCase ):
  lowercase_						:			str						=					(
      (
          FocalNetModel,
          FocalNetForImageClassification,
          FocalNetForMaskedImageModeling,
          FocalNetBackbone,
      )
      if is_torch_available()
      else ()
  )
  lowercase_						:			Optional[Any]						=					(
      {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
      if is_torch_available()
      else {}
  )
  lowercase_						:			List[Any]						=					False

  lowercase_						:			str						=					False
  lowercase_						:			Any						=					False
  lowercase_						:			Any						=					False
  lowercase_						:			Union[str, Any]						=					False

  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			List[str]					=					FocalNetModelTester(self			)
     __UpperCamelCase	:			Any					=					ConfigTester(self   ,				config_class=lowerCamelCase__   ,				embed_dim=37   ,				has_text_modality=lowerCamelCase__			)

  def    a					(    self						:	List[str]			):
     """simple docstring"""

     self.create_and_test_config_common_properties()
     self.config_tester.create_and_test_config_to_json_string()
     self.config_tester.create_and_test_config_to_json_file()
     self.config_tester.create_and_test_config_from_and_save_pretrained()
     self.config_tester.create_and_test_config_with_num_labels()
     self.config_tester.check_config_can_be_init_without_params()
     self.config_tester.check_config_arguments_init()

  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

     return

  def    a					(    self						:	Dict			):
     """simple docstring"""

     __UpperCamelCase	:			Union[str, Any]					=					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCamelCase__			)

  def    a					(    self						:	Dict			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[int]					=					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*lowerCamelCase__			)

  def    a					(    self						:	Union[str, Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[int]					=					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase__			)

  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Tuple					=					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__			)

  @unittest.skip(reason="""FocalNet does not use inputs_embeds"""			)
  def    a					(    self						:	Dict			):
     """simple docstring"""

     pass

  @unittest.skip(reason="""FocalNet does not use feedforward chunking"""			)
  def    a					(    self						:	Optional[Any]			):
     """simple docstring"""

     pass

  def    a					(    self						:	List[Any]			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			Tuple					=					self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes[:-1]:
        __UpperCamelCase	:			int					=					model_class(lowerCamelCase__			)
        self.assertIsInstance(model.get_input_embeddings()   ,				(nn.Module)			)
        __UpperCamelCase	:			Dict					=					model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(lowerCamelCase__   ,				nn.Linear			)			)

  def    a					(    self						:	int			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			Dict					=					self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes[:-1]:
        __UpperCamelCase	:			Any					=					model_class(lowerCamelCase__			)
        __UpperCamelCase	:			Any					=					inspect.signature(model.forward			)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        __UpperCamelCase	:			Tuple					=					[*signature.parameters.keys()]

        __UpperCamelCase	:			List[Any]					=					["""pixel_values"""]
        self.assertListEqual(arg_names[:1]   ,				lowerCamelCase__			)

  def    a					(    self						:	Optional[int]   ,				lowerCamelCase__						:	Optional[Any]   ,				lowerCamelCase__						:	Optional[int]   ,				lowerCamelCase__						:	List[Any]   ,				lowerCamelCase__						:	str			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[Any]					=					model_class(lowerCamelCase__			)
     model.to(lowerCamelCase__			)
     model.eval()

     with torch.no_grad():
        __UpperCamelCase	:			Optional[Any]					=					model(**self._prepare_for_class(lowerCamelCase__   ,				lowerCamelCase__			)			)

     __UpperCamelCase	:			List[str]					=					outputs.hidden_states

     __UpperCamelCase	:			Optional[Any]					=					getattr(
         self.model_tester   ,				"""expected_num_hidden_layers"""   ,				len(self.model_tester.depths			) + 1			)
     self.assertEqual(len(lowerCamelCase__			)   ,				lowerCamelCase__			)

     # FocalNet has a different seq_length
     __UpperCamelCase	:			List[str]					=					(
         config.patch_size
         if isinstance(config.patch_size   ,				collections.abc.Iterable			)
         else (config.patch_size, config.patch_size)
     )

     __UpperCamelCase	:			Tuple					=					(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

     self.assertListEqual(
         list(hidden_states[0].shape[-2:]			)   ,				[num_patches, self.model_tester.embed_dim]   ,				)

     __UpperCamelCase	:			List[str]					=					outputs.reshaped_hidden_states
     self.assertEqual(len(lowerCamelCase__			)   ,				lowerCamelCase__			)

     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	:			Tuple					=					reshaped_hidden_states[0].shape
     __UpperCamelCase	:			Union[str, Any]					=					(
         reshaped_hidden_states[0].view(lowerCamelCase__   ,				lowerCamelCase__   ,				height * width			).permute(0   ,				2   ,				1			)
     )
     self.assertListEqual(
         list(reshaped_hidden_states.shape[-2:]			)   ,				[num_patches, self.model_tester.embed_dim]   ,				)

  def    a					(    self						:	List[str]			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			Union[str, Any]					=					self.model_tester.prepare_config_and_inputs_for_common()

     __UpperCamelCase	:			Union[str, Any]					=					(
         self.model_tester.image_size
         if isinstance(self.model_tester.image_size   ,				collections.abc.Iterable			)
         else (self.model_tester.image_size, self.model_tester.image_size)
     )

     for model_class in self.all_model_classes[:-1]:
        __UpperCamelCase	:			str					=					True
        self.check_hidden_states_output(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__			)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __UpperCamelCase	:			Union[str, Any]					=					True

        self.check_hidden_states_output(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__			)

  def    a					(    self						:	List[str]			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			Dict					=					self.model_tester.prepare_config_and_inputs_for_common()
     __UpperCamelCase	:			str					=					3

     __UpperCamelCase	:			Union[str, Any]					=					(
         self.model_tester.image_size
         if isinstance(self.model_tester.image_size   ,				collections.abc.Iterable			)
         else (self.model_tester.image_size, self.model_tester.image_size)
     )
     __UpperCamelCase	:			Tuple					=					(
         config.patch_size
         if isinstance(config.patch_size   ,				collections.abc.Iterable			)
         else (config.patch_size, config.patch_size)
     )

     __UpperCamelCase	:			Optional[Any]					=					image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
     __UpperCamelCase	:			str					=					image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

     for model_class in self.all_model_classes[:-1]:
        __UpperCamelCase	:			Union[str, Any]					=					True
        self.check_hidden_states_output(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__   ,				(padded_height, padded_width)			)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        __UpperCamelCase	:			List[str]					=					True
        self.check_hidden_states_output(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__   ,				(padded_height, padded_width)			)

  @slow
  def    a					(    self						:	Tuple			):
     """simple docstring"""

     for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __UpperCamelCase	:			Union[str, Any]					=					FocalNetModel.from_pretrained(lowerCamelCase__			)
        self.assertIsNotNone(lowerCamelCase__			)

  def    a					(    self						:	Optional[int]			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			Optional[Any]					=					self.model_tester.prepare_config_and_inputs_for_common()

     __UpperCamelCase	:			str					=					_config_zero_init(lowerCamelCase__			)
     for model_class in self.all_model_classes:
        __UpperCamelCase	:			int					=					model_class(config=lowerCamelCase__			)
        for name, param in model.named_parameters():
           if "embeddings" not in name and param.requires_grad:
              self.assertIn(
                  ((param.data.mean() * 1e9).round() / 1e9).item()   ,				[0.0, 1.0]   ,				msg=f'Parameter {name} of model {model_class} seems not properly initialized'   ,				)







@require_vision
@require_torch
class 		_A						( unittest.TestCase ):

  @cached_property
  def    a					(    self						:	List[Any]			):
     """simple docstring"""

     return AutoImageProcessor.from_pretrained("""microsoft/focalnet-tiny"""			) if is_vision_available() else None

  @slow
  def    a					(    self						:	List[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Optional[int]					=					FocalNetForImageClassification.from_pretrained("""microsoft/focalnet-tiny"""			).to(lowerCamelCase__			)
     __UpperCamelCase	:			str					=					self.default_image_processor

     __UpperCamelCase	:			Tuple					=					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
     __UpperCamelCase	:			List[str]					=					image_processor(images=lowerCamelCase__   ,				return_tensors="""pt"""			).to(lowerCamelCase__			)

     # forward pass
     with torch.no_grad():
        __UpperCamelCase	:			Optional[Any]					=					model(**lowerCamelCase__			)

     # verify the logits
     __UpperCamelCase	:			Tuple					=					torch.Size((1, 10_00)			)
     self.assertEqual(outputs.logits.shape   ,				lowerCamelCase__			)
     __UpperCamelCase	:			Optional[Any]					=					torch.tensor([0.2166, -0.4368, 0.2191]			).to(lowerCamelCase__			)
     self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,				lowerCamelCase__   ,				atol=1e-4			)			)
     self.assertTrue(outputs.logits.argmax(dim=-1			).item()   ,				2_81			)







@require_torch
class 		_A						( UpperCAmelCase_	,				unittest.TestCase ):
  lowercase_						:			List[str]						=					(FocalNetBackbone,) if is_torch_available() else ()
  lowercase_						:			str						=					FocalNetConfig

  lowercase_						:			Tuple						=					False

  def    a					(    self						:	Tuple			):
     """simple docstring"""

     __UpperCamelCase	:			List[Any]					=					FocalNetModelTester(self			)











from __future__ import annotations

from typing import Any







class 		_A						:

  def __init__(    self						:	List[Any]   ,				lowerCamelCase__						:	int   ,				lowerCamelCase__						:	int   ,				lowerCamelCase__						:	float = 0			):
     """simple docstring"""

     __UpperCamelCase	,     __UpperCamelCase	:			Tuple					=					row, column
     __UpperCamelCase	:			Tuple					=					[[default_value for c in range(lowerCamelCase__			)] for r in range(lowerCamelCase__			)]

  def __str__(    self						:	List[Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Dict					=					f'Matrix consist of {self.row} rows and {self.column} columns\n'

     # Make string identifier
     __UpperCamelCase	:			Optional[int]					=					0
     for row_vector in self.array:
        for obj in row_vector:
           __UpperCamelCase	:			int					=					max(lowerCamelCase__   ,				len(str(lowerCamelCase__			)			)			)
     __UpperCamelCase	:			Union[str, Any]					=					f'%{max_element_length}s'

     # Make string and return
     def single_line(lowerCamelCase__						:	list[float]			) -> str:
        nonlocal string_format_identifier
        __UpperCamelCase	:			List[Any]					=					"""["""
        line += ", ".join(string_format_identifier % (obj,) for obj in row_vector			)
        line += "]"
        return line

     s += "\n".join(single_line(lowerCamelCase__			) for row_vector in self.array			)
     return s

  def __repr__(    self						:	Any			):
     """simple docstring"""

     return str(self			)

  def    a					(    self						:	str   ,				lowerCamelCase__						:	tuple[int, int]			):
     """simple docstring"""

     if not (isinstance(lowerCamelCase__   ,				(list, tuple)			) and len(lowerCamelCase__			) == 2):
        return False
     elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
        return False
     else:
        return True

  def __getitem__(    self						:	Union[str, Any]   ,				lowerCamelCase__						:	tuple[int, int]			):
     """simple docstring"""

     assert self.validate_indicies(lowerCamelCase__			)
     return self.array[loc[0]][loc[1]]

  def __setitem__(    self						:	Union[str, Any]   ,				lowerCamelCase__						:	tuple[int, int]   ,				lowerCamelCase__						:	float			):
     """simple docstring"""

     assert self.validate_indicies(lowerCamelCase__			)
     __UpperCamelCase	:			str					=					value

  def __add__(    self						:	int   ,				lowerCamelCase__						:	Matrix			):
     """simple docstring"""

     assert isinstance(lowerCamelCase__   ,				lowerCamelCase__			)
     assert self.row == another.row and self.column == another.column

     # Add
     __UpperCamelCase	:			Tuple					=					Matrix(self.row   ,				self.column			)
     for r in range(self.row			):
        for c in range(self.column			):
           __UpperCamelCase	:			Optional[int]					=					self[r, c] + another[r, c]
     return result

  def __neg__(    self						:	Optional[int]			):
     """simple docstring"""

     __UpperCamelCase	:			str					=					Matrix(self.row   ,				self.column			)
     for r in range(self.row			):
        for c in range(self.column			):
           __UpperCamelCase	:			Any					=					-self[r, c]
     return result

  def __sub__(    self						:	Tuple   ,				lowerCamelCase__						:	Matrix			):
     """simple docstring"""

     return self + (-another)

  def __mul__(    self						:	Tuple   ,				lowerCamelCase__						:	int | float | Matrix			):
     """simple docstring"""

     if isinstance(lowerCamelCase__   ,				(int, float)			):  # Scalar multiplication
        __UpperCamelCase	:			List[str]					=					Matrix(self.row   ,				self.column			)
        for r in range(self.row			):
           for c in range(self.column			):
              __UpperCamelCase	:			Tuple					=					self[r, c] * another
        return result
     elif isinstance(lowerCamelCase__   ,				lowerCamelCase__			):  # Matrix multiplication
        assert self.column == another.row
        __UpperCamelCase	:			List[Any]					=					Matrix(self.row   ,				another.column			)
        for r in range(self.row			):
           for c in range(another.column			):
              for i in range(self.column			):
                 result[r, c] += self[r, i] * another[i, c]
        return result
     else:
        __UpperCamelCase	:			Any					=					f'Unsupported type given for another ({type(lowerCamelCase__			)})'
        raise TypeError(lowerCamelCase__			)

  def    a					(    self						:	Union[str, Any]			):
     """simple docstring"""

     __UpperCamelCase	:			Dict					=					Matrix(self.column   ,				self.row			)
     for r in range(self.row			):
        for c in range(self.column			):
           __UpperCamelCase	:			str					=					self[r, c]
     return result

  def    a					(    self						:	Any   ,				lowerCamelCase__						:	Matrix   ,				lowerCamelCase__						:	Matrix			):
     """simple docstring"""

     assert isinstance(lowerCamelCase__   ,				lowerCamelCase__			) and isinstance(lowerCamelCase__   ,				lowerCamelCase__			)
     assert self.row == self.column == u.row == v.row  # u, v should be column vector
     assert u.column == v.column == 1  # u, v should be column vector

     # Calculate
     __UpperCamelCase	:			Optional[int]					=					v.transpose()
     __UpperCamelCase	:			Tuple					=					(v_t * self * u)[0, 0] + 1
     if numerator_factor == 0:
        return None  # It's not invertable
     return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))


# Testing
if __name__ == "__main__":


       def 				__lowerCamelCase     (							)     ->  None:
          # a^(-1)
          __UpperCamelCase	:			str					=					Matrix(3					,							3					,							0							)
          for i in range(3							):
             __UpperCamelCase	:			List[str]					=					1
          print(f'a^(-1) is {ainv}'							)
          # u, v
          __UpperCamelCase	:			Any					=					Matrix(3					,							1					,							0							)
          __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	:			Any					=					1, 2, -3
          __UpperCamelCase	:			int					=					Matrix(3					,							1					,							0							)
          __UpperCamelCase	,     __UpperCamelCase	,     __UpperCamelCase	:			Dict					=					4, -2, 5
          print(f'u is {u}'							)
          print(f'v is {v}'							)
          print(f'uv^T is {u * v.transpose()}'							)
          # Sherman Morrison
          print(f'(a + uv^T)^(-1) is {ainv.sherman_morrison(__lowerCAmelCase					,							__lowerCAmelCase							)}'							)


       def 				__lowerCamelCase     (							)     ->  None:
          import doctest

          doctest.testmod()



       testa()



