
'''simple docstring'''



import math
from typing import Optional

import numpy as np
import torch
from torch import nn

from .activations import get_activation


def A      (__lowerCamelCase      :torch.Tensor ,	__lowerCamelCase      :int ,	__lowerCamelCase      :bool = False ,	__lowerCamelCase      :float = 1 ,	__lowerCamelCase      :float = 1 ,	__lowerCamelCase      :int = 10000 ,	):
						assert len(timesteps.shape		) == 1, "Timesteps should be a 1d-array"

						_lowerCAmelCase  						= embedding_dim // 2
						_lowerCAmelCase  						= -math.log(__lowerCamelCase		) * torch.arange(
						    start=0 ,	end=__lowerCamelCase ,	dtype=torch.floataa ,	device=timesteps.device		)
						_lowerCAmelCase  						= exponent / (half_dim - downscale_freq_shift)

						_lowerCAmelCase  						= torch.exp(__lowerCamelCase		)
						_lowerCAmelCase  						= timesteps[:, None].float() * emb[None, :]

						# scale embeddings
						_lowerCAmelCase  						= scale * emb

						# concat sine and cosine embeddings
						_lowerCAmelCase  						= torch.cat([torch.sin(__lowerCamelCase		), torch.cos(__lowerCamelCase		)] ,	dim=-1		)

						# flip sine and cosine embeddings
						if flip_sin_to_cos:
												_lowerCAmelCase  						= torch.cat([emb[:, half_dim:], emb[:, :half_dim]] ,	dim=-1		)

						# zero pad
						if embedding_dim % 2 == 1:
												_lowerCAmelCase  						= torch.nn.functional.pad(__lowerCamelCase ,	(0, 1, 0, 0)		)
						return emb


def A      (__lowerCamelCase      :Union[str, Any] ,	__lowerCamelCase      :Tuple ,	__lowerCamelCase      :List[str]=False ,	__lowerCamelCase      :str=0		):
						_lowerCAmelCase  						= np.arange(__lowerCamelCase ,	dtype=np.floataa		)
						_lowerCAmelCase  						= np.arange(__lowerCamelCase ,	dtype=np.floataa		)
						_lowerCAmelCase  						= np.meshgrid(__lowerCamelCase ,	__lowerCamelCase		)  # here w goes first
						_lowerCAmelCase  						= np.stack(__lowerCamelCase ,	axis=0		)

						_lowerCAmelCase  						= grid.reshape([2, 1, grid_size, grid_size]		)
						_lowerCAmelCase  						= get_ad_sincos_pos_embed_from_grid(__lowerCamelCase ,	__lowerCamelCase		)
						if cls_token and extra_tokens > 0:
												_lowerCAmelCase  						= np.concatenate([np.zeros([extra_tokens, embed_dim]		), pos_embed] ,	axis=0		)
						return pos_embed


