





"""simple docstring"""






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 					__lowercase      :







					'''simple docstring'''




					def __init__(    self						,      _UpperCAmelCase						,      _UpperCAmelCase=13						,      _UpperCAmelCase=32						,      _UpperCAmelCase=2						,      _UpperCAmelCase=3						,      _UpperCAmelCase=16						,      _UpperCAmelCase=[32, 64, 128]						,      _UpperCAmelCase=[1, 2, 1]						,      _UpperCAmelCase=[2, 2, 4]						,      _UpperCAmelCase=2						,      _UpperCAmelCase=2.0						,      _UpperCAmelCase=True						,      _UpperCAmelCase=0.0						,      _UpperCAmelCase=0.0						,      _UpperCAmelCase=0.1						,      _UpperCAmelCase="gelu"						,      _UpperCAmelCase=False						,      _UpperCAmelCase=True						,      _UpperCAmelCase=0.0_2						,      _UpperCAmelCase=1e-5						,      _UpperCAmelCase=True						,      _UpperCAmelCase=None						,      _UpperCAmelCase=True						,      _UpperCAmelCase=10						,      _UpperCAmelCase=8						,      _UpperCAmelCase=["stage1", "stage2"]						,      _UpperCAmelCase=[1, 2]						,      ):
									__a			:    List[str]      							=	parent
									__a			:    Optional[int]      							=	batch_size
									__a			:    Dict      							=	image_size
									__a			:    Union[str, Any]      							=	patch_size
									__a			:    Any      							=	num_channels
									__a			:    List[Any]      							=	embed_dim
									__a			:    str      							=	hidden_sizes
									__a			:    Any      							=	depths
									__a			:    str      							=	num_heads
									__a			:    Tuple      							=	window_size
									__a			:    Tuple      							=	mlp_ratio
									__a			:    Any      							=	qkv_bias
									__a			:    Any      							=	hidden_dropout_prob
									__a			:    List[str]      							=	attention_probs_dropout_prob
									__a			:    str      							=	drop_path_rate
									__a			:    Optional[Any]      							=	hidden_act
									__a			:    List[str]      							=	use_absolute_embeddings
									__a			:    Union[str, Any]      							=	patch_norm
									__a			:    Optional[int]      							=	layer_norm_eps
									__a			:    Union[str, Any]      							=	initializer_range
									__a			:    List[Any]      							=	is_training
									__a			:    Any      							=	scope
									__a			:    int      							=	use_labels
									__a			:    Optional[Any]      							=	type_sequence_label_size
									__a			:    Optional[Any]      							=	encoder_stride
									__a			:    int      							=	out_features
									__a			:    int      							=	out_indices







					def 			_lowerCamelCase		(    self  ):
									__a			:    Dict      							=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

									__a			:    int      							=	self.get_config()

									return config, pixel_values, labels







					def 			_lowerCamelCase		(    self  ):
									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 			_lowerCamelCase		(    self						,      _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase  ):
									__a			:    int      							=	FocalNetModel(config=lowerCamelCase__  )
									model.to(lowerCamelCase__  )
									model.eval()
									__a			:    Optional[Any]      							=	model(lowerCamelCase__  )

									__a			:    Optional[int]      							=	((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths  ) - 1))
									__a			:    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 			_lowerCamelCase		(    self						,      _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase  ):
									__a			:    int      							=	FocalNetBackbone(config=lowerCamelCase__  )
									model.to(lowerCamelCase__  )
									model.eval()
									__a			:    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
									__a			:    List[str]      							=	None
									__a			:    str      							=	FocalNetBackbone(config=lowerCamelCase__  )
									model.to(lowerCamelCase__  )
									model.eval()
									__a			:    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 			_lowerCamelCase		(    self						,      _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase  ):
									__a			:    int      							=	FocalNetForMaskedImageModeling(config=lowerCamelCase__  )
									model.to(lowerCamelCase__  )
									model.eval()
									__a			:    Tuple      							=	model(lowerCamelCase__  )
									self.parent.assertEqual(
									    result.reconstruction.shape						,      (self.batch_size, self.num_channels, self.image_size, self.image_size)  )

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

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







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

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

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







					def 			_lowerCamelCase		(    self  ):
									__a			:    Optional[Any]      							=	self.prepare_config_and_inputs()

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






