





import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionSAGPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


class   A			(SCREAMING_SNAKE_CASE   ,     SCREAMING_SNAKE_CASE   ,     unittest.TestCase    ):
			'''simple docstring'''




			__lowerCamelCase	:       List[str]							=    StableDiffusionSAGPipeline
			__lowerCamelCase	:       Union[str, Any]							=    TEXT_TO_IMAGE_PARAMS
			__lowerCamelCase	:       List[Any]							=    TEXT_TO_IMAGE_BATCH_PARAMS
			__lowerCamelCase	:       List[Any]							=    TEXT_TO_IMAGE_IMAGE_PARAMS
			__lowerCamelCase	:       Tuple							=    TEXT_TO_IMAGE_IMAGE_PARAMS
			__lowerCamelCase	:       int							=    False






			def    a_       (			self   :    Any   )	->	Optional[int]:







					"""simple docstring"""






					torch.manual_seed(0   )
					A__        =   UNetaDConditionModel(
					    block_out_channels=(32, 64)							,	layers_per_block=2							,	sample_size=32							,	in_channels=4							,	out_channels=4							,	down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")							,	up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")							,	cross_attention_dim=32							,	)
					A__        =   DDIMScheduler(
					    beta_start=0.0_0_0_8_5							,	beta_end=0.0_1_2							,	beta_schedule="""scaled_linear"""							,	clip_sample=__lowerCAmelCase							,	set_alpha_to_one=__lowerCAmelCase							,	)
					torch.manual_seed(0   )
					A__        =   AutoencoderKL(
					    block_out_channels=[32, 64]							,	in_channels=3							,	out_channels=3							,	down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]							,	up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]							,	latent_channels=4							,	)
					torch.manual_seed(0   )
					A__        =   CLIPTextConfig(
					    bos_token_id=0							,	eos_token_id=2							,	hidden_size=32							,	intermediate_size=37							,	layer_norm_eps=1e-05							,	num_attention_heads=4							,	num_hidden_layers=5							,	pad_token_id=1							,	vocab_size=10_00							,	)
					A__        =   CLIPTextModel(__lowerCAmelCase   )
					A__        =   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""   )

					A__        =   {
					    """unet""": unet,
					    """scheduler""": scheduler,
					    """vae""": vae,
					    """text_encoder""": text_encoder,
					    """tokenizer""": tokenizer,
					    """safety_checker""": None,
					    """feature_extractor""": None,
					}
					return components






			def    a_       (			self   :    Optional[int]							,	__lowerCAmelCase   :    Union[str, Any]							,	__lowerCAmelCase   :    List[str]=0   )	->	Union[str, Any]:







					"""simple docstring"""






					if str(__lowerCAmelCase   ).startswith("""mps"""   ):
							A__        =   torch.manual_seed(__lowerCAmelCase   )
					else:
							A__        =   torch.Generator(device=__lowerCAmelCase   ).manual_seed(__lowerCAmelCase   )
					A__        =   {
					    """prompt""": """.""",
					    """generator""": generator,
					    """num_inference_steps""": 2,
					    """guidance_scale""": 1.0,
					    """sag_scale""": 1.0,
					    """output_type""": """numpy""",
					}
					return inputs







			def    a_       (			self   :    Optional[Any]   )	->	int:







					"""simple docstring"""






					super().test_inference_batch_single_identical(expected_max_diff=3e-3   )


