



'''simple docstring'''





import tempfile
import unittest

import transformers
from transformers import XGLMConfig, XGLMTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, require_sentencepiece, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
   import jax
   import jax.numpy as jnp
   import numpy as np

   from transformers.modeling_flax_pytorch_utils import (
       convert_pytorch_state_dict_to_flax,
       load_flax_weights_in_pytorch_model,
   )
   from transformers.models.xglm.modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel


if is_torch_available():
   import torch






@require_flax
class  lowerCamelCase_   :
  """simple docstring"""




  def __init__(			self				:     Optional[Any]      ,     _a				:     List[str]      ,     _a				:     Dict=14      ,     _a				:     Optional[int]=7      ,     _a				:     Tuple=True      ,     _a				:     str=True      ,     _a				:     Dict=True      ,     _a				:     Tuple=99      ,     _a				:     Tuple=32      ,     _a				:     List[Any]=5      ,     _a				:     Any=4      ,     _a				:     List[Any]=37      ,     _a				:     Union[str, Any]="gelu"      ,     _a				:     List[str]=0.1      ,     _a				:     Dict=0.1      ,     _a				:     Dict=512      ,     _a				:     Any=0.02      ,     _a				:     List[Any]=None      ,     ) -> Dict:
    __lowerCamelCase	:	Union[str, Any]   	=			parent
    __lowerCamelCase	:	List[str]   	=			batch_size
    __lowerCamelCase	:	List[Any]   	=			seq_length
    __lowerCamelCase	:	Union[str, Any]   	=			is_training
    __lowerCamelCase	:	Optional[Any]   	=			use_input_mask
    __lowerCamelCase	:	Dict   	=			use_labels
    __lowerCamelCase	:	List[Any]   	=			vocab_size
    __lowerCamelCase	:	Optional[int]   	=			d_model
    __lowerCamelCase	:	Optional[int]   	=			num_hidden_layers
    __lowerCamelCase	:	str   	=			num_attention_heads
    __lowerCamelCase	:	Tuple   	=			ffn_dim
    __lowerCamelCase	:	str   	=			activation_function
    __lowerCamelCase	:	List[str]   	=			activation_dropout
    __lowerCamelCase	:	Tuple   	=			attention_dropout
    __lowerCamelCase	:	Optional[int]   	=			max_position_embeddings
    __lowerCamelCase	:	List[str]   	=			initializer_range
    __lowerCamelCase	:	List[Any]   	=			None
    __lowerCamelCase	:	Optional[Any]   	=			0
    __lowerCamelCase	:	Optional[Any]   	=			2
    __lowerCamelCase	:	str   	=			1




  def 						_lowercase					(			self				:     Union[str, Any]       ) -> str:
    __lowerCamelCase	:	str   	=			np.clip(ids_tensor([self.batch_size, self.seq_length]      ,     self.vocab_size       )      ,     3      ,     self.vocab_size       )

    __lowerCamelCase	:	List[str]   	=			None
    if self.use_input_mask:
      __lowerCamelCase	:	Union[str, Any]   	=			random_attention_mask([self.batch_size, self.seq_length]       )

    __lowerCamelCase	:	List[Any]   	=			XGLMConfig(
        vocab_size=self.vocab_size      ,     d_model=self.hidden_size      ,     num_layers=self.num_hidden_layers      ,     attention_heads=self.num_attention_heads      ,     ffn_dim=self.ffn_dim      ,     activation_function=self.activation_function      ,     activation_dropout=self.activation_dropout      ,     attention_dropout=self.attention_dropout      ,     max_position_embeddings=self.max_position_embeddings      ,     initializer_range=self.initializer_range      ,     use_cache=_a      ,     bos_token_id=self.bos_token_id      ,     eos_token_id=self.eos_token_id      ,     pad_token_id=self.pad_token_id      ,     )

    return (config, input_ids, input_mask)




  def 						_lowercase					(			self				:     Dict       ) -> Optional[Any]:
    __lowerCamelCase	:	Optional[int]   	=			self.prepare_config_and_inputs()
    __lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase	:	str   	=			config_and_inputs
    __lowerCamelCase	:	List[Any]   	=			{'input_ids': input_ids, 'attention_mask': attention_mask}
    return config, inputs_dict




  def 						_lowercase					(			self				:     int       ) -> List[Any]:
    __lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase	:	Dict   	=			self.prepare_config_and_inputs()

    __lowerCamelCase	:	Dict   	=			floats_tensor([self.batch_size, self.seq_length, self.hidden_size]       )
    __lowerCamelCase	:	str   	=			ids_tensor([self.batch_size, self.seq_length]      ,     vocab_size=2       )

    return (
        config,
        input_ids,
        attention_mask,
        encoder_hidden_states,
        encoder_attention_mask,
    )




  def 						_lowercase					(			self				:     int      ,     _a				:     Union[str, Any]      ,     _a				:     str      ,     _a				:     Tuple      ,     _a				:     List[str]       ) -> Any:
    __lowerCamelCase	:	Optional[Any]   	=			20
    __lowerCamelCase	:	str   	=			model_class_name(_a       )

    __lowerCamelCase	:	Union[str, Any]   	=			model.init_cache(input_ids.shape[0]      ,     _a       )
    __lowerCamelCase	:	Optional[int]   	=			jnp.ones((input_ids.shape[0], max_decoder_length)      ,     dtype='i4'       )

    __lowerCamelCase	:	int   	=			jnp.broadcast_to(
        jnp.arange(input_ids.shape[-1] - 1       )[None, :]      ,     (input_ids.shape[0], input_ids.shape[-1] - 1)       )
    __lowerCamelCase	:	List[str]   	=			model(
        input_ids[:, :-1]      ,     attention_mask=_a      ,     past_key_values=_a      ,     position_ids=_a      ,     )

    __lowerCamelCase	:	Tuple   	=			jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]      ,     dtype='i4'       )
    __lowerCamelCase	:	Union[str, Any]   	=			model(
        input_ids[:, -1:]      ,     attention_mask=_a      ,     past_key_values=outputs_cache.past_key_values      ,     position_ids=_a      ,     )

    __lowerCamelCase	:	Optional[Any]   	=			model(_a       )

    __lowerCamelCase	:	List[str]   	=			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])       )       )
    self.parent.assertTrue(diff < 1e-3      ,     msg=f'Max diff is {diff}'       )




  def 						_lowercase					(			self				:     Tuple      ,     _a				:     Optional[Any]      ,     _a				:     Union[str, Any]      ,     _a				:     Any      ,     _a				:     Optional[int]       ) -> Optional[Any]:
    __lowerCamelCase	:	Any   	=			20
    __lowerCamelCase	:	List[str]   	=			model_class_name(_a       )

    __lowerCamelCase	:	List[Any]   	=			jnp.concatenate(
        [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])       )]      ,     axis=-1      ,     )

    __lowerCamelCase	:	str   	=			model.init_cache(input_ids.shape[0]      ,     _a       )
    __lowerCamelCase	:	Optional[int]   	=			jnp.broadcast_to(
        jnp.arange(input_ids.shape[-1] - 1       )[None, :]      ,     (input_ids.shape[0], input_ids.shape[-1] - 1)       )

    __lowerCamelCase	:	Union[str, Any]   	=			model(
        input_ids[:, :-1]      ,     attention_mask=_a      ,     past_key_values=_a      ,     position_ids=_a      ,     )
    __lowerCamelCase	:	List[Any]   	=			jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]      ,     dtype='i4'       )
    __lowerCamelCase	:	str   	=			model(
        input_ids[:, -1:]      ,     past_key_values=outputs_cache.past_key_values      ,     attention_mask=_a      ,     position_ids=_a      ,     )

    __lowerCamelCase	:	List[str]   	=			model(_a      ,     attention_mask=_a       )
    __lowerCamelCase	:	int   	=			np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])       )       )
    self.parent.assertTrue(diff < 1e-3      ,     msg=f'Max diff is {diff}'       )






