import gc
import random
import unittest

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

import diffusers
from diffusers import (
    AutoencoderKL,
    EulerDiscreteScheduler,
    StableDiffusionLatentUpscalePipeline,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.schedulers import KarrasDiffusionSchedulers
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
def 					_snake_case	(  __snake_case						):
					_UpperCamelCase			     =     [tensor.shape for tensor in tensor_list]
					return all(shape == shapes[0] for shape in shapes[1:]						)
class     lowerCAmelCase_     (       __lowercase,  __lowercase,  __lowercase,  unittest.TestCase ):
							UpperCAmelCase				   =     StableDiffusionLatentUpscalePipeline
							UpperCAmelCase				   =     TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
							    "height",
							    "width",
							    "cross_attention_kwargs",
							    "negative_prompt_embeds",
							    "prompt_embeds",
							}
							UpperCAmelCase				   =     PipelineTesterMixin.required_optional_params - {"num_images_per_prompt"}
							UpperCAmelCase				   =     TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							UpperCAmelCase				   =     frozenset(
							    [] )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
							UpperCAmelCase				   =     frozenset([] )

							UpperCAmelCase				   =     True







							@property
							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												_UpperCamelCase			     =     1
												_UpperCamelCase			     =     4
												_UpperCamelCase			     =     (16, 16)

												_UpperCamelCase			     =     floats_tensor((batch_size, num_channels) + sizes ,			rng=random.Random(0		)		).to(_A		)
												return image







							def  UpperCamelCase_						(   self      :     Optional[int]		):
												torch.manual_seed(0		)
												_UpperCamelCase			     =     UNetaDConditionModel(
												    act_fn='''gelu''' ,			attention_head_dim=8 ,			norm_num_groups=_A ,			block_out_channels=[32, 32, 64, 64] ,			time_cond_proj_dim=160 ,			conv_in_kernel=1 ,			conv_out_kernel=1 ,			cross_attention_dim=32 ,			down_block_types=(
												        '''KDownBlock2D''',
												        '''KCrossAttnDownBlock2D''',
												        '''KCrossAttnDownBlock2D''',
												        '''KCrossAttnDownBlock2D''',
												    ) ,			in_channels=8 ,			mid_block_type=_A ,			only_cross_attention=_A ,			out_channels=5 ,			resnet_time_scale_shift='''scale_shift''' ,			time_embedding_type='''fourier''' ,			timestep_post_act='''gelu''' ,			up_block_types=('''KCrossAttnUpBlock2D''', '''KCrossAttnUpBlock2D''', '''KCrossAttnUpBlock2D''', '''KUpBlock2D''') ,			)
												_UpperCamelCase			     =     AutoencoderKL(
												    block_out_channels=[32, 32, 64, 64] ,			in_channels=3 ,			out_channels=3 ,			down_block_types=[
												        '''DownEncoderBlock2D''',
												        '''DownEncoderBlock2D''',
												        '''DownEncoderBlock2D''',
												        '''DownEncoderBlock2D''',
												    ] ,			up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,			latent_channels=4 ,			)
												_UpperCamelCase			     =     EulerDiscreteScheduler(prediction_type='''sample'''		)
												_UpperCamelCase			     =     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=1000 ,			hidden_act='''quick_gelu''' ,			projection_dim=512 ,			)
												_UpperCamelCase			     =     CLIPTextModel(_A		)
												_UpperCamelCase			     =     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''		)

												_UpperCamelCase			     =     {
												    '''unet''': model.eval(),
												    '''vae''': vae.eval(),
												    '''scheduler''': scheduler,
												    '''text_encoder''': text_encoder,
												    '''tokenizer''': tokenizer,
												}

												return components







							def  UpperCamelCase_						(   self      :     Dict ,			_A      :     int ,			_A      :     List[Any]=0		):
												if str(_A		).startswith('''mps'''		):
																	_UpperCamelCase			     =     torch.manual_seed(_A		)
												else:
																	_UpperCamelCase			     =     torch.Generator(device=_A		).manual_seed(_A		)
												_UpperCamelCase			     =     {
												    '''prompt''': '''A painting of a squirrel eating a burger''',
												    '''image''': self.dummy_image.cpu(),
												    '''generator''': generator,
												    '''num_inference_steps''': 2,
												    '''output_type''': '''numpy''',
												}
												return inputs







							def  UpperCamelCase_						(   self      :     str		):
												_UpperCamelCase			     =     '''cpu'''

												_UpperCamelCase			     =     self.get_dummy_components()
												_UpperCamelCase			     =     self.pipeline_class(**_A		)
												pipe.to(_A		)
												pipe.set_progress_bar_config(disable=_A		)

												_UpperCamelCase			     =     self.get_dummy_inputs(_A		)
												_UpperCamelCase			     =     pipe(**_A		).images
												_UpperCamelCase			     =     image[0, -3:, -3:, -1]

												self.assertEqual(image.shape ,			(1, 256, 256, 3)		)
												_UpperCamelCase			     =     np.array(
												    [0.4722_2412, 0.4192_1633, 0.4471_7434, 0.4687_4192, 0.4258_8258, 0.4615_0726, 0.467_7534, 0.4558_3832, 0.4857_9055]		)
												_UpperCamelCase			     =     np.abs(image_slice.flatten() - expected_slice		).max()
												self.assertLessEqual(_A ,			1e-3		)







							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												super().test_attention_slicing_forward_pass(expected_max_diff=7e-3		)







							def  UpperCamelCase_						(   self      :     int		):
												super().test_cpu_offload_forward_pass(expected_max_diff=3e-3		)







							def  UpperCamelCase_						(   self      :     str		):
												super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3		)







							def  UpperCamelCase_						(   self      :     str		):
												super().test_inference_batch_single_identical(expected_max_diff=7e-3		)







							def  UpperCamelCase_						(   self      :     Optional[int]		):
												super().test_pt_np_pil_outputs_equivalent(expected_max_diff=3e-3		)







							def  UpperCamelCase_						(   self      :     int		):
												super().test_save_load_local(expected_max_difference=3e-3		)







							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												super().test_save_load_optional_components(expected_max_difference=3e-3		)







							def  UpperCamelCase_						(   self      :     Union[str, Any]		):
												_UpperCamelCase			     =     [
												    '''DDIMScheduler''',
												    '''DDPMScheduler''',
												    '''PNDMScheduler''',
												    '''HeunDiscreteScheduler''',
												    '''EulerAncestralDiscreteScheduler''',
												    '''KDPM2DiscreteScheduler''',
												    '''KDPM2AncestralDiscreteScheduler''',
												    '''DPMSolverSDEScheduler''',
												]
												_UpperCamelCase			     =     self.get_dummy_components()
												_UpperCamelCase			     =     self.pipeline_class(**_A		)

												# make sure that PNDM does not need warm-up
												pipe.scheduler.register_to_config(skip_prk_steps=_A		)

												pipe.to(_A		)
												pipe.set_progress_bar_config(disable=_A		)
												_UpperCamelCase			     =     self.get_dummy_inputs(_A		)
												_UpperCamelCase			     =     2

												_UpperCamelCase			     =     []
												for scheduler_enum in KarrasDiffusionSchedulers:
																	if scheduler_enum.name in skip_schedulers:
																						# no sigma schedulers are not supported
																						# no schedulers
																						continue

																	_UpperCamelCase			     =     getattr(_A ,			scheduler_enum.name		)
																	_UpperCamelCase			     =     scheduler_cls.from_config(pipe.scheduler.config		)
																	_UpperCamelCase			     =     pipe(**_A		)[0]
																	outputs.append(_A		)

												assert check_same_shape(_A		)




