






'''simple docstring'''
import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
  from transformers.trainer import DEFAULT_CALLBACKS

  from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel






class   __SCREAMING_SNAKE_CASE   (      a__					):




 def __init__(   self						:				Dict   )						->    Any:
       SCREAMING_SNAKE_CASE__  :					List[Any]						=[]




 def   __magic_name__						(   self						:				Union[str, Any]       ,   __lowercase						:				Dict       ,   __lowercase						:				int       ,   __lowercase						:				int       ,   **__lowercase						:				Union[str, Any]   )						->    List[Any]:
       self.events.append('''on_init_end'''   )




 def   __magic_name__						(   self						:				List[str]       ,   __lowercase						:				Dict       ,   __lowercase						:				Any       ,   __lowercase						:				Any       ,   **__lowercase						:				Optional[Any]   )						->    List[Any]:
       self.events.append('''on_train_begin'''   )




 def   __magic_name__						(   self						:				str       ,   __lowercase						:				str       ,   __lowercase						:				List[Any]       ,   __lowercase						:				Dict       ,   **__lowercase						:				Dict   )						->    List[Any]:
       self.events.append('''on_train_end'''   )




 def   __magic_name__						(   self						:				str       ,   __lowercase						:				Optional[Any]       ,   __lowercase						:				Optional[Any]       ,   __lowercase						:				str       ,   **__lowercase						:				str   )						->    Tuple:
       self.events.append('''on_epoch_begin'''   )




 def   __magic_name__						(   self						:				Union[str, Any]       ,   __lowercase						:				Dict       ,   __lowercase						:				List[str]       ,   __lowercase						:				int       ,   **__lowercase						:				Optional[int]   )						->    Optional[int]:
       self.events.append('''on_epoch_end'''   )




 def   __magic_name__						(   self						:				int       ,   __lowercase						:				Any       ,   __lowercase						:				Dict       ,   __lowercase						:				Tuple       ,   **__lowercase						:				List[str]   )						->    List[str]:
       self.events.append('''on_step_begin'''   )




 def   __magic_name__						(   self						:				Any       ,   __lowercase						:				Dict       ,   __lowercase						:				Union[str, Any]       ,   __lowercase						:				Union[str, Any]       ,   **__lowercase						:				Optional[Any]   )						->    Tuple:
       self.events.append('''on_step_end'''   )




 def   __magic_name__						(   self						:				List[str]       ,   __lowercase						:				Union[str, Any]       ,   __lowercase						:				Tuple       ,   __lowercase						:				Tuple       ,   **__lowercase						:				List[str]   )						->    Dict:
       self.events.append('''on_evaluate'''   )




 def   __magic_name__						(   self						:				Union[str, Any]       ,   __lowercase						:				Optional[Any]       ,   __lowercase						:				Any       ,   __lowercase						:				Dict       ,   **__lowercase						:				List[Any]   )						->    Dict:
       self.events.append('''on_predict'''   )




 def   __magic_name__						(   self						:				List[str]       ,   __lowercase						:				str       ,   __lowercase						:				Dict       ,   __lowercase						:				str       ,   **__lowercase						:				Any   )						->    Tuple:
       self.events.append('''on_save'''   )




 def   __magic_name__						(   self						:				Dict       ,   __lowercase						:				Optional[Any]       ,   __lowercase						:				Tuple       ,   __lowercase						:				Dict       ,   **__lowercase						:				Optional[Any]   )						->    Tuple:
       self.events.append('''on_log'''   )




 def   __magic_name__						(   self						:				str       ,   __lowercase						:				Any       ,   __lowercase						:				List[str]       ,   __lowercase						:				List[Any]       ,   **__lowercase						:				int   )						->    List[str]:
       self.events.append('''on_prediction_step'''   )