@require_sentencepiece
@require_flax
class  lowerCamelCase_   (    SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_       ,       unittest.TestCase					):
  """simple docstring"""




  a_							 =(FlaxXGLMModel, FlaxXGLMForCausalLM) if is_flax_available() else ()
  a_							 =(FlaxXGLMForCausalLM,) if is_flax_available() else ()




  def 						_lowercase					(			self				:     Union[str, Any]       ) -> Any:
    __lowerCamelCase	:	Optional[int]   	=			FlaxXGLMModelTester(self       )




  def 						_lowercase					(			self				:     str       ) -> List[str]:
    for model_class_name in self.all_model_classes:
      __lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase	:	Optional[int]   	=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.check_use_cache_forward(_a      ,     _a      ,     _a      ,     _a       )




  def 						_lowercase					(			self				:     Any       ) -> Dict:
    for model_class_name in self.all_model_classes:
      __lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase	:	List[Any]   	=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.check_use_cache_forward_with_attn_mask(
          _a      ,     _a      ,     _a      ,     _a       )




  @slow
  def 						_lowercase					(			self				:     List[Any]       ) -> Union[str, Any]:
    __lowerCamelCase	:	List[Any]   	=			XGLMTokenizer.from_pretrained('XGLM'      ,     padding_side='left'       )
    __lowerCamelCase	:	Optional[int]   	=			tokenizer(['Hello this is a long string', 'Hey']      ,     return_tensors='np'      ,     padding=_a      ,     truncation=_a       )

    __lowerCamelCase	:	Tuple   	=			FlaxXGLMForCausalLM.from_pretrained('facebook/xglm-564M'       )
    __lowerCamelCase	:	Optional[int]   	=			1
    __lowerCamelCase	:	Optional[int]   	=			False

    __lowerCamelCase	:	Dict   	=			jax.jit(model.generate       )

    __lowerCamelCase	:	List[str]   	=			jit_generate(inputs['input_ids']      ,     attention_mask=inputs['attention_mask']       ).sequences

    __lowerCamelCase	:	List[str]   	=			tokenizer.batch_decode(_a      ,     skip_special_tokens=_a       )

    __lowerCamelCase	:	int   	=			[
        'Hello this is a long string of questions, but I\'m not sure if I\'m',
        'Hey, I\'m a newbie to the forum and I\'',
    ]

    self.assertListEqual(_a      ,     _a       )




  @is_pt_flax_cross_test
  def 						_lowercase					(			self				:     List[Any]       ) -> Tuple:
    __lowerCamelCase	,__lowerCamelCase	:	List[Any]   	=			self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      with self.subTest(model_class.__name__       ):
        # prepare inputs
        __lowerCamelCase	:	List[str]   	=			self._prepare_for_class(_a      ,     _a       )
        __lowerCamelCase	:	Dict   	=			{k: torch.tensor(v.tolist()       ) for k, v in prepared_inputs_dict.items()}

        # load corresponding PyTorch class
        __lowerCamelCase	:	List[str]   	=			model_class.__name__[4:]  # Skip the "Flax" at the beginning
        __lowerCamelCase	:	str   	=			getattr(_a      ,     _a       )

        __lowerCamelCase	,__lowerCamelCase	:	Optional[int]   	=			pt_inputs['input_ids'].shape
        __lowerCamelCase	:	int   	=			np.random.randint(0      ,     seq_length - 1      ,     size=(batch_size,)       )
        for batch_idx, start_index in enumerate(_a       ):
          __lowerCamelCase	:	Tuple   	=			0
          __lowerCamelCase	:	List[str]   	=			1
          __lowerCamelCase	:	str   	=			0
          __lowerCamelCase	:	List[Any]   	=			1
        __lowerCamelCase	:	Dict   	=			pt_model_class(_a       ).eval()
        # Flax models don't use the `use_cache` option and cache is not returned as a default.
        # So we disable `use_cache` here for PyTorch model.
        __lowerCamelCase	:	int   	=			False
        __lowerCamelCase	:	List[str]   	=			model_class(_a      ,     dtype=jnp.floataa       )
        __lowerCamelCase	:	Any   	=			convert_pytorch_state_dict_to_flax(pt_model.state_dict()      ,     _a       )
        __lowerCamelCase	:	Optional[int]   	=			fx_state

        with torch.no_grad():
          __lowerCamelCase	:	Dict   	=			pt_model(**_a       ).to_tuple()

        __lowerCamelCase	:	Tuple   	=			fx_model(**_a       ).to_tuple()
        self.assertEqual(len(_a       )      ,     len(_a       )      ,     'Output lengths differ between Flax and PyTorch'       )
        for fx_output, pt_output in zip(_a      ,     _a       ):
          self.assert_almost_equals(fx_output[:, -1]      ,     pt_output[:, -1].numpy()      ,     4e-2       )

        with tempfile.TemporaryDirectory() as tmpdirname:
          pt_model.save_pretrained(_a       )
          __lowerCamelCase	:	str   	=			model_class.from_pretrained(_a      ,     from_pt=_a       )

        __lowerCamelCase	:	Optional[int]   	=			fx_model_loaded(**_a       ).to_tuple()
        self.assertEqual(
            len(_a       )      ,     len(_a       )      ,     'Output lengths differ between Flax and PyTorch'       )
        for fx_output_loaded, pt_output in zip(_a      ,     _a       ):
          self.assert_almost_equals(fx_output_loaded[:, -1]      ,     pt_output[:, -1].numpy()      ,     4e-2       )




  @is_pt_flax_cross_test
  def 						_lowercase					(			self				:     Dict       ) -> Dict:
    __lowerCamelCase	,__lowerCamelCase	:	Tuple   	=			self.model_tester.prepare_config_and_inputs_for_common()
    for model_class in self.all_model_classes:
      with self.subTest(model_class.__name__       ):
        # prepare inputs
        __lowerCamelCase	:	Optional[int]   	=			self._prepare_for_class(_a      ,     _a       )
        __lowerCamelCase	:	Optional[int]   	=			{k: torch.tensor(v.tolist()       ) for k, v in prepared_inputs_dict.items()}

        # load corresponding PyTorch class
        __lowerCamelCase	:	List[str]   	=			model_class.__name__[4:]  # Skip the "Flax" at the beginning
        __lowerCamelCase	:	str   	=			getattr(_a      ,     _a       )

        __lowerCamelCase	:	str   	=			pt_model_class(_a       ).eval()
        __lowerCamelCase	:	Optional[Any]   	=			False
        __lowerCamelCase	:	str   	=			model_class(_a      ,     dtype=jnp.floataa       )

        __lowerCamelCase	:	List[str]   	=			load_flax_weights_in_pytorch_model(_a      ,     fx_model.params       )
        __lowerCamelCase	,__lowerCamelCase	:	List[str]   	=			pt_inputs['input_ids'].shape
        __lowerCamelCase	:	int   	=			np.random.randint(0      ,     seq_length - 1      ,     size=(batch_size,)       )
        for batch_idx, start_index in enumerate(_a       ):
          __lowerCamelCase	:	List[Any]   	=			0
          __lowerCamelCase	:	Tuple   	=			1
          __lowerCamelCase	:	int   	=			0
          __lowerCamelCase	:	Optional[int]   	=			1

        # make sure weights are tied in PyTorch
        pt_model.tie_weights()

        with torch.no_grad():
          __lowerCamelCase	:	List[Any]   	=			pt_model(**_a       ).to_tuple()

        __lowerCamelCase	:	Dict   	=			fx_model(**_a       ).to_tuple()
        self.assertEqual(len(_a       )      ,     len(_a       )      ,     'Output lengths differ between Flax and PyTorch'       )
        for fx_output, pt_output in zip(_a      ,     _a       ):
          self.assert_almost_equals(fx_output[:, -1]      ,     pt_output[:, -1].numpy()      ,     4e-2       )

        with tempfile.TemporaryDirectory() as tmpdirname:
          fx_model.save_pretrained(_a       )
          __lowerCamelCase	:	int   	=			pt_model_class.from_pretrained(_a      ,     from_flax=_a       )

        with torch.no_grad():
          __lowerCamelCase	:	Optional[int]   	=			pt_model_loaded(**_a       ).to_tuple()

        self.assertEqual(
            len(_a       )      ,     len(_a       )      ,     'Output lengths differ between Flax and PyTorch'       )
        for fx_output, pt_output in zip(_a      ,     _a       ):
          self.assert_almost_equals(fx_output[:, -1]      ,     pt_output[:, -1].numpy()      ,     4e-2       )




  @slow
  def 						_lowercase					(			self				:     Any       ) -> Union[str, Any]:
    for model_class_name in self.all_model_classes:
      __lowerCamelCase	:	str   	=			model_class_name.from_pretrained('facebook/xglm-564M'       )
      __lowerCamelCase	:	Dict   	=			model(np.ones((1, 1)       )       )
      self.assertIsNotNone(_a       )