@require_torch_gpu
@slow
class     lowerCAmelCase_     (       unittest.TestCase ):







							def  UpperCamelCase_						(   self      :     Optional[Any]		):
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()







							def  UpperCamelCase_						(   self      :     Any		):
												_UpperCamelCase			     =     torch.manual_seed(33		)

												_UpperCamelCase			     =     StableDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ,			torch_dtype=torch.floataa		)
												pipe.to('''cuda'''		)

												_UpperCamelCase			     =     StableDiffusionLatentUpscalePipeline.from_pretrained(
												    '''stabilityai/sd-x2-latent-upscaler''' ,			torch_dtype=torch.floataa		)
												upscaler.to('''cuda'''		)

												_UpperCamelCase			     =     '''a photo of an astronaut high resolution, unreal engine, ultra realistic'''

												_UpperCamelCase			     =     pipe(_A ,			generator=_A ,			output_type='''latent'''		).images

												_UpperCamelCase			     =     upscaler(
												    prompt=_A ,			image=_A ,			num_inference_steps=20 ,			guidance_scale=0 ,			generator=_A ,			output_type='''np''' ,			).images[0]

												_UpperCamelCase			     =     load_numpy(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/astronaut_1024.npy'''		)
												assert np.abs((expected_image - image).mean()		) < 5e-2







							def  UpperCamelCase_						(   self      :     Optional[Any]		):
												_UpperCamelCase			     =     torch.manual_seed(33		)

												_UpperCamelCase			     =     StableDiffusionLatentUpscalePipeline.from_pretrained(
												    '''stabilityai/sd-x2-latent-upscaler''' ,			torch_dtype=torch.floataa		)
												upscaler.to('''cuda'''		)

												_UpperCamelCase			     =     '''the temple of fire by Ross Tran and Gerardo Dottori, oil on canvas'''

												_UpperCamelCase			     =     load_image(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_512.png'''		)

												_UpperCamelCase			     =     upscaler(
												    prompt=_A ,			image=_A ,			num_inference_steps=20 ,			guidance_scale=0 ,			generator=_A ,			output_type='''np''' ,			).images[0]

												_UpperCamelCase			     =     load_numpy(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/latent-upscaler/fire_temple_1024.npy'''		)
												assert np.abs((expected_image - image).max()		) < 5e-2

import sys
from collections import defaultdict
class     lowerCAmelCase_     :







							def __init__(   self      :     Optional[int]		):
												_UpperCamelCase			     =     []







							def  UpperCamelCase_						(   self      :     Any ,			_A      :     str		):
												return self.node_position[vertex]







							def  UpperCamelCase_						(   self      :     Optional[Any] ,			_A      :     List[str] ,			_A      :     Union[str, Any]		):
												_UpperCamelCase			     =     pos







							def  UpperCamelCase_						(   self      :     Any ,			_A      :     List[str] ,			_A      :     int ,			_A      :     Optional[Any] ,			_A      :     Union[str, Any]		):
												if start > size // 2 - 1:
																	return
												else:
																	if 2 * start + 2 >= size:
																						_UpperCamelCase			     =     2 * start + 1
																	else:
																						if heap[2 * start + 1] < heap[2 * start + 2]:
																											_UpperCamelCase			     =     2 * start + 1
																						else:
																											_UpperCamelCase			     =     2 * start + 2
																	if heap[smallest_child] < heap[start]:
																						_UpperCamelCase     ,    _UpperCamelCase			     =     heap[smallest_child], positions[smallest_child]
																						_UpperCamelCase     ,    _UpperCamelCase			     =     (
																						    heap[start],
																						    positions[start],
																						)
																						_UpperCamelCase     ,    _UpperCamelCase			     =     temp, tempa

																						_UpperCamelCase			     =     self.get_position(positions[smallest_child]		)
																						self.set_position(
																						    positions[smallest_child] ,			self.get_position(positions[start]		)		)
																						self.set_position(positions[start] ,			_A		)

																						self.top_to_bottom(_A ,			_A ,			_A ,			_A		)







							def  UpperCamelCase_						(   self      :     List[str] ,			_A      :     Tuple ,			_A      :     Optional[Any] ,			_A      :     int ,			_A      :     Optional[int]		):
												_UpperCamelCase			     =     position[index]

												while index != 0:
																	_UpperCamelCase			     =     int((index - 2) / 2		) if index % 2 == 0 else int((index - 1) / 2		)

																	if val < heap[parent]:
																						_UpperCamelCase			     =     heap[parent]
																						_UpperCamelCase			     =     position[parent]
																						self.set_position(position[parent] ,			_A		)
																	else:
																						_UpperCamelCase			     =     val
																						_UpperCamelCase			     =     temp
																						self.set_position(_A ,			_A		)
																						break
																	_UpperCamelCase			     =     parent
												else:
																	_UpperCamelCase			     =     val
																	_UpperCamelCase			     =     temp
																	self.set_position(_A ,			0		)







							def  UpperCamelCase_						(   self      :     int ,			_A      :     Tuple ,			_A      :     int		):
												_UpperCamelCase			     =     len(_A		) // 2 - 1
												for i in range(_A ,			-1 ,			-1		):
																	self.top_to_bottom(_A ,			_A ,			len(_A		) ,			_A		)







							def  UpperCamelCase_						(   self      :     Any ,			_A      :     int ,			_A      :     List[str]		):
												_UpperCamelCase			     =     positions[0]
												_UpperCamelCase			     =     sys.maxsize
												self.top_to_bottom(_A ,			0 ,			len(_A		) ,			_A		)
												return temp




def 					_snake_case	(  __snake_case						):
					_UpperCamelCase			     =     Heap()

					_UpperCamelCase			     =     [0] * len(__snake_case						)
					_UpperCamelCase			     =     [-1] * len(__snake_case						)  # Neighboring Tree Vertex of selected vertex
					# Minimum Distance of explored vertex with neighboring vertex of partial tree
					# formed in graph
					_UpperCamelCase			     =     []  # Heap of Distance of vertices from their neighboring vertex
					_UpperCamelCase			     =     []

					for vertex in range(len(__snake_case						)						):
										distance_tv.append(sys.maxsize						)
										positions.append(__snake_case						)
										heap.node_position.append(__snake_case						)

					_UpperCamelCase			     =     []
					_UpperCamelCase			     =     1
					_UpperCamelCase			     =     sys.maxsize
					for neighbor, distance in adjacency_list[0]:
										_UpperCamelCase			     =     0
										_UpperCamelCase			     =     distance
					heap.heapify(__snake_case  ,     __snake_case						)

					for _ in range(1  ,     len(__snake_case						)						):
										_UpperCamelCase			     =     heap.delete_minimum(__snake_case  ,     __snake_case						)
										if visited[vertex] == 0:
															tree_edges.append((nbr_tv[vertex], vertex)						)
															_UpperCamelCase			     =     1
															for neighbor, distance in adjacency_list[vertex]:
																				if (
																				    visited[neighbor] == 0
																				    and distance < distance_tv[heap.get_position(__snake_case						)]
																				):
																									_UpperCamelCase			     =     distance
																									heap.bottom_to_top(
																									    __snake_case  ,     heap.get_position(__snake_case						)  ,     __snake_case  ,     __snake_case						)
																									_UpperCamelCase			     =     vertex
					return tree_edges


if __name__ == "__main__":  # pragma: no cover
					# < --------- Prims Algorithm --------- >
					_lowerCAmelCase       =		int(input("Enter number of edges: ").strip())
					_lowerCAmelCase       =		defaultdict(list)
					for _ in range(edges_number):
										_lowerCAmelCase       =		[int(x) for x in input().strip().split()]
										adjacency_list[edge[0]].append([edge[1], edge[2]])
										adjacency_list[edge[1]].append([edge[0], edge[2]])
					print(prisms_algorithm(adjacency_list))
