





'''simple docstring'''







import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock

import torch

from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config


# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)

lowerCAmelCase_   :       List[Any]       =     [
    'cross_validation.py',
    'gradient_accumulation.py',
    'local_sgd.py',
    'multi_process_metrics.py',
    'memory.py',
    'automatic_gradient_accumulation.py',
    'fsdp_with_peak_mem_tracking.py',
    'deepspeed_with_config_support.py',
    'megatron_lm_gpt_pretraining.py',
]
class 							__SCREAMING_SNAKE_CASE    (unittest.TestCase ):






				"""simple docstring"""







				def     UpperCamelCase__  (    self	:   Any   ,							__a	:   str   ,							__a	:   Union[str, Any]   ,							__a	:   Any = None   ,							__a	:   Optional[int] = None   ):
								_a				      =					None
								_a				      =					os.path.abspath(os.path.join("examples"   ,							"by_feature"   )   )
								_a				      =					os.path.abspath("examples"   )
								for item in os.listdir(__a   ):
												if item not in EXCLUDE_EXAMPLES:
																_a				      =					os.path.join(__a   ,							__a   )
																if os.path.isfile(__a   ) and ".py" in item_path:
																				with self.subTest(
																				    tested_script=__a   ,							feature_script=__a   ,							tested_section="main()" if parser_only else "training_function()"   ,							):
																								_a				      =					compare_against_test(
																								    os.path.join(__a   ,							__a   )   ,							__a   ,							__a   ,							__a   )
																								_a				      =					"\n".join(__a   )
																								if special_strings is not None:
																												for string in special_strings:
																																_a				      =					diff.replace(__a   ,							""   )
																								self.assertEqual(__a   ,							""   )




				def     UpperCamelCase__  (    self	:   Optional[int]   ):
								self.one_complete_example("complete_nlp_example.py"   ,							__a   )
								self.one_complete_example("complete_nlp_example.py"   ,							__a   )




				def     UpperCamelCase__  (    self	:   List[str]   ):
								_a				      =					os.path.abspath(os.path.join("examples"   ,							"cv_example.py"   )   )
								_a				      =					[
								    " " * 16 + "{\n\n",
								    " " * 20 + "\"accuracy\": eval_metric[\"accuracy\"],\n\n",
								    " " * 20 + "\"f1\": eval_metric[\"f1\"],\n\n",
								    " " * 20 + "\"train_loss\": total_loss.item() / len(train_dataloader),\n\n",
								    " " * 20 + "\"epoch\": epoch,\n\n",
								    " " * 16 + "},\n\n",
								    " " * 16 + "step=epoch,\n",
								    " " * 12,
								    " " * 8 + "for step, batch in enumerate(active_dataloader):\n",
								]
								self.one_complete_example("complete_cv_example.py"   ,							__a   ,							__a   ,							__a   )
								self.one_complete_example("complete_cv_example.py"   ,							__a   ,							__a   ,							__a   )


