


"""simple docstring"""






import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import OPTConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, slow

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


if is_flax_available():
   import os

   # The slow tests are often failing with OOM error on GPU
   # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
   # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
   __snake_case												=							'''platform'''

   import jax
   import jax.numpy as jnp

   from transformers import FlaxOPTForCausalLM, FlaxOPTModel, GPTaTokenizer
def    A_ ( _lowerCAmelCase  :       Any,  _lowerCAmelCase  :       int,  _lowerCAmelCase  :       Tuple=None,  _lowerCAmelCase  :       int=None							):






     """simple docstring"""

     if attention_mask is None:
          _a     						=					np.where(input_ids != config.pad_token_id,  1,  0							)
     return {
         "input_ids": input_ids,
         "attention_mask": attention_mask,
     }


@require_flax
class      __lowerCamelCase	:

     '''simple docstring'''


     def __init__(   self     ,					__UpperCAmelCase     ,					__UpperCAmelCase=13     ,					__UpperCAmelCase=7     ,					__UpperCAmelCase=True     ,					__UpperCAmelCase=False     ,					__UpperCAmelCase=99     ,					__UpperCAmelCase=16     ,					__UpperCAmelCase=2     ,					__UpperCAmelCase=4     ,					__UpperCAmelCase=4     ,					__UpperCAmelCase="gelu"     ,					__UpperCAmelCase=0.1     ,					__UpperCAmelCase=0.1     ,					__UpperCAmelCase=20     ,					__UpperCAmelCase=2     ,					__UpperCAmelCase=1     ,					__UpperCAmelCase=0     ,					__UpperCAmelCase=16     ,					__UpperCAmelCase=16     ,					__UpperCAmelCase=0.02     ,					)							->				Optional[Any]:
          _a     						=					parent
          _a     						=					batch_size
          _a     						=					seq_length
          _a     						=					is_training
          _a     						=					use_labels
          _a     						=					vocab_size
          _a     						=					hidden_size
          _a     						=					num_hidden_layers
          _a     						=					num_attention_heads
          _a     						=					intermediate_size
          _a     						=					hidden_act
          _a     						=					hidden_dropout_prob
          _a     						=					attention_probs_dropout_prob
          _a     						=					max_position_embeddings
          _a     						=					eos_token_id
          _a     						=					pad_token_id
          _a     						=					bos_token_id
          _a     						=					embed_dim
          _a     						=					word_embed_proj_dim
          _a     						=					initializer_range
          _a     						=					False


     def 				_UpperCAmelCase   (   self				)							->				Optional[int]:
          _a     						=					np.clip(ids_tensor([self.batch_size, self.seq_length - 1]     ,					self.vocab_size				)     ,					3     ,					self.vocab_size				)
          _a     						=					np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)     ,					dtype=np.intaa				))     ,					-1				)

          _a     						=					OPTConfig(
              vocab_size=self.vocab_size     ,					hidden_size=self.hidden_size     ,					num_hidden_layers=self.num_hidden_layers     ,					num_attention_heads=self.num_attention_heads     ,					ffn_dim=self.intermediate_size     ,					dropout=self.hidden_dropout_prob     ,					attention_dropout=self.attention_probs_dropout_prob     ,					max_position_embeddings=self.max_position_embeddings     ,					eos_token_id=self.eos_token_id     ,					bos_token_id=self.bos_token_id     ,					pad_token_id=self.pad_token_id     ,					embed_dim=self.embed_dim     ,					is_encoder_decoder=lowercase__     ,					word_embed_proj_dim=self.word_embed_proj_dim     ,					initializer_range=self.initializer_range     ,					use_cache=lowercase__     ,					)
          _a     						=					prepare_opt_inputs_dict(lowercase__     ,					lowercase__				)
          return config, inputs_dict


     def 				_UpperCAmelCase   (   self				)							->				List[Any]:
          _a						,   _a     						=					self.prepare_config_and_inputs()
          return config, inputs_dict


     def 				_UpperCAmelCase   (   self     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				)							->				Tuple:
          _a     						=					20
          _a     						=					model_class_name(lowercase__				)

          _a     						=					inputs_dict['''input_ids''']
          _a     						=					inputs_dict['''attention_mask''']

          _a     						=					model.init_cache(input_ids.shape[0]     ,					lowercase__				)
          _a     						=					jnp.ones((input_ids.shape[0], max_length)     ,					dtype='''i4'''				)

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

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

          _a     						=					model(lowercase__				)

          _a     						=					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 				_UpperCAmelCase   (   self     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				)							->				Tuple:
          _a     						=					20
          _a     						=					model_class_name(lowercase__				)

          _a						,   _a     						=					(
              inputs_dict['''input_ids'''],
              inputs_dict['''attention_mask'''],
          )

          _a     						=					jnp.concatenate(
              [
                  attention_mask,
                  jnp.zeros((attention_mask.shape[0], max_length - attention_mask.shape[1])				),
              ]     ,					axis=-1     ,					)

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

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

          _a     						=					model(lowercase__     ,					attention_mask=lowercase__				)

          _a     						=					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_flax
