




"""simple docstring"""

import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()
class      lowerCamelCase__      (					unittest.TestCase     ):


			@property
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  int        =			1
					snake_case						:  int        =			3
					snake_case						:  Union[str, Any]        =			(32, 32)

					snake_case						:  Any        =			floats_tensor((batch_size, num_channels) + sizes			,	rng=random.Random(0							)							).to(SCREAMING_SNAKE_CASE							)
					return image


			@property
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					torch.manual_seed(0							)
					snake_case						:  Tuple        =			UNetaDModel(
					    block_out_channels=(32, 64)			,	layers_per_block=2			,	sample_size=32			,	in_channels=6			,	out_channels=3			,	down_block_types=("DownBlock2D", "AttnDownBlock2D")			,	up_block_types=("AttnUpBlock2D", "UpBlock2D")			,	)
					return model


			@property
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					torch.manual_seed(0							)
					snake_case						:  List[str]        =			VQModel(
					    block_out_channels=[32, 64]			,	in_channels=3			,	out_channels=3			,	down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]			,	up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]			,	latent_channels=3			,	)
					return model


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Tuple        =			"cpu"
					snake_case						:  Union[str, Any]        =			self.dummy_uncond_unet
					snake_case						:  Any        =			DDIMScheduler()
					snake_case						:  List[str]        =			self.dummy_vq_model

					snake_case						:  Tuple        =			LDMSuperResolutionPipeline(unet=SCREAMING_SNAKE_CASE			,	vqvae=SCREAMING_SNAKE_CASE			,	scheduler=SCREAMING_SNAKE_CASE							)
					ldm.to(SCREAMING_SNAKE_CASE							)
					ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE							)

					snake_case						:  Union[str, Any]        =			self.dummy_image.to(SCREAMING_SNAKE_CASE							)

					snake_case						:  Optional[Any]        =			torch.Generator(device=SCREAMING_SNAKE_CASE							).manual_seed(0							)
					snake_case						:  Dict        =			ldm(image=SCREAMING_SNAKE_CASE			,	generator=SCREAMING_SNAKE_CASE			,	num_inference_steps=2			,	output_type="numpy"							).images

					snake_case						:  Tuple        =			image[0, -3:, -3:, -1]

					assert image.shape == (1, 64, 64, 3)
					snake_case						:  str        =			np.array([0.86_78, 0.82_45, 0.63_81, 0.68_30, 0.43_85, 0.55_99, 0.46_41, 0.62_01, 0.51_50]							)

					assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2



			@unittest.skipIf(torch_device != "cuda"			,	"This test requires a GPU"							)
			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  Any        =			self.dummy_uncond_unet
					snake_case						:  Union[str, Any]        =			DDIMScheduler()
					snake_case						:  List[Any]        =			self.dummy_vq_model

					# put models in fp16
					snake_case						:  str        =			unet.half()
					snake_case						:  Tuple        =			vqvae.half()

					snake_case						:  Optional[int]        =			LDMSuperResolutionPipeline(unet=SCREAMING_SNAKE_CASE			,	vqvae=SCREAMING_SNAKE_CASE			,	scheduler=SCREAMING_SNAKE_CASE							)
					ldm.to(SCREAMING_SNAKE_CASE							)
					ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE							)

					snake_case						:  List[Any]        =			self.dummy_image.to(SCREAMING_SNAKE_CASE							)

					snake_case						:  Dict        =			ldm(SCREAMING_SNAKE_CASE			,	num_inference_steps=2			,	output_type="numpy"							).images

					assert image.shape == (1, 64, 64, 3)