@require_torch
class   __SCREAMING_SNAKE_CASE   (      unittest.TestCase					):




 def   __magic_name__						(   self						:				Optional[Any]   )						->    str:
       SCREAMING_SNAKE_CASE__  :					Union[str, Any]						=tempfile.mkdtemp()




 def   __magic_name__						(   self						:				Dict   )						->    Union[str, Any]:
       shutil.rmtree(self.output_dir   )




 def   __magic_name__						(   self						:				Tuple       ,   __lowercase						:				Any=0       ,   __lowercase						:				Optional[int]=0       ,   __lowercase						:				Optional[int]=64       ,   __lowercase						:				str=64       ,   __lowercase						:				Tuple=None       ,   __lowercase						:				Optional[int]=False       ,   **__lowercase						:				Dict   )						->    List[str]:
       # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure
       # its set to False since the tests later on depend on its value.
       SCREAMING_SNAKE_CASE__  :					Optional[int]						=RegressionDataset(length=lowerCAmelCase__   )
       SCREAMING_SNAKE_CASE__  :					List[str]						=RegressionDataset(length=lowerCAmelCase__   )
       SCREAMING_SNAKE_CASE__  :					int						=RegressionModelConfig(a=lowerCAmelCase__       ,   b=lowerCAmelCase__   )
       SCREAMING_SNAKE_CASE__  :					str						=RegressionPreTrainedModel(lowerCAmelCase__   )

       SCREAMING_SNAKE_CASE__  :					str						=TrainingArguments(self.output_dir       ,   disable_tqdm=lowerCAmelCase__       ,   report_to=[]       ,   **lowerCAmelCase__   )
       return Trainer(
           lowerCAmelCase__       ,   lowerCAmelCase__       ,   train_dataset=lowerCAmelCase__       ,   eval_dataset=lowerCAmelCase__       ,   callbacks=lowerCAmelCase__       ,   )




 def   __magic_name__						(   self						:				Union[str, Any]       ,   __lowercase						:				Union[str, Any]       ,   __lowercase						:				List[Any]   )						->    Optional[int]:
       self.assertEqual(len(lowerCAmelCase__   )       ,   len(lowerCAmelCase__   )   )

       # Order doesn't matter
       SCREAMING_SNAKE_CASE__  :					Union[str, Any]						=sorted(lowerCAmelCase__       ,   key=lambda __lowercase   : cb.__name__ if isinstance(lowerCAmelCase__       ,   lowerCAmelCase__   ) else cb.__class__.__name__   )
       SCREAMING_SNAKE_CASE__  :					Any						=sorted(lowerCAmelCase__       ,   key=lambda __lowercase   : cb.__name__ if isinstance(lowerCAmelCase__       ,   lowerCAmelCase__   ) else cb.__class__.__name__   )

       for cba, cba in zip(lowerCAmelCase__       ,   lowerCAmelCase__   ):
             if isinstance(lowerCAmelCase__       ,   lowerCAmelCase__   ) and isinstance(lowerCAmelCase__       ,   lowerCAmelCase__   ):
                   self.assertEqual(lowerCAmelCase__       ,   lowerCAmelCase__   )
             elif isinstance(lowerCAmelCase__       ,   lowerCAmelCase__   ) and not isinstance(lowerCAmelCase__       ,   lowerCAmelCase__   ):
                   self.assertEqual(lowerCAmelCase__       ,   cba.__class__   )
             elif not isinstance(lowerCAmelCase__       ,   lowerCAmelCase__   ) and isinstance(lowerCAmelCase__       ,   lowerCAmelCase__   ):
                   self.assertEqual(cba.__class__       ,   lowerCAmelCase__   )
             else:
                   self.assertEqual(lowerCAmelCase__       ,   lowerCAmelCase__   )




 def   __magic_name__						(   self						:				Union[str, Any]       ,   __lowercase						:				Dict   )						->    Tuple:
       SCREAMING_SNAKE_CASE__  :					List[str]						=["on_init_end", "on_train_begin"]
       SCREAMING_SNAKE_CASE__  :					str						=0
       SCREAMING_SNAKE_CASE__  :					List[str]						=len(trainer.get_eval_dataloader()   )
       SCREAMING_SNAKE_CASE__  :					List[str]						=["on_prediction_step"] * len(trainer.get_eval_dataloader()   ) + ["on_log", "on_evaluate"]
       for _ in range(trainer.state.num_train_epochs   ):
             expected_events.append('''on_epoch_begin'''   )
             for _ in range(lowerCAmelCase__   ):
                   step += 1
                   expected_events += ["on_step_begin", "on_step_end"]
                   if step % trainer.args.logging_steps == 0:
                         expected_events.append('''on_log'''   )
                   if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
                         expected_events += evaluation_events.copy()
                   if step % trainer.args.save_steps == 0:
                         expected_events.append('''on_save'''   )
             expected_events.append('''on_epoch_end'''   )
             if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
                   expected_events += evaluation_events.copy()
       expected_events += ["on_log", "on_train_end"]
       return expected_events




 def   __magic_name__						(   self						:				List[Any]   )						->    Any:
       SCREAMING_SNAKE_CASE__  :					Union[str, Any]						=self.get_trainer()
       SCREAMING_SNAKE_CASE__  :					Dict						=DEFAULT_CALLBACKS.copy() + [ProgressCallback]
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )

       # Callbacks passed at init are added to the default callbacks
       SCREAMING_SNAKE_CASE__  :					Optional[int]						=self.get_trainer(callbacks=[MyTestTrainerCallback]   )
       expected_callbacks.append(lowerCAmelCase__   )
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )

       # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
       SCREAMING_SNAKE_CASE__  :					List[str]						=self.get_trainer(disable_tqdm=lowerCAmelCase__   )
       SCREAMING_SNAKE_CASE__  :					Optional[int]						=DEFAULT_CALLBACKS.copy() + [PrinterCallback]
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )




 def   __magic_name__						(   self						:				Dict   )						->    Any:
       SCREAMING_SNAKE_CASE__  :					List[Any]						=DEFAULT_CALLBACKS.copy() + [ProgressCallback]
       SCREAMING_SNAKE_CASE__  :					Tuple						=self.get_trainer()

       # We can add, pop, or remove by class name
       trainer.remove_callback(lowerCAmelCase__   )
       expected_callbacks.remove(lowerCAmelCase__   )
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )

       SCREAMING_SNAKE_CASE__  :					List[str]						=self.get_trainer()
       SCREAMING_SNAKE_CASE__  :					int						=trainer.pop_callback(lowerCAmelCase__   )
       self.assertEqual(cb.__class__       ,   lowerCAmelCase__   )
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )

       trainer.add_callback(lowerCAmelCase__   )
       expected_callbacks.insert(0       ,   lowerCAmelCase__   )
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )

       # We can also add, pop, or remove by instance
       SCREAMING_SNAKE_CASE__  :					List[str]						=self.get_trainer()
       SCREAMING_SNAKE_CASE__  :					List[str]						=trainer.callback_handler.callbacks[0]
       trainer.remove_callback(lowerCAmelCase__   )
       expected_callbacks.remove(lowerCAmelCase__   )
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )

       SCREAMING_SNAKE_CASE__  :					List[str]						=self.get_trainer()
       SCREAMING_SNAKE_CASE__  :					Optional[Any]						=trainer.callback_handler.callbacks[0]
       SCREAMING_SNAKE_CASE__  :					Union[str, Any]						=trainer.pop_callback(lowerCAmelCase__   )
       self.assertEqual(lowerCAmelCase__       ,   lowerCAmelCase__   )
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )

       trainer.add_callback(lowerCAmelCase__   )
       expected_callbacks.insert(0       ,   lowerCAmelCase__   )
       self.check_callbacks_equality(trainer.callback_handler.callbacks       ,   lowerCAmelCase__   )




 def   __magic_name__						(   self						:				Any   )						->    Optional[int]:
       import warnings

       # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
       warnings.simplefilter(action='''ignore'''       ,   category=lowerCAmelCase__   )

       SCREAMING_SNAKE_CASE__  :					Optional[int]						=self.get_trainer(callbacks=[MyTestTrainerCallback]   )
       trainer.train()
       SCREAMING_SNAKE_CASE__  :					Optional[Any]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(lowerCAmelCase__       ,   self.get_expected_events(lowerCAmelCase__   )   )

       # Independent log/save/eval
       SCREAMING_SNAKE_CASE__  :					Tuple						=self.get_trainer(callbacks=[MyTestTrainerCallback]       ,   logging_steps=5   )
       trainer.train()
       SCREAMING_SNAKE_CASE__  :					Optional[int]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(lowerCAmelCase__       ,   self.get_expected_events(lowerCAmelCase__   )   )

       SCREAMING_SNAKE_CASE__  :					Tuple						=self.get_trainer(callbacks=[MyTestTrainerCallback]       ,   save_steps=5   )
       trainer.train()
       SCREAMING_SNAKE_CASE__  :					Tuple						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(lowerCAmelCase__       ,   self.get_expected_events(lowerCAmelCase__   )   )

       SCREAMING_SNAKE_CASE__  :					List[str]						=self.get_trainer(callbacks=[MyTestTrainerCallback]       ,   eval_steps=5       ,   evaluation_strategy='''steps'''   )
       trainer.train()
       SCREAMING_SNAKE_CASE__  :					Tuple						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(lowerCAmelCase__       ,   self.get_expected_events(lowerCAmelCase__   )   )

       SCREAMING_SNAKE_CASE__  :					Optional[Any]						=self.get_trainer(callbacks=[MyTestTrainerCallback]       ,   evaluation_strategy='''epoch'''   )
       trainer.train()
       SCREAMING_SNAKE_CASE__  :					List[str]						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(lowerCAmelCase__       ,   self.get_expected_events(lowerCAmelCase__   )   )

       # A bit of everything
       SCREAMING_SNAKE_CASE__  :					List[str]						=self.get_trainer(
           callbacks=[MyTestTrainerCallback]       ,   logging_steps=3       ,   save_steps=10       ,   eval_steps=5       ,   evaluation_strategy='''steps'''       ,   )
       trainer.train()
       SCREAMING_SNAKE_CASE__  :					int						=trainer.callback_handler.callbacks[-2].events
       self.assertEqual(lowerCAmelCase__       ,   self.get_expected_events(lowerCAmelCase__   )   )

       # warning should be emitted for duplicated callbacks
       with patch('''transformers.trainer_callback.logger.warning'''   ) as warn_mock:
             SCREAMING_SNAKE_CASE__  :					int						=self.get_trainer(
                 callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]       ,   )
             assert str(lowerCAmelCase__   ) in warn_mock.call_args[0][0]






