






'''simple docstring'''







import csv
import json
import logging
import os
import re
import subprocess
import tempfile
import unittest
import zipfile
from pathlib import Path
from typing import Optional
from unittest import mock

import torch

# We use TF to parse the logs
from accelerate import Accelerator
from accelerate.test_utils.testing import (
    MockingTestCase,
    TempDirTestCase,
    require_comet_ml,
    require_tensorboard,
    require_wandb,
    skip,
)
from accelerate.tracking import CometMLTracker, GeneralTracker
from accelerate.utils import ProjectConfiguration, is_comet_ml_available, is_tensorboard_available


if is_comet_ml_available():
  from comet_ml import OfflineExperiment

if is_tensorboard_available():
  import struct

  import tensorboard.compat.proto.event_pba as event_pba

UpperCamelCase_					=				logging.getLogger(__name__)




@require_tensorboard
class 					__UpperCAmelCase (		unittest.TestCase	):

      '''simple docstring'''





      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   Any												=	"test_project_with_config"
             with tempfile.TemporaryDirectory() as dirpath:
                    UpperCAmelCase__	:   List[Any]												=	Accelerator(log_with='''tensorboard'''  ,		project_dir=_UpperCAmelCase						)
                    UpperCAmelCase__	:   Dict												=	{"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
                    accelerator.init_trackers(_UpperCAmelCase  ,		_UpperCAmelCase						)
                    accelerator.end_training()
                    for child in Path(F"""{dirpath}/{project_name}"""						).glob('''*/**'''						):
                           UpperCAmelCase__	:   Optional[Any]												=	list(filter(lambda _UpperCAmelCase						: x.is_file()  ,		child.iterdir()						)						)[0]
                    self.assertNotEqual(str(_UpperCAmelCase						)  ,		''''''						)




      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   Tuple												=	"test_project_with_log"
             with tempfile.TemporaryDirectory() as dirpath:
                    UpperCAmelCase__	:   str												=	Accelerator(log_with='''tensorboard'''  ,		project_dir=_UpperCAmelCase						)
                    accelerator.init_trackers(_UpperCAmelCase						)
                    UpperCAmelCase__	:   Union[str, Any]												=	{"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
                    accelerator.log(_UpperCAmelCase  ,		step=0						)
                    accelerator.end_training()
                    # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
                    # Names are randomly generated each time
                    UpperCAmelCase__	:   Dict												=	list(filter(lambda _UpperCAmelCase						: x.is_file()  ,		Path(F"""{dirpath}/{project_name}"""						).iterdir()						)						)[0]
                    self.assertNotEqual(str(_UpperCAmelCase						)  ,		''''''						)




      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   Optional[int]												=	"test_project_with_log"
             with tempfile.TemporaryDirectory() as dirpath:
                    UpperCAmelCase__	:   str												=	Accelerator(log_with='''tensorboard'''  ,		project_dir=_UpperCAmelCase						)
                    accelerator.init_trackers(_UpperCAmelCase						)
                    UpperCAmelCase__	:   Optional[Any]												=	{"tensor": torch.tensor(1						)}
                    accelerator.log(_UpperCAmelCase  ,		step=0						)
                    accelerator.end_training()
                    # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
                    # Names are randomly generated each time
                    UpperCAmelCase__	:   Optional[Any]												=	list(filter(lambda _UpperCAmelCase						: x.is_file()  ,		Path(F"""{dirpath}/{project_name}"""						).iterdir()						)						)[0]
                    # Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
                    with open(_UpperCAmelCase  ,		'''rb'''						) as f:
                           UpperCAmelCase__	:   Optional[int]												=	f.read()
                    UpperCAmelCase__	:   Optional[int]												=	False
                    while data:
                           UpperCAmelCase__	:   List[str]												=	struct.unpack('''Q'''  ,		data[:8]						)

                           UpperCAmelCase__	:   List[Any]												=	data[12 : 12 + int(header[0]						)]  # 8+4
                           UpperCAmelCase__	:   List[Any]												=	data[12 + int(header[0]						) + 4 :]
                           UpperCAmelCase__	:   Any												=	event_pba.Event()

                           event.ParseFromString(_UpperCAmelCase						)
                           if event.HasField('''summary'''						):
                                  for value in event.summary.value:
                                         if value.simple_value == 1.0 and value.tag == "tensor":
                                                UpperCAmelCase__	:   Tuple												=	True
                    self.assertTrue(_UpperCAmelCase  ,		'''Converted tensor was not found in the log file!'''						)




      def 							lowerCamelCase     (					self						):





             with self.assertRaisesRegex(_UpperCAmelCase  ,		'''Logging with `tensorboard` requires a `logging_dir`'''						):
                    UpperCAmelCase__	:   Union[str, Any]												=	Accelerator(log_with='''tensorboard'''						)
             with tempfile.TemporaryDirectory() as dirpath:
                    UpperCAmelCase__	:   Union[str, Any]												=	Accelerator(log_with='''tensorboard'''  ,		project_dir=_UpperCAmelCase						)




      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   Any												=	ProjectConfiguration(total_limit=30						)
             with tempfile.TemporaryDirectory() as dirpath:
                    UpperCAmelCase__	:   List[Any]												=	Accelerator(log_with='''tensorboard'''  ,		project_dir=_UpperCAmelCase  ,		project_config=_UpperCAmelCase						)




@require_wandb
@mock.patch.dict(os.environ      ,				{"WANDB_MODE": "offline"}	)
class 					__UpperCAmelCase (		lowercase__      ,				lowercase__	):

      '''simple docstring'''





      def 							lowerCamelCase     (					self						):
             super().setUp()
             # wandb let's us override where logs are stored to via the WANDB_DIR env var
             self.add_mocks(mock.patch.dict(os.environ  ,		{'''WANDB_DIR''': self.tmpdir}						)						)




      @staticmethod
      def 							lowerCamelCase     (					_UpperCAmelCase  ,		_UpperCAmelCase  ,		_UpperCAmelCase = True						):
             UpperCAmelCase__	:   int												=	RF"""{section} ([\S\s]*?)\n\n"""
             if record:
                    UpperCAmelCase__	:   Optional[Any]												=	RF"""Record: {pattern}"""
             UpperCAmelCase__	:   Union[str, Any]												=	re.findall(_UpperCAmelCase  ,		_UpperCAmelCase						)[0]
             # A config
             if section == "config" or section == "history":
                    UpperCAmelCase__	:   Dict												=	re.findall(R'''\"([a-zA-Z0-9_.,]+)'''  ,		_UpperCAmelCase						)
                    return {key: val for key, val in zip(cleaned_record[0::2]  ,		cleaned_record[1::2]						)}
             # Everything else
             else:
                    return dict(re.findall(R'''(\w+): \"([^\s]+)\"'''  ,		_UpperCAmelCase						)						)




      @skip
      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   int												=	"test_project_with_config"
             UpperCAmelCase__	:   List[Any]												=	Accelerator(log_with='''wandb'''						)
             UpperCAmelCase__	:   str												=	{"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
             UpperCAmelCase__	:   Tuple												=	{"wandb": {"tags": ["my_tag"]}}
             accelerator.init_trackers(_UpperCAmelCase  ,		_UpperCAmelCase  ,		_UpperCAmelCase						)
             UpperCAmelCase__	:   Optional[Any]												=	{"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
             accelerator.log(_UpperCAmelCase  ,		step=0						)
             accelerator.end_training()
             # The latest offline log is stored at wandb/latest-run/*.wandb
             for child in Path(F"""{self.tmpdir}/wandb/latest-run"""						).glob('''*'''						):
                    if child.is_file() and child.suffix == ".wandb":
                           UpperCAmelCase__	:   Optional[Any]												=	subprocess.check_output(
                               ['''wandb''', '''sync''', '''--view''', '''--verbose''', str(_UpperCAmelCase						)]  ,		env=os.environ.copy()						).decode('''utf8'''  ,		'''ignore'''						)
                           break

        # Check HPS through careful parsing and cleaning
             UpperCAmelCase__	:   List[Any]												=	self.parse_log(_UpperCAmelCase  ,		'''config'''						)
             self.assertEqual(logged_items['''num_iterations''']  ,		'''12'''						)
             self.assertEqual(logged_items['''learning_rate''']  ,		'''0.01'''						)
             self.assertEqual(logged_items['''some_boolean''']  ,		'''false'''						)
             self.assertEqual(logged_items['''some_string''']  ,		'''some_value'''						)
             self.assertEqual(logged_items['''some_string''']  ,		'''some_value'''						)

             # Run tags
             UpperCAmelCase__	:   List[Any]												=	self.parse_log(_UpperCAmelCase  ,		'''run'''  ,		_UpperCAmelCase						)
             self.assertEqual(logged_items['''tags''']  ,		'''my_tag'''						)

             # Actual logging
             UpperCAmelCase__	:   int												=	self.parse_log(_UpperCAmelCase  ,		'''history'''						)
             self.assertEqual(logged_items['''total_loss''']  ,		'''0.1'''						)
             self.assertEqual(logged_items['''iteration''']  ,		'''1'''						)
             self.assertEqual(logged_items['''my_text''']  ,		'''some_value'''						)
             self.assertEqual(logged_items['''_step''']  ,		'''0'''						)






def  lowerCAmelCase__		(					self  :     Optional[Any]			,						a_  :     Tuple			,						a_  :     Any			)   -> Union[str, Any]:
       UpperCAmelCase__	:   Tuple												=	run_name
       UpperCAmelCase__	:   Optional[int]												=	OfflineExperiment(project_name=__snake_case			,						offline_directory=__snake_case			)
       logger.info(f"""Initialized offline CometML project {self.run_name}"""			)
       logger.info('''Make sure to log any initial configurations with `self.store_init_configuration` before training!'''			)




@require_comet_ml
@mock.patch.object(lowercase__      ,				"__init__"      ,				lowercase__	)
class 					__UpperCAmelCase (		unittest.TestCase	):

      '''simple docstring'''





      @staticmethod
      def 							lowerCamelCase     (					_UpperCAmelCase  ,		_UpperCAmelCase  ,		_UpperCAmelCase = False						):





             for log in log_list:
                    UpperCAmelCase__	:   Tuple												=	json.loads(_UpperCAmelCase						)["payload"]
                    if is_param and "param" in j.keys():
                           if j["param"]["paramName"] == key:
                                  return j["param"]["paramValue"]
                    if "log_other" in j.keys():
                           if j["log_other"]["key"] == key:
                                  return j["log_other"]["val"]
                    if "metric" in j.keys():
                           if j["metric"]["metricName"] == key:
                                  return j["metric"]["metricValue"]




      def 							lowerCamelCase     (					self						):





             with tempfile.TemporaryDirectory() as d:
                    UpperCAmelCase__	:   int												=	CometMLTracker('''test_project_with_config'''  ,		_UpperCAmelCase						)
                    UpperCAmelCase__	:   List[Any]												=	Accelerator(log_with=_UpperCAmelCase						)
                    UpperCAmelCase__	:   Any												=	{"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
                    accelerator.init_trackers(_UpperCAmelCase  ,		_UpperCAmelCase						)
                    accelerator.end_training()
                    UpperCAmelCase__	:   Dict												=	os.listdir(_UpperCAmelCase						)[0]  # Comet is nice, it's just a zip file here
                    # We parse the raw logs
                    UpperCAmelCase__	:   Union[str, Any]												=	os.path.join(_UpperCAmelCase  ,		_UpperCAmelCase						)
                    UpperCAmelCase__	:   List[str]												=	zipfile.ZipFile(_UpperCAmelCase  ,		'''r'''						)
                    UpperCAmelCase__	:   str												=	archive.open('''messages.json'''						).read().decode('''utf-8'''						)
             UpperCAmelCase__	:   int												=	log.split('''\n'''						)[:-1]
             self.assertEqual(self.get_value_from_key(_UpperCAmelCase  ,		'''num_iterations'''  ,		_UpperCAmelCase						)  ,		12						)
             self.assertEqual(self.get_value_from_key(_UpperCAmelCase  ,		'''learning_rate'''  ,		_UpperCAmelCase						)  ,		0.01						)
             self.assertEqual(self.get_value_from_key(_UpperCAmelCase  ,		'''some_boolean'''  ,		_UpperCAmelCase						)  ,		_UpperCAmelCase						)
             self.assertEqual(self.get_value_from_key(_UpperCAmelCase  ,		'''some_string'''  ,		_UpperCAmelCase						)  ,		'''some_value'''						)




      def 							lowerCamelCase     (					self						):





             with tempfile.TemporaryDirectory() as d:
                    UpperCAmelCase__	:   Dict												=	CometMLTracker('''test_project_with_config'''  ,		_UpperCAmelCase						)
                    UpperCAmelCase__	:   Optional[Any]												=	Accelerator(log_with=_UpperCAmelCase						)
                    accelerator.init_trackers(_UpperCAmelCase						)
                    UpperCAmelCase__	:   Tuple												=	{"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
                    accelerator.log(_UpperCAmelCase  ,		step=0						)
                    accelerator.end_training()
                    UpperCAmelCase__	:   List[str]												=	os.listdir(_UpperCAmelCase						)[0]  # Comet is nice, it's just a zip file here
                    # We parse the raw logs
                    UpperCAmelCase__	:   List[str]												=	os.path.join(_UpperCAmelCase  ,		_UpperCAmelCase						)
                    UpperCAmelCase__	:   Any												=	zipfile.ZipFile(_UpperCAmelCase  ,		'''r'''						)
                    UpperCAmelCase__	:   Union[str, Any]												=	archive.open('''messages.json'''						).read().decode('''utf-8'''						)
             UpperCAmelCase__	:   int												=	log.split('''\n'''						)[:-1]
             self.assertEqual(self.get_value_from_key(_UpperCAmelCase  ,		'''curr_step'''  ,		_UpperCAmelCase						)  ,		0						)
             self.assertEqual(self.get_value_from_key(_UpperCAmelCase  ,		'''total_loss'''						)  ,		0.1						)
             self.assertEqual(self.get_value_from_key(_UpperCAmelCase  ,		'''iteration'''						)  ,		1						)
             self.assertEqual(self.get_value_from_key(_UpperCAmelCase  ,		'''my_text'''						)  ,		'''some_value'''						)




class 					__UpperCAmelCase (		lowercase__	):

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    Optional[Any]				       =					[
          "total_loss",
          "iteration",
          "my_text",
          "learning_rate",
          "num_iterations",
          "some_boolean",
          "some_string",
      ]

      SCREAMING_SNAKE_CASE				:    Tuple				       =					"my_custom_tracker"
      SCREAMING_SNAKE_CASE				:    List[str]				       =					False




      def __init__(					self  ,		_UpperCAmelCase						):
             UpperCAmelCase__	:   Optional[Any]												=	open(F"""{dir}/log.csv"""  ,		'''w+'''						)
             UpperCAmelCase__	:   List[str]												=	csv.DictWriter(self.f  ,		fieldnames=self._col_names						)
             self.writer.writeheader()




      @property
      def 							lowerCamelCase     (					self						):
             return self.writer




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase						):
             logger.info('''Call init'''						)
             self.writer.writerow(_UpperCAmelCase						)




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase  ,		_UpperCAmelCase						):
             logger.info('''Call log'''						)
             self.writer.writerow(_UpperCAmelCase						)




      def 							lowerCamelCase     (					self						):
             self.f.close()




class 					__UpperCAmelCase (		unittest.TestCase	):

      '''simple docstring'''





      def 							lowerCamelCase     (					self						):





             with tempfile.TemporaryDirectory() as d:
                    UpperCAmelCase__	:   Union[str, Any]												=	MyCustomTracker(_UpperCAmelCase						)
                    UpperCAmelCase__	:   Optional[int]												=	Accelerator(log_with=_UpperCAmelCase						)
                    UpperCAmelCase__	:   List[Any]												=	{"num_iterations": 12, "learning_rate": 1E-2, "some_boolean": False, "some_string": "some_value"}
                    accelerator.init_trackers('''Some name'''  ,		_UpperCAmelCase						)
                    accelerator.end_training()
                    with open(F"""{d}/log.csv"""  ,		'''r'''						) as f:
                           UpperCAmelCase__	:   List[Any]												=	csv.DictReader(_UpperCAmelCase						)
                           UpperCAmelCase__	:   List[str]												=	next(_UpperCAmelCase						)
                           UpperCAmelCase__	:   Union[str, Any]												=	{
                               "total_loss": "",
                               "iteration": "",
                               "my_text": "",
                               "learning_rate": "0.01",
                               "num_iterations": "12",
                               "some_boolean": "False",
                               "some_string": "some_value",
                           }
                           self.assertDictEqual(_UpperCAmelCase  ,		_UpperCAmelCase						)




      def 							lowerCamelCase     (					self						):





             with tempfile.TemporaryDirectory() as d:
                    UpperCAmelCase__	:   Dict												=	MyCustomTracker(_UpperCAmelCase						)
                    UpperCAmelCase__	:   Optional[int]												=	Accelerator(log_with=_UpperCAmelCase						)
                    accelerator.init_trackers('''Some name'''						)
                    UpperCAmelCase__	:   Any												=	{"total_loss": 0.1, "iteration": 1, "my_text": "some_value"}
                    accelerator.log(_UpperCAmelCase  ,		step=0						)
                    accelerator.end_training()
                    with open(F"""{d}/log.csv"""  ,		'''r'''						) as f:
                           UpperCAmelCase__	:   str												=	csv.DictReader(_UpperCAmelCase						)
                           UpperCAmelCase__	:   Union[str, Any]												=	next(_UpperCAmelCase						)
                           UpperCAmelCase__	:   Any												=	{
                               "total_loss": "0.1",
                               "iteration": "1",
                               "my_text": "some_value",
                               "learning_rate": "",
                               "num_iterations": "",
                               "some_boolean": "",
                               "some_string": "",
                           }
                           self.assertDictEqual(_UpperCAmelCase  ,		_UpperCAmelCase						)




import heapq







def  _snake_case			(							__snake_case       ,	__snake_case       ,	__snake_case     )  ->  str:






      '''simple docstring'''







      UpperCAmelCase_	:						List[str]					   =		[(0, start)]  # cost from start node,end node
      UpperCAmelCase_	:						List[Any]					   =		set()
      while heap:
            ((UpperCAmelCase_)   ,   (UpperCAmelCase_))	:						str					   =		heapq.heappop(__snake_case     )
            if u in visited:
                  continue
            visited.add(__snake_case     )
            if u == end:
                  return cost
            for v, c in graph[u]:
                  if v in visited:
                        continue
                  UpperCAmelCase_	:						Tuple					   =		cost + c
                  heapq.heappush(__snake_case       ,	(next_item, v)     )
      return -1


__lowerCamelCase								=      {
    '''A''': [['''B''', 2], ['''C''', 5]],
    '''B''': [['''A''', 2], ['''D''', 3], ['''E''', 1], ['''F''', 1]],
    '''C''': [['''A''', 5], ['''F''', 3]],
    '''D''': [['''B''', 3]],
    '''E''': [['''B''', 4], ['''F''', 3]],
    '''F''': [['''C''', 3], ['''E''', 3]],
}
__lowerCamelCase								=      {
    '''B''': [['''C''', 1]],
    '''C''': [['''D''', 1]],
    '''D''': [['''F''', 1]],
    '''E''': [['''B''', 1], ['''F''', 3]],
    '''F''': [],
}
__lowerCamelCase								=      {
    '''B''': [['''C''', 1]],
    '''C''': [['''D''', 1]],
    '''D''': [['''F''', 1]],
    '''E''': [['''B''', 1], ['''G''', 2]],
    '''F''': [],
    '''G''': [['''F''', 1]],
}

__lowerCamelCase								=      dijkstra(G, '''E''', '''C''')
print(short_distance)  # E -- 3 --> F -- 3 --> C == 6

__lowerCamelCase								=      dijkstra(Ga, '''E''', '''F''')
print(short_distance)  # E -- 3 --> F == 3

__lowerCamelCase								=      dijkstra(Ga, '''E''', '''F''')
print(short_distance)  # E -- 2 --> G -- 1 --> F == 3

if __name__ == "__main__":
   import doctest

   doctest.testmod()