class      __lowerCamelCase	(       a__	,       unittest.TestCase	,       a__					):

     '''simple docstring'''
     A_							:						Tuple     =		(FlaxOPTModel, FlaxOPTForCausalLM) if is_flax_available() else ()
     A_							:						Union[str, Any]     =		() if is_flax_available() else ()


     def 				_UpperCAmelCase   (   self				)							->				Optional[int]:
          _a     						=					FlaxOPTModelTester(self				)


     def 				_UpperCAmelCase   (   self				)							->				int:
          _a						,   _a     						=					self.model_tester.prepare_config_and_inputs()
          for model_class in self.all_model_classes:
               self.model_tester.check_use_cache_forward(lowercase__     ,					lowercase__     ,					lowercase__				)


     def 				_UpperCAmelCase   (   self				)							->				Union[str, Any]:
          _a						,   _a     						=					self.model_tester.prepare_config_and_inputs()
          for model_class in self.all_model_classes:
               self.model_tester.check_use_cache_forward_with_attn_mask(lowercase__     ,					lowercase__     ,					lowercase__				)





     @slow
     def 				_UpperCAmelCase   (   self				)							->				Optional[Any]:



          for model_class_name in self.all_model_classes:
               _a     						=					model_class_name.from_pretrained('''facebook/opt-125m'''				)
               _a     						=					np.ones((1, 1)				) * model.config.eos_token_id
               _a     						=					model(lowercase__				)
               self.assertIsNotNone(lowercase__				)







@require_sentencepiece
@require_flax
class      __lowerCamelCase	(       unittest.TestCase					):

     '''simple docstring'''


     @slow
     def 				_UpperCAmelCase   (   self				)							->				Union[str, Any]:
          _a     						=					FlaxOPTModel.from_pretrained('''facebook/opt-350m'''				)
          _a     						=					jnp.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]				)
          _a     						=					model(input_ids=lowercase__				).last_hidden_state
          _a     						=					(1, 11, 512)
          self.assertEqual(output.shape     ,					lowercase__				)
          _a     						=					jnp.array(
              [[-0.2867, -1.9256, -0.3062], [-1.2711, -0.1337, -0.1897], [0.4109, 0.1187, -1.3142]]				)
          self.assertTrue(jnp.allclose(output[:, :3, :3]     ,					lowercase__     ,					atol=4e-2				)				)







@require_flax
@slow
class      __lowerCamelCase	(       unittest.TestCase					):

     '''simple docstring'''


     def 				_UpperCAmelCase   (   self				)							->				Union[str, Any]:
          super().setUp()
          _a     						=					'''facebook/opt-350m'''





     def 				_UpperCAmelCase   (   self				)							->				Tuple:
          _a     						=					FlaxOPTForCausalLM.from_pretrained(self.path_model				)
          _a     						=					GPTaTokenizer.from_pretrained(self.path_model				)

          _a     						=					[
              '''Today is a beautiful day and I want to''',
              '''In the city of''',
              '''Paris is the capital of France and''',
              '''Computers and mobile phones have taken''',
          ]
          # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
          _a     						=					tokenizer(lowercase__     ,					return_tensors='''jax'''     ,					padding=lowercase__     ,					add_special_tokens=lowercase__				)
          _a     						=					model(inputs.input_ids     ,					attention_mask=inputs.attention_mask				)[0].mean(axis=-1				)
          _a     						=					jnp.array(
              [
                  [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670],
                  [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822],
                  [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703],
                  [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477],
              ]				)
          self.assertTrue(jnp.allclose(lowercase__     ,					lowercase__     ,					atol=4e-2				)				)

          _a     						=					jax.jit(lowercase__				)
          _a     						=					model(inputs.input_ids     ,					attention_mask=inputs.attention_mask				)[0].mean(axis=-1				)
          self.assertTrue(jnp.allclose(lowercase__     ,					lowercase__     ,					atol=4e-2				)				)