@slow
@require_torch_gpu
class   A			(unittest.TestCase    ):
			'''simple docstring'''




			def    a_       (			self   :    int   )	->	Any:







					"""simple docstring"""






					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()






			def    a_       (			self   :    Optional[Any]   )	->	str:







					"""simple docstring"""






					A__        =   StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4"""   )
					A__        =   sag_pipe.to(__lowerCAmelCase   )
					sag_pipe.set_progress_bar_config(disable=__lowerCAmelCase   )

					A__        =   """."""
					A__        =   torch.manual_seed(0   )
					A__        =   sag_pipe(
					    [prompt]							,	generator=__lowerCAmelCase							,	guidance_scale=7.5							,	sag_scale=1.0							,	num_inference_steps=20							,	output_type="""np"""   )

					A__        =   output.images

					A__        =   image[0, -3:, -3:, -1]

					assert image.shape == (1, 5_12, 5_12, 3)
					A__        =   np.array([0.1_5_6_8, 0.1_7_3_8, 0.1_6_9_5, 0.1_6_9_3, 0.1_5_0_7, 0.1_7_0_5, 0.1_5_4_7, 0.1_7_5_1, 0.1_9_4_9]   )

					assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5e-2






			def    a_       (			self   :    Optional[int]   )	->	str:







					"""simple docstring"""






					A__        =   StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base"""   )
					A__        =   sag_pipe.to(__lowerCAmelCase   )
					sag_pipe.set_progress_bar_config(disable=__lowerCAmelCase   )

					A__        =   """."""
					A__        =   torch.manual_seed(0   )
					A__        =   sag_pipe(
					    [prompt]							,	generator=__lowerCAmelCase							,	guidance_scale=7.5							,	sag_scale=1.0							,	num_inference_steps=20							,	output_type="""np"""   )

					A__        =   output.images

					A__        =   image[0, -3:, -3:, -1]

					assert image.shape == (1, 5_12, 5_12, 3)
					A__        =   np.array([0.3_4_5_9, 0.2_8_7_6, 0.2_5_3_7, 0.3_0_0_2, 0.2_6_7_1, 0.2_1_6_0, 0.3_0_2_6, 0.2_2_6_2, 0.2_3_7_1]   )

					assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5e-2







			def    a_       (			self   :    Optional[Any]   )	->	Optional[Any]:







					"""simple docstring"""






					A__        =   StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base"""   )
					A__        =   sag_pipe.to(__lowerCAmelCase   )
					sag_pipe.set_progress_bar_config(disable=__lowerCAmelCase   )

					A__        =   """."""
					A__        =   torch.manual_seed(0   )
					A__        =   sag_pipe(
					    [prompt]							,	width=7_68							,	height=5_12							,	generator=__lowerCAmelCase							,	guidance_scale=7.5							,	sag_scale=1.0							,	num_inference_steps=20							,	output_type="""np"""							,	)

					A__        =   output.images

					assert image.shape == (1, 5_12, 7_68, 3)










from __future__ import annotations

import time
from math import sqrt

# 1 for manhattan, 0 for euclidean
A    :					str =      0

A    :					Any =      [
    [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],
]

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

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


class   A			:
			'''simple docstring'''




			def __init__(			self   :    int							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    int							,	__lowerCAmelCase   :    Node | None							,	)	->	None:







					"""simple docstring"""






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






			def    a_       (			self   :    Dict   )	->	float:







					"""simple docstring"""






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







			def __lt__(			self   :    int							,	__lowerCAmelCase   :    Node   )	->	bool:







					"""simple docstring"""






					return self.f_cost < other.f_cost


class   A			:
			'''simple docstring'''




			def __init__(			self   :    Union[str, Any]							,	__lowerCAmelCase   :    TPosition							,	__lowerCAmelCase   :    TPosition   )	->	Tuple:







					"""simple docstring"""






					A__        =   Node(start[1]							,	start[0]							,	goal[1]							,	goal[0]							,	0							,	__lowerCAmelCase   )
					A__        =   Node(goal[1]							,	goal[0]							,	goal[1]							,	goal[0]							,	9_99_99							,	__lowerCAmelCase   )

					A__        =   [self.start]
					A__        =   []

					A__        =   False






			def    a_       (			self   :    List[str]   )	->	list[TPosition]:







					"""simple docstring"""






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

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

							self.closed_nodes.append(__lowerCAmelCase   )
							A__        =   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
											A__        =   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    a_       (			self   :    Optional[Any]							,	__lowerCAmelCase   :    Node   )	->	list[Node]:







					"""simple docstring"""






					A__        =   []
					for action in delta:
							A__        =   parent.pos_x + action[1]
							A__        =   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    a_       (			self   :    List[Any]							,	__lowerCAmelCase   :    Node | None   )	->	list[TPosition]:







					"""simple docstring"""






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


class   A			:
			'''simple docstring'''




			def __init__(			self   :    Optional[Any]							,	__lowerCAmelCase   :    TPosition							,	__lowerCAmelCase   :    TPosition   )	->	None:







					"""simple docstring"""






					A__        =   AStar(__lowerCAmelCase							,	__lowerCAmelCase   )
					A__        =   AStar(__lowerCAmelCase							,	__lowerCAmelCase   )
					A__        =   False






			def    a_       (			self   :    int   )	->	list[TPosition]:







					"""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()
							A__        =   self.fwd_astar.open_nodes.pop(0   )
							A__        =   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   )

							A__        =   current_bwd_node
							A__        =   current_fwd_node

							A__        =   {
							    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
													A__        =   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    a_       (			self   :    List[str]							,	__lowerCAmelCase   :    Node							,	__lowerCAmelCase   :    Node   )	->	list[TPosition]:







					"""simple docstring"""






					A__        =   self.fwd_astar.retrace_path(__lowerCAmelCase   )
					A__        =   self.bwd_astar.retrace_path(__lowerCAmelCase   )
					bwd_path.pop()
					bwd_path.reverse()
					A__        =   fwd_path + bwd_path
					return path


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

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

					A    :					Dict =      time.time()
					A    :					Tuple =      BidirectionalAStar(init, goal)
					A    :					List[Any] =      time.time() - bd_start_time
					print(F'''BidirectionalAStar execution time = {bd_end_time:f} seconds''')