'''simple docstring'''





from __future__ import annotations

from collections.abc import Iterable






class  lowerCamelCase_   :
  """simple docstring"""




  def __init__(			self				:     int      ,     _a				:     Dict      ,     _a				:     Optional[Any]       ) -> str:
    __lowerCamelCase	,__lowerCamelCase	:	List[Any]   	=			float(_a       ), float(_a       )




  def __eq__(			self				:     Tuple      ,     _a				:     List[Any]       ) -> Optional[int]:
    return self.x == other.x and self.y == other.y




  def __ne__(			self				:     Tuple      ,     _a				:     Optional[int]       ) -> List[str]:
    return not self == other




  def __gt__(			self				:     Tuple      ,     _a				:     str       ) -> str:
    if self.x > other.x:
      return True
    elif self.x == other.x:
      return self.y > other.y
    return False




  def __lt__(			self				:     Union[str, Any]      ,     _a				:     List[Any]       ) -> Optional[Any]:
    return not self > other




  def __ge__(			self				:     Tuple      ,     _a				:     Optional[Any]       ) -> Optional[int]:
    if self.x > other.x:
      return True
    elif self.x == other.x:
      return self.y >= other.y
    return False




  def __le__(			self				:     Any      ,     _a				:     List[str]       ) -> Optional[int]:
    if self.x < other.x:
      return True
    elif self.x == other.x:
      return self.y <= other.y
    return False




  def __repr__(			self				:     int       ) -> Optional[int]:
    return f'({self.x}, {self.y})'




  def __hash__(			self				:     Optional[Any]       ) -> Union[str, Any]:
    return hash(self.x       )