def A      (__lowerCamelCase      :Any ,	__lowerCamelCase      :Tuple		):
						if embed_dim % 2 != 0:
												raise ValueError("""embed_dim must be divisible by 2"""		)

						# use half of dimensions to encode grid_h
						_lowerCAmelCase  						= get_ad_sincos_pos_embed_from_grid(embed_dim // 2 ,	grid[0]		)  # (H*W, D/2)
						_lowerCAmelCase  						= get_ad_sincos_pos_embed_from_grid(embed_dim // 2 ,	grid[1]		)  # (H*W, D/2)

						_lowerCAmelCase  						= np.concatenate([emb_h, emb_w] ,	axis=1		)  # (H*W, D)
						return emb


def A      (__lowerCamelCase      :Union[str, Any] ,	__lowerCamelCase      :Dict		):
						if embed_dim % 2 != 0:
												raise ValueError("""embed_dim must be divisible by 2"""		)

						_lowerCAmelCase  						= np.arange(embed_dim // 2 ,	dtype=np.floataa		)
						omega /= embed_dim / 2.0
						_lowerCAmelCase  						= 1.0 / 10000**omega  # (D/2,)

						_lowerCAmelCase  						= pos.reshape(-1		)  # (M,)
						_lowerCAmelCase  						= np.einsum("""m,d->md""" ,	__lowerCamelCase ,	__lowerCamelCase		)  # (M, D/2), outer product

						_lowerCAmelCase  						= np.sin(__lowerCamelCase		)  # (M, D/2)
						_lowerCAmelCase  						= np.cos(__lowerCamelCase		)  # (M, D/2)

						_lowerCAmelCase  						= np.concatenate([emb_sin, emb_cos] ,	axis=1		)  # (M, D)
						return emb




class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase=224    ,   _lowercase=224    ,   _lowercase=16    ,   _lowercase=3    ,   _lowercase=768    ,   _lowercase=False    ,   _lowercase=True    ,   _lowercase=True    ,   ):

												"""simple docstring"""



												super().__init__()

												_lowerCAmelCase  						= (height // patch_size) * (width // patch_size)
												_lowerCAmelCase  						= flatten
												_lowerCAmelCase  						= layer_norm

												_lowerCAmelCase  						= nn.Convad(
												    A_    ,   A_    ,   kernel_size=(patch_size, patch_size)    ,   stride=A_    ,   bias=A_      )
												if layer_norm:
																		_lowerCAmelCase  						= nn.LayerNorm(A_    ,   elementwise_affine=A_    ,   eps=1e-6      )
												else:
																		_lowerCAmelCase  						= None

												_lowerCAmelCase  						= get_ad_sincos_pos_embed(A_    ,   int(num_patches**0.5      )      )
												self.register_buffer("""pos_embed"""    ,   torch.from_numpy(A_      ).float().unsqueeze(0      )    ,   persistent=A_      )




						def 					_lowercase	(					self    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= self.proj(A_      )
												if self.flatten:
																		_lowerCAmelCase  						= latent.flatten(2      ).transpose(1    ,   2      )  # BCHW -> BNC
												if self.layer_norm:
																		_lowerCAmelCase  						= self.norm(A_      )
												return latent + self.pos_embed






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase    ,   _lowercase    ,   _lowercase = "silu"    ,   _lowercase = None    ,   _lowercase = None    ,   _lowercase=None    ,   ):

												"""simple docstring"""



												super().__init__()

												_lowerCAmelCase  						= nn.Linear(A_    ,   A_      )

												if cond_proj_dim is not None:
																		_lowerCAmelCase  						= nn.Linear(A_    ,   A_    ,   bias=A_      )
												else:
																		_lowerCAmelCase  						= None

												_lowerCAmelCase  						= get_activation(A_      )

												if out_dim is not None:
																		_lowerCAmelCase  						= out_dim
												else:
																		_lowerCAmelCase  						= time_embed_dim
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_      )

												if post_act_fn is None:
																		_lowerCAmelCase  						= None
												else:
																		_lowerCAmelCase  						= get_activation(A_      )




						def 					_lowercase	(					self    ,   _lowercase    ,   _lowercase=None      ):

												"""simple docstring"""



												if condition is not None:
																		_lowerCAmelCase  						= sample + self.cond_proj(A_      )
												_lowerCAmelCase  						= self.linear_a(A_      )

												if self.act is not None:
																		_lowerCAmelCase  						= self.act(A_      )

												_lowerCAmelCase  						= self.linear_a(A_      )

												if self.post_act is not None:
																		_lowerCAmelCase  						= self.post_act(A_      )
												return sample






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase    ,   _lowercase    ,   _lowercase      ):

												"""simple docstring"""



												super().__init__()
												_lowerCAmelCase  						= num_channels
												_lowerCAmelCase  						= flip_sin_to_cos
												_lowerCAmelCase  						= downscale_freq_shift




						def 					_lowercase	(					self    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= get_timestep_embedding(
												    A_    ,   self.num_channels    ,   flip_sin_to_cos=self.flip_sin_to_cos    ,   downscale_freq_shift=self.downscale_freq_shift    ,   )
												return t_emb






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase = 256    ,   _lowercase = 1.0    ,   _lowercase=True    ,   _lowercase=True    ,   _lowercase=False      ):

												"""simple docstring"""



												super().__init__()
												_lowerCAmelCase  						= nn.Parameter(torch.randn(A_      ) * scale    ,   requires_grad=A_      )
												_lowerCAmelCase  						= log
												_lowerCAmelCase  						= flip_sin_to_cos

												if set_W_to_weight:
																		# to delete later
																		_lowerCAmelCase  						= nn.Parameter(torch.randn(A_      ) * scale    ,   requires_grad=A_      )

																		_lowerCAmelCase  						= self.W




						def 					_lowercase	(					self    ,   _lowercase      ):

												"""simple docstring"""



												if self.log:
																		_lowerCAmelCase  						= torch.log(A_      )

												_lowerCAmelCase  						= x[:, None] * self.weight[None, :] * 2 * np.pi

												if self.flip_sin_to_cos:
																		_lowerCAmelCase  						= torch.cat([torch.cos(A_      ), torch.sin(A_      )]    ,   dim=-1      )
												else:
																		_lowerCAmelCase  						= torch.cat([torch.sin(A_      ), torch.cos(A_      )]    ,   dim=-1      )
												return out






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase    ,   _lowercase    ,   _lowercase    ,   _lowercase    ,   ):

												"""simple docstring"""



												super().__init__()

												_lowerCAmelCase  						= height
												_lowerCAmelCase  						= width
												_lowerCAmelCase  						= num_embed
												_lowerCAmelCase  						= embed_dim

												_lowerCAmelCase  						= nn.Embedding(self.num_embed    ,   A_      )
												_lowerCAmelCase  						= nn.Embedding(self.height    ,   A_      )
												_lowerCAmelCase  						= nn.Embedding(self.width    ,   A_      )




						def 					_lowercase	(					self    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= self.emb(A_      )

												_lowerCAmelCase  						= self.height_emb(torch.arange(self.height    ,   device=index.device      ).view(1    ,   self.height      )      )

												# 1 x H x D -> 1 x H x 1 x D
												_lowerCAmelCase  						= height_emb.unsqueeze(2      )

												_lowerCAmelCase  						= self.width_emb(torch.arange(self.width    ,   device=index.device      ).view(1    ,   self.width      )      )

												# 1 x W x D -> 1 x 1 x W x D
												_lowerCAmelCase  						= width_emb.unsqueeze(1      )

												_lowerCAmelCase  						= height_emb + width_emb

												# 1 x H x W x D -> 1 x L xD
												_lowerCAmelCase  						= pos_emb.view(1    ,   self.height * self.width    ,   -1      )

												_lowerCAmelCase  						= emb + pos_emb[:, : emb.shape[1], :]

												return emb






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase    ,   _lowercase    ,   _lowercase      ):

												"""simple docstring"""



												super().__init__()
												_lowerCAmelCase  						= dropout_prob > 0
												_lowerCAmelCase  						= nn.Embedding(num_classes + use_cfg_embedding    ,   A_      )
												_lowerCAmelCase  						= num_classes
												_lowerCAmelCase  						= dropout_prob




						def 					_lowercase	(					self    ,   _lowercase    ,   _lowercase=None      ):

												"""simple docstring"""



												if force_drop_ids is None:
																		_lowerCAmelCase  						= torch.rand(labels.shape[0]    ,   device=labels.device      ) < self.dropout_prob
												else:
																		_lowerCAmelCase  						= torch.tensor(force_drop_ids == 1      )
												_lowerCAmelCase  						= torch.where(A_    ,   self.num_classes    ,   A_      )
												return labels




						def 					_lowercase	(					self    ,   _lowercase    ,   _lowercase=None      ):

												"""simple docstring"""



												_lowerCAmelCase  						= self.dropout_prob > 0
												if (self.training and use_dropout) or (force_drop_ids is not None):
																		_lowerCAmelCase  						= self.token_drop(A_    ,   A_      )
												_lowerCAmelCase  						= self.embedding_table(A_      )
												return embeddings






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase = 1_024    ,   _lowercase = 768    ,   _lowercase = 768    ,   _lowercase = 10    ,   ):

												"""simple docstring"""



												super().__init__()

												_lowerCAmelCase  						= num_image_text_embeds
												_lowerCAmelCase  						= nn.Linear(A_    ,   self.num_image_text_embeds * cross_attention_dim      )
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_      )




						def 					_lowercase	(					self    ,   _lowercase    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= text_embeds.shape[0]

												# image
												_lowerCAmelCase  						= self.image_embeds(A_      )
												_lowerCAmelCase  						= image_text_embeds.reshape(A_    ,   self.num_image_text_embeds    ,   -1      )

												# text
												_lowerCAmelCase  						= self.text_proj(A_      )

												return torch.cat([image_text_embeds, text_embeds]    ,   dim=1      )






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase = 768    ,   _lowercase = 768    ,   _lowercase = 32    ,   ):

												"""simple docstring"""



												super().__init__()

												_lowerCAmelCase  						= num_image_text_embeds
												_lowerCAmelCase  						= nn.Linear(A_    ,   self.num_image_text_embeds * cross_attention_dim      )
												_lowerCAmelCase  						= nn.LayerNorm(A_      )




						def 					_lowercase	(					self    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= image_embeds.shape[0]

												# image
												_lowerCAmelCase  						= self.image_embeds(A_      )
												_lowerCAmelCase  						= image_embeds.reshape(A_    ,   self.num_image_text_embeds    ,   -1      )
												_lowerCAmelCase  						= self.norm(A_      )
												return image_embeds






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase    ,   _lowercase    ,   _lowercase=0.1      ):

												"""simple docstring"""



												super().__init__()

												_lowerCAmelCase  						= Timesteps(num_channels=256    ,   flip_sin_to_cos=A_    ,   downscale_freq_shift=1      )
												_lowerCAmelCase  						= TimestepEmbedding(in_channels=256    ,   time_embed_dim=A_      )
												_lowerCAmelCase  						= LabelEmbedding(A_    ,   A_    ,   A_      )




						def 					_lowercase	(					self    ,   _lowercase    ,   _lowercase    ,   _lowercase=None      ):

												"""simple docstring"""



												_lowerCAmelCase  						= self.time_proj(A_      )
												_lowerCAmelCase  						= self.timestep_embedder(timesteps_proj.to(dtype=A_      )      )  # (N, D)

												_lowerCAmelCase  						= self.class_embedder(A_      )  # (N, D)

												_lowerCAmelCase  						= timesteps_emb + class_labels  # (N, D)

												return conditioning






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase    ,   _lowercase    ,   _lowercase = 64      ):

												"""simple docstring"""



												super().__init__()
												_lowerCAmelCase  						= nn.LayerNorm(A_      )
												_lowerCAmelCase  						= AttentionPooling(A_    ,   A_      )
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_      )
												_lowerCAmelCase  						= nn.LayerNorm(A_      )




						def 					_lowercase	(					self    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= self.norma(A_      )
												_lowerCAmelCase  						= self.pool(A_      )
												_lowerCAmelCase  						= self.proj(A_      )
												_lowerCAmelCase  						= self.norma(A_      )
												return hidden_states






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase = 768    ,   _lowercase = 768    ,   _lowercase = 1_536      ):

												"""simple docstring"""



												super().__init__()
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_      )
												_lowerCAmelCase  						= nn.LayerNorm(A_      )
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_      )




						def 					_lowercase	(					self    ,   _lowercase    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= self.text_proj(A_      )
												_lowerCAmelCase  						= self.text_norm(A_      )

												# image
												_lowerCAmelCase  						= self.image_proj(A_      )

												return time_image_embeds + time_text_embeds






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase = 768    ,   _lowercase = 1_536      ):

												"""simple docstring"""



												super().__init__()
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_      )
												_lowerCAmelCase  						= nn.LayerNorm(A_      )




						def 					_lowercase	(					self    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= self.image_proj(A_      )
												_lowerCAmelCase  						= self.image_norm(A_      )
												return time_image_embeds






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase = 768    ,   _lowercase = 1_536      ):

												"""simple docstring"""



												super().__init__()
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_      )
												_lowerCAmelCase  						= nn.LayerNorm(A_      )
												_lowerCAmelCase  						= nn.Sequential(
												    nn.Convad(3    ,   16    ,   3    ,   padding=1      )    ,   nn.SiLU()    ,   nn.Convad(16    ,   16    ,   3    ,   padding=1      )    ,   nn.SiLU()    ,   nn.Convad(16    ,   32    ,   3    ,   padding=1    ,   stride=2      )    ,   nn.SiLU()    ,   nn.Convad(32    ,   32    ,   3    ,   padding=1      )    ,   nn.SiLU()    ,   nn.Convad(32    ,   96    ,   3    ,   padding=1    ,   stride=2      )    ,   nn.SiLU()    ,   nn.Convad(96    ,   96    ,   3    ,   padding=1      )    ,   nn.SiLU()    ,   nn.Convad(96    ,   256    ,   3    ,   padding=1    ,   stride=2      )    ,   nn.SiLU()    ,   nn.Convad(256    ,   4    ,   3    ,   padding=1      )    ,   )




						def 					_lowercase	(					self    ,   _lowercase    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= self.image_proj(A_      )
												_lowerCAmelCase  						= self.image_norm(A_      )
												_lowerCAmelCase  						= self.input_hint_block(A_      )
												return time_image_embeds, hint






class   UpperCAmelCase_     (		nn.Module ):






						'''simple docstring'''






						def __init__(					self    ,   _lowercase    ,   _lowercase    ,   _lowercase=None      ):

												"""simple docstring"""



												super().__init__()
												_lowerCAmelCase  						= dtype
												_lowerCAmelCase  						= nn.Parameter(torch.randn(1    ,   A_      ) / embed_dim**0.5      )
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_    ,   dtype=self.dtype      )
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_    ,   dtype=self.dtype      )
												_lowerCAmelCase  						= nn.Linear(A_    ,   A_    ,   dtype=self.dtype      )
												_lowerCAmelCase  						= num_heads
												_lowerCAmelCase  						= embed_dim // self.num_heads




						def 					_lowercase	(					self    ,   _lowercase      ):

												"""simple docstring"""



												_lowerCAmelCase  						= x.size()

												def shape(_lowercase      ):
																		# (bs, length, width) --> (bs, length, n_heads, dim_per_head)
																		_lowerCAmelCase  						= x.view(A_    ,   -1    ,   self.num_heads    ,   self.dim_per_head      )
																		# (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
																		_lowerCAmelCase  						= x.transpose(1    ,   2      )
																		# (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
																		_lowerCAmelCase  						= x.reshape(bs * self.num_heads    ,   -1    ,   self.dim_per_head      )
																		# (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length)
																		_lowerCAmelCase  						= x.transpose(1    ,   2      )
																		return x

												_lowerCAmelCase  						= x.mean(dim=1    ,   keepdim=A_      ) + self.positional_embedding.to(x.dtype      )
												_lowerCAmelCase  						= torch.cat([class_token, x]    ,   dim=1      )  # (bs, length+1, width)

												# (bs*n_heads, class_token_length, dim_per_head)
												_lowerCAmelCase  						= shape(self.q_proj(A_      )      )
												# (bs*n_heads, length+class_token_length, dim_per_head)
												_lowerCAmelCase  						= shape(self.k_proj(A_      )      )
												_lowerCAmelCase  						= shape(self.v_proj(A_      )      )

												# (bs*n_heads, class_token_length, length+class_token_length):
												_lowerCAmelCase  						= 1 / math.sqrt(math.sqrt(self.dim_per_head      )      )
												_lowerCAmelCase  						= torch.einsum("""bct,bcs->bts"""    ,   q * scale    ,   k * scale      )  # More stable with f16 than dividing afterwards
												_lowerCAmelCase  						= torch.softmax(weight.float()    ,   dim=-1      ).type(weight.dtype      )

												# (bs*n_heads, dim_per_head, class_token_length)
												_lowerCAmelCase  						= torch.einsum("""bts,bcs->bct"""    ,   A_    ,   A_      )

												# (bs, length+1, width)
												_lowerCAmelCase  						= a.reshape(A_    ,   -1    ,   1      ).transpose(1    ,   2      )

												return a[:, 0, :]  # cls_token