"""simple docstring"""




from __future__ import annotations

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

# initial triangle of Koch snowflake
a		:					int	      =     numpy.array([0, 0])
a		:					Optional[Any]	      =     numpy.array([0.5, 0.866_0254])
a		:					Tuple	      =     numpy.array([1, 0])
a		:					List[str]	      =     [VECTOR_1, VECTOR_2, VECTOR_3, VECTOR_1]






def  _SCREAMING_SNAKE_CASE						(      _lowercase		:       list[numpy.ndarray]       ,			_lowercase		:       int   )					->list[numpy.ndarray]:






	'''simple docstring'''






	a :						List[str]      =							initial_vectors
	for _ in range(_lowercase   ):
		a :						Optional[Any]      =							iteration_step(_lowercase   )
	return vectors






def  _SCREAMING_SNAKE_CASE						(      _lowercase		:       list[numpy.ndarray]   )					->list[numpy.ndarray]:






	'''simple docstring'''






	a :						Union[str, Any]      =							[]
	for i, start_vector in enumerate(vectors[:-1]   ):
		a :						str      =							vectors[i + 1]
		new_vectors.append(_lowercase   )
		a :						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       ,			60   )   )
		new_vectors.append(start_vector + difference_vector * 2 / 3   )
	new_vectors.append(vectors[-1]   )
	return new_vectors






def  _SCREAMING_SNAKE_CASE						(      _lowercase		:       numpy.ndarray       ,			_lowercase		:       float   )					->numpy.ndarray:






	'''simple docstring'''






	a :						int      =							numpy.radians(_lowercase   )
	a,			a :						Optional[int]      =							numpy.cos(_lowercase   ), numpy.sin(_lowercase   )
	a :						Dict      =							numpy.array(((c, -s), (s, c))   )
	return numpy.dot(_lowercase       ,			_lowercase   )






def  _SCREAMING_SNAKE_CASE						(      _lowercase		:       list[numpy.ndarray]   )					->None:






	'''simple docstring'''






	a :						Dict      =							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()
	a,			a :						Any      =							zip(*_lowercase   )
	plt.plot(_lowercase       ,			_lowercase   )
	plt.show()


if __name__ == "__main__":
		import doctest

		doctest.testmod()

		a		:					Optional[int]	      =     iterate(INITIAL_VECTORS, 5)
		plot(processed_vectors)


