


"""simple docstring"""







import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_=False     ):




					'''simple docstring'''


					try:
										__SCREAMING_SNAKE_CASE		     =       os.environ[key]
					except KeyError:
										# KEY isn't set, default to `default`.
										__SCREAMING_SNAKE_CASE		     =       default
					else:
										# KEY is set, convert it to True or False.
										try:
															__SCREAMING_SNAKE_CASE		     =       strtobool(lowerCAmelCase_     )
										except ValueError:
															# More values are supported, but let's keep the message simple.
															raise ValueError(f"""If set, {key} must be yes or no."""     )
					return _value


a__       :							Optional[int]        =  parse_flag_from_env('''RUN_SLOW''', default=False)




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skip("Test was skipped"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(_run_slow_tests						,		"test is slow"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(not torch.cuda.is_available()						,		"test requires only a CPU"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(torch.cuda.is_available()						,		"test requires a GPU"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_xpu_available()						,		"test requires a XPU"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_mps_available()						,		"test requires a `mps` backend support in `torch`"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(
					    is_transformers_available() and is_datasets_available()						,		"test requires the Hugging Face suite"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_bnb_available()						,		"test requires the bitsandbytes library"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_tpu_available()						,		"test requires TPU"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(torch.cuda.device_count() == 1						,		"test requires a GPU"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(torch.xpu.device_count() == 1						,		"test requires a XPU"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(torch.cuda.device_count() > 1						,		"test requires multiple GPUs"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(torch.xpu.device_count() > 1						,		"test requires multiple XPUs"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_safetensors_available()						,		"test requires safetensors"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_deepspeed_available()						,		"test requires DeepSpeed"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_torch_version(">="						,		"1.12.0"     )						,		"test requires torch version >= 1.12.0"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_=None						,		lowerCAmelCase_=None     ):




					'''simple docstring'''


					if test_case is None:
										return partial(lowerCAmelCase_						,		version=lowerCAmelCase_     )
					return unittest.skipUnless(is_torch_version(">="						,		lowerCAmelCase_     )						,		f"""test requires torch version >= {version}"""     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_tensorboard_available()						,		"test requires Tensorboard"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_wandb_available()						,		"test requires wandb"     )(lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(is_comet_ml_available()						,		"test requires comet_ml"     )(lowerCAmelCase_     )


a__       :							List[Any]        =  (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					return unittest.skipUnless(
					    _atleast_one_tracker_available						,		"test requires at least one tracker to be available and for `comet_ml` to not be installed"						,		)(lowerCAmelCase_     )




class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	snake_case__       :						Any					      =    True




	@classmethod
	def 						UpperCAmelCase_   (				cls    :       List[Any]     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE		     =       tempfile.mkdtemp()




	@classmethod
	def 						UpperCAmelCase_   (				cls    :       Union[str, Any]     ) ->			str:
						if os.path.exists(cls.tmpdir     ):
											shutil.rmtree(cls.tmpdir     )




	def 						UpperCAmelCase_   (				self    :       List[Any]     ) ->			Any:
						if self.clear_on_setup:
											for path in Path(self.tmpdir     ).glob("**/*"     ):
																if path.is_file():
																					path.unlink()
																elif path.is_dir():
																					shutil.rmtree(UpperCAmelCase__     )




class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	def 						UpperCAmelCase_   (				self    :       Optional[int]     ) ->			str:
						super().tearDown()
						# Reset the state of the AcceleratorState singleton.
						AcceleratorState._reset_state()
						PartialState._reset_state()




class 				UpperCamelCase_			(				unittest.TestCase):

	"""simple docstring"""





	def 						UpperCAmelCase_   (				self    :       Any    ,    UpperCAmelCase__    :       Union[mock.Mock, List[mock.Mock]]     ) ->			Union[str, Any]:
						__SCREAMING_SNAKE_CASE		     =       mocks if isinstance(UpperCAmelCase__    ,    (tuple, list)     ) else [mocks]
						for m in self.mocks:
											m.start()
											self.addCleanup(m.stop     )




def      UpperCAmelCase__ (lowerCAmelCase_     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       AcceleratorState()
					__SCREAMING_SNAKE_CASE		     =       tensor[None].clone().to(state.device     )
					__SCREAMING_SNAKE_CASE		     =       gather(lowerCAmelCase_     ).cpu()
					__SCREAMING_SNAKE_CASE		     =       tensor[0].cpu()
					for i in range(tensors.shape[0]     ):
										if not torch.equal(tensors[i]						,		lowerCAmelCase_     ):
															return False
					return True




class 				UpperCamelCase_			:

	"""simple docstring"""





	def __init__(				self    :       int    ,    UpperCAmelCase__    :       str    ,    UpperCAmelCase__    :       List[str]    ,    UpperCAmelCase__    :       Optional[int]     ) ->			str:
						__SCREAMING_SNAKE_CASE		     =       returncode
						__SCREAMING_SNAKE_CASE		     =       stdout
						__SCREAMING_SNAKE_CASE		     =       stderr




async def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_     ):




					'''simple docstring'''


					while True:
										__SCREAMING_SNAKE_CASE		     =       await stream.readline()
										if line:
															callback(lowerCAmelCase_     )
										else:
															break




async def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_=None						,		lowerCAmelCase_=None						,		lowerCAmelCase_=None						,		lowerCAmelCase_=False						,		lowerCAmelCase_=False     ):




					'''simple docstring'''


					if echo:
										print("\nRunning: "						,		" ".join(lowerCAmelCase_     )     )

					__SCREAMING_SNAKE_CASE		     =       await asyncio.create_subprocess_exec(
					    cmd[0]						,		*cmd[1:]						,		stdin=lowerCAmelCase_						,		stdout=asyncio.subprocess.PIPE						,		stderr=asyncio.subprocess.PIPE						,		env=lowerCAmelCase_						,		)

					# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
					# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
					#
					# If it starts hanging, will need to switch to the following code. The problem is that no data
					# will be seen until it's done and if it hangs for example there will be no debug info.
					# out, err = await p.communicate()
					# return _RunOutput(p.returncode, out, err)

					__SCREAMING_SNAKE_CASE		     =       []
					__SCREAMING_SNAKE_CASE		     =       []

					def tee(lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_=""     ):
										__SCREAMING_SNAKE_CASE		     =       line.decode("utf-8"     ).rstrip()
										sink.append(lowerCAmelCase_     )
										if not quiet:
															print(lowerCAmelCase_						,		lowerCAmelCase_						,		file=lowerCAmelCase_     )

    # XXX: the timeout doesn't seem to make any difference here
					await asyncio.wait(
					    [
					        asyncio.create_task(_read_stream(p.stdout						,		lambda lowerCAmelCase_     : tee(lowerCAmelCase_						,		lowerCAmelCase_						,		sys.stdout						,		label="stdout:"     )     )     ),
					        asyncio.create_task(_read_stream(p.stderr						,		lambda lowerCAmelCase_     : tee(lowerCAmelCase_						,		lowerCAmelCase_						,		sys.stderr						,		label="stderr:"     )     )     ),
					    ]						,		timeout=lowerCAmelCase_						,		)
					return _RunOutput(await p.wait()						,		lowerCAmelCase_						,		lowerCAmelCase_     )




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_=None						,		lowerCAmelCase_=None						,		lowerCAmelCase_=180						,		lowerCAmelCase_=False						,		lowerCAmelCase_=True     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       asyncio.get_event_loop()
					__SCREAMING_SNAKE_CASE		     =       loop.run_until_complete(
					    _stream_subprocess(lowerCAmelCase_						,		env=lowerCAmelCase_						,		stdin=lowerCAmelCase_						,		timeout=lowerCAmelCase_						,		quiet=lowerCAmelCase_						,		echo=lowerCAmelCase_     )     )

					__SCREAMING_SNAKE_CASE		     =       " ".join(lowerCAmelCase_     )
					if result.returncode > 0:
										__SCREAMING_SNAKE_CASE		     =       "\n".join(result.stderr     )
										raise RuntimeError(
										    f"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
										    f"""The combined stderr from workers follows:\n{stderr}"""     )

					return result




class 				UpperCamelCase_			(				UpperCamelCase):

	"""simple docstring"""





	pass




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_=False     ):




					'''simple docstring'''


					try:
										__SCREAMING_SNAKE_CASE		     =       subprocess.check_output(lowerCAmelCase_						,		stderr=subprocess.STDOUT     )
										if return_stdout:
															if hasattr(lowerCAmelCase_						,		"decode"     ):
																				__SCREAMING_SNAKE_CASE		     =       output.decode("utf-8"     )
															return output
					except subprocess.CalledProcessError as e:
										raise SubprocessCallException(
										    f"""Command `{' '.join(lowerCAmelCase_     )}` failed with the following error:\n\n{e.output.decode()}"""     ) from e




"""simple docstring"""







from math import asin, atan, cos, radians, sin, sqrt, tan

a__       :							List[str]        =  6_37_81_37.0
a__       :							Tuple        =  6_35_67_52.31_42_45
a__       :							str        =  6_3_7_8_1_3_7




def      UpperCAmelCase__ (lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_						,		lowerCAmelCase_     ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE		     =       (AXIS_A - AXIS_B) / AXIS_A
					__SCREAMING_SNAKE_CASE		     =       atan((1 - flattening) * tan(radians(lowerCAmelCase_     )     )     )
					__SCREAMING_SNAKE_CASE		     =       atan((1 - flattening) * tan(radians(lowerCAmelCase_     )     )     )
					__SCREAMING_SNAKE_CASE		     =       radians(lowerCAmelCase_     )
					__SCREAMING_SNAKE_CASE		     =       radians(lowerCAmelCase_     )
					# Equation
					__SCREAMING_SNAKE_CASE		     =       sin((phi_a - phi_a) / 2     )
					__SCREAMING_SNAKE_CASE		     =       sin((lambda_a - lambda_a) / 2     )
					# Square both values
					sin_sq_phi *= sin_sq_phi
					sin_sq_lambda *= sin_sq_lambda
					__SCREAMING_SNAKE_CASE		     =       sqrt(sin_sq_phi + (cos(lowerCAmelCase_     ) * cos(lowerCAmelCase_     ) * sin_sq_lambda)     )
					return 2 * RADIUS * asin(lowerCAmelCase_     )


if __name__ == "__main__":
		import doctest

		doctest.testmod()