from __future__ import annotations

from collections.abc import Iterable

class  a     :


						def __init__(				self  ,    A_  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase						,							_UpperCAmelCase				:						Optional[Any]       						=			float(A_		), float(A_		)


						def __eq__(				self  ,    A_		):







										'''simple docstring'''


										return self.x == other.x and self.y == other.y


						def __ne__(				self  ,    A_		):







										'''simple docstring'''


										return not self == other


						def __gt__(				self  ,    A_		):







										'''simple docstring'''


										if self.x > other.x:
														return True
										elif self.x == other.x:
														return self.y > other.y
										return False


						def __lt__(				self  ,    A_		):







										'''simple docstring'''


										return not self > other


						def __ge__(				self  ,    A_		):







										'''simple docstring'''


										if self.x > other.x:
														return True
										elif self.x == other.x:
														return self.y >= other.y
										return False


						def __le__(				self  ,    A_		):







										'''simple docstring'''


										if self.x < other.x:
														return True
										elif self.x == other.x:
														return self.y <= other.y
										return False


						def __repr__(				self		):







										'''simple docstring'''


										return f'({self.x}, {self.y})'





						def __hash__(				self		):







										'''simple docstring'''


										return hash(self.x		)







def 							__SCREAMING_SNAKE_CASE							( lowerCAmelCase:     list[Point] | list[list[float]] | Iterable[list[float]]     ,					)      ->				list[Point]:
				_UpperCAmelCase				:						list[Point]       						=			[]
				if list_of_tuples:
								for p in list_of_tuples:
												if isinstance(lowerCAmelCase     ,					lowerCAmelCase       ):
																points.append(lowerCAmelCase       )
												else:
																try:
																				points.append(Point(p[0]     ,					p[1]       )       )
																except (IndexError, TypeError):
																				print(
																				    F'Ignoring deformed point {p}. All points'
																				    " must have at least 2 coordinates."       )
				return points

def 							__SCREAMING_SNAKE_CASE							( lowerCAmelCase:     list[Point] | list[list[float]]       )      ->				list[Point]:

				if not hasattr(lowerCAmelCase     ,					"__iter__"       ):
								_UpperCAmelCase				:						Optional[Any]       						=			F'Expecting an iterable object but got an non-iterable type {points}'
								raise ValueError(lowerCAmelCase       )

				if not points:
								_UpperCAmelCase				:						str       						=			F'Expecting a list of points but got {points}'
								raise ValueError(lowerCAmelCase       )

				return _construct_points(lowerCAmelCase       )

def 							__SCREAMING_SNAKE_CASE							( lowerCAmelCase:     Point     ,					lowerCAmelCase:     Point     ,					lowerCAmelCase:     Point       )      ->				float:
				_UpperCAmelCase				:						Union[str, Any]       						=			(a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
				return det

def 							__SCREAMING_SNAKE_CASE							( lowerCAmelCase:     list[Point]       )      ->				list[Point]:
				_UpperCAmelCase				:						Union[str, Any]       						=			sorted(_validate_input(lowerCAmelCase       )       )
				_UpperCAmelCase				:						Any       						=			len(lowerCAmelCase       )
				_UpperCAmelCase				:						Any       						=			set()

				for i in range(n - 1       ):
								for j in range(i + 1     ,					lowerCAmelCase       ):
												_UpperCAmelCase				:						Optional[int]       						=			False
												_UpperCAmelCase				:						Union[str, Any]       						=			True
												for k in range(lowerCAmelCase       ):
																if k != i and k != j:
																				_UpperCAmelCase				:						Tuple       						=			_det(points[i]     ,					points[j]     ,					points[k]       )

																				if det_k > 0:
																								_UpperCAmelCase				:						str       						=			True
																				elif det_k < 0:
																								_UpperCAmelCase				:						Optional[Any]       						=			True
																				else:
																								# point[i], point[j], point[k] all lie on a straight line
																								# if point[k] is to the left of point[i] or it's to the
																								# right of point[j], then point[i], point[j] cannot be
																								# part of the convex hull of A
																								if points[k] < points[i] or points[k] > points[j]:
																												_UpperCAmelCase				:						Any       						=			False
																												break

																if points_left_of_ij and points_right_of_ij:
																				_UpperCAmelCase				:						int       						=			False
																				break

												if ij_part_of_convex_hull:
																convex_set.update([points[i], points[j]]       )

				return sorted(lowerCAmelCase       )

def 							__SCREAMING_SNAKE_CASE							( lowerCAmelCase:     list[Point]       )      ->				list[Point]:
				_UpperCAmelCase				:						List[Any]       						=			sorted(_validate_input(lowerCAmelCase       )       )
				_UpperCAmelCase				:						int       						=			len(lowerCAmelCase       )

				# divide all the points into an upper hull and a lower hull
				# the left most point and the right most point are definitely
				# members of the convex hull by definition.
				# use these two anchors to divide all the points into two hulls,
				# an upper hull and a lower hull.

				# all points to the left (above) the line joining the extreme points belong to the
				# upper hull
				# all points to the right (below) the line joining the extreme points below to the
				# lower hull
				# ignore all points on the line joining the extreme points since they cannot be
				# part of the convex hull

				_UpperCAmelCase				:						Tuple       						=			points[0]
				_UpperCAmelCase				:						Optional[Any]       						=			points[n - 1]

				_UpperCAmelCase				:						Optional[Any]       						=			{left_most_point, right_most_point}
				_UpperCAmelCase				:						Tuple       						=			[]
				_UpperCAmelCase				:						Optional[Any]       						=			[]

				for i in range(1     ,					n - 1       ):
								_UpperCAmelCase				:						Optional[int]       						=			_det(lowerCAmelCase     ,					lowerCAmelCase     ,					points[i]       )

								if det > 0:
												upper_hull.append(points[i]       )
								elif det < 0:
												lower_hull.append(points[i]       )

				_construct_hull(lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase       )
				_construct_hull(lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase       )

				return sorted(lowerCAmelCase       )

def 							__SCREAMING_SNAKE_CASE							( lowerCAmelCase:     list[Point]     ,					lowerCAmelCase:     Point     ,					lowerCAmelCase:     Point     ,					lowerCAmelCase:     set[Point]       )      ->				None:
				if points:
								_UpperCAmelCase				:						List[str]       						=			None
								_UpperCAmelCase				:						Optional[int]       						=			float("-inf"       )
								_UpperCAmelCase				:						Dict       						=			[]

								for p in points:
												_UpperCAmelCase				:						int       						=			_det(lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase       )

												if det > 0:
																candidate_points.append(lowerCAmelCase       )

																if det > extreme_point_distance:
																				_UpperCAmelCase				:						Dict       						=			det
																				_UpperCAmelCase				:						Union[str, Any]       						=			p

								if extreme_point:
												_construct_hull(lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase       )
												convex_set.add(lowerCAmelCase       )
												_construct_hull(lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase     ,					lowerCAmelCase       )

def 							__SCREAMING_SNAKE_CASE							( lowerCAmelCase:     list[Point]       )      ->				list[Point]:
				_UpperCAmelCase				:						int       						=			sorted(_validate_input(lowerCAmelCase       )       )
				_UpperCAmelCase				:						Any       						=			len(lowerCAmelCase       )

				_UpperCAmelCase				:						List[Any]       						=			points[:2]
				for i in range(2     ,					lowerCAmelCase       ):
								_UpperCAmelCase				:						Tuple       						=			_det(convex_hull[1]     ,					convex_hull[0]     ,					points[i]       )
								if det > 0:
												convex_hull.insert(0     ,					points[i]       )
												break
								elif det < 0:
												convex_hull.append(points[i]       )
												break
								else:
												_UpperCAmelCase				:						Optional[int]       						=			points[i]
				i += 1

				for j in range(lowerCAmelCase     ,					lowerCAmelCase       ):
								if (
								    _det(convex_hull[0]     ,					convex_hull[-1]     ,					points[j]       ) > 0
								    and _det(convex_hull[-1]     ,					convex_hull[0]     ,					points[1]       ) < 0
								):
												# The point lies within the convex hull
												continue

								convex_hull.insert(0     ,					points[j]       )
								convex_hull.append(points[j]       )
								while _det(convex_hull[0]     ,					convex_hull[1]     ,					convex_hull[2]       ) >= 0:
												del convex_hull[1]
								while _det(convex_hull[-1]     ,					convex_hull[-2]     ,					convex_hull[-3]       ) <= 0:
												del convex_hull[-2]

    # `convex_hull` is contains the convex hull in circular order
				return sorted(convex_hull[1:] if len(lowerCAmelCase       ) > 3 else convex_hull       )

def 							__SCREAMING_SNAKE_CASE							( )      ->				List[str]:
				_UpperCAmelCase				:						Union[str, Any]       						=			[
				    (0, 3),
				    (2, 2),
				    (1, 1),
				    (2, 1),
				    (3, 0),
				    (0, 0),
				    (3, 3),
				    (2, -1),
				    (2, -4),
				    (1, -3),
				]
				# the convex set of points is
				# [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
				_UpperCAmelCase				:						int       						=			convex_hull_bf(lowerCAmelCase       )

				_UpperCAmelCase				:						Union[str, Any]       						=			convex_hull_recursive(lowerCAmelCase       )
				assert results_bf == results_recursive

				_UpperCAmelCase				:						int       						=			convex_hull_melkman(lowerCAmelCase       )
				assert results_bf == results_melkman

				print(lowerCAmelCase       )


if __name__ == "__main__":
					main()