@slow
@require_torch
class      lowerCamelCase__      (					unittest.TestCase     ):


			def 							lowerCamelCase_			(       self							):



					"""simple docstring"""







					snake_case						:  int        =			load_image(
					    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
					    "/vq_diffusion/teddy_bear_pool.png"							)
					snake_case						:  List[Any]        =			init_image.resize((64, 64)			,	resample=PIL_INTERPOLATION["lanczos"]							)

					snake_case						:  Tuple        =			LDMSuperResolutionPipeline.from_pretrained("duongna/ldm-super-resolution"			,	device_map="auto"							)
					ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE							)

					snake_case						:  str        =			torch.manual_seed(0							)
					snake_case						:  Any        =			ldm(image=SCREAMING_SNAKE_CASE			,	generator=SCREAMING_SNAKE_CASE			,	num_inference_steps=20			,	output_type="numpy"							).images

					snake_case						:  Union[str, Any]        =			image[0, -3:, -3:, -1]

					assert image.shape == (1, 256, 256, 3)
					snake_case						:  List[Any]        =			np.array([0.76_44, 0.76_79, 0.76_42, 0.76_33, 0.76_66, 0.75_60, 0.74_25, 0.72_57, 0.69_07]							)

					assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2







"""simple docstring"""

import matplotlib.pyplot as plt
import numpy as np



def 					UpperCamelCase__       (						lowercase__					:       np.ndarray    ,       lowercase__					:       np.ndarray    ,       lowercase__					:       float				):
		snake_case						:  Any        =			len(lowercase__				)  # Number of training samples
		snake_case						:  str        =			np.eye(lowercase__				)  # Initialize weights as identity matrix
		for j in range(lowercase__				):
				snake_case						:  Any        =			point - x_train[j]
				snake_case						:  Dict        =			np.exp(diff @ diff.T / (-2.0 * tau**2)				)

		return weights



def 					UpperCamelCase__       (						lowercase__					:       np.ndarray    ,       lowercase__					:       np.ndarray    ,       lowercase__					:       np.ndarray    ,       lowercase__					:       float				):
		snake_case						:  str        =			weight_matrix(lowercase__    ,       lowercase__    ,       lowercase__				)
		snake_case						:  str        =			np.linalg.inv(x_train.T @ weight_mat @ x_train				) @ (
		    x_train.T @ weight_mat @ y_train.T
		)

		return weight



def 					UpperCamelCase__       (						lowercase__					:       np.ndarray    ,       lowercase__					:       np.ndarray    ,       lowercase__					:       float				):
		snake_case						:  Optional[int]        =			np.zeros(len(lowercase__				)				)  # Initialize array of predictions
		for i, item in enumerate(lowercase__				):
				snake_case						:  Dict        =			item @ local_weight(lowercase__    ,       lowercase__    ,       lowercase__    ,       lowercase__				)

		return y_pred



def 					UpperCamelCase__       (						lowercase__					:       str    ,       lowercase__					:       str    ,       lowercase__					:       str				):
		import seaborn as sns

		snake_case						:  Union[str, Any]        =			sns.load_dataset(lowercase__				)
		snake_case						:  Any        =			np.array(data[x_name]				)
		snake_case						:  str        =			np.array(data[y_name]				)

		snake_case						:  Any        =			np.ones(len(lowercase__				)				)

		# pairing elements of one and x_data
		snake_case						:  Optional[int]        =			np.column_stack((one, x_data)				)

		return x_train, x_data, y_data



def 					UpperCamelCase__       (						lowercase__					:       np.ndarray    ,       lowercase__					:       np.ndarray    ,       lowercase__					:       np.ndarray    ,       lowercase__					:       np.ndarray    ,       lowercase__					:       str    ,       lowercase__					:       str    ,       ):
		snake_case						:  List[str]        =			np.sort(lowercase__    ,       axis=0				)
		plt.scatter(lowercase__    ,       lowercase__    ,       color="blue"				)
		plt.plot(
		    x_train_sorted[:, 1]    ,       preds[x_train[:, 1].argsort(0				)]    ,       color="yellow"    ,       linewidth=5    ,       )
		plt.title("Local Weighted Regression"				)
		plt.xlabel(lowercase__				)
		plt.ylabel(lowercase__				)
		plt.show()


if __name__ == "__main__":
							import doctest

							doctest.testmod()

							# Demo with a dataset from the seaborn module
							__A						,    __A						,    __A							=     load_data("tips", "total_bill", "tip")
							__A							=     local_weight_regression(training_data_x, tip, 5)
							plot_preds(training_data_x, predictions, total_bill, tip, "total_bill", "tip")