@require_flax
@slow
class      __lowerCamelCase	(       unittest.TestCase					):

     '''simple docstring'''


     @property
     def 				_UpperCAmelCase   (   self				)							->				List[str]:
          return [
              "Today is a beautiful day and I want",
              "In the city of",
              "Paris is the capital of France and",
              "Computers and mobile phones have taken",
          ]


     def 				_UpperCAmelCase   (   self				)							->				List[Any]:
          _a     						=					'''facebook/opt-125m'''

          _a     						=					[
              '''Today is a beautiful day and I want to''',
              '''In the city of New York, the city''',
              '''Paris is the capital of France and the capital''',
              '''Computers and mobile phones have taken over the''',
          ]

          _a     						=					[]

          _a     						=					FlaxOPTForCausalLM.from_pretrained(lowercase__				)
          _a     						=					GPTaTokenizer.from_pretrained(lowercase__				)

          for prompt in self.prompts:
               _a     						=					tokenizer(lowercase__     ,					return_tensors='''jax'''				).input_ids

               _a     						=					model.generate(lowercase__     ,					max_length=10				)
               _a     						=					generated_ids[0]

               _a     						=					tokenizer.batch_decode(lowercase__     ,					skip_special_tokens=lowercase__				)
               predicted_outputs += generated_string

          self.assertListEqual(lowercase__     ,					lowercase__				)


     def 				_UpperCAmelCase   (   self				)							->				Any:
          _a     						=					'''facebook/opt-350m'''

          _a     						=					[
              '''Today is a beautiful day and I want to''',
              '''In the city of San Francisco, the city''',
              '''Paris is the capital of France and the capital''',
              '''Computers and mobile phones have taken over the''',
          ]

          _a     						=					[]
          _a     						=					FlaxOPTForCausalLM.from_pretrained(lowercase__				)
          _a     						=					GPTaTokenizer.from_pretrained(lowercase__				)

          for prompt in self.prompts:
               _a     						=					tokenizer(lowercase__     ,					return_tensors='''jax'''				).input_ids

               _a     						=					model.generate(lowercase__     ,					max_length=10				)
               _a     						=					generated_ids[0]

               _a     						=					tokenizer.batch_decode(lowercase__     ,					skip_special_tokens=lowercase__				)
               predicted_outputs += generated_string

          self.assertListEqual(lowercase__     ,					lowercase__				)


     def 				_UpperCAmelCase   (   self				)							->				List[Any]:
          _a     						=					'''facebook/opt-125m'''
          _a     						=					[
              '''Today is a beautiful day and I want to thank''',
              '''In the city of Rome Canaver Canaver Canaver Canaver''',
          ]
          _a     						=					FlaxOPTForCausalLM.from_pretrained(lowercase__				)
          _a     						=					GPTaTokenizer.from_pretrained(lowercase__				)
          _a     						=					tokenizer(
              [
                  '''Today is a beautiful day and I want to''',
                  '''In the city of''',
              ]     ,					return_tensors='''jax'''     ,					padding=lowercase__     ,					)

          _a     						=					jax.jit(model.generate				)

          _a     						=					jit_generate(inputs['''input_ids''']     ,					attention_mask=inputs['''attention_mask''']				).sequences

          _a     						=					tokenizer.batch_decode(lowercase__     ,					skip_special_tokens=lowercase__				)

          self.assertIsNotNone(lowercase__     ,					lowercase__				)





     def 				_UpperCAmelCase   (   self				)							->				Optional[int]:
          _a     						=					'''facebook/opt-350m'''

          _a     						=					GPTaTokenizer.from_pretrained(lowercase__				)
          _a     						=					FlaxOPTForCausalLM.from_pretrained(lowercase__				)

          _a     						=					'''left'''

          # use different length sentences to test batching
          _a     						=					[
              '''Hello, my dog is a little''',
              '''Today, I''',
          ]

          _a     						=					tokenizer(lowercase__     ,					return_tensors='''jax'''     ,					padding=lowercase__				)
          _a     						=					inputs['''input_ids''']

          _a     						=					model.generate(input_ids=lowercase__     ,					attention_mask=inputs['''attention_mask''']     ,					trace=lowercase__				)

          _a     						=					tokenizer(sentences[0]     ,					return_tensors='''jax'''				).input_ids
          _a     						=					model.generate(input_ids=lowercase__				)

          _a     						=					inputs_non_padded.shape[-1] - inputs['''attention_mask'''][-1].sum()
          _a     						=					tokenizer(sentences[1]     ,					return_tensors='''jax'''				).input_ids
          _a     						=					model.generate(input_ids=lowercase__     ,					max_length=model.config.max_length - num_paddings				)

          _a     						=					tokenizer.batch_decode(outputs[0]     ,					skip_special_tokens=lowercase__				)
          _a     						=					tokenizer.decode(output_non_padded[0][0]     ,					skip_special_tokens=lowercase__				)
          _a     						=					tokenizer.decode(output_padded[0][0]     ,					skip_special_tokens=lowercase__				)

          _a     						=					[
              '''Hello, my dog is a little bit of a dork.\nI\'m a little bit''',
              '''Today, I was in the middle of a conversation with a friend about the''',
          ]
          self.assertListEqual(lowercase__     ,					lowercase__				)
          self.assertListEqual(lowercase__     ,					[non_padded_sentence, padded_sentence]				)
