


'''simple docstring'''







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import DeiTImageProcessor







class A__	(						unittest.TestCase				):






      def __init__(			self      :Union[str, Any]					,						SCREAMING_SNAKE_CASE      :int					,						SCREAMING_SNAKE_CASE      :Union[str, Any]=7					,						SCREAMING_SNAKE_CASE      :List[str]=3					,						SCREAMING_SNAKE_CASE      :int=1_8					,						SCREAMING_SNAKE_CASE      :Tuple=3_0					,						SCREAMING_SNAKE_CASE      :Union[str, Any]=4_0_0					,						SCREAMING_SNAKE_CASE      :Any=True					,						SCREAMING_SNAKE_CASE      :Union[str, Any]=None					,						SCREAMING_SNAKE_CASE      :Optional[Any]=True					,						SCREAMING_SNAKE_CASE      :List[str]=None					,						SCREAMING_SNAKE_CASE      :Dict=True					,						SCREAMING_SNAKE_CASE      :int=[0.5, 0.5, 0.5]					,						SCREAMING_SNAKE_CASE      :int=[0.5, 0.5, 0.5]					,						)	-> int:




             '''simple docstring'''
             _a   :			Optional[int]					 =size if size is not None else {"""height""": 2_0, """width""": 2_0}
             _a   :			List[Any]					 =crop_size if crop_size is not None else {"""height""": 1_8, """width""": 1_8}

             _a   :			Union[str, Any]					 =parent
             _a   :			List[Any]					 =batch_size
             _a   :			Optional[Any]					 =num_channels
             _a   :			Tuple					 =image_size
             _a   :			Any					 =min_resolution
             _a   :			str					 =max_resolution
             _a   :			str					 =do_resize
             _a   :			str					 =size
             _a   :			str					 =do_center_crop
             _a   :			Optional[Any]					 =crop_size
             _a   :			Union[str, Any]					 =do_normalize
             _a   :			List[Any]					 =image_mean
             _a   :			str					 =image_std






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




             '''simple docstring'''
             return {
                 "do_resize": self.do_resize,
                 "size": self.size,
                 "do_center_crop": self.do_center_crop,
                 "crop_size": self.crop_size,
                 "do_normalize": self.do_normalize,
                 "image_mean": self.image_mean,
                 "image_std": self.image_std,
             }







@require_torch
@require_vision
class A__	(						SCREAMING_SNAKE_CASE__			,					unittest.TestCase				):
      __UpperCamelCase	:  Tuple     	=							DeiTImageProcessor if is_vision_available() else None
      __UpperCamelCase	:  int     	=							True






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




             '''simple docstring'''
             _a   :			Any					 =DeiTImageProcessingTester(self     )






      @property
      def __UpperCAmelCase	(			self      :Tuple     )	-> Optional[int]:




             '''simple docstring'''
             return self.image_processor_tester.prepare_image_processor_dict()






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




             '''simple docstring'''
             _a   :			Dict					 =self.image_processing_class(**self.image_processor_dict     )
             self.assertTrue(hasattr(SCREAMING_SNAKE_CASE					,						"""do_resize"""     )     )
             self.assertTrue(hasattr(SCREAMING_SNAKE_CASE					,						"""size"""     )     )
             self.assertTrue(hasattr(SCREAMING_SNAKE_CASE					,						"""do_center_crop"""     )     )
             self.assertTrue(hasattr(SCREAMING_SNAKE_CASE					,						"""center_crop"""     )     )
             self.assertTrue(hasattr(SCREAMING_SNAKE_CASE					,						"""do_normalize"""     )     )
             self.assertTrue(hasattr(SCREAMING_SNAKE_CASE					,						"""image_mean"""     )     )
             self.assertTrue(hasattr(SCREAMING_SNAKE_CASE					,						"""image_std"""     )     )






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




             '''simple docstring'''
             _a   :			List[Any]					 =self.image_processing_class.from_dict(self.image_processor_dict     )
             self.assertEqual(image_processor.size					,						{"""height""": 2_0, """width""": 2_0}     )
             self.assertEqual(image_processor.crop_size					,						{"""height""": 1_8, """width""": 1_8}     )

             _a   :			Optional[Any]					 =self.image_processing_class.from_dict(self.image_processor_dict					,						size=4_2					,						crop_size=8_4     )
             self.assertEqual(image_processor.size					,						{"""height""": 4_2, """width""": 4_2}     )
             self.assertEqual(image_processor.crop_size					,						{"""height""": 8_4, """width""": 8_4}     )






      def __UpperCAmelCase	(			self      :Tuple     )	-> Any:




             '''simple docstring'''
             pass






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




             '''simple docstring'''
             _a   :			Optional[Any]					 =self.image_processing_class(**self.image_processor_dict     )
             # create random PIL images
             _a   :			List[str]					 =prepare_image_inputs(self.image_processor_tester					,						equal_resolution=SCREAMING_SNAKE_CASE     )
             for image in image_inputs:
                    self.assertIsInstance(SCREAMING_SNAKE_CASE					,						Image.Image     )

             # Test not batched input
             _a   :			Any					 =image_processing(image_inputs[0]					,						return_tensors="""pt"""     ).pixel_values
             self.assertEqual(
                 encoded_images.shape					,						(
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["""height"""],
                     self.image_processor_tester.crop_size["""width"""],
                 )					,						)

             # Test batched
             _a   :			int					 =image_processing(SCREAMING_SNAKE_CASE					,						return_tensors="""pt"""     ).pixel_values
             self.assertEqual(
                 encoded_images.shape					,						(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["""height"""],
                     self.image_processor_tester.crop_size["""width"""],
                 )					,						)






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




             '''simple docstring'''
             _a   :			Optional[int]					 =self.image_processing_class(**self.image_processor_dict     )
             # create random numpy tensors
             _a   :			List[Any]					 =prepare_image_inputs(self.image_processor_tester					,						equal_resolution=SCREAMING_SNAKE_CASE					,						numpify=SCREAMING_SNAKE_CASE     )
             for image in image_inputs:
                    self.assertIsInstance(SCREAMING_SNAKE_CASE					,						np.ndarray     )

             # Test not batched input
             _a   :			Tuple					 =image_processing(image_inputs[0]					,						return_tensors="""pt"""     ).pixel_values
             self.assertEqual(
                 encoded_images.shape					,						(
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["""height"""],
                     self.image_processor_tester.crop_size["""width"""],
                 )					,						)

             # Test batched
             _a   :			Any					 =image_processing(SCREAMING_SNAKE_CASE					,						return_tensors="""pt"""     ).pixel_values
             self.assertEqual(
                 encoded_images.shape					,						(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["""height"""],
                     self.image_processor_tester.crop_size["""width"""],
                 )					,						)






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




             '''simple docstring'''
             _a   :			List[Any]					 =self.image_processing_class(**self.image_processor_dict     )
             # create random PyTorch tensors
             _a   :			List[Any]					 =prepare_image_inputs(self.image_processor_tester					,						equal_resolution=SCREAMING_SNAKE_CASE					,						torchify=SCREAMING_SNAKE_CASE     )
             for image in image_inputs:
                    self.assertIsInstance(SCREAMING_SNAKE_CASE					,						torch.Tensor     )

             # Test not batched input
             _a   :			int					 =image_processing(image_inputs[0]					,						return_tensors="""pt"""     ).pixel_values
             self.assertEqual(
                 encoded_images.shape					,						(
                     1,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["""height"""],
                     self.image_processor_tester.crop_size["""width"""],
                 )					,						)

             # Test batched
             _a   :			List[str]					 =image_processing(SCREAMING_SNAKE_CASE					,						return_tensors="""pt"""     ).pixel_values
             self.assertEqual(
                 encoded_images.shape					,						(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size["""height"""],
                     self.image_processor_tester.crop_size["""width"""],
                 )					,						)