def 	a_					(							_lowerCAmelCase	,)				->				list[Point]:
  __lowerCamelCase	:	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 	a_					(							_lowerCAmelCase	)				->				list[Point]:

  if not hasattr(_lowerCAmelCase	,'__iter__'	):
    __lowerCamelCase	:	str   	=			F'Expecting an iterable object but got an non-iterable type {points}'
    raise ValueError(_lowerCAmelCase	)

  if not points:
    __lowerCamelCase	:	Any   	=			F'Expecting a list of points but got {points}'
    raise ValueError(_lowerCAmelCase	)

  return _construct_points(_lowerCAmelCase	)

def 	a_					(							_lowerCAmelCase	,_lowerCAmelCase	,_lowerCAmelCase	)				->				float:
  __lowerCamelCase	:	Optional[int]   	=			(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 	a_					(							_lowerCAmelCase	)				->				list[Point]:
  __lowerCamelCase	:	Optional[Any]   	=			sorted(_validate_input(_lowerCAmelCase	)	)
  __lowerCamelCase	:	Optional[int]   	=			len(_lowerCAmelCase	)
  __lowerCamelCase	:	Union[str, Any]   	=			set()

  for i in range(n - 1	):
    for j in range(i + 1	,_lowerCAmelCase	):
      __lowerCamelCase	:	List[Any]   	=			False
      __lowerCamelCase	:	Union[str, Any]   	=			True
      for k in range(_lowerCAmelCase	):
        if k != i and k != j:
          __lowerCamelCase	:	Any   	=			_det(points[i]	,points[j]	,points[k]	)

          if det_k > 0:
            __lowerCamelCase	:	List[Any]   	=			True
          elif det_k < 0:
            __lowerCamelCase	:	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]:
              __lowerCamelCase	:	Dict   	=			False
              break

        if points_left_of_ij and points_right_of_ij:
          __lowerCamelCase	:	int   	=			False
          break

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

  return sorted(_lowerCAmelCase	)

