'''simple docstring'''






from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers import TFCvtForImageClassification, TFCvtModel
    from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor




class    a (       __lowerCAmelCase				):



  """simple docstring"""







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Union[str, Any]		= self.config_class(**self.inputs_dict					)
    self.parent.assertTrue(hasattr(snake_case_   ,    """embed_dim"""					)					)
    self.parent.assertTrue(hasattr(snake_case_   ,    """num_heads"""					)					)




class    a :



  """simple docstring"""







  def __init__(							self   ,    snake_case_   ,    snake_case_=13   ,    snake_case_=64   ,    snake_case_=3   ,    snake_case_=[16, 48, 96]   ,    snake_case_=[1, 3, 6]   ,    snake_case_=[1, 2, 10]   ,    snake_case_=[7, 3, 3]   ,    snake_case_=[4, 2, 2]   ,    snake_case_=[2, 1, 1]   ,    snake_case_=[2, 2, 2]   ,    snake_case_=[False, False, True]   ,    snake_case_=[0.0, 0.0, 0.0]   ,    snake_case_=0.0_2   ,    snake_case_=1e-1_2   ,    snake_case_=True   ,    snake_case_=True   ,    snake_case_=2   ,    ):

    '''simple docstring'''







    __UpperCAmelCase:					Union[str, Any]		= parent
    __UpperCAmelCase:					Union[str, Any]		= batch_size
    __UpperCAmelCase:					List[str]		= image_size
    __UpperCAmelCase:					List[Any]		= patch_sizes
    __UpperCAmelCase:					Dict		= patch_stride
    __UpperCAmelCase:					str		= patch_padding
    __UpperCAmelCase:					int		= is_training
    __UpperCAmelCase:					List[Any]		= use_labels
    __UpperCAmelCase:					Any		= num_labels
    __UpperCAmelCase:					Any		= num_channels
    __UpperCAmelCase:					List[str]		= embed_dim
    __UpperCAmelCase:					Union[str, Any]		= num_heads
    __UpperCAmelCase:					Any		= stride_kv
    __UpperCAmelCase:					Any		= depth
    __UpperCAmelCase:					List[str]		= cls_token
    __UpperCAmelCase:					Optional[Any]		= attention_drop_rate
    __UpperCAmelCase:					str		= initializer_range
    __UpperCAmelCase:					Optional[int]		= layer_norm_eps







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[Any]		= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

    __UpperCAmelCase:					Tuple		= None
    if self.use_labels:
      # create a random int32 tensor of given shape
      __UpperCAmelCase:					Any		= ids_tensor([self.batch_size]   ,    self.num_labels					)

    __UpperCAmelCase:					Union[str, Any]		= self.get_config()
    return config, pixel_values, labels







  def    lowercase_  (							self					):

    '''simple docstring'''







    return CvtConfig(
        image_size=self.image_size   ,    num_labels=self.num_labels   ,    num_channels=self.num_channels   ,    embed_dim=self.embed_dim   ,    num_heads=self.num_heads   ,    patch_sizes=self.patch_sizes   ,    patch_padding=self.patch_padding   ,    patch_stride=self.patch_stride   ,    stride_kv=self.stride_kv   ,    depth=self.depth   ,    cls_token=self.cls_token   ,    attention_drop_rate=self.attention_drop_rate   ,    initializer_range=self.initializer_range   ,    )







  def    lowercase_  (							self   ,    snake_case_   ,    snake_case_   ,    snake_case_					):

    '''simple docstring'''







    __UpperCAmelCase:					Dict		= TFCvtModel(config=snake_case_					)
    __UpperCAmelCase:					Tuple		= model(snake_case_   ,    training=snake_case_					)
    __UpperCAmelCase:					int		= (self.image_size, self.image_size)
    __UpperCAmelCase, __UpperCAmelCase:					Optional[int]		= image_size[0], image_size[1]
    for i in range(len(self.depth					)					):
      __UpperCAmelCase:					str		= floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1					)
      __UpperCAmelCase:					Optional[Any]		= floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1					)
    self.parent.assertEqual(result.last_hidden_state.shape   ,    (self.batch_size, self.embed_dim[-1], height, width)					)







  def    lowercase_  (							self   ,    snake_case_   ,    snake_case_   ,    snake_case_					):

    '''simple docstring'''







    __UpperCAmelCase:					Optional[int]		= self.num_labels
    __UpperCAmelCase:					int		= TFCvtForImageClassification(snake_case_					)
    __UpperCAmelCase:					Union[str, Any]		= model(snake_case_   ,    labels=snake_case_   ,    training=snake_case_					)
    self.parent.assertEqual(result.logits.shape   ,    (self.batch_size, self.num_labels)					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Dict		= self.prepare_config_and_inputs()
    __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase:					Optional[int]		= config_and_inputs
    __UpperCAmelCase:					int		= {"""pixel_values""": pixel_values}
    return config, inputs_dict




@require_tf
class    a (       __lowerCAmelCase						,  __lowerCAmelCase						,  unittest.TestCase				):



  """simple docstring"""
  __lowerCAmelCase				      =					(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
  __lowerCAmelCase				      =					(
      {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
      if is_tf_available()
      else {}
  )
  __lowerCAmelCase				      =					False
  __lowerCAmelCase				      =					False
  __lowerCAmelCase				      =					False
  __lowerCAmelCase				      =					False
  __lowerCAmelCase				      =					False







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					str		= TFCvtModelTester(self					)
    __UpperCAmelCase:					Optional[int]		= TFCvtConfigTester(self   ,    config_class=snake_case_   ,    has_text_modality=snake_case_   ,    hidden_size=37					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    self.config_tester.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()







  @unittest.skip(reason="""Cvt does not output attentions"""					)
  def    lowercase_  (							self					):

    '''simple docstring'''







    pass







  @unittest.skip(reason="""Cvt does not use inputs_embeds"""					)
  def    lowercase_  (							self					):

    '''simple docstring'''







    pass







  @unittest.skip(reason="""Cvt does not support input and output embeddings"""					)
  def    lowercase_  (							self					):

    '''simple docstring'''







    pass







  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""					)					) == 0   ,    reason="""TF does not support backprop for grouped convolutions on CPU."""   ,    )
  def    lowercase_  (							self					):

    '''simple docstring'''







    super().test_dataset_conversion()







  @unittest.skipIf(
      not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""					)					) == 0   ,    reason="""TF does not support backprop for grouped convolutions on CPU."""   ,    )
  @slow
  def    lowercase_  (							self					):

    '''simple docstring'''







    super().test_keras_fit()







  @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8"""					)
  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= tf.keras.mixed_precision.Policy("""mixed_float16"""					)
    tf.keras.mixed_precision.set_global_policy(snake_case_					)
    super().test_keras_fit()
    tf.keras.mixed_precision.set_global_policy("""float32"""					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase, __UpperCAmelCase:					int		= self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      __UpperCAmelCase:					str		= model_class(snake_case_					)
      __UpperCAmelCase:					str		= inspect.signature(model.call					)
      # signature.parameters is an OrderedDict => so arg_names order is deterministic
      __UpperCAmelCase:					Union[str, Any]		= [*signature.parameters.keys()]

      __UpperCAmelCase:					int		= ["""pixel_values"""]
      self.assertListEqual(arg_names[:1]   ,    snake_case_					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    def check_hidden_states_output(snake_case_   ,    snake_case_   ,    snake_case_					):
      __UpperCAmelCase:					Optional[Any]		= model_class(snake_case_					)

      __UpperCAmelCase:					str		= model(**self._prepare_for_class(snake_case_   ,    snake_case_					)					)
      __UpperCAmelCase:					int		= outputs.hidden_states

      __UpperCAmelCase:					Dict		= len(self.model_tester.depth					)
      self.assertEqual(len(snake_case_					)   ,    snake_case_					)

      # verify the first hidden states (first block)
      self.assertListEqual(
          list(hidden_states[0].shape[-3:]					)   ,    [
              self.model_tester.embed_dim[0],
              self.model_tester.image_size // 4,
              self.model_tester.image_size // 4,
          ]   ,    )

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

    for model_class in self.all_model_classes:
      __UpperCAmelCase:					Dict		= True
      check_hidden_states_output(snake_case_   ,    snake_case_   ,    snake_case_					)

      # check that output_hidden_states also work using config
      del inputs_dict["output_hidden_states"]
      __UpperCAmelCase:					str		= True

      check_hidden_states_output(snake_case_   ,    snake_case_   ,    snake_case_					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[Any]		= self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*snake_case_					)







  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					List[str]		= self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*snake_case_					)







  @slow
  def    lowercase_  (							self					):

    '''simple docstring'''







    for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __UpperCAmelCase:					Union[str, Any]		= TFCvtModel.from_pretrained(snake_case_					)
      self.assertIsNotNone(snake_case_					)






def  UpperCamelCase__					(					)							->	int:
  __UpperCAmelCase:					Tuple		= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
  return image







@require_tf
@require_vision
class    a (       unittest.TestCase				):



  """simple docstring"""







  @cached_property
  def    lowercase_  (							self					):

    '''simple docstring'''







    return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)







  @slow
  def    lowercase_  (							self					):

    '''simple docstring'''







    __UpperCAmelCase:					Dict		= TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)

    __UpperCAmelCase:					Union[str, Any]		= self.default_image_processor
    __UpperCAmelCase:					List[Any]		= prepare_img()
    __UpperCAmelCase:					str		= image_processor(images=snake_case_   ,    return_tensors="""tf"""					)

    # forward pass
    __UpperCAmelCase:					Tuple		= model(**snake_case_					)

    # verify the logits
    __UpperCAmelCase:					str		= tf.TensorShape((1, 1000)					)
    self.assertEqual(outputs.logits.shape   ,    snake_case_					)

    __UpperCAmelCase:					str		= tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]					)
    self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()   ,    snake_case_   ,    atol=1e-4					)					)
'''simple docstring'''






from __future__ import annotations

import matplotlib.pyplot as plt  # type: ignore
import numpy

# initial triangle of Koch snowflake
SCREAMING_SNAKE_CASE_	   =			numpy.array([0, 0])
SCREAMING_SNAKE_CASE_	   =			numpy.array([0.5, 0.866_0254])
SCREAMING_SNAKE_CASE_	   =			numpy.array([1, 0])
SCREAMING_SNAKE_CASE_	   =			[VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]






def  UpperCamelCase__					(					_lowercase    :				list[numpy.ndarray]   ,    _lowercase    :				int     )							->	list[numpy.ndarray]:
  __UpperCAmelCase:					int		= initial_vectors
  for _ in range(_lowercase     ):
    __UpperCAmelCase:					Any		= iteration_step(_lowercase     )
  return vectors






def  UpperCamelCase__					(					_lowercase    :				list[numpy.ndarray]     )							->	list[numpy.ndarray]:
  __UpperCAmelCase:					Optional[int]		= []
  for i, start_vector in enumerate(vectors[:-1]     ):
    __UpperCAmelCase:					Union[str, Any]		= vectors[i + 1]
    new_vectors.append(_lowercase     )
    __UpperCAmelCase:					Optional[int]		= end_vector - start_vector
    new_vectors.append(start_vector + difference_vector / 3     )
    new_vectors.append(
        start_vector + difference_vector / 3 + rotate(difference_vector / 3   ,    6_0     )     )
    new_vectors.append(start_vector + difference_vector * 2 / 3     )
  new_vectors.append(vectors[-1]     )
  return new_vectors






def  UpperCamelCase__					(					_lowercase    :				numpy.ndarray   ,    _lowercase    :				float     )							->	numpy.ndarray:
  __UpperCAmelCase:					Tuple		= numpy.radians(_lowercase     )
  __UpperCAmelCase, __UpperCAmelCase:					Optional[Any]		= numpy.cos(_lowercase     ), numpy.sin(_lowercase     )
  __UpperCAmelCase:					Tuple		= numpy.array(((c, -s), (s, c))     )
  return numpy.dot(_lowercase   ,    _lowercase     )






def  UpperCamelCase__					(					_lowercase    :				list[numpy.ndarray]     )							->	None:
  __UpperCAmelCase:					Union[str, Any]		= plt.gca()
  axes.set_aspect("""equal"""     )

  # matplotlib.pyplot.plot takes a list of all x-coordinates and a list of all
  # y-coordinates as inputs, which are constructed from the vector-list using
  # zip()
  __UpperCAmelCase, __UpperCAmelCase:					Dict		= zip(*_lowercase     )
  plt.plot(_lowercase   ,    _lowercase     )
  plt.show()


if __name__ == "__main__":
    import doctest

    doctest.testmod()

    SCREAMING_SNAKE_CASE_	   =			iterate(INITIAL_VECTORS, 5)
    plot(processed_vectors)