'''simple docstring'''







from typing import Dict, Optional, Tuple

import torch


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor  )  ->      torch.Tensor:
       _a   :			Tuple					 =boundaries[1] - boundaries[0]
       _a   :			Dict					 =boundaries + step / 2
       _a   :			List[Any]					 =torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1  )]   ,dim=0  )
       return bin_centers


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     torch.Tensor   ,)  ->      Tuple[torch.Tensor, torch.Tensor]:
       _a   :			Any					 =_calculate_bin_centers(_UpperCAmelCase  )
       return (
           torch.sum(aligned_distance_error_probs * bin_centers   ,dim=-1  ),
           bin_centers[-1],
       )


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     int = 31   ,_UpperCAmelCase     :     int = 64   ,**_UpperCAmelCase     :     Dict   ,)  ->      Dict[str, torch.Tensor]:
       _a   :			Dict					 =torch.linspace(0   ,_UpperCAmelCase   ,steps=(no_bins - 1)   ,device=logits.device  )

       _a   :			int					 =torch.nn.functional.softmax(_UpperCAmelCase   ,dim=-1  )
       _a ,   _a   :			List[Any]					 =_calculate_expected_aligned_error(
           alignment_confidence_breaks=_UpperCAmelCase   ,aligned_distance_error_probs=_UpperCAmelCase   ,)

       return {
           "aligned_confidence_probs": aligned_confidence_probs,
           "predicted_aligned_error": predicted_aligned_error,
           "max_predicted_aligned_error": max_predicted_aligned_error,
       }


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     Optional[torch.Tensor] = None   ,_UpperCAmelCase     :     int = 31   ,_UpperCAmelCase     :     int = 64   ,_UpperCAmelCase     :     float = 1e-8   ,**_UpperCAmelCase     :     Optional[Any]   ,)  ->      torch.Tensor:
       if residue_weights is None:
              _a   :			Dict					 =logits.new_ones(logits.shape[-2]  )

       _a   :			str					 =torch.linspace(0   ,_UpperCAmelCase   ,steps=(no_bins - 1)   ,device=logits.device  )

       _a   :			Optional[int]					 =_calculate_bin_centers(_UpperCAmelCase  )
       torch.sum(_UpperCAmelCase  )
       _a   :			List[str]					 =logits.shape[-2]
       _a   :			List[Any]					 =max(_UpperCAmelCase   ,19  )

       _a   :			Union[str, Any]					 =1.2_4 * (clipped_n - 15) ** (1.0 / 3) - 1.8

       _a   :			Tuple					 =torch.nn.functional.softmax(_UpperCAmelCase   ,dim=-1  )

       _a   :			Dict					 =1.0 / (1 + (bin_centers**2) / (da**2))
       _a   :			int					 =torch.sum(probs * tm_per_bin   ,dim=-1  )

       _a   :			List[Any]					 =residue_weights / (eps + residue_weights.sum())
       _a   :			List[str]					 =torch.sum(predicted_tm_term * normed_residue_mask   ,dim=-1  )

       _a   :			int					 =per_alignment * residue_weights

       _a   :			List[Any]					 =(weighted == torch.max(_UpperCAmelCase  )).nonzero()[0]
       return per_alignment[tuple(_UpperCAmelCase  )]


