
'''simple docstring'''







from __future__ import annotations

import time
from math import sqrt

# 1 for manhattan, 0 for euclidean
lowercase    :							Any      =					0

lowercase    :							Dict      =					[
    [0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 0, 0, 0],  # 0 are free path whereas 1's are obstacles
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [1, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
]

lowercase    :							Dict      =					[[-1, 0], [0, -1], [1, 0], [0, 1]]  # up, left, down, right

lowercase    :							Union[str, Any]      =					tuple[int, int]


class 						__UpperCAmelCase      :


							def __init__(       self    ,   lowerCAmelCase_    ,   lowerCAmelCase_    ,   lowerCAmelCase_    ,   lowerCAmelCase_    ,   lowerCAmelCase_    ,   lowerCAmelCase_    ,   ):





								"""simple docstring"""






								_snake_case   						=		pos_x
								_snake_case   						=		pos_y
								_snake_case   						=		(pos_y, pos_x)
								_snake_case   						=		goal_x
								_snake_case   						=		goal_y
								_snake_case   						=		g_cost
								_snake_case   						=		parent
								_snake_case   						=		self.calculate_heuristic()
								_snake_case   						=		self.g_cost + self.h_cost


							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								_snake_case   						=		self.pos_x - self.goal_x
								_snake_case   						=		self.pos_y - self.goal_y
								if HEURISTIC == 1:
									return abs(lowerCAmelCase_  ) + abs(lowerCAmelCase_  )
								else:
									return sqrt(dy**2 + dx**2  )




							def __lt__(       self    ,   lowerCAmelCase_  ):





								"""simple docstring"""






								return self.f_cost < other.f_cost


class 						__UpperCAmelCase      :


							def __init__(       self    ,   lowerCAmelCase_    ,   lowerCAmelCase_  ):





								"""simple docstring"""






								_snake_case   						=		Node(start[1]    ,   start[0]    ,   goal[1]    ,   goal[0]    ,   0    ,   lowerCAmelCase_  )
								_snake_case   						=		Node(goal[1]    ,   goal[0]    ,   goal[1]    ,   goal[0]    ,   9_99_99    ,   lowerCAmelCase_  )

								_snake_case   						=		[self.start]
								_snake_case   						=		[]

								_snake_case   						=		False


							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								while self.open_nodes:
									# Open Nodes are sorted using __lt__
									self.open_nodes.sort()
									_snake_case   						=		self.open_nodes.pop(0  )

									if current_node.pos == self.target.pos:
										return self.retrace_path(lowerCAmelCase_  )

									self.closed_nodes.append(lowerCAmelCase_  )
									_snake_case   						=		self.get_successors(lowerCAmelCase_  )

									for child_node in successors:
										if child_node in self.closed_nodes:
											continue

										if child_node not in self.open_nodes:
											self.open_nodes.append(lowerCAmelCase_  )
										else:
											# retrieve the best current path
											_snake_case   						=		self.open_nodes.pop(self.open_nodes.index(lowerCAmelCase_  )  )

											if child_node.g_cost < better_node.g_cost:
												self.open_nodes.append(lowerCAmelCase_  )
											else:
												self.open_nodes.append(lowerCAmelCase_  )

								return [self.start.pos]


							def  lowerCamelCase				(       self    ,   lowerCAmelCase_  ):





								"""simple docstring"""






								_snake_case   						=		[]
								for action in delta:
									_snake_case   						=		parent.pos_x + action[1]
									_snake_case   						=		parent.pos_y + action[0]
									if not (0 <= pos_x <= len(grid[0]  ) - 1 and 0 <= pos_y <= len(lowerCAmelCase_  ) - 1):
										continue

									if grid[pos_y][pos_x] != 0:
										continue

									successors.append(
									    Node(
									        lowerCAmelCase_    ,   lowerCAmelCase_    ,   self.target.pos_y    ,   self.target.pos_x    ,   parent.g_cost + 1    ,   lowerCAmelCase_    ,   )  )
								return successors




							def  lowerCamelCase				(       self    ,   lowerCAmelCase_  ):





								"""simple docstring"""






								_snake_case   						=		node
								_snake_case   						=		[]
								while current_node is not None:
									path.append((current_node.pos_y, current_node.pos_x)  )
									_snake_case   						=		current_node.parent
								path.reverse()
								return path


class 						__UpperCAmelCase      :


							def __init__(       self    ,   lowerCAmelCase_    ,   lowerCAmelCase_  ):





								"""simple docstring"""






								_snake_case   						=		AStar(lowerCAmelCase_    ,   lowerCAmelCase_  )
								_snake_case   						=		AStar(lowerCAmelCase_    ,   lowerCAmelCase_  )
								_snake_case   						=		False


							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes:
									self.fwd_astar.open_nodes.sort()
									self.bwd_astar.open_nodes.sort()
									_snake_case   						=		self.fwd_astar.open_nodes.pop(0  )
									_snake_case   						=		self.bwd_astar.open_nodes.pop(0  )

									if current_bwd_node.pos == current_fwd_node.pos:
										return self.retrace_bidirectional_path(
										    lowerCAmelCase_    ,   lowerCAmelCase_  )

									self.fwd_astar.closed_nodes.append(lowerCAmelCase_  )
									self.bwd_astar.closed_nodes.append(lowerCAmelCase_  )

									_snake_case   						=		current_bwd_node
									_snake_case   						=		current_fwd_node

									_snake_case   						=		{
									    self.fwd_astar: self.fwd_astar.get_successors(lowerCAmelCase_  ),
									    self.bwd_astar: self.bwd_astar.get_successors(lowerCAmelCase_  ),
									}

									for astar in [self.fwd_astar, self.bwd_astar]:
										for child_node in successors[astar]:
											if child_node in astar.closed_nodes:
												continue

											if child_node not in astar.open_nodes:
												astar.open_nodes.append(lowerCAmelCase_  )
											else:
												# retrieve the best current path
												_snake_case   						=		astar.open_nodes.pop(
												    astar.open_nodes.index(lowerCAmelCase_  )  )

												if child_node.g_cost < better_node.g_cost:
													astar.open_nodes.append(lowerCAmelCase_  )
												else:
													astar.open_nodes.append(lowerCAmelCase_  )

								return [self.fwd_astar.start.pos]




							def  lowerCamelCase				(       self    ,   lowerCAmelCase_    ,   lowerCAmelCase_  ):





								"""simple docstring"""






								_snake_case   						=		self.fwd_astar.retrace_path(lowerCAmelCase_  )
								_snake_case   						=		self.bwd_astar.retrace_path(lowerCAmelCase_  )
								bwd_path.pop()
								bwd_path.reverse()
								_snake_case   						=		fwd_path + bwd_path
								return path


if __name__ == "__main__":
					# all coordinates are given in format [y,x]
					lowercase    :							Dict      =					(0, 0)
					lowercase    :							str      =					(len(grid) - 1, len(grid[0]) - 1)
					for elem in grid:
										print(elem)

					lowercase    :							Dict      =					time.time()
					lowercase    :							Tuple      =					AStar(init, goal)
					lowercase    :							Optional[int]      =					a_star.search()
					lowercase    :							str      =					time.time() - start_time
					print(F'''AStar execution time = {end_time:f} seconds''')

					lowercase    :							List[str]      =					time.time()
					lowercase    :							int      =					BidirectionalAStar(init, goal)
					lowercase    :							str      =					time.time() - bd_start_time
					print(F'''BidirectionalAStar execution time = {bd_end_time:f} seconds''')



'''simple docstring'''







import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch


class 						__UpperCAmelCase      (					_lowerCamelCase						):


							@require_torch
							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								_snake_case   						=		'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

								_snake_case   						=		'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

								_snake_case   						=		'\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n        '

								# Force fetching the files so that we can use the cache
								_snake_case   						=		'hf-internal-testing/tiny-random-bert'
								BertConfig.from_pretrained(lowerCAmelCase_  )
								BertModel.from_pretrained(lowerCAmelCase_  )
								BertTokenizer.from_pretrained(lowerCAmelCase_  )
								pipeline(task='fill-mask'    ,   model=lowerCAmelCase_  )

								# baseline - just load from_pretrained with normal network
								_snake_case   						=		[sys.executable, '-c', '\n'.join([load, run, mock]  )]

								# should succeed
								_snake_case   						=		self.get_env()
								# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
								_snake_case   						=		'1'
								_snake_case   						=		subprocess.run(lowerCAmelCase_    ,   env=lowerCAmelCase_    ,   check=lowerCAmelCase_    ,   capture_output=lowerCAmelCase_  )
								self.assertEqual(result.returncode    ,   0    ,   result.stderr  )
								self.assertIn('success'    ,   result.stdout.decode()  )


							@require_torch
							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								_snake_case   						=		'\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

								_snake_case   						=		'\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

								_snake_case   						=		'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n        '

								# Force fetching the files so that we can use the cache
								_snake_case   						=		'hf-internal-testing/tiny-random-bert'
								BertConfig.from_pretrained(lowerCAmelCase_  )
								BertModel.from_pretrained(lowerCAmelCase_  )
								BertTokenizer.from_pretrained(lowerCAmelCase_  )
								pipeline(task='fill-mask'    ,   model=lowerCAmelCase_  )

								# baseline - just load from_pretrained with normal network
								_snake_case   						=		[sys.executable, '-c', '\n'.join([load, run, mock]  )]

								# should succeed
								_snake_case   						=		self.get_env()
								_snake_case   						=		subprocess.run(lowerCAmelCase_    ,   env=lowerCAmelCase_    ,   check=lowerCAmelCase_    ,   capture_output=lowerCAmelCase_  )
								self.assertEqual(result.returncode    ,   0    ,   result.stderr  )
								self.assertIn('success'    ,   result.stdout.decode()  )


							@require_torch
							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								_snake_case   						=		'\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        '

								_snake_case   						=		'\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n        '

								_snake_case   						=		'\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n        '

								# baseline - just load from_pretrained with normal network
								_snake_case   						=		[sys.executable, '-c', '\n'.join([load, run]  )]

								# should succeed
								_snake_case   						=		self.get_env()
								_snake_case   						=		subprocess.run(lowerCAmelCase_    ,   env=lowerCAmelCase_    ,   check=lowerCAmelCase_    ,   capture_output=lowerCAmelCase_  )
								self.assertEqual(result.returncode    ,   0    ,   result.stderr  )
								self.assertIn('success'    ,   result.stdout.decode()  )

								# next emulate no network
								_snake_case   						=		[sys.executable, '-c', '\n'.join([load, mock, run]  )]

								# Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
								# env["TRANSFORMERS_OFFLINE"] = "0"
								# result = subprocess.run(cmd, env=env, check=False, capture_output=True)
								# self.assertEqual(result.returncode, 1, result.stderr)

								# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
								_snake_case   						=		'1'
								_snake_case   						=		subprocess.run(lowerCAmelCase_    ,   env=lowerCAmelCase_    ,   check=lowerCAmelCase_    ,   capture_output=lowerCAmelCase_  )
								self.assertEqual(result.returncode    ,   0    ,   result.stderr  )
								self.assertIn('success'    ,   result.stdout.decode()  )


							@require_torch
							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								_snake_case   						=		'\nfrom transformers import pipeline\n        '
								_snake_case   						=		'\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n        '

								_snake_case   						=		'\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n        '
								_snake_case   						=		self.get_env()
								_snake_case   						=		'1'
								_snake_case   						=		[sys.executable, '-c', '\n'.join([load, mock, run]  )]
								_snake_case   						=		subprocess.run(lowerCAmelCase_    ,   env=lowerCAmelCase_    ,   check=lowerCAmelCase_    ,   capture_output=lowerCAmelCase_  )
								self.assertEqual(result.returncode    ,   1    ,   result.stderr  )
								self.assertIn(
								    'You cannot infer task automatically within `pipeline` when using offline mode'    ,   result.stderr.decode().replace('\n'    ,   ''  )    ,   )




							@require_torch
							def  lowerCamelCase				(       self  ):





								"""simple docstring"""






								_snake_case   						=		'\nfrom transformers import AutoModel\n        '
								_snake_case   						=		'\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n        '

								# baseline - just load from_pretrained with normal network
								_snake_case   						=		[sys.executable, '-c', '\n'.join([load, run]  )]

								# should succeed
								_snake_case   						=		self.get_env()
								_snake_case   						=		subprocess.run(lowerCAmelCase_    ,   env=lowerCAmelCase_    ,   check=lowerCAmelCase_    ,   capture_output=lowerCAmelCase_  )
								self.assertEqual(result.returncode    ,   0    ,   result.stderr  )
								self.assertIn('success'    ,   result.stdout.decode()  )

								# should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
								_snake_case   						=		'1'
								_snake_case   						=		subprocess.run(lowerCAmelCase_    ,   env=lowerCAmelCase_    ,   check=lowerCAmelCase_    ,   capture_output=lowerCAmelCase_  )
								self.assertEqual(result.returncode    ,   0    ,   result.stderr  )
								self.assertIn('success'    ,   result.stdout.decode()  )

