import inspect
import unittest

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

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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
  from transformers.models.mobilevitva.modeling_mobilevitva import (
      MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
      make_divisible,
  )


if is_vision_available():
  from PIL import Image

  from transformers import MobileViTImageProcessor







class __snake_case       (		lowerCamelCase_	):




   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.config_class(**self.inputs_dict   )
     self.parent.assertTrue(hasattr(UpperCamelCase__ ,			"""width_multiplier"""   )   )







class __snake_case       :




   def __init__(					self    :       Dict ,			_lowercase    :       List[str] ,			_lowercase    :       Any=13 ,			_lowercase    :       List[Any]=64 ,			_lowercase    :       str=2 ,			_lowercase    :       List[Any]=3 ,			_lowercase    :       Dict="swish" ,			_lowercase    :       Any=3 ,			_lowercase    :       List[Any]=32 ,			_lowercase    :       List[Any]=0.1 ,			_lowercase    :       List[str]=0.02 ,			_lowercase    :       Tuple=True ,			_lowercase    :       str=True ,			_lowercase    :       Tuple=10 ,			_lowercase    :       Optional[Any]=None ,			_lowercase    :       Union[str, Any]=0.25 ,			_lowercase    :       List[Any]=0.0 ,			_lowercase    :       Tuple=0.0 ,			):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   parent
     SCREAMING_SNAKE_CASE__    							=   batch_size
     SCREAMING_SNAKE_CASE__    							=   image_size
     SCREAMING_SNAKE_CASE__    							=   patch_size
     SCREAMING_SNAKE_CASE__    							=   num_channels
     SCREAMING_SNAKE_CASE__    							=   make_divisible(5_12 * width_multiplier ,			divisor=8   )
     SCREAMING_SNAKE_CASE__    							=   hidden_act
     SCREAMING_SNAKE_CASE__    							=   conv_kernel_size
     SCREAMING_SNAKE_CASE__    							=   output_stride
     SCREAMING_SNAKE_CASE__    							=   classifier_dropout_prob
     SCREAMING_SNAKE_CASE__    							=   use_labels
     SCREAMING_SNAKE_CASE__    							=   is_training
     SCREAMING_SNAKE_CASE__    							=   num_labels
     SCREAMING_SNAKE_CASE__    							=   initializer_range
     SCREAMING_SNAKE_CASE__    							=   scope
     SCREAMING_SNAKE_CASE__    							=   width_multiplier
     SCREAMING_SNAKE_CASE__    							=   ffn_dropout
     SCREAMING_SNAKE_CASE__    							=   attn_dropout




   def 			__a		(					self    :       Tuple   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

     SCREAMING_SNAKE_CASE__    							=   self.get_config()

     return config, pixel_values, labels, pixel_labels




   def 			__a		(					self    :       Tuple   ):



     """simple docstring"""






     return MobileViTVaConfig(
         image_size=self.image_size ,			patch_size=self.patch_size ,			num_channels=self.num_channels ,			hidden_act=self.hidden_act ,			conv_kernel_size=self.conv_kernel_size ,			output_stride=self.output_stride ,			classifier_dropout_prob=self.classifier_dropout_prob ,			initializer_range=self.initializer_range ,			width_multiplier=self.width_multiplier ,			ffn_dropout=self.ffn_dropout_prob ,			attn_dropout=self.attn_dropout_prob ,			)




   def 			__a		(					self    :       List[Any] ,			_lowercase    :       Optional[int] ,			_lowercase    :       str ,			_lowercase    :       Optional[Any] ,			_lowercase    :       Union[str, Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   MobileViTVaModel(config=UpperCamelCase__   )
     model.to(UpperCamelCase__   )
     model.eval()
     SCREAMING_SNAKE_CASE__    							=   model(UpperCamelCase__   )
     self.parent.assertEqual(
         result.last_hidden_state.shape ,			(
             self.batch_size,
             self.last_hidden_size,
             self.image_size // self.output_stride,
             self.image_size // self.output_stride,
         ) ,			)




   def 			__a		(					self    :       List[Any] ,			_lowercase    :       Optional[Any] ,			_lowercase    :       int ,			_lowercase    :       Union[str, Any] ,			_lowercase    :       Any   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.num_labels
     SCREAMING_SNAKE_CASE__    							=   MobileViTVaForImageClassification(UpperCamelCase__   )
     model.to(UpperCamelCase__   )
     model.eval()
     SCREAMING_SNAKE_CASE__    							=   model(UpperCamelCase__ ,			labels=UpperCamelCase__   )
     self.parent.assertEqual(result.logits.shape ,			(self.batch_size, self.num_labels)   )




   def 			__a		(					self    :       str ,			_lowercase    :       int ,			_lowercase    :       Any ,			_lowercase    :       Optional[Any] ,			_lowercase    :       Any   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.num_labels
     SCREAMING_SNAKE_CASE__    							=   MobileViTVaForSemanticSegmentation(UpperCamelCase__   )
     model.to(UpperCamelCase__   )
     model.eval()
     SCREAMING_SNAKE_CASE__    							=   model(UpperCamelCase__   )
     self.parent.assertEqual(
         result.logits.shape ,			(
             self.batch_size,
             self.num_labels,
             self.image_size // self.output_stride,
             self.image_size // self.output_stride,
         ) ,			)
     SCREAMING_SNAKE_CASE__    							=   model(UpperCamelCase__ ,			labels=UpperCamelCase__   )
     self.parent.assertEqual(
         result.logits.shape ,			(
             self.batch_size,
             self.num_labels,
             self.image_size // self.output_stride,
             self.image_size // self.output_stride,
         ) ,			)




   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






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







@require_torch
class __snake_case       (		lowerCamelCase_     ,	lowerCamelCase_     ,	unittest.TestCase	):
   lowerCAmelCase_														=							(
       (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )

   lowerCAmelCase_														=							(
       {
           "feature-extraction": MobileViTVaModel,
           "image-classification": MobileViTVaForImageClassification,
           "image-segmentation": MobileViTVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False




   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   MobileViTVaModelTester(self   )
     SCREAMING_SNAKE_CASE__    							=   MobileViTVaConfigTester(self ,			config_class=UpperCamelCase__ ,			has_text_modality=UpperCamelCase__   )




   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






     self.config_tester.run_common_tests()




   @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds"""   )
   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     pass




   @unittest.skip(reason="""MobileViTV2 does not support input and output embeddings"""   )
   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






     pass




   @unittest.skip(reason="""MobileViTV2 does not output attentions"""   )
   def 			__a		(					self    :       Union[str, Any]   ):



     """simple docstring"""






     pass




   @require_torch_multi_gpu
   @unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run."""   )
   def 			__a		(					self    :       Optional[int]   ):



     """simple docstring"""






     pass




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



     """simple docstring"""






     pass




   def 			__a		(					self    :       Any   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs_for_common()

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

       SCREAMING_SNAKE_CASE__    							=   ["""pixel_values"""]
       self.assertListEqual(arg_names[:1] ,			UpperCamelCase__   )




   def 			__a		(					self    :       Union[str, Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*UpperCamelCase__   )




   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     def check_hidden_states_output(_lowercase    :       Optional[int] ,			_lowercase    :       List[Any] ,			_lowercase    :       List[Any]   ):
       SCREAMING_SNAKE_CASE__    							=   model_class(UpperCamelCase__   )
       model.to(UpperCamelCase__   )
       model.eval()

       with torch.no_grad():
         SCREAMING_SNAKE_CASE__    							=   model(**self._prepare_for_class(UpperCamelCase__ ,			UpperCamelCase__   )   )

       SCREAMING_SNAKE_CASE__    							=   outputs.hidden_states

       SCREAMING_SNAKE_CASE__    							=   5
       self.assertEqual(len(UpperCamelCase__   ) ,			UpperCamelCase__   )

       # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
       # with the width and height being successively divided by 2.
       SCREAMING_SNAKE_CASE__    							=   2
       for i in range(len(UpperCamelCase__   )   ):
         self.assertListEqual(
             list(hidden_states[i].shape[-2:]   ) ,			[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] ,			)
         divisor *= 2

       self.assertEqual(self.model_tester.output_stride ,			divisor // 2   )

     SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       SCREAMING_SNAKE_CASE__    							=   True
       check_hidden_states_output(UpperCamelCase__ ,			UpperCamelCase__ ,			UpperCamelCase__   )

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

       check_hidden_states_output(UpperCamelCase__ ,			UpperCamelCase__ ,			UpperCamelCase__   )




   def 			__a		(					self    :       Any   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__   )




   def 			__a		(					self    :       Any   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__   )




   @slow
   def 			__a		(					self    :       int   ):



     """simple docstring"""






     for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       SCREAMING_SNAKE_CASE__    							=   MobileViTVaModel.from_pretrained(UpperCamelCase__   )
       self.assertIsNotNone(UpperCamelCase__   )





def 			__SCREAMING_SNAKE_CASE						(      )							->      Optional[int]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
  return image







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




   @cached_property
   def 			__a		(					self    :       int   ):



     """simple docstring"""






     return (
         MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""   )
         if is_vision_available()
         else None
     )




   @slow
   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""   ).to(
         UpperCamelCase__   )

     SCREAMING_SNAKE_CASE__    							=   self.default_image_processor
     SCREAMING_SNAKE_CASE__    							=   prepare_img()
     SCREAMING_SNAKE_CASE__    							=   image_processor(images=UpperCamelCase__ ,			return_tensors="""pt"""   ).to(UpperCamelCase__   )

     # forward pass
     with torch.no_grad():
       SCREAMING_SNAKE_CASE__    							=   model(**UpperCamelCase__   )

     # verify the logits
     SCREAMING_SNAKE_CASE__    							=   torch.Size((1, 10_00)   )
     self.assertEqual(outputs.logits.shape ,			UpperCamelCase__   )

     SCREAMING_SNAKE_CASE__    							=   torch.tensor([-1.6336E00, -7.3204E-02, -5.1883E-01]   ).to(UpperCamelCase__   )

     self.assertTrue(torch.allclose(outputs.logits[0, :3] ,			UpperCamelCase__ ,			atol=1E-4   )   )




   @slow
   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""   )
     SCREAMING_SNAKE_CASE__    							=   model.to(UpperCamelCase__   )

     SCREAMING_SNAKE_CASE__    							=   MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""   )

     SCREAMING_SNAKE_CASE__    							=   prepare_img()
     SCREAMING_SNAKE_CASE__    							=   image_processor(images=UpperCamelCase__ ,			return_tensors="""pt"""   ).to(UpperCamelCase__   )

     # forward pass
     with torch.no_grad():
       SCREAMING_SNAKE_CASE__    							=   model(**UpperCamelCase__   )
     SCREAMING_SNAKE_CASE__    							=   outputs.logits

     # verify the logits
     SCREAMING_SNAKE_CASE__    							=   torch.Size((1, 21, 32, 32)   )
     self.assertEqual(logits.shape ,			UpperCamelCase__   )

     SCREAMING_SNAKE_CASE__    							=   torch.tensor(
         [
             [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
             [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
             [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
         ] ,			device=UpperCamelCase__ ,			)

     self.assertTrue(torch.allclose(logits[0, :3, :3, :3] ,			UpperCamelCase__ ,			atol=1E-4   )   )




   @slow
   def 			__a		(					self    :       List[Any]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""   )
     SCREAMING_SNAKE_CASE__    							=   model.to(UpperCamelCase__   )

     SCREAMING_SNAKE_CASE__    							=   MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""   )

     SCREAMING_SNAKE_CASE__    							=   prepare_img()
     SCREAMING_SNAKE_CASE__    							=   image_processor(images=UpperCamelCase__ ,			return_tensors="""pt"""   ).to(UpperCamelCase__   )

     # forward pass
     with torch.no_grad():
       SCREAMING_SNAKE_CASE__    							=   model(**UpperCamelCase__   )

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

     SCREAMING_SNAKE_CASE__    							=   image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__ ,			target_sizes=[(50, 60)]   )
     SCREAMING_SNAKE_CASE__    							=   torch.Size((50, 60)   )
     self.assertEqual(segmentation[0].shape ,			UpperCamelCase__   )

     SCREAMING_SNAKE_CASE__    							=   image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__   )
     SCREAMING_SNAKE_CASE__    							=   torch.Size((32, 32)   )
     self.assertEqual(segmentation[0].shape ,			UpperCamelCase__   )

from math import log

from scipy.constants import Boltzmann, physical_constants

__lowerCamelCase    :				int							     =	300  # TEMPERATURE (unit = K)



def 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: float				,  __UpperCamelCase					: float				,  __UpperCamelCase					: float				,  )							->      float:







  """simple docstring"""





  if donor_conc <= 0:
    raise ValueError("""Donor concentration should be positive"""			)
  elif acceptor_conc <= 0:
    raise ValueError("""Acceptor concentration should be positive"""			)
  elif intrinsic_conc <= 0:
    raise ValueError("""Intrinsic concentration should be positive"""			)
  elif donor_conc <= intrinsic_conc:
    raise ValueError(
        """Donor concentration should be greater than intrinsic concentration"""			)
  elif acceptor_conc <= intrinsic_conc:
    raise ValueError(
        """Acceptor concentration should be greater than intrinsic concentration"""			)
  else:
    return (
        Boltzmann
        * T
        * log((donor_conc * acceptor_conc) / intrinsic_conc**2			)
        / physical_constants["electron volt"][0]
    )


if __name__ == "__main__":
   import doctest

   doctest.testmod()