def 	a_					(							_lowerCAmelCase	)				->				list[Point]:
  __lowerCamelCase	:	Dict   	=			sorted(_validate_input(_lowerCAmelCase	)	)
  __lowerCamelCase	:	Optional[Any]   	=			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

  __lowerCamelCase	:	str   	=			points[0]
  __lowerCamelCase	:	Optional[Any]   	=			points[n - 1]

  __lowerCamelCase	:	Tuple   	=			{left_most_point, right_most_point}
  __lowerCamelCase	:	int   	=			[]
  __lowerCamelCase	:	Tuple   	=			[]

  for i in range(1	,n - 1	):
    __lowerCamelCase	:	Dict   	=			_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 	a_					(							_lowerCAmelCase	,_lowerCAmelCase	,_lowerCAmelCase	,_lowerCAmelCase	)				->				None:
  if points:
    __lowerCamelCase	:	Optional[int]   	=			None
    __lowerCamelCase	:	Optional[Any]   	=			float('-inf'	)
    __lowerCamelCase	:	Optional[int]   	=			[]

    for p in points:
      __lowerCamelCase	:	List[str]   	=			_det(_lowerCAmelCase	,_lowerCAmelCase	,_lowerCAmelCase	)

      if det > 0:
        candidate_points.append(_lowerCAmelCase	)

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

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

def 	a_					(							_lowerCAmelCase	)				->				list[Point]:
  __lowerCamelCase	:	Optional[int]   	=			sorted(_validate_input(_lowerCAmelCase	)	)
  __lowerCamelCase	:	List[Any]   	=			len(_lowerCAmelCase	)

  __lowerCamelCase	:	Tuple   	=			points[:2]
  for i in range(2	,_lowerCAmelCase	):
    __lowerCamelCase	:	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:
      __lowerCamelCase	:	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 	a_					(							)				->				Optional[int]:
  __lowerCamelCase	:	List[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)]
  __lowerCamelCase	:	Any   	=			convex_hull_bf(_lowerCAmelCase	)

  __lowerCamelCase	:	Optional[int]   	=			convex_hull_recursive(_lowerCAmelCase	)
  assert results_bf == results_recursive

  __lowerCamelCase	:	int   	=			convex_hull_melkman(_lowerCAmelCase	)
  assert results_bf == results_melkman

  print(_lowerCAmelCase	)


if __name__ == "__main__":
   main()






