






'''simple docstring'''


import collections
import inspect
import unittest

from transformers import DonutSwinConfig
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import is_torch_available

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 DonutSwinModel
  from transformers.models.donut.modeling_donut_swin import DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST




class 							lowerCAmelCase					:







   """simple docstring"""







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



   def    __magic_name__    ( self			)    ->   int:
    __a    :	Optional[int]									=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

    __a    :	Any									=						self.get_config()

    return config, pixel_values, labels



   def    __magic_name__    ( self			)    ->   Optional[Any]:
    return DonutSwinConfig(
        image_size=self.image_size   ,   patch_size=self.patch_size   ,   num_channels=self.num_channels   ,   embed_dim=self.embed_dim   ,   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   ,   )



   def    __magic_name__    ( self   ,   _A   ,   _A   ,   _A			)    ->   Optional[int]:
    __a    :	Optional[Any]									=						DonutSwinModel(config=_A			)
    model.to(_A			)
    model.eval()
    __a    :	int									=						model(_A			)

    __a    :	List[Any]									=						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
    __a    :	Any									=						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    __magic_name__    ( self			)    ->   str:
    __a    :	List[str]									=						self.prepare_config_and_inputs()
    (
        (
        __a
    )			,    (
        __a
    )			,    (
        __a
    )			,    
    )    :	Union[str, Any]									=						config_and_inputs
    __a    :	int									=						{'pixel_values': pixel_values}
    return config, inputs_dict