@require_torch
class 					__lowercase      (      UpperCAmelCase_ ,   UpperCAmelCase_ ,   unittest.TestCase				):







					'''simple docstring'''




					__lowerCAmelCase	=	(
					    (
					        FocalNetModel,
					        FocalNetForImageClassification,
					        FocalNetForMaskedImageModeling,
					        FocalNetBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					__lowerCAmelCase	=	(
					    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
					    if is_torch_available()
					    else {}
					)
					__lowerCAmelCase	=	False

					__lowerCAmelCase	=	False
					__lowerCAmelCase	=	False
					__lowerCAmelCase	=	False
					__lowerCAmelCase	=	False







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







					def 			_lowerCamelCase		(    self  ):
									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 			_lowerCamelCase		(    self  ):
									return







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







					def 			_lowerCamelCase		(    self  ):
									__a			:    Optional[int]      							=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*lowerCamelCase__  )







					def 			_lowerCamelCase		(    self  ):
									__a			:    Optional[int]      							=	self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase__  )







					def 			_lowerCamelCase		(    self  ):
									__a			:    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 			_lowerCamelCase		(    self  ):
									pass







					@unittest.skip(reason='''FocalNet does not use feedforward chunking'''  )
					def 			_lowerCamelCase		(    self  ):
									pass







					def 			_lowerCamelCase		(    self  ):
									__a			:    Tuple      							=	self.model_tester.prepare_config_and_inputs_for_common()

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







					def 			_lowerCamelCase		(    self  ):
									__a			:    Dict      							=	self.model_tester.prepare_config_and_inputs_for_common()

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

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







					def 			_lowerCamelCase		(    self						,      _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase						,      _UpperCAmelCase  ):
									__a			:    Optional[Any]      							=	model_class(lowerCamelCase__  )
									model.to(lowerCamelCase__  )
									model.eval()

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

									__a			:    List[str]      							=	outputs.hidden_states

									__a			:    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
									__a			:    List[str]      							=	(
									    config.patch_size
									    if isinstance(config.patch_size						,      collections.abc.Iterable  )
									    else (config.patch_size, config.patch_size)
									)

									__a			:    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]						,      )

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

									__a			:    Tuple      							=	reshaped_hidden_states[0].shape
									__a			:    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 			_lowerCamelCase		(    self  ):
									__a			:    Union[str, Any]      							=	self.model_tester.prepare_config_and_inputs_for_common()

									__a			:    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]:
													__a			:    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"]
													__a			:    Union[str, Any]      							=	True

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







					def 			_lowerCamelCase		(    self  ):
									__a			:    Dict      							=	self.model_tester.prepare_config_and_inputs_for_common()
									__a			:    str      							=	3

									__a			:    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)
									)
									__a			:    Tuple      							=	(
									    config.patch_size
									    if isinstance(config.patch_size						,      collections.abc.Iterable  )
									    else (config.patch_size, config.patch_size)
									)

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

									for model_class in self.all_model_classes[:-1]:
													__a			:    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"]
													__a			:    List[str]      							=	True
													self.check_hidden_states_output(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      (padded_height, padded_width)  )







					@slow
					def 			_lowerCamelCase		(    self  ):

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







					def 			_lowerCamelCase		(    self  ):
									__a			:    Optional[Any]      							=	self.model_tester.prepare_config_and_inputs_for_common()

									__a			:    str      							=	_config_zero_init(lowerCamelCase__  )
									for model_class in self.all_model_classes:
													__a			:    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 					__lowercase      (      unittest.TestCase				):







					'''simple docstring'''




					@cached_property
					def 			_lowerCamelCase		(    self  ):
									return AutoImageProcessor.from_pretrained('''microsoft/focalnet-tiny'''  ) if is_vision_available() else None







					@slow
					def 			_lowerCamelCase		(    self  ):
									__a			:    Optional[int]      							=	FocalNetForImageClassification.from_pretrained('''microsoft/focalnet-tiny'''  ).to(lowerCamelCase__  )
									__a			:    str      							=	self.default_image_processor

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

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

									# verify the logits
									__a			:    Tuple      							=	torch.Size((1, 1000)  )
									self.assertEqual(outputs.logits.shape						,      lowerCamelCase__  )
									__a			:    Optional[Any]      							=	torch.tensor([0.2_1_6_6, -0.4_3_6_8, 0.2_1_9_1]  ).to(lowerCamelCase__  )
									self.assertTrue(torch.allclose(outputs.logits[0, :3]						,      lowerCamelCase__						,      atol=1e-4  )  )
									self.assertTrue(outputs.logits.argmax(dim=-1  ).item()						,      281  )






@require_torch
class 					__lowercase      (      UpperCAmelCase_ ,   unittest.TestCase				):







					'''simple docstring'''




					__lowerCAmelCase	=	(FocalNetBackbone,) if is_torch_available() else ()
					__lowerCAmelCase	=	FocalNetConfig

					__lowerCAmelCase	=	False







					def 			_lowerCamelCase		(    self  ):
									__a			:    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()



