





'''simple docstring'''




import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
  from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import DPTImageProcessor


class  SCREAMING_SNAKE_CASE    :


     def __init__(						self						,	_UpperCAmelCase						,	_UpperCAmelCase=2						,	_UpperCAmelCase=32						,	_UpperCAmelCase=16						,	_UpperCAmelCase=3						,	_UpperCAmelCase=True						,	_UpperCAmelCase=True						,	_UpperCAmelCase=32						,	_UpperCAmelCase=4						,	_UpperCAmelCase=[0, 1, 2, 3]						,	_UpperCAmelCase=4						,	_UpperCAmelCase=37						,	_UpperCAmelCase="gelu"						,	_UpperCAmelCase=0.1						,	_UpperCAmelCase=0.1						,	_UpperCAmelCase=0.02						,	_UpperCAmelCase=3						,	_UpperCAmelCase=[1, 384, 24, 24]						,	_UpperCAmelCase=True						,	_UpperCAmelCase=None						,	):

          '''simple docstring'''






          __A						: str      =       parent
          __A						: str      =       batch_size
          __A						: Dict      =       image_size
          __A						: Optional[Any]      =       patch_size
          __A						: str      =       num_channels
          __A						: Optional[int]      =       is_training
          __A						: List[str]      =       use_labels
          __A						: Any      =       hidden_size
          __A						: Optional[Any]      =       num_hidden_layers
          __A						: Optional[Any]      =       backbone_out_indices
          __A						: List[str]      =       num_attention_heads
          __A						: Dict      =       intermediate_size
          __A						: Any      =       hidden_act
          __A						: int      =       hidden_dropout_prob
          __A						: List[Any]      =       attention_probs_dropout_prob
          __A						: Tuple      =       initializer_range
          __A						: Dict      =       num_labels
          __A						: str      =       backbone_featmap_shape
          __A						: str      =       scope
          __A						: Dict      =       is_hybrid
          # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
          __A						: Union[str, Any]      =       (image_size // patch_size) ** 2
          __A						: List[Any]      =       num_patches + 1


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: str      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          __A						: Optional[Any]      =       None
          if self.use_labels:
               __A						: int      =       ids_tensor([self.batch_size, self.image_size, self.image_size]						,	self.num_labels)

          __A						: int      =       self.get_config()

          return config, pixel_values, labels


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Union[str, Any]      =       {
              'global_padding': 'same',
              'layer_type': 'bottleneck',
              'depths': [3, 4, 9],
              'out_features': ['stage1', 'stage2', 'stage3'],
              'embedding_dynamic_padding': True,
              'hidden_sizes': [96, 192, 384, 768],
              'num_groups': 2,
          }

          return DPTConfig(
              image_size=self.image_size						,	patch_size=self.patch_size						,	num_channels=self.num_channels						,	hidden_size=self.hidden_size						,	num_hidden_layers=self.num_hidden_layers						,	backbone_out_indices=self.backbone_out_indices						,	num_attention_heads=self.num_attention_heads						,	intermediate_size=self.intermediate_size						,	hidden_act=self.hidden_act						,	hidden_dropout_prob=self.hidden_dropout_prob						,	attention_probs_dropout_prob=self.attention_probs_dropout_prob						,	is_decoder=_UpperCAmelCase						,	initializer_range=self.initializer_range						,	is_hybrid=self.is_hybrid						,	backbone_config=_UpperCAmelCase						,	backbone_featmap_shape=self.backbone_featmap_shape						,	)


     def 							SCREAMING_SNAKE_CASE  (						self						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase):

          '''simple docstring'''






          __A						: Optional[Any]      =       DPTModel(config=_UpperCAmelCase)
          model.to(_UpperCAmelCase)
          model.eval()
          __A						: Dict      =       model(_UpperCAmelCase)
          self.parent.assertEqual(result.last_hidden_state.shape						,	(self.batch_size, self.seq_length, self.hidden_size))


     def 							SCREAMING_SNAKE_CASE  (						self						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase):

          '''simple docstring'''






          __A						: List[str]      =       self.num_labels
          __A						: Union[str, Any]      =       DPTForDepthEstimation(_UpperCAmelCase)
          model.to(_UpperCAmelCase)
          model.eval()
          __A						: Union[str, Any]      =       model(_UpperCAmelCase)
          self.parent.assertEqual(result.predicted_depth.shape						,	(self.batch_size, self.image_size, self.image_size))


     def 							SCREAMING_SNAKE_CASE  (						self						,	_UpperCAmelCase						,	_UpperCAmelCase						,	_UpperCAmelCase):

          '''simple docstring'''






          __A						: str      =       self.num_labels
          __A						: Tuple      =       DPTForSemanticSegmentation(_UpperCAmelCase)
          model.to(_UpperCAmelCase)
          model.eval()
          __A						: Optional[int]      =       model(_UpperCAmelCase						,	labels=_UpperCAmelCase)
          self.parent.assertEqual(
              result.logits.shape						,	(self.batch_size, self.num_labels, self.image_size, self.image_size))


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Dict      =       self.prepare_config_and_inputs()
          __A ,__A ,__A						: List[Any]      =       config_and_inputs
          __A						: Optional[Any]      =       {'pixel_values': pixel_values}
          return config, inputs_dict




@require_torch
class  SCREAMING_SNAKE_CASE    (a__					,		a__					,		unittest.TestCase							):
     lowerCAmelCase					=       (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
     lowerCAmelCase					=       (
         {
             '''depth-estimation''': DPTForDepthEstimation,
             '''feature-extraction''': DPTModel,
             '''image-segmentation''': DPTForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     lowerCAmelCase					=       False
     lowerCAmelCase					=       False
     lowerCAmelCase					=       False


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: int      =       DPTModelTester(self)
          __A						: int      =       ConfigTester(self						,	config_class=_UpperCAmelCase						,	has_text_modality=_UpperCAmelCase						,	hidden_size=37)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          self.config_tester.run_common_tests()


     @unittest.skip(reason='DPT does not use inputs_embeds')
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          pass


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A ,__A						: str      =       self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __A						: Dict      =       model_class(_UpperCAmelCase)
               self.assertIsInstance(model.get_input_embeddings()						,	(nn.Module))
               __A						: List[Any]      =       model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(_UpperCAmelCase						,	nn.Linear))


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






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

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

               __A						: str      =       ['pixel_values']
               self.assertListEqual(arg_names[:1]						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Any      =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: int      =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_depth_estimation(*_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: int      =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          for model_class in self.all_model_classes:
               if model_class.__name__ == "DPTForDepthEstimation":
                    continue

               __A ,__A						: List[Any]      =       self.model_tester.prepare_config_and_inputs_for_common()
               __A						: str      =       True

               if model_class in get_values(_UpperCAmelCase):
                    continue

               __A						: Tuple      =       model_class(_UpperCAmelCase)
               model.to(_UpperCAmelCase)
               model.train()
               __A						: Dict      =       self._prepare_for_class(_UpperCAmelCase						,	_UpperCAmelCase						,	return_labels=_UpperCAmelCase)
               __A						: Any      =       model(**_UpperCAmelCase).loss
               loss.backward()


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          for model_class in self.all_model_classes:
               if model_class.__name__ == "DPTForDepthEstimation":
                    continue

               __A ,__A						: Tuple      =       self.model_tester.prepare_config_and_inputs_for_common()
               __A						: Tuple      =       False
               __A						: Tuple      =       True

               if model_class in get_values(_UpperCAmelCase) or not model_class.supports_gradient_checkpointing:
                    continue
               __A						: Union[str, Any]      =       model_class(_UpperCAmelCase)
               model.to(_UpperCAmelCase)
               model.gradient_checkpointing_enable()
               model.train()
               __A						: int      =       self._prepare_for_class(_UpperCAmelCase						,	_UpperCAmelCase						,	return_labels=_UpperCAmelCase)
               __A						: str      =       model(**_UpperCAmelCase).loss
               loss.backward()


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A ,__A						: Optional[int]      =       self.model_tester.prepare_config_and_inputs_for_common()

          __A						: Union[str, Any]      =       _config_zero_init(_UpperCAmelCase)
          for model_class in self.all_model_classes:
               __A						: Dict      =       model_class(config=_UpperCAmelCase)
               # Skip the check for the backbone
               __A						: Any      =       []
               for name, module in model.named_modules():
                    if module.__class__.__name__ == "DPTViTHybridEmbeddings":
                         __A						: str      =       [F'{name}.{key}' for key in module.state_dict().keys()]
                         break

               for name, param in model.named_parameters():
                    if param.requires_grad:
                         if name in backbone_params:
                              continue
                         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'						,	)


     @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          pass


     @slow
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
               __A						: List[str]      =       DPTModel.from_pretrained(_UpperCAmelCase)
               self.assertIsNotNone(_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A ,__A						: Tuple      =       self.model_tester.prepare_config_and_inputs_for_common()
          __A						: int      =       'add'
          with self.assertRaises(_UpperCAmelCase):
               __A						: Tuple      =       DPTForDepthEstimation(_UpperCAmelCase)






def        _lowerCAmelCase			(  )     ->     List[Any]:
     __A						: Optional[Any]      =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
     return image







@require_torch
@require_vision
@slow
class  SCREAMING_SNAKE_CASE    (unittest.TestCase							):


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Tuple      =       DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas')
          __A						: Union[str, Any]      =       DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas').to(_UpperCAmelCase)

          __A						: Dict      =       prepare_img()
          __A						: Union[str, Any]      =       image_processor(images=_UpperCAmelCase						,	return_tensors='pt').to(_UpperCAmelCase)

          # forward pass
          with torch.no_grad():
               __A						: Union[str, Any]      =       model(**_UpperCAmelCase)
               __A						: Any      =       outputs.predicted_depth

          # verify the predicted depth
          __A						: List[str]      =       torch.Size((1, 384, 384))
          self.assertEqual(predicted_depth.shape						,	_UpperCAmelCase)

          __A						: int      =       torch.tensor(
              [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]).to(_UpperCAmelCase)

          self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100						,	_UpperCAmelCase						,	atol=1e-4))






'''simple docstring'''




from __future__ import annotations

from numpy import array, cos, cross, floataa, radians, sin
from numpy.typing import NDArray






def        _lowerCAmelCase			(  __snake_case  : float ,							__snake_case  : float ,							__snake_case  : bool = False			)     ->     list[float]:
     if radian_mode:
          return [magnitude * cos(__snake_case			), magnitude * sin(__snake_case			)]
     return [magnitude * cos(radians(__snake_case			)			), magnitude * sin(radians(__snake_case			)			)]






def        _lowerCAmelCase			(  __snake_case  : NDArray[floataa] ,							__snake_case  : NDArray[floataa] ,							__snake_case  : float = 10**-1			)     ->     bool:
     __A						: NDArray[floataa]      =       cross(__snake_case ,							__snake_case			)
     __A						: float      =       sum(__snake_case			)
     return abs(__snake_case			) < eps


if __name__ == "__main__":
  # Test to check if it works
  lowercase__    :      List[Any]						=    array(
      [
          polar_force(718.4, 1_80 - 30),
          polar_force(879.54, 45),
          polar_force(1_00, -90),
      ]
  )

  lowercase__    :      NDArray[floataa]						=    array([[0, 0], [0, 0], [0, 0]])

  assert in_static_equilibrium(forces, location)

  # Problem 1 in image_data/2D_problems.jpg
  lowercase__    :      Dict						=    array(
      [
          polar_force(30 * 9.81, 15),
          polar_force(2_15, 1_80 - 45),
          polar_force(2_64, 90 - 30),
      ]
  )

  lowercase__    :      Any						=    array([[0, 0], [0, 0], [0, 0]])

  assert in_static_equilibrium(forces, location)

  # Problem in image_data/2D_problems_1.jpg
  lowercase__    :      Optional[int]						=    array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]])

  lowercase__    :      Optional[int]						=    array([[0, 0], [6, 0], [10, 0], [12, 0]])

  assert in_static_equilibrium(forces, location)

  import doctest

  doctest.testmod()