@mock.patch.dict(os.environ			,				{'TESTING_MOCKED_DATALOADERS': '1'} )
class 							__SCREAMING_SNAKE_CASE    (_UpperCAmelCase ):






				"""simple docstring"""







				__a  =False




				@classmethod
				def     UpperCamelCase__  (    cls	:   Dict   ):
								super().setUpClass()
								_a				      =					tempfile.mkdtemp()
								_a				      =					os.path.join(cls._tmpdir   ,							"default_config.yml"   )

								write_basic_config(save_location=cls.configPath   )
								_a				      =					["accelerate", "launch", "--config_file", cls.configPath]




				@classmethod
				def     UpperCamelCase__  (    cls	:   Tuple   ):
								super().tearDownClass()
								shutil.rmtree(cls._tmpdir   )




				def     UpperCamelCase__  (    self	:   List[str]   ):
								_a				      =					f'\n        examples/by_feature/checkpointing.py\n        --checkpointing_steps epoch\n        --output_dir {self.tmpdir}\n        '.split()
								run_command(self._launch_args + testargs   )
								self.assertTrue(os.path.exists(os.path.join(self.tmpdir   ,							"epoch_0"   )   )   )




				def     UpperCamelCase__  (    self	:   int   ):
								_a				      =					f'\n        examples/by_feature/checkpointing.py\n        --checkpointing_steps 1\n        --output_dir {self.tmpdir}\n        '.split()
								_a				      =					run_command(self._launch_args + testargs   )
								self.assertTrue(os.path.exists(os.path.join(self.tmpdir   ,							"step_2"   )   )   )




				def     UpperCamelCase__  (    self	:   Optional[int]   ):
								_a				      =					f'\n        examples/by_feature/checkpointing.py\n        --resume_from_checkpoint {os.path.join(self.tmpdir   ,							"epoch_0"   )}\n        '.split()
								_a				      =					run_command(self._launch_args + testargs   ,							return_stdout=__a   )
								self.assertNotIn("epoch 0:"   ,							__a   )
								self.assertIn("epoch 1:"   ,							__a   )




				def     UpperCamelCase__  (    self	:   Union[str, Any]   ):
								_a				      =					f'\n        examples/by_feature/checkpointing.py\n        --resume_from_checkpoint {os.path.join(self.tmpdir   ,							"step_2"   )}\n        '.split()
								_a				      =					run_command(self._launch_args + testargs   ,							return_stdout=__a   )
								if torch.cuda.is_available():
												_a				      =					torch.cuda.device_count()
								else:
												_a				      =					1
								if num_processes > 1:
												self.assertNotIn("epoch 0:"   ,							__a   )
												self.assertIn("epoch 1:"   ,							__a   )
								else:
												self.assertIn("epoch 0:"   ,							__a   )
												self.assertIn("epoch 1:"   ,							__a   )




				@slow
				def     UpperCamelCase__  (    self	:   Dict   ):
								_a				      =					"\n        examples/by_feature/cross_validation.py\n        --num_folds 2\n        ".split()
								with mock.patch.dict(os.environ   ,							{"TESTING_MOCKED_DATALOADERS": "0"}   ):
												_a				      =					run_command(self._launch_args + testargs   ,							return_stdout=__a   )
												_a				      =					re.findall("({.+})"   ,							__a   )
												_a				      =					[r for r in results if "accuracy" in r][-1]
												_a				      =					ast.literal_eval(__a   )
												self.assertGreaterEqual(results["accuracy"]   ,							0.75   )




				def     UpperCamelCase__  (    self	:   Tuple   ):
								_a				      =					["examples/by_feature/multi_process_metrics.py"]
								run_command(self._launch_args + testargs   )




				@require_trackers
				@mock.patch.dict(os.environ   ,							{"WANDB_MODE": "offline"}   )
				def     UpperCamelCase__  (    self	:   Any   ):
								with tempfile.TemporaryDirectory() as tmpdir:
												_a				      =					f'\n            examples/by_feature/tracking.py\n            --with_tracking\n            --project_dir {tmpdir}\n            '.split()
												run_command(self._launch_args + testargs   )
												self.assertTrue(os.path.exists(os.path.join(__a   ,							"tracking"   )   )   )




				def     UpperCamelCase__  (    self	:   Optional[int]   ):
								_a				      =					["examples/by_feature/gradient_accumulation.py"]
								run_command(self._launch_args + testargs   )




				def     UpperCamelCase__  (    self	:   Tuple   ):
								_a				      =					["examples/by_feature/local_sgd.py"]
								run_command(self._launch_args + testargs   )







"""simple docstring"""





from math import log

from scipy.constants import Boltzmann, physical_constants

SCREAMING_SNAKE_CASE__   =  300  # TEMPERATURE (unit = K)


def      UpperCAmelCase__				(    SCREAMING_SNAKE_CASE	:		float				,		SCREAMING_SNAKE_CASE	:		float				,		SCREAMING_SNAKE_CASE	:		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()