@require_torch
class 							lowerCAmelCase					(							lowerCamelCase__							,      lowerCamelCase__							,      unittest.TestCase   ):







   """simple docstring"""







   _A						=   (DonutSwinModel,) if is_torch_available() else ()
   _A						=   {'feature-extraction': DonutSwinModel} if is_torch_available() else {}
   _A						=   True

   _A						=   False
   _A						=   False
   _A						=   False



   def    __magic_name__    ( self			)    ->   List[str]:
    __a    :	Dict									=						DonutSwinModelTester(self			)
    __a    :	List[str]									=						ConfigTester(self   ,   config_class=_A   ,   embed_dim=37			)



   def    __magic_name__    ( self			)    ->   List[Any]:
    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    __magic_name__    ( self			)    ->   Union[str, Any]:
    return



   def    __magic_name__    ( self			)    ->   Optional[int]:
    __a    :	Tuple									=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*_A			)



   def    __magic_name__    ( self			)    ->   Dict:
    # DonutSwin does not use inputs_embeds
    pass



   def    __magic_name__    ( self			)    ->   Optional[Any]:
    __a			,    __a    :	int									=						self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     __a    :	Tuple									=						model_class(_A			)
     self.assertIsInstance(model.get_input_embeddings()   ,   (nn.Module)			)
     __a    :	str									=						model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(_A   ,   nn.Linear			)			)



   def    __magic_name__    ( self			)    ->   List[str]:
    __a			,    __a    :	int									=						self.model_tester.prepare_config_and_inputs_for_common()

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

     __a    :	Optional[Any]									=						['pixel_values']
     self.assertListEqual(arg_names[:1]   ,   _A			)



   def    __magic_name__    ( self			)    ->   Any:
    __a			,    __a    :	Optional[Any]									=						self.model_tester.prepare_config_and_inputs_for_common()
    __a    :	Union[str, Any]									=						True

    for model_class in self.all_model_classes:
     __a    :	List[str]									=						True
     __a    :	Any									=						False
     __a    :	Union[str, Any]									=						True
     __a    :	Union[str, Any]									=						model_class(_A			)
     model.to(_A			)
     model.eval()
     with torch.no_grad():
      __a    :	Optional[Any]									=						model(**self._prepare_for_class(_A   ,   _A			)			)
     __a    :	Dict									=						outputs.attentions
     __a    :	List[Any]									=						len(self.model_tester.depths			)
     self.assertEqual(len(_A			)   ,   _A			)

     # check that output_attentions also work using config
     del inputs_dict["output_attentions"]
     __a    :	Union[str, Any]									=						True
     __a    :	Optional[int]									=						config.window_size**2
     __a    :	List[Any]									=						model_class(_A			)
     model.to(_A			)
     model.eval()
     with torch.no_grad():
      __a    :	Union[str, Any]									=						model(**self._prepare_for_class(_A   ,   _A			)			)
     __a    :	Any									=						outputs.attentions
     self.assertEqual(len(_A			)   ,   _A			)

     self.assertListEqual(
         list(attentions[0].shape[-3:]			)   ,   [self.model_tester.num_heads[0], window_size_squared, window_size_squared]   ,   )
     __a    :	int									=						len(_A			)

     # Check attention is always last and order is fine
     __a    :	Optional[Any]									=						True
     __a    :	Dict									=						True
     __a    :	str									=						model_class(_A			)
     model.to(_A			)
     model.eval()
     with torch.no_grad():
      __a    :	Optional[int]									=						model(**self._prepare_for_class(_A   ,   _A			)			)

     if hasattr(self.model_tester   ,   'num_hidden_states_types'			):
      __a    :	str									=						self.model_tester.num_hidden_states_types
     else:
      # also another +1 for reshaped_hidden_states
      __a    :	Optional[Any]									=						2
     self.assertEqual(out_len + added_hidden_states   ,   len(_A			)			)

     __a    :	str									=						outputs.attentions

     self.assertEqual(len(_A			)   ,   _A			)

     self.assertListEqual(
         list(self_attentions[0].shape[-3:]			)   ,   [self.model_tester.num_heads[0], window_size_squared, window_size_squared]   ,   )



   def    __magic_name__    ( self   ,   _A   ,   _A   ,   _A   ,   _A			)    ->   Tuple:
    __a    :	str									=						model_class(_A			)
    model.to(_A			)
    model.eval()

    with torch.no_grad():
     __a    :	List[str]									=						model(**self._prepare_for_class(_A   ,   _A			)			)

    __a    :	Dict									=						outputs.hidden_states

    __a    :	Union[str, Any]									=						getattr(
        self.model_tester   ,   'expected_num_hidden_layers'   ,   len(self.model_tester.depths			) + 1			)
    self.assertEqual(len(_A			)   ,   _A			)

    # DonutSwin has a different seq_length
    __a    :	List[Any]									=						(
        config.patch_size
        if isinstance(config.patch_size   ,   collections.abc.Iterable			)
        else (config.patch_size, config.patch_size)
    )

    __a    :	Dict									=						(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[Any]									=						outputs.reshaped_hidden_states
    self.assertEqual(len(_A			)   ,   _A			)

    __a			,    __a			,    __a			,    __a    :	Tuple									=						reshaped_hidden_states[0].shape
    __a    :	int									=						(
        reshaped_hidden_states[0].view(_A   ,   _A   ,   height * width			).permute(0   ,   2   ,   1			)
    )
    self.assertListEqual(
        list(reshaped_hidden_states.shape[-2:]			)   ,   [num_patches, self.model_tester.embed_dim]   ,   )



   def    __magic_name__    ( self			)    ->   Tuple:
    __a			,    __a    :	List[str]									=						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:
     __a    :	Dict									=						True
     self.check_hidden_states_output(_A   ,   _A   ,   _A   ,   _A			)

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

     self.check_hidden_states_output(_A   ,   _A   ,   _A   ,   _A			)



   def    __magic_name__    ( self			)    ->   int:
    __a			,    __a    :	List[Any]									=						self.model_tester.prepare_config_and_inputs_for_common()
    __a    :	Any									=						3

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

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

    for model_class in self.all_model_classes:
     __a    :	Any									=						True
     self.check_hidden_states_output(_A   ,   _A   ,   _A   ,   (padded_height, padded_width)			)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     __a    :	Dict									=						True
     self.check_hidden_states_output(_A   ,   _A   ,   _A   ,   (padded_height, padded_width)			)



   @slow
   def    __magic_name__    ( self			)    ->   List[str]:
    for model_name in DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a    :	str									=						DonutSwinModel.from_pretrained(_A			)
     self.assertIsNotNone(_A			)



   def    __magic_name__    ( self			)    ->   int:
    __a			,    __a    :	str									=						self.model_tester.prepare_config_and_inputs_for_common()

    __a    :	List[str]									=						_config_zero_init(_A			)
    for model_class in self.all_model_classes:
     __a    :	Dict									=						model_class(config=_A			)
     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'''   ,   )












'''simple docstring'''


from __future__ import annotations

import random

from matplotlib import animation
from matplotlib import pyplot as plt

# Frame rate of the animation
SCREAMING_SNAKE_CASE_				      =							2_0

# Time between time steps in seconds
SCREAMING_SNAKE_CASE_				      =							INTERVAL / 1_0_0_0




class 							lowerCAmelCase					:







   """simple docstring"""







   def __init__( self   ,   _A   ,   _A   ,   _A   ,   _A   ,   _A = 1.0   ,   _A = 1.0   ,   _A = "blue"   ,   )    ->   None:
    __a    :	str									=						position_x
    __a    :	Optional[Any]									=						position_y
    __a    :	List[Any]									=						velocity_x
    __a    :	Tuple									=						velocity_y
    __a    :	Dict									=						mass
    __a    :	int									=						size
    __a    :	Tuple									=						color



   @property
   def    __magic_name__    ( self			)    ->   tuple[float, float]:
    return self.position_x, self.position_y



   @property
   def    __magic_name__    ( self			)    ->   tuple[float, float]:
    return self.velocity_x, self.velocity_y



   def    __magic_name__    ( self   ,   _A   ,   _A   ,   _A			)    ->   None:
    self.velocity_x += force_x * delta_time
    self.velocity_y += force_y * delta_time



   def    __magic_name__    ( self   ,   _A			)    ->   None:
    self.position_x += self.velocity_x * delta_time
    self.position_y += self.velocity_y * delta_time




class 							lowerCAmelCase					:







   """simple docstring"""







   def __init__( self   ,   _A   ,   _A = 1.0   ,   _A = 1.0   ,   _A = 0.0   ,   )    ->   None:
    __a    :	List[str]									=						bodies
    __a    :	List[str]									=						gravitation_constant
    __a    :	int									=						time_factor
    __a    :	List[str]									=						softening_factor



   def __len__( self			)    ->   int:
    return len(self.bodies			)



   def    __magic_name__    ( self   ,   _A			)    ->   None:
    for bodya in self.bodies:
     __a    :	Any									=						0.0
     __a    :	str									=						0.0
     for bodya in self.bodies:
      if bodya != bodya:
       __a    :	Optional[Any]									=						bodya.position_x - bodya.position_x
       __a    :	Dict									=						bodya.position_y - bodya.position_y

       # Calculation of the distance using Pythagoras's theorem
       # Extra factor due to the softening technique
       __a    :	Optional[Any]									=						(dif_x**2 + dif_y**2 + self.softening_factor) ** (
           1 / 2
       )

       # Newton's law of universal gravitation.
       force_x += (
           self.gravitation_constant * bodya.mass * dif_x / distance**3
       )
       force_y += (
           self.gravitation_constant * bodya.mass * dif_y / distance**3
       )

            # Update the body's velocity once all the force components have been added
     bodya.update_velocity(_A   ,   _A   ,   delta_time * self.time_factor			)

    # Update the positions only after all the velocities have been updated
    for body in self.bodies:
     body.update_position(delta_time * self.time_factor			)






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		):
 body_system.update_system(SCREAMING_SNAKE_CASE__		)

 # Update the positions of the patches
 for patch, body in zip(SCREAMING_SNAKE_CASE__       ,		body_system.bodies		):
  __a    :	Dict									=						(body.position_x, body.position_y)






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__ = -1       ,		SCREAMING_SNAKE_CASE__ = 1       ,		SCREAMING_SNAKE_CASE__ = -1       ,		SCREAMING_SNAKE_CASE__ = 1       ,		):
 __a    :	int									=						plt.figure()
 fig.canvas.set_window_title(SCREAMING_SNAKE_CASE__		)
 __a    :	int									=						plt.axes(
     xlim=(x_start, x_end)       ,		ylim=(y_start, y_end)		)  # Set section to be plotted
 plt.gca().set_aspect('equal'		)  # Fix aspect ratio

 # Each body is drawn as a patch by the plt-function
 __a    :	str									=						[
     plt.Circle((body.position_x, body.position_y)       ,		body.size       ,		fc=body.color		)
     for body in body_system.bodies
 ]

 for patch in patches:
  ax.add_patch(SCREAMING_SNAKE_CASE__		)

 # Function called at each step of the animation
 def update(SCREAMING_SNAKE_CASE__		) -> list[plt.Circle]:
  update_step(SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		)
  return patches

 __a    :	Dict									=						animation.FuncAnimation(  # noqa: F841
     SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		interval=SCREAMING_SNAKE_CASE__       ,		blit=SCREAMING_SNAKE_CASE__		)

 plt.show()






def   lowerCAmelCase__			(					):
 __a    :	Dict									=						0.970_0436
 __a    :	List[Any]									=						-0.2430_8753
 __a    :	Union[str, Any]									=						0.4_6620_3685
 __a    :	Any									=						0.4323_6573

 __a    :	Optional[int]									=						[
     Body(SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		size=0.2       ,		color='red'		),
     Body(-position_x       ,		-position_y       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		size=0.2       ,		color='green'		),
     Body(0       ,		0       ,		-2 * velocity_x       ,		-2 * velocity_y       ,		size=0.2       ,		color='blue'		),
 ]
 return BodySystem(SCREAMING_SNAKE_CASE__       ,		time_factor=3		)






def   lowerCAmelCase__			(					):
 __a    :	Optional[int]									=						7.34_76E22
 __a    :	List[Any]									=						5.9_72E24
 __a    :	List[Any]									=						1022
 __a    :	str									=						384399000
 __a    :	Optional[int]									=						6.6_74E-11

 # Calculation of the respective velocities so that total impulse is zero,
 # i.e. the two bodies together don't move
 __a    :	str									=						earth_mass * velocity_dif / (earth_mass + moon_mass)
 __a    :	Optional[int]									=						moon_velocity - velocity_dif

 __a    :	Union[str, Any]									=						Body(-earth_moon_distance       ,		0       ,		0       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		10000000       ,		'grey'		)
 __a    :	Union[str, Any]									=						Body(0       ,		0       ,		0       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		50000000       ,		'blue'		)
 return BodySystem([earth, moon]       ,		SCREAMING_SNAKE_CASE__       ,		time_factor=1000000		)






def   lowerCAmelCase__			(					):
 __a    :	Tuple									=						[]
 for _ in range(10		):
  __a    :	Dict									=						random.uniform(-0.5       ,		0.5		)
  __a    :	Optional[int]									=						random.uniform(-0.5       ,		0.5		)

  # Bodies are created pairwise with opposite velocities so that the
  # total impulse remains zero
  bodies.append(
      Body(
          random.uniform(-0.5       ,		0.5		)       ,		random.uniform(-0.5       ,		0.5		)       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		size=0.05       ,		)		)
  bodies.append(
      Body(
          random.uniform(-0.5       ,		0.5		)       ,		random.uniform(-0.5       ,		0.5		)       ,		-velocity_x       ,		-velocity_y       ,		size=0.05       ,		)		)
 return BodySystem(SCREAMING_SNAKE_CASE__       ,		0.01       ,		10       ,		0.1		)


if __name__ == "__main__":
  plot("Figure-8 solution to the 3-body-problem", example_a(), -2, 2, -2, 2)
  plot(
      "Moon's orbit around the earth",
      example_a(),
      -4_3_0_0_0_0_0_0_0,
      4_3_0_0_0_0_0_0_0,
      -4_3_0_0_0_0_0_0_0,
      4_3_0_0_0_0_0_0_0,
  )
  plot("Random system with many bodies", example_a(), -1.5, 1.5, -1.5, 1.5)