from __future__ import annotations

from collections.abc import Iterable
class 							a_					:






 '''simple docstring'''






 def __init__(     self   :    int     ,       lowercase__   :    Optional[int]     ,       lowercase__   :    List[str]):







        '''simple docstring'''



        lowerCAmelCase__      ,   lowerCAmelCase__	      =   float(lowercase__), float(lowercase__)




 def __eq__(     self   :    int     ,       lowercase__   :    int):







        '''simple docstring'''



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




 def __ne__(     self   :    Tuple     ,       lowercase__   :    List[Any]):







        '''simple docstring'''



        return not self == other




 def __gt__(     self   :    Optional[Any]     ,       lowercase__   :    List[Any]):







        '''simple docstring'''



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




 def __lt__(     self   :    str     ,       lowercase__   :    List[str]):







        '''simple docstring'''



        return not self > other




 def __ge__(     self   :    List[Any]     ,       lowercase__   :    Any):







        '''simple docstring'''



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




 def __le__(     self   :    Dict     ,       lowercase__   :    str):







        '''simple docstring'''



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




 def __repr__(     self   :    List[str]):







        '''simple docstring'''



        return F"""({self.x}, {self.y})"""




 def __hash__(     self   :    Dict):







        '''simple docstring'''



        return hash(self.x)






def  __lowerCamelCase						(		lowerCAmelCase__      ,    ):
       lowerCAmelCase__	      =   []
       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  __lowerCamelCase						(		lowerCAmelCase__      ):

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

       if not points:
              lowerCAmelCase__	      =   F"""Expecting a list of points but got {points}"""
              raise ValueError(lowerCAmelCase__      )

       return _construct_points(lowerCAmelCase__      )






def  __lowerCamelCase						(		lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ):
       lowerCAmelCase__	      =   (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  __lowerCamelCase						(		lowerCAmelCase__      ):
       lowerCAmelCase__	      =   sorted(_validate_input(lowerCAmelCase__      )      )
       lowerCAmelCase__	      =   len(lowerCAmelCase__      )
       lowerCAmelCase__	      =   set()

       for i in range(n - 1      ):
              for j in range(i + 1      ,    lowerCAmelCase__      ):
                     lowerCAmelCase__	      =   lowerCAmelCase__	      =   False
                     lowerCAmelCase__	      =   True
                     for k in range(lowerCAmelCase__      ):
                            if k != i and k != j:
                                   lowerCAmelCase__	      =   _det(points[i]      ,    points[j]      ,    points[k]      )

                                   if det_k > 0:
                                          lowerCAmelCase__	      =   True
                                   elif det_k < 0:
                                          lowerCAmelCase__	      =   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__	      =   False
                                                 break

                            if points_left_of_ij and points_right_of_ij:
                                   lowerCAmelCase__	      =   False
                                   break

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

       return sorted(lowerCAmelCase__      )






def  __lowerCamelCase						(		lowerCAmelCase__      ):
       lowerCAmelCase__	      =   sorted(_validate_input(lowerCAmelCase__      )      )
       lowerCAmelCase__	      =   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__	      =   points[0]
       lowerCAmelCase__	      =   points[n - 1]

       lowerCAmelCase__	      =   {left_most_point, right_most_point}
       lowerCAmelCase__	      =   []
       lowerCAmelCase__	      =   []

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

              for p in points:
                     lowerCAmelCase__	      =   _det(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      )

                     if det > 0:
                            candidate_points.append(lowerCAmelCase__      )

                            if det > extreme_point_distance:
                                   lowerCAmelCase__	      =   det
                                   lowerCAmelCase__	      =   p

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






def  __lowerCamelCase						(		lowerCAmelCase__      ):
       lowerCAmelCase__	      =   sorted(_validate_input(lowerCAmelCase__      )      )
       lowerCAmelCase__	      =   len(lowerCAmelCase__      )

       lowerCAmelCase__	      =   points[:2]
       for i in range(2      ,    lowerCAmelCase__      ):
              lowerCAmelCase__	      =   _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__	      =   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  __lowerCamelCase						(		):
       lowerCAmelCase__	      =   [
           (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__	      =   convex_hull_bf(lowerCAmelCase__      )

       lowerCAmelCase__	      =   convex_hull_recursive(lowerCAmelCase__      )
       assert results_bf == results_recursive

       lowerCAmelCase__	      =   convex_hull_melkman(lowerCAmelCase__      )
       assert results_bf == results_melkman

       print(lowerCAmelCase__      )


if __name__ == "__main__":
    main